Compare commits

..

3 Commits

2019 changed files with 38439 additions and 55557 deletions

View File

@@ -15,6 +15,7 @@ Checks: >
-readability-misleading-indentation, -readability-misleading-indentation,
-readability-redundant-member-init,
-readability-use-anyofallof, -readability-use-anyofallof,
-readability-function-cognitive-complexity, -readability-function-cognitive-complexity,
@@ -32,20 +33,4 @@ Checks: >
-bugprone-exception-escape, -bugprone-exception-escape,
-bugprone-redundant-branch-condition, -bugprone-redundant-branch-condition,
modernize-*,
-modernize-use-auto,
-modernize-use-trailing-return-type,
-modernize-deprecated-headers,
-modernize-avoid-c-arrays,
-modernize-use-equals-default,
-modernize-use-nodiscard,
-modernize-use-using,
-modernize-loop-convert,
-modernize-pass-by-value,
-modernize-use-default-member-init,
-modernize-raw-string-literal,
-modernize-avoid-bind,
-modernize-use-override,
-modernize-use-transparent-functors,
WarningsAsErrors: '*' WarningsAsErrors: '*'

View File

@@ -1,93 +0,0 @@
# git config blame.ignoreRevsFile .git-blame-ignore-revs
#
# After running the above, commits listed in this file will be
# ignored by git blame. The blame will be shifted to the person
# who edited the line(s) before the ignored commit.
#
# To disable this ignorance for a command, run as follows
# git blame --ignore-revs-file="" <other options>
#
# Changes that belong here:
# - Massive comment, doxy-sections, or spelling corrections.
# - Clang-format, PEP8 or other automated changes which are *strictly* "no functional change".
# - Several smaller commits should be added to this list at once, because adding
# one extra commit (to edit this file) after every small cleanup is noisy.
#
# Note:
# - The comment above the SHA should be the first line of the commit.
# - It is fine to pack together similar commits if they have the same explanatory comment.
# - Use only 40 character git SHAs; not smaller ones, not prefixed with rB.
#
# https://git-scm.com/docs/git-blame/2.23.0
# white space commit. (2 spaces -> tab).
0a3694cd6ebec710da7110e9f168a72d47c71ee0
# Cycles: Cleanup, spacing after preprocessor
cb4b5e12abf1fc6cf9ffc0944e0a1bc406286c63
# ClangFormat: apply to source, most of intern
e12c08e8d170b7ca40f204a5b0423c23a9fbc2c1
# Code Style: use "#pragma once" in source directory
91694b9b58ab953f3b313be9389cc1303e472fc2
# Code Style: use "#pragma once" in some newer headers
8198dbb888856b8c11757586df02aca15f132f90
# Code Style: use "#pragma once" in intern/ghost
1b1129f82a9cf316b54fbc025f8cfcc1a74b8589
# Cleanup: mostly comments, use doxy syntax & typos
e0cb02587012b4b2f4b18363dc7d0a7da2c02093
# Cleanup: use C comments for descriptive text
2abfcebb0eb7989e3d1e7d03f37ecf5c088210af
# use lowercase for cmake builtin names and macros, remove contents in else() and endif() which is no longer needed.
afacd184982e58a9c830a3d5366e25983939a7ba
# Spelling: It's Versus Its
3a7fd309fce89213b0224b3c6807adb2d1fe7ca8
# Spelling: Then Versus Than
d1eefc421544e2ea632fb35cb6bcaade4c39ce6b
# Spelling: Miscellaneous
84ef3b80de4915a24a9fd2fd214d0fa44e59b854
# Spelling: Loose Versus Lose
c0a6bc19794c69843c38451c762e91bc10136e0f
# Spelling: Apart Versus A Part
3d26cd01b9ba6381eb165e11536345ae652dfb41
# Cleanup: use 2 space indentation for CMake
3076d95ba441cd32706a27d18922a30f8fd28b8a
# Cleanup: use over-line for doxy comments
4b188bb08cf5aaae3c68ab57bbcfa037eef1ac10
# Cleanup: General comment style clean up of graph_edit.c and fcurve.c
0105f146bb40bd609ccbda3d3f6aeb8e14ad3f9e
# Cleanup: pep8 (indentation, spacing, long lines)
41d2d6da0c96d351b47acb64d3e0decdba16cb16
# Cleanup: pep8, blank lines
bab9de2a52929fe2b45ecddb1eb09da3378e303b
# Cleanup: PEP8 for python changes
1e7e94588daa66483190f45a9de5e98228f80e05
# GPencil: Cleanup pep8
a09cc3ee1a99f2cd5040bbf30c8ab8c588bb2bb1
# Cleanup: trailing space, remove tabs, pep8
c42a6b77b52560d257279de2cb624b4ef2c0d24c
# Cleanup: use C style doxygen comments
8c1726918374e1d2d2123e17bae8db5aadde3433
# Cleanup: use doxy sections for imbuf
c207f7c22e1439e0b285fba5d2c072bdae23f981

View File

@@ -203,7 +203,7 @@ option(WITH_OPENVDB "Enable features relying on OpenVDB" ON)
option(WITH_OPENVDB_BLOSC "Enable blosc compression for OpenVDB, only enable if OpenVDB was built with blosc support" ON) option(WITH_OPENVDB_BLOSC "Enable blosc compression for OpenVDB, only enable if OpenVDB was built with blosc support" ON)
option(WITH_OPENVDB_3_ABI_COMPATIBLE "Assume OpenVDB library has been compiled with version 3 ABI compatibility" OFF) option(WITH_OPENVDB_3_ABI_COMPATIBLE "Assume OpenVDB library has been compiled with version 3 ABI compatibility" OFF)
mark_as_advanced(WITH_OPENVDB_3_ABI_COMPATIBLE) mark_as_advanced(WITH_OPENVDB_3_ABI_COMPATIBLE)
option(WITH_NANOVDB "Enable usage of NanoVDB data structure for rendering on the GPU" ON) option(WITH_NANOVDB "Enable usage of NanoVDB data structure for accelerated rendering on the GPU" OFF)
# GHOST Windowing Library Options # GHOST Windowing Library Options
option(WITH_GHOST_DEBUG "Enable debugging output for the GHOST library" OFF) option(WITH_GHOST_DEBUG "Enable debugging output for the GHOST library" OFF)
@@ -526,10 +526,10 @@ if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang")
# Silence the warning that object-size is not effective in -O0. # Silence the warning that object-size is not effective in -O0.
set(_asan_defaults "${_asan_defaults}") set(_asan_defaults "${_asan_defaults}")
else() else()
string(APPEND _asan_defaults " -fsanitize=object-size") set(_asan_defaults "${_asan_defaults} -fsanitize=object-size")
endif() endif()
else() else()
string(APPEND _asan_defaults " -fsanitize=leak -fsanitize=object-size") set(_asan_defaults "${_asan_defaults} -fsanitize=leak -fsanitize=object-size")
endif() endif()
set(COMPILER_ASAN_CFLAGS "${_asan_defaults}" CACHE STRING "C flags for address sanitizer") set(COMPILER_ASAN_CFLAGS "${_asan_defaults}" CACHE STRING "C flags for address sanitizer")
@@ -570,11 +570,6 @@ if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang")
endif() endif()
endif() endif()
if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang")
option(WITH_COMPILER_SHORT_FILE_MACRO "Make paths in macros like __FILE__ relative to top level source and build directories." ON)
mark_as_advanced(WITH_COMPILER_SHORT_FILE_MACRO)
endif()
if(WIN32) if(WIN32)
# Use hardcoded paths or find_package to find externals # Use hardcoded paths or find_package to find externals
option(WITH_WINDOWS_FIND_MODULES "Use find_package to locate libraries" OFF) option(WITH_WINDOWS_FIND_MODULES "Use find_package to locate libraries" OFF)
@@ -863,11 +858,11 @@ if(NOT CMAKE_BUILD_TYPE MATCHES "Release")
# Since linker flags are not set, all compiler checks and `find_package` # Since linker flags are not set, all compiler checks and `find_package`
# calls that rely on `try_compile` will fail. # calls that rely on `try_compile` will fail.
# See CMP0066 also. # See CMP0066 also.
string(APPEND CMAKE_C_FLAGS_DEBUG " ${COMPILER_ASAN_CFLAGS}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${COMPILER_ASAN_CFLAGS}")
string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO " ${COMPILER_ASAN_CFLAGS}") set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} ${COMPILER_ASAN_CFLAGS}")
string(APPEND CMAKE_CXX_FLAGS_DEBUG " ${COMPILER_ASAN_CXXFLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${COMPILER_ASAN_CXXFLAGS}")
string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO " ${COMPILER_ASAN_CXXFLAGS}") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} ${COMPILER_ASAN_CXXFLAGS}")
endif() endif()
if(MSVC) if(MSVC)
set(COMPILER_ASAN_LINKER_FLAGS "/FUNCTIONPADMIN:6") set(COMPILER_ASAN_LINKER_FLAGS "/FUNCTIONPADMIN:6")
@@ -946,11 +941,11 @@ endif()
# Do it globally, SSE2 is required for quite some time now. # Do it globally, SSE2 is required for quite some time now.
# Doing it now allows to use SSE/SSE2 in inline headers. # Doing it now allows to use SSE/SSE2 in inline headers.
if(SUPPORT_SSE_BUILD) if(SUPPORT_SSE_BUILD)
string(PREPEND PLATFORM_CFLAGS "${COMPILER_SSE_FLAG} ") set(PLATFORM_CFLAGS " ${COMPILER_SSE_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE__ -D__MMX__) add_definitions(-D__SSE__ -D__MMX__)
endif() endif()
if(SUPPORT_SSE2_BUILD) if(SUPPORT_SSE2_BUILD)
string(APPEND PLATFORM_CFLAGS " ${COMPILER_SSE2_FLAG}") set(PLATFORM_CFLAGS " ${PLATFORM_CFLAGS} ${COMPILER_SSE2_FLAG}")
add_definitions(-D__SSE2__) add_definitions(-D__SSE2__)
if(NOT SUPPORT_SSE_BUILD) # don't double up if(NOT SUPPORT_SSE_BUILD) # don't double up
add_definitions(-D__MMX__) add_definitions(-D__MMX__)
@@ -1162,8 +1157,8 @@ if(WITH_OPENMP)
if(OPENMP_FOUND) if(OPENMP_FOUND)
if(NOT WITH_OPENMP_STATIC) if(NOT WITH_OPENMP_STATIC)
string(APPEND CMAKE_C_FLAGS " ${OpenMP_C_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
string(APPEND CMAKE_CXX_FLAGS " ${OpenMP_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
else() else()
# Typically avoid adding flags as defines but we can't # Typically avoid adding flags as defines but we can't
# pass OpenMP flags to the linker for static builds, meaning # pass OpenMP flags to the linker for static builds, meaning
@@ -1480,12 +1475,10 @@ if(CMAKE_COMPILER_IS_GNUCC)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INT_IN_BOOL_CONTEXT -Wno-int-in-bool-context) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INT_IN_BOOL_CONTEXT -Wno-int-in-bool-context)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_FORMAT -Wno-format) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_FORMAT -Wno-format)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_SWITCH -Wno-switch) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_SWITCH -Wno-switch)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_VARIABLE -Wno-unused-variable)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_CLASS_MEMACCESS -Wno-class-memaccess) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_CLASS_MEMACCESS -Wno-class-memaccess)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_COMMENT -Wno-comment) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_COMMENT -Wno-comment)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_TYPEDEFS -Wno-unused-local-typedefs) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_TYPEDEFS -Wno-unused-local-typedefs)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_VARIABLE -Wno-unused-variable)
if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "7.0")) if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "7.0"))
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_IMPLICIT_FALLTHROUGH -Wno-implicit-fallthrough) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_IMPLICIT_FALLTHROUGH -Wno-implicit-fallthrough)
@@ -1524,7 +1517,6 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Clang")
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_VARIABLE -Wno-unused-variable) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_VARIABLE -Wno-unused-variable)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_MACROS -Wno-unused-macros) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_MACROS -Wno-unused-macros)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISLEADING_INDENTATION -Wno-misleading-indentation)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_VARIABLE_DECLARATIONS -Wno-missing-variable-declarations) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_VARIABLE_DECLARATIONS -Wno-missing-variable-declarations)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INCOMPAT_PTR_DISCARD_QUAL -Wno-incompatible-pointer-types-discards-qualifiers) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INCOMPAT_PTR_DISCARD_QUAL -Wno-incompatible-pointer-types-discards-qualifiers)
@@ -1535,18 +1527,15 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Clang")
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNDEF -Wno-undef) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNDEF -Wno-undef)
ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_NORETURN -Wno-missing-noreturn) ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_NORETURN -Wno-missing-noreturn)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_PRIVATE_FIELD -Wno-unused-private-field) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_PRIVATE_FIELD -Wno-unused-private-field)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_CXX11_NARROWING -Wno-c++11-narrowing) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_CXX11_NARROWING -Wno-c++11-narrowing)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_NON_VIRTUAL_DTOR -Wno-non-virtual-dtor) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_NON_VIRTUAL_DTOR -Wno-non-virtual-dtor)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_MACROS -Wno-unused-macros) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_MACROS -Wno-unused-macros)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_VARIABLE -Wno-unused-variable)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_REORDER -Wno-reorder) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_REORDER -Wno-reorder)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_COMMENT -Wno-comment) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_COMMENT -Wno-comment)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_TYPEDEFS -Wno-unused-local-typedefs) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_TYPEDEFS -Wno-unused-local-typedefs)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNDEFINED_VAR_TEMPLATE -Wno-undefined-var-template) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNDEFINED_VAR_TEMPLATE -Wno-undefined-var-template)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_INSTANTIATION_AFTER_SPECIALIZATION -Wno-instantiation-after-specialization) ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_INSTANTIATION_AFTER_SPECIALIZATION -Wno-instantiation-after-specialization)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_MISLEADING_INDENTATION -Wno-misleading-indentation)
elseif(CMAKE_C_COMPILER_ID MATCHES "Intel") elseif(CMAKE_C_COMPILER_ID MATCHES "Intel")
@@ -1559,8 +1548,8 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Intel")
ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_SIGN_COMPARE -Wno-sign-compare) ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_NO_SIGN_COMPARE -Wno-sign-compare)
# disable numbered, false positives # disable numbered, false positives
string(APPEND C_WARNINGS " -wd188,186,144,913,556,858,597,177,1292,167,279,592,94,2722,3199") set(C_WARNINGS "${C_WARNINGS} -wd188,186,144,913,556,858,597,177,1292,167,279,592,94,2722,3199")
string(APPEND CXX_WARNINGS " -wd188,186,144,913,556,858,597,177,1292,167,279,592,94,2722,3199") set(CXX_WARNINGS "${CXX_WARNINGS} -wd188,186,144,913,556,858,597,177,1292,167,279,592,94,2722,3199")
elseif(CMAKE_C_COMPILER_ID MATCHES "MSVC") elseif(CMAKE_C_COMPILER_ID MATCHES "MSVC")
# most msvc warnings are C & C++ # most msvc warnings are C & C++
set(_WARNINGS set(_WARNINGS
@@ -1591,7 +1580,7 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "MSVC")
if(MSVC_VERSION GREATER_EQUAL 1911) if(MSVC_VERSION GREATER_EQUAL 1911)
# see https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/c5038?view=vs-2017 # see https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/c5038?view=vs-2017
string(APPEND _WARNINGS " /w35038") # order of initialization in c++ constructors set(_WARNINGS "${_WARNINGS} /w35038") # order of initialization in c++ constructors
endif() endif()
string(REPLACE ";" " " _WARNINGS "${_WARNINGS}") string(REPLACE ";" " " _WARNINGS "${_WARNINGS}")
@@ -1632,19 +1621,19 @@ if(WITH_PYTHON)
endif() endif()
if(MSVC) if(MSVC)
string(APPEND CMAKE_CXX_FLAGS " /std:c++17") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++17")
# Make MSVC properly report the value of the __cplusplus preprocessor macro # Make MSVC properly report the value of the __cplusplus preprocessor macro
# Available MSVC 15.7 (1914) and up, without this it reports 199711L regardless # Available MSVC 15.7 (1914) and up, without this it reports 199711L regardless
# of the C++ standard chosen above # of the C++ standard chosen above
if(MSVC_VERSION GREATER 1913) if(MSVC_VERSION GREATER 1913)
string(APPEND CMAKE_CXX_FLAGS " /Zc:__cplusplus") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zc:__cplusplus")
endif() endif()
elseif( elseif(
CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCC OR
CMAKE_C_COMPILER_ID MATCHES "Clang" OR CMAKE_C_COMPILER_ID MATCHES "Clang" OR
CMAKE_C_COMPILER_ID MATCHES "Intel" CMAKE_C_COMPILER_ID MATCHES "Intel"
) )
string(APPEND CMAKE_CXX_FLAGS " -std=c++17") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
else() else()
message(FATAL_ERROR "Unknown compiler ${CMAKE_C_COMPILER_ID}, can't enable C++17 build") message(FATAL_ERROR "Unknown compiler ${CMAKE_C_COMPILER_ID}, can't enable C++17 build")
endif() endif()
@@ -1657,47 +1646,12 @@ if(
(CMAKE_C_COMPILER_ID MATCHES "Intel") (CMAKE_C_COMPILER_ID MATCHES "Intel")
) )
# Use C11 + GNU extensions, works with GCC, Clang, ICC # Use C11 + GNU extensions, works with GCC, Clang, ICC
string(APPEND CMAKE_C_FLAGS " -std=gnu11") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11")
endif() endif()
if(UNIX AND NOT APPLE) if(UNIX AND NOT APPLE)
if(NOT WITH_CXX11_ABI) if(NOT WITH_CXX11_ABI)
string(APPEND PLATFORM_CFLAGS " -D_GLIBCXX_USE_CXX11_ABI=0") set(PLATFORM_CFLAGS "${PLATFORM_CFLAGS} -D_GLIBCXX_USE_CXX11_ABI=0")
endif()
endif()
if(WITH_COMPILER_SHORT_FILE_MACRO)
# Use '-fmacro-prefix-map' for Clang and GCC (MSVC doesn't support this).
ADD_CHECK_C_COMPILER_FLAG(C_PREFIX_MAP_FLAGS C_MACRO_PREFIX_MAP -fmacro-prefix-map=foo=bar)
ADD_CHECK_CXX_COMPILER_FLAG(CXX_PREFIX_MAP_FLAGS CXX_MACRO_PREFIX_MAP -fmacro-prefix-map=foo=bar)
if(C_MACRO_PREFIX_MAP AND CXX_MACRO_PREFIX_MAP)
if(APPLE)
if(XCODE AND ${XCODE_VERSION} VERSION_LESS 12.0)
# Developers may have say LLVM Clang-10.0.1 toolchain (which supports the flag)
# with Xcode-11 (the Clang of which doesn't support the flag).
message(WARNING
"-fmacro-prefix-map flag is NOT supported by Clang shipped with Xcode-${XCODE_VERSION}."
" Some Xcode functionality in Product menu may not work. Disabling WITH_COMPILER_SHORT_FILE_MACRO."
)
set(WITH_COMPILER_SHORT_FILE_MACRO OFF)
endif()
endif()
if(WITH_COMPILER_SHORT_FILE_MACRO)
path_ensure_trailing_slash(_src_dir "${CMAKE_SOURCE_DIR}")
path_ensure_trailing_slash(_bin_dir "${CMAKE_BINARY_DIR}")
# Keep this variable so it can be stripped from build-info.
set(PLATFORM_CFLAGS_FMACRO_PREFIX_MAP
"-fmacro-prefix-map=\"${_src_dir}\"=\"\" -fmacro-prefix-map=\"${_bin_dir}\"=\"\"")
string(APPEND PLATFORM_CFLAGS " ${PLATFORM_CFLAGS_FMACRO_PREFIX_MAP}")
unset(_src_dir)
unset(_bin_dir)
endif()
else()
message(WARNING
"-fmacro-prefix-map flag is NOT supported by C/C++ compiler."
" Disabling WITH_COMPILER_SHORT_FILE_MACRO."
)
set(WITH_COMPILER_SHORT_FILE_MACRO OFF)
endif() endif()
endif() endif()
@@ -1801,7 +1755,7 @@ if(FIRST_RUN)
set(_msg " - ${_setting}") set(_msg " - ${_setting}")
string(LENGTH "${_msg}" _len) string(LENGTH "${_msg}" _len)
while("32" GREATER "${_len}") while("32" GREATER "${_len}")
string(APPEND _msg " ") set(_msg "${_msg} ")
math(EXPR _len "${_len} + 1") math(EXPR _len "${_len} + 1")
endwhile() endwhile()
@@ -1819,24 +1773,24 @@ if(FIRST_RUN)
message(STATUS "C++ Compiler: \"${CMAKE_CXX_COMPILER_ID}\"") message(STATUS "C++ Compiler: \"${CMAKE_CXX_COMPILER_ID}\"")
info_cfg_text("Build Options:") info_cfg_text("Build Options:")
info_cfg_option(WITH_ALEMBIC)
info_cfg_option(WITH_BULLET) info_cfg_option(WITH_BULLET)
info_cfg_option(WITH_CYCLES)
info_cfg_option(WITH_FFTW3)
info_cfg_option(WITH_FREESTYLE)
info_cfg_option(WITH_GMP)
info_cfg_option(WITH_IK_ITASC)
info_cfg_option(WITH_IK_SOLVER) info_cfg_option(WITH_IK_SOLVER)
info_cfg_option(WITH_INPUT_NDOF) info_cfg_option(WITH_IK_ITASC)
info_cfg_option(WITH_INTERNATIONAL)
info_cfg_option(WITH_OPENCOLLADA) info_cfg_option(WITH_OPENCOLLADA)
info_cfg_option(WITH_FFTW3)
info_cfg_option(WITH_INTERNATIONAL)
info_cfg_option(WITH_INPUT_NDOF)
info_cfg_option(WITH_CYCLES)
info_cfg_option(WITH_FREESTYLE)
info_cfg_option(WITH_OPENCOLORIO) info_cfg_option(WITH_OPENCOLORIO)
info_cfg_option(WITH_XR_OPENXR)
info_cfg_option(WITH_OPENIMAGEDENOISE) info_cfg_option(WITH_OPENIMAGEDENOISE)
info_cfg_option(WITH_OPENVDB) info_cfg_option(WITH_OPENVDB)
info_cfg_option(WITH_ALEMBIC)
info_cfg_option(WITH_QUADRIFLOW) info_cfg_option(WITH_QUADRIFLOW)
info_cfg_option(WITH_TBB)
info_cfg_option(WITH_USD) info_cfg_option(WITH_USD)
info_cfg_option(WITH_XR_OPENXR) info_cfg_option(WITH_TBB)
info_cfg_option(WITH_GMP)
info_cfg_text("Compiler Options:") info_cfg_text("Compiler Options:")
info_cfg_option(WITH_BUILDINFO) info_cfg_option(WITH_BUILDINFO)
@@ -1844,58 +1798,58 @@ if(FIRST_RUN)
info_cfg_text("System Options:") info_cfg_text("System Options:")
info_cfg_option(WITH_INSTALL_PORTABLE) info_cfg_option(WITH_INSTALL_PORTABLE)
info_cfg_option(WITH_MEM_JEMALLOC)
info_cfg_option(WITH_MEM_VALGRIND)
info_cfg_option(WITH_SYSTEM_GLEW)
info_cfg_option(WITH_X11_ALPHA) info_cfg_option(WITH_X11_ALPHA)
info_cfg_option(WITH_X11_XF86VMODE) info_cfg_option(WITH_X11_XF86VMODE)
info_cfg_option(WITH_X11_XFIXES) info_cfg_option(WITH_X11_XFIXES)
info_cfg_option(WITH_X11_XINPUT) info_cfg_option(WITH_X11_XINPUT)
info_cfg_option(WITH_MEM_JEMALLOC)
info_cfg_option(WITH_MEM_VALGRIND)
info_cfg_option(WITH_SYSTEM_GLEW)
info_cfg_text("Image Formats:") info_cfg_text("Image Formats:")
info_cfg_option(WITH_OPENIMAGEIO)
info_cfg_option(WITH_IMAGE_CINEON) info_cfg_option(WITH_IMAGE_CINEON)
info_cfg_option(WITH_IMAGE_DDS) info_cfg_option(WITH_IMAGE_DDS)
info_cfg_option(WITH_IMAGE_HDR) info_cfg_option(WITH_IMAGE_HDR)
info_cfg_option(WITH_IMAGE_OPENEXR) info_cfg_option(WITH_IMAGE_OPENEXR)
info_cfg_option(WITH_IMAGE_OPENJPEG) info_cfg_option(WITH_IMAGE_OPENJPEG)
info_cfg_option(WITH_IMAGE_TIFF) info_cfg_option(WITH_IMAGE_TIFF)
info_cfg_option(WITH_OPENIMAGEIO)
info_cfg_text("Audio:") info_cfg_text("Audio:")
info_cfg_option(WITH_CODEC_AVI)
info_cfg_option(WITH_CODEC_FFMPEG)
info_cfg_option(WITH_CODEC_SNDFILE)
info_cfg_option(WITH_JACK)
info_cfg_option(WITH_JACK_DYNLOAD)
info_cfg_option(WITH_OPENAL) info_cfg_option(WITH_OPENAL)
info_cfg_option(WITH_SDL) info_cfg_option(WITH_SDL)
info_cfg_option(WITH_SDL_DYNLOAD) info_cfg_option(WITH_SDL_DYNLOAD)
info_cfg_option(WITH_JACK)
info_cfg_option(WITH_JACK_DYNLOAD)
info_cfg_option(WITH_CODEC_AVI)
info_cfg_option(WITH_CODEC_FFMPEG)
info_cfg_option(WITH_CODEC_SNDFILE)
info_cfg_text("Compression:") info_cfg_text("Compression:")
info_cfg_option(WITH_LZMA) info_cfg_option(WITH_LZMA)
info_cfg_option(WITH_LZO) info_cfg_option(WITH_LZO)
info_cfg_text("Python:") info_cfg_text("Python:")
if(APPLE)
info_cfg_option(WITH_PYTHON_FRAMEWORK)
endif()
info_cfg_option(WITH_PYTHON_INSTALL) info_cfg_option(WITH_PYTHON_INSTALL)
info_cfg_option(WITH_PYTHON_INSTALL_NUMPY) info_cfg_option(WITH_PYTHON_INSTALL_NUMPY)
info_cfg_option(WITH_PYTHON_MODULE) info_cfg_option(WITH_PYTHON_MODULE)
info_cfg_option(WITH_PYTHON_SAFETY) info_cfg_option(WITH_PYTHON_SAFETY)
if(APPLE)
info_cfg_option(WITH_PYTHON_FRAMEWORK)
endif()
info_cfg_text("Modifiers:") info_cfg_text("Modifiers:")
info_cfg_option(WITH_MOD_REMESH)
info_cfg_option(WITH_MOD_FLUID) info_cfg_option(WITH_MOD_FLUID)
info_cfg_option(WITH_MOD_OCEANSIM) info_cfg_option(WITH_MOD_OCEANSIM)
info_cfg_option(WITH_MOD_REMESH)
info_cfg_text("OpenGL:") info_cfg_text("OpenGL:")
info_cfg_option(WITH_GLEW_ES)
info_cfg_option(WITH_GL_EGL)
info_cfg_option(WITH_GL_PROFILE_ES20)
if(WIN32) if(WIN32)
info_cfg_option(WITH_GL_ANGLE) info_cfg_option(WITH_GL_ANGLE)
endif() endif()
info_cfg_option(WITH_GL_EGL)
info_cfg_option(WITH_GL_PROFILE_ES20)
info_cfg_option(WITH_GLEW_ES)
info_cfg_text("") info_cfg_text("")

View File

@@ -85,7 +85,6 @@ include(cmake/flexbison.cmake)
include(cmake/osl.cmake) include(cmake/osl.cmake)
include(cmake/tbb.cmake) include(cmake/tbb.cmake)
include(cmake/openvdb.cmake) include(cmake/openvdb.cmake)
include(cmake/nanovdb.cmake)
include(cmake/python.cmake) include(cmake/python.cmake)
include(cmake/python_site_packages.cmake) include(cmake/python_site_packages.cmake)
include(cmake/package_python.cmake) include(cmake/package_python.cmake)

View File

@@ -43,7 +43,7 @@ if(UNIX)
if(APPLE) if(APPLE)
if(NOT EXISTS "/usr/local/opt/bison/bin/bison") if(NOT EXISTS "/usr/local/opt/bison/bin/bison")
string(APPEND _software_missing " bison") set(_software_missing "${_software_missing} bison")
endif() endif()
endif() endif()

View File

@@ -146,8 +146,10 @@ harvest(openjpeg/lib openjpeg/lib "*.a")
harvest(opensubdiv/include opensubdiv/include "*.h") harvest(opensubdiv/include opensubdiv/include "*.h")
harvest(opensubdiv/lib opensubdiv/lib "*.a") harvest(opensubdiv/lib opensubdiv/lib "*.a")
harvest(openvdb/include/openvdb openvdb/include/openvdb "*.h") harvest(openvdb/include/openvdb openvdb/include/openvdb "*.h")
if(WITH_NANOVDB)
harvest(openvdb/nanovdb nanovdb/include/nanovdb "*.h")
endif()
harvest(openvdb/lib openvdb/lib "*.a") harvest(openvdb/lib openvdb/lib "*.a")
harvest(nanovdb/nanovdb nanovdb/include/nanovdb "*.h")
harvest(xr_openxr_sdk/include/openxr xr_openxr_sdk/include/openxr "*.h") harvest(xr_openxr_sdk/include/openxr xr_openxr_sdk/include/openxr "*.h")
harvest(xr_openxr_sdk/lib xr_openxr_sdk/lib "*.a") harvest(xr_openxr_sdk/lib xr_openxr_sdk/lib "*.a")
harvest(osl/bin osl/bin "oslc") harvest(osl/bin osl/bin "oslc")

View File

@@ -1,54 +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.
#
# ***** END GPL LICENSE BLOCK *****
set(NANOVDB_EXTRA_ARGS
# NanoVDB is header-only, so only need the install target
-DNANOVDB_BUILD_UNITTESTS=OFF
-DNANOVDB_BUILD_EXAMPLES=OFF
-DNANOVDB_BUILD_BENCHMARK=OFF
-DNANOVDB_BUILD_DOCS=OFF
-DNANOVDB_BUILD_TOOLS=OFF
-DNANOVDB_CUDA_KEEP_PTX=OFF
# Do not need to include any of the dependencies because of this
-DNANOVDB_USE_OPENVDB=OFF
-DNANOVDB_USE_OPENGL=OFF
-DNANOVDB_USE_OPENCL=OFF
-DNANOVDB_USE_CUDA=OFF
-DNANOVDB_USE_TBB=OFF
-DNANOVDB_USE_BLOSC=OFF
-DNANOVDB_USE_ZLIB=OFF
-DNANOVDB_USE_OPTIX=OFF
-DNANOVDB_ALLOW_FETCHCONTENT=OFF
)
ExternalProject_Add(nanovdb
URL ${NANOVDB_URI}
DOWNLOAD_DIR ${DOWNLOAD_DIR}
URL_HASH MD5=${NANOVDB_HASH}
PREFIX ${BUILD_DIR}/nanovdb
SOURCE_SUBDIR nanovdb
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/nanovdb ${DEFAULT_CMAKE_FLAGS} ${NANOVDB_EXTRA_ARGS}
INSTALL_DIR ${LIBDIR}/nanovdb
)
if(WIN32)
ExternalProject_Add_Step(nanovdb after_install
COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/nanovdb/nanovdb ${HARVEST_TARGET}/nanovdb/include/nanovdb
DEPENDEES install
)
endif()

View File

@@ -54,6 +54,20 @@ set(OPENVDB_EXTRA_ARGS
-DOPENVDB_CORE_STATIC=${OPENVDB_STATIC} -DOPENVDB_CORE_STATIC=${OPENVDB_STATIC}
-DOPENVDB_BUILD_BINARIES=Off -DOPENVDB_BUILD_BINARIES=Off
-DCMAKE_DEBUG_POSTFIX=_d -DCMAKE_DEBUG_POSTFIX=_d
# NanoVDB is header-only, so only need the install target
-DNANOVDB_BUILD_UNITTESTS=OFF
-DNANOVDB_BUILD_EXAMPLES=OFF
-DNANOVDB_BUILD_BENCHMARK=OFF
-DNANOVDB_BUILD_DOCS=OFF
-DNANOVDB_BUILD_TOOLS=OFF
-DNANOVDB_CUDA_KEEP_PTX=OFF
-DNANOVDB_USE_OPENGL=OFF
-DNANOVDB_USE_OPENGL=OFF
-DNANOVDB_USE_CUDA=OFF
-DNANOVDB_USE_TBB=OFF
-DNANOVDB_USE_OPTIX=OFF
-DNANOVDB_USE_OPENVDB=OFF
-DNANOVDB_ALLOW_FETCHCONTENT=OFF
) )
if(WIN32) if(WIN32)
@@ -74,12 +88,18 @@ else()
) )
endif() endif()
if(WITH_NANOVDB)
set(OPENVDB_PATCH_FILE openvdb_nanovdb.diff)
else()
set(OPENVDB_PATCH_FILE openvdb.diff)
endif()
ExternalProject_Add(openvdb ExternalProject_Add(openvdb
URL ${OPENVDB_URI} URL ${OPENVDB_URI}
DOWNLOAD_DIR ${DOWNLOAD_DIR} DOWNLOAD_DIR ${DOWNLOAD_DIR}
URL_HASH MD5=${OPENVDB_HASH} URL_HASH MD5=${OPENVDB_HASH}
PREFIX ${BUILD_DIR}/openvdb PREFIX ${BUILD_DIR}/openvdb
PATCH_COMMAND ${PATCH_CMD} -p 1 -d ${BUILD_DIR}/openvdb/src/openvdb < ${PATCH_DIR}/openvdb.diff PATCH_COMMAND ${PATCH_CMD} -p 1 -d ${BUILD_DIR}/openvdb/src/openvdb < ${PATCH_DIR}/${OPENVDB_PATCH_FILE}
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openvdb ${DEFAULT_CMAKE_FLAGS} ${OPENVDB_EXTRA_ARGS} CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openvdb ${DEFAULT_CMAKE_FLAGS} ${OPENVDB_EXTRA_ARGS}
INSTALL_DIR ${LIBDIR}/openvdb INSTALL_DIR ${LIBDIR}/openvdb
) )
@@ -101,6 +121,12 @@ if(WIN32)
COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openvdb/bin/openvdb.dll ${HARVEST_TARGET}/openvdb/bin/openvdb.dll COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openvdb/bin/openvdb.dll ${HARVEST_TARGET}/openvdb/bin/openvdb.dll
DEPENDEES install DEPENDEES install
) )
if(WITH_NANOVDB)
ExternalProject_Add_Step(openvdb nanovdb_install
COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openvdb/nanovdb ${HARVEST_TARGET}/nanovdb/include/nanovdb
DEPENDEES after_install
)
endif()
endif() endif()
if(BUILD_MODE STREQUAL Debug) if(BUILD_MODE STREQUAL Debug)
ExternalProject_Add_Step(openvdb after_install ExternalProject_Add_Step(openvdb after_install

View File

@@ -21,6 +21,7 @@ if(WIN32)
endif() endif()
option(WITH_WEBP "Enable building of oiio with webp support" OFF) option(WITH_WEBP "Enable building of oiio with webp support" OFF)
option(WITH_BOOST_PYTHON "Enable building of boost with python support" OFF) option(WITH_BOOST_PYTHON "Enable building of boost with python support" OFF)
option(WITH_NANOVDB "Enable building of OpenVDB with NanoVDB included" OFF)
set(MAKE_THREADS 1 CACHE STRING "Number of threads to run make with") set(MAKE_THREADS 1 CACHE STRING "Number of threads to run make with")
if(NOT BUILD_MODE) if(NOT BUILD_MODE)
@@ -56,7 +57,7 @@ if(WIN32)
if(MSVC_VERSION GREATER 1909) if(MSVC_VERSION GREATER 1909)
set(COMMON_MSVC_FLAGS "/Wv:18") #some deps with warnings as error aren't quite ready for dealing with the new 2017 warnings. set(COMMON_MSVC_FLAGS "/Wv:18") #some deps with warnings as error aren't quite ready for dealing with the new 2017 warnings.
endif() endif()
string(APPEND COMMON_MSVC_FLAGS " /bigobj") set(COMMON_MSVC_FLAGS "${COMMON_MSVC_FLAGS} /bigobj")
if(WITH_OPTIMIZED_DEBUG) if(WITH_OPTIMIZED_DEBUG)
set(BLENDER_CMAKE_C_FLAGS_DEBUG "/MDd ${COMMON_MSVC_FLAGS} /O2 /Ob2 /DNDEBUG /DPSAPI_VERSION=1 /DOIIO_STATIC_BUILD /DTINYFORMAT_ALLOW_WCHAR_STRINGS") set(BLENDER_CMAKE_C_FLAGS_DEBUG "/MDd ${COMMON_MSVC_FLAGS} /O2 /Ob2 /DNDEBUG /DPSAPI_VERSION=1 /DOIIO_STATIC_BUILD /DTINYFORMAT_ALLOW_WCHAR_STRINGS")
else() else()

View File

@@ -145,13 +145,15 @@ set(TBB_VERSION 2019_U9)
set(TBB_URI https://github.com/oneapi-src/oneTBB/archive/${TBB_VERSION}.tar.gz) set(TBB_URI https://github.com/oneapi-src/oneTBB/archive/${TBB_VERSION}.tar.gz)
set(TBB_HASH 26263622e9187212ec240dcf01b66207) set(TBB_HASH 26263622e9187212ec240dcf01b66207)
if(WITH_NANOVDB)
set(OPENVDB_GIT_UID e62f7a0bf1e27397223c61ddeaaf57edf111b77f)
set(OPENVDB_URI https://github.com/AcademySoftwareFoundation/openvdb/archive/${OPENVDB_GIT_UID}.tar.gz)
set(OPENVDB_HASH 90919510bc6ccd630fedc56f748cb199)
else()
set(OPENVDB_VERSION 7.0.0) set(OPENVDB_VERSION 7.0.0)
set(OPENVDB_URI https://github.com/AcademySoftwareFoundation/openvdb/archive/v${OPENVDB_VERSION}.tar.gz) set(OPENVDB_URI https://github.com/AcademySoftwareFoundation/openvdb/archive/v${OPENVDB_VERSION}.tar.gz)
set(OPENVDB_HASH fd6c4f168282f7e0e494d290cd531fa8) set(OPENVDB_HASH fd6c4f168282f7e0e494d290cd531fa8)
endif()
set(NANOVDB_GIT_UID e62f7a0bf1e27397223c61ddeaaf57edf111b77f)
set(NANOVDB_URI https://github.com/AcademySoftwareFoundation/openvdb/archive/${NANOVDB_GIT_UID}.tar.gz)
set(NANOVDB_HASH 90919510bc6ccd630fedc56f748cb199)
set(IDNA_VERSION 2.9) set(IDNA_VERSION 2.9)
set(CHARDET_VERSION 3.0.4) set(CHARDET_VERSION 3.0.4)

View File

@@ -51,7 +51,7 @@ ARGS=$( \
getopt \ getopt \
-o s:i:t:h \ -o s:i:t:h \
--long source:,install:,tmp:,info:,threads:,help,show-deps,no-sudo,no-build,no-confirm,\ --long source:,install:,tmp:,info:,threads:,help,show-deps,no-sudo,no-build,no-confirm,\
with-all,with-opencollada,with-jack,with-embree,with-oidn,with-nanovdb,\ with-all,with-opencollada,with-jack,with-embree,with-oidn,\
ver-ocio:,ver-oiio:,ver-llvm:,ver-osl:,ver-osd:,ver-openvdb:,ver-xr-openxr:,\ ver-ocio:,ver-oiio:,ver-llvm:,ver-osl:,ver-osd:,ver-openvdb:,ver-xr-openxr:,\
force-all,force-python,force-numpy,force-boost,force-tbb,\ force-all,force-python,force-numpy,force-boost,force-tbb,\
force-ocio,force-openexr,force-oiio,force-llvm,force-osl,force-osd,force-openvdb,\ force-ocio,force-openexr,force-oiio,force-llvm,force-osl,force-osd,force-openvdb,\
@@ -151,9 +151,6 @@ ARGUMENTS_INFO="\"COMMAND LINE ARGUMENTS:
--with-oidn --with-oidn
Build and install the OpenImageDenoise libraries. Build and install the OpenImageDenoise libraries.
--with-nanovdb
Build and install the NanoVDB branch of OpenVDB (instead of official release of OpenVDB).
--with-jack --with-jack
Install the jack libraries. Install the jack libraries.
@@ -438,7 +435,7 @@ _with_built_openexr=false
OIIO_VERSION="2.1.15.0" OIIO_VERSION="2.1.15.0"
OIIO_VERSION_SHORT="2.1" OIIO_VERSION_SHORT="2.1"
OIIO_VERSION_MIN="2.1.12" OIIO_VERSION_MIN="1.8"
OIIO_VERSION_MAX="3.0" OIIO_VERSION_MAX="3.0"
OIIO_FORCE_BUILD=false OIIO_FORCE_BUILD=false
OIIO_FORCE_REBUILD=false OIIO_FORCE_REBUILD=false
@@ -679,10 +676,6 @@ while true; do
--with-oidn) --with-oidn)
WITH_OIDN=true; shift; continue WITH_OIDN=true; shift; continue
;; ;;
--with-nanovdb)
WITH_NANOVDB=true;
shift; continue
;;
--with-jack) --with-jack)
WITH_JACK=true; shift; continue; WITH_JACK=true; shift; continue;
;; ;;
@@ -964,11 +957,6 @@ if [ "$WITH_ALL" = true -a "$OIDN_SKIP" = false ]; then
fi fi
if [ "$WITH_ALL" = true ]; then if [ "$WITH_ALL" = true ]; then
WITH_JACK=true WITH_JACK=true
WITH_NANOVDB=true
fi
if [ "$WITH_NANOVDB" = true ]; then
OPENVDB_FORCE_BUILD=true
fi fi
@@ -1041,15 +1029,11 @@ OSD_SOURCE=( "https://github.com/PixarAnimationStudios/OpenSubdiv/archive/v${OSD
OPENVDB_USE_REPO=false OPENVDB_USE_REPO=false
OPENVDB_BLOSC_SOURCE=( "https://github.com/Blosc/c-blosc/archive/v${OPENVDB_BLOSC_VERSION}.tar.gz" ) OPENVDB_BLOSC_SOURCE=( "https://github.com/Blosc/c-blosc/archive/v${OPENVDB_BLOSC_VERSION}.tar.gz" )
OPENVDB_SOURCE=( "https://github.com/AcademySoftwareFoundation/openvdb/archive/v${OPENVDB_VERSION}.tar.gz" ) OPENVDB_SOURCE=( "https://github.com/dreamworksanimation/openvdb/archive/v${OPENVDB_VERSION}.tar.gz" )
#~ OPENVDB_SOURCE_REPO=( "https://github.com/AcademySoftwareFoundation/openvdb.git" ) #~ OPENVDB_SOURCE_REPO=( "https:///dreamworksanimation/openvdb.git" )
#~ OPENVDB_SOURCE_REPO_UID="404659fffa659da075d1c9416e4fc939139a84ee" #~ OPENVDB_SOURCE_REPO_UID="404659fffa659da075d1c9416e4fc939139a84ee"
#~ OPENVDB_SOURCE_REPO_BRANCH="dev" #~ OPENVDB_SOURCE_REPO_BRANCH="dev"
NANOVDB_USE_REPO=false
NANOVDB_SOURCE_REPO_UID="e62f7a0bf1e27397223c61ddeaaf57edf111b77f"
NANOVDB_SOURCE=( "https://github.com/AcademySoftwareFoundation/openvdb/archive/${NANOVDB_SOURCE_REPO_UID}.tar.gz" )
ALEMBIC_USE_REPO=false ALEMBIC_USE_REPO=false
ALEMBIC_SOURCE=( "https://github.com/alembic/alembic/archive/${ALEMBIC_VERSION}.tar.gz" ) ALEMBIC_SOURCE=( "https://github.com/alembic/alembic/archive/${ALEMBIC_VERSION}.tar.gz" )
# ALEMBIC_SOURCE_REPO=( "https://github.com/alembic/alembic.git" ) # ALEMBIC_SOURCE_REPO=( "https://github.com/alembic/alembic.git" )
@@ -2610,115 +2594,11 @@ compile_BLOSC() {
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# Build OpenVDB # Build OpenVDB
_init_nanovdb() {
_src=$SRC/openvdb-$OPENVDB_VERSION/nanovdb
_inst=$INST/nanovdb-$OPENVDB_VERSION_SHORT
_inst_shortcut=$INST/nanovdb
}
_update_deps_nanovdb() {
:
}
clean_nanovdb() {
_init_nanovdb
if [ -d $_inst ]; then
_update_deps_nanovdb
fi
_git=true # Mere trick to prevent clean from removing $_src...
_clean
}
install_NanoVDB() {
# To be changed each time we make edits that would modify the compiled results!
nanovdb_magic=1
_init_nanovdb
# Clean install if needed!
magic_compile_check nanovdb-$OPENVDB_VERSION $nanovdb_magic
if [ $? -eq 1 ]; then
clean_nanovdb
fi
if [ ! -d $_inst ]; then
INFO "Installing NanoVDB v$OPENVDB_VERSION"
_is_building=true
# Rebuild dependencies as well!
_update_deps_nanovdb
prepare_inst
if [ ! -d $_src ]; then
ERROR "NanoVDB not found in openvdb-$OPENVDB_VERSION ($_src), exiting"
exit 1
fi
# Always refresh the whole build!
if [ -d build ]; then
rm -rf build
fi
mkdir build
cd build
cmake_d="-D CMAKE_BUILD_TYPE=Release"
cmake_d="$cmake_d -D CMAKE_INSTALL_PREFIX=$_inst"
# NanoVDB is header-only, so only need the install target
cmake_d="$cmake_d -D NANOVDB_BUILD_UNITTESTS=OFF"
cmake_d="$cmake_d -D NANOVDB_BUILD_EXAMPLES=OFF"
cmake_d="$cmake_d -D NANOVDB_BUILD_BENCHMARK=OFF"
cmake_d="$cmake_d -D NANOVDB_BUILD_DOCS=OFF"
cmake_d="$cmake_d -D NANOVDB_BUILD_TOOLS=OFF"
cmake_d="$cmake_d -D NANOVDB_CUDA_KEEP_PTX=OFF"
# Do not need to include any of the dependencies because of this
cmake_d="$cmake_d -D NANOVDB_USE_OPENVDB=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_OPENGL=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_OPENCL=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_CUDA=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_TBB=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_BLOSC=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_ZLIB=OFF"
cmake_d="$cmake_d -D NANOVDB_USE_OPTIX=OFF"
cmake_d="$cmake_d -D NANOVDB_ALLOW_FETCHCONTENT=OFF"
cmake $cmake_d $_src
make -j$THREADS install
make clean
#~ mkdir -p $_inst
#~ cp -r $_src/include $_inst/include
if [ -d $_inst ]; then
_create_inst_shortcut
else
ERROR "NanoVDB-v$OPENVDB_VERSION failed to install, exiting"
exit 1
fi
magic_compile_set nanovdb-$OPENVDB_VERSION $nanovdb_magic
cd $CWD
INFO "Done compiling NanoVDB-v$OPENVDB_VERSION!"
_is_building=false
else
INFO "Own NanoVDB-v$OPENVDB_VERSION is up to date, nothing to do!"
fi
}
_init_openvdb() { _init_openvdb() {
_src=$SRC/openvdb-$OPENVDB_VERSION _src=$SRC/openvdb-$OPENVDB_VERSION
_git=false _git=false
_inst=$INST/openvdb-$OPENVDB_VERSION_SHORT _inst=$INST/openvdb-$OPENVDB_VERSION_SHORT
_inst_shortcut=$INST/openvdb _inst_shortcut=$INST/openvdb
_openvdb_source=$OPENVDB_SOURCE
if [ "$WITH_NANOVDB" = true ]; then
_openvdb_source=$NANOVDB_SOURCE
fi
} }
_update_deps_openvdb() { _update_deps_openvdb() {
@@ -2743,7 +2623,7 @@ compile_OPENVDB() {
PRINT "" PRINT ""
# To be changed each time we make edits that would modify the compiled result! # To be changed each time we make edits that would modify the compiled result!
openvdb_magic=2 openvdb_magic=1
_init_openvdb _init_openvdb
# Clean install if needed! # Clean install if needed!
@@ -2753,7 +2633,7 @@ compile_OPENVDB() {
fi fi
if [ ! -d $_inst ]; then if [ ! -d $_inst ]; then
INFO "Building OpenVDB-$OPENVDB_VERSION (with NanoVDB: $WITH_NANOVDB)" INFO "Building OpenVDB-$OPENVDB_VERSION"
_is_building=true _is_building=true
# Rebuild dependencies as well! # Rebuild dependencies as well!
@@ -2761,18 +2641,13 @@ compile_OPENVDB() {
prepare_inst prepare_inst
if [ ! -d $_src ]; then if [ ! -d $_src -o true ]; then
mkdir -p $SRC mkdir -p $SRC
download _openvdb_source[@] "$_src.tar.gz" download OPENVDB_SOURCE[@] "$_src.tar.gz"
INFO "Unpacking OpenVDB-$OPENVDB_VERSION" INFO "Unpacking OpenVDB-$OPENVDB_VERSION"
if [ "$WITH_NANOVDB" = true ]; then
tar -C $SRC --transform "s,(.*/?)openvdb-$NANOVDB_SOURCE_REPO_UID[^/]*(.*),\1openvdb-$OPENVDB_VERSION\2,x" \
-xf $_src.tar.gz
else
tar -C $SRC -xf $_src.tar.gz tar -C $SRC -xf $_src.tar.gz
fi fi
fi
cd $_src cd $_src
@@ -2785,40 +2660,33 @@ compile_OPENVDB() {
#~ git reset --hard #~ git reset --hard
#~ fi #~ fi
# Always refresh the whole build! # Source builds here
if [ -d build ]; then cd openvdb
rm -rf build
fi
mkdir build
cd build
cmake_d="-D CMAKE_BUILD_TYPE=Release" make_d="DESTDIR=$_inst"
cmake_d="$cmake_d -D CMAKE_INSTALL_PREFIX=$_inst" make_d="$make_d HDSO=/usr"
cmake_d="$cmake_d -D USE_STATIC_DEPENDENCIES=OFF"
cmake_d="$cmake_d -D OPENVDB_BUILD_BINARIES=OFF"
if [ -d $INST/boost ]; then if [ -d $INST/boost ]; then
cmake_d="$cmake_d -D BOOST_ROOT=$INST/boost" make_d="$make_d BOOST_INCL_DIR=$INST/boost/include BOOST_LIB_DIR=$INST/boost/lib"
cmake_d="$cmake_d -D Boost_USE_MULTITHREADED=ON"
cmake_d="$cmake_d -D Boost_NO_SYSTEM_PATHS=ON"
cmake_d="$cmake_d -D Boost_NO_BOOST_CMAKE=ON"
fi fi
if [ -d $INST/tbb ]; then if [ -d $INST/tbb ]; then
cmake_d="$cmake_d -D TBB_ROOT=$INST/tbb" make_d="$make_d TBB_ROOT=$INST/tbb TBB_USE_STATIC_LIBS=OFF"
fi fi
if [ "$_with_built_openexr" = true ]; then if [ "$_with_built_openexr" = true ]; then
cmake_d="$cmake_d -D IlmBase_ROOT=$INST/openexr" make_d="$make_d ILMBASE_INCL_DIR=$INST/openexr/include ILMBASE_LIB_DIR=$INST/openexr/lib"
cmake_d="$cmake_d -D OpenEXR_ROOT=$INST/openexr" make_d="$make_d EXR_INCL_DIR=$INST/openexr/include EXR_LIB_DIR=$INST/openexr/lib"
INFO "ILMBASE_HOME=$INST/openexr"
fi fi
if [ -d $INST/blosc ]; then if [ -d $INST/blosc ]; then
cmake_d="$cmake_d -D Blosc_ROOT=$INST/blosc" make_d="$make_d BLOSC_INCL_DIR=$INST/blosc/include BLOSC_LIB_DIR=$INST/blosc/lib"
fi fi
cmake $cmake_d .. # Build without log4cplus, glfw, python module & docs
make_d="$make_d LOG4CPLUS_INCL_DIR= GLFW_INCL_DIR= PYTHON_VERSION= DOXYGEN="
make -j$THREADS install make -j$THREADS lib $make_d install
make clean make clean
if [ -d $_inst ]; then if [ -d $_inst ]; then
@@ -2839,10 +2707,6 @@ compile_OPENVDB() {
fi fi
run_ldconfig "openvdb" run_ldconfig "openvdb"
if [ "$WITH_NANOVDB" = true ]; then
install_NanoVDB
fi
} }
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
@@ -5827,13 +5691,6 @@ print_info() {
PRINT " $_1" PRINT " $_1"
_buildargs="$_buildargs $_1" _buildargs="$_buildargs $_1"
fi fi
if [ -d $INST/nanovdb ]; then
_1="-D WITH_NANOVDB=ON"
_2="-D NANOVDB_ROOT_DIR=$INST/nanovdb"
PRINT " $_1"
PRINT " $_2"
_buildargs="$_buildargs $_1 $_2"
fi
fi fi
if [ "$WITH_OPENCOLLADA" = true ]; then if [ "$WITH_OPENCOLLADA" = true ]; then

View File

@@ -0,0 +1,135 @@
diff -Naur orig/cmake/FindIlmBase.cmake openvdb/cmake/FindIlmBase.cmake
--- orig/cmake/FindIlmBase.cmake 2019-12-06 12:11:33 -0700
+++ openvdb/cmake/FindIlmBase.cmake 2020-08-12 12:48:44 -0600
@@ -217,6 +217,8 @@
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib")
endif()
list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES "${_IlmBase_Version_Suffix}.lib")
+ list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES "_s.lib")
+ list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES "_s_d.lib")
else()
if(ILMBASE_USE_STATIC_LIBS)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
diff -Naur orig/cmake/FindOpenEXR.cmake openvdb/cmake/FindOpenEXR.cmake
--- orig/cmake/FindOpenEXR.cmake 2019-12-06 12:11:33 -0700
+++ openvdb/cmake/FindOpenEXR.cmake 2020-08-12 12:48:44 -0600
@@ -210,6 +210,8 @@
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib")
endif()
list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES "${_OpenEXR_Version_Suffix}.lib")
+ list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES "_s.lib")
+ list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES "_s_d.lib")
else()
if(OPENEXR_USE_STATIC_LIBS)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
diff -Naur orig/openvdb/openvdb/CMakeLists.txt openvdb/openvdb/openvdb/CMakeLists.txt
--- orig/openvdb/openvdb/CMakeLists.txt 2019-12-06 12:11:33 -0700
+++ openvdb/openvdb/openvdb/CMakeLists.txt 2020-08-12 14:12:26 -0600
@@ -105,7 +105,9 @@
# http://boost.2283326.n4.nabble.com/CMake-config-scripts-broken-in-1-70-td4708957.html
# https://github.com/boostorg/boost_install/commit/160c7cb2b2c720e74463865ef0454d4c4cd9ae7c
set(BUILD_SHARED_LIBS ON)
- set(Boost_USE_STATIC_LIBS OFF)
+ if(NOT WIN32) # blender links boost statically on windows
+ set(Boost_USE_STATIC_LIBS OFF)
+ endif()
endif()
find_package(Boost ${MINIMUM_BOOST_VERSION} REQUIRED COMPONENTS iostreams system)
@@ -193,6 +195,7 @@
if(OPENVDB_DISABLE_BOOST_IMPLICIT_LINKING)
add_definitions(-DBOOST_ALL_NO_LIB)
endif()
+ add_definitions(-D__TBB_NO_IMPLICIT_LINKAGE -DOPENVDB_OPENEXR_STATICLIB)
endif()
# @todo Should be target definitions
@@ -383,7 +386,12 @@
# imported targets.
if(OPENVDB_CORE_SHARED)
- add_library(openvdb_shared SHARED ${OPENVDB_LIBRARY_SOURCE_FILES})
+ if(WIN32)
+ configure_file(version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY)
+ add_library(openvdb_shared SHARED ${OPENVDB_LIBRARY_SOURCE_FILES} ${CMAKE_CURRENT_BINARY_DIR}/version.rc)
+ else()
+ add_library(openvdb_shared SHARED ${OPENVDB_LIBRARY_SOURCE_FILES})
+ endif()
endif()
if(OPENVDB_CORE_STATIC)
diff -Naur orig/openvdb/openvdb/version.rc.in openvdb/openvdb/openvdb/version.rc.in
--- orig/openvdb/openvdb/version.rc.in 1969-12-31 17:00:00 -0700
+++ openvdb/openvdb/openvdb/version.rc.in 2020-08-12 14:15:01 -0600
@@ -0,0 +1,48 @@
+#include <winver.h>
+
+#define VER_FILEVERSION @OpenVDB_MAJOR_VERSION@,@OpenVDB_MINOR_VERSION@,@OpenVDB_PATCH_VERSION@,0
+#define VER_FILEVERSION_STR "@OpenVDB_MAJOR_VERSION@.@OpenVDB_MINOR_VERSION@.@OpenVDB_PATCH_VERSION@.0\0"
+
+#define VER_PRODUCTVERSION @OpenVDB_MAJOR_VERSION@,@OpenVDB_MINOR_VERSION@,@OpenVDB_PATCH_VERSION@,0
+#define VER_PRODUCTVERSION_STR "@OpenVDB_MAJOR_VERSION@.@OpenVDB_MINOR_VERSION@\0"
+
+#ifndef DEBUG
+#define VER_DEBUG 0
+#else
+#define VER_DEBUG VS_FF_DEBUG
+#endif
+
+VS_VERSION_INFO VERSIONINFO
+FILEVERSION VER_FILEVERSION
+PRODUCTVERSION VER_PRODUCTVERSION
+FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
+FILEFLAGS (VER_DEBUG)
+FILEOS VOS__WINDOWS32
+FILETYPE VFT_DLL
+FILESUBTYPE VFT2_UNKNOWN
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904E4"
+ BEGIN
+ VALUE "FileDescription", "OpenVDB"
+ VALUE "FileVersion", VER_FILEVERSION_STR
+ VALUE "InternalName", "OpenVDB"
+ VALUE "ProductName", "OpenVDB"
+ VALUE "ProductVersion", VER_PRODUCTVERSION_STR
+ END
+ END
+
+ BLOCK "VarFileInfo"
+ BEGIN
+ /* The following line should only be modified for localized versions. */
+ /* It consists of any number of WORD,WORD pairs, with each pair */
+ /* describing a language,codepage combination supported by the file. */
+ /* */
+ /* For example, a file might have values "0x409,1252" indicating that it */
+ /* supports English language (0x409) in the Windows ANSI codepage (1252). */
+
+ VALUE "Translation", 0x409, 1252
+
+ END
+END
diff -Naur openvdb-original/CMakeLists.txt openvdb/CMakeLists.txt
--- openvdb-original/CMakeLists.txt 2020-08-27 03:34:02.000000000 +0200
+++ openvdb/CMakeLists.txt 2020-09-02 10:56:21.665735244 +0200
@@ -68,6 +68,7 @@
option(OPENVDB_INSTALL_HOUDINI_PYTHONRC [=[Install a Houdini startup script that sets
the visibilty of OpenVDB nodes and their native equivalents.]=] OFF)
option(OPENVDB_BUILD_MAYA_PLUGIN "Build the Maya plugin" OFF)
+option(OPENVDB_BUILD_NANOVDB "Build nanovdb" ON)
option(OPENVDB_ENABLE_RPATH "Build with RPATH information" ON)
option(OPENVDB_CXX_STRICT "Enable or disable pre-defined compiler warnings" OFF)
option(OPENVDB_CODE_COVERAGE "Enable code coverage. This also overrides CMAKE_BUILD_TYPE to Debug" OFF)
@@ -740,6 +741,10 @@
add_subdirectory(openvdb_maya)
endif()
+if(OPENVDB_BUILD_NANOVDB)
+ add_subdirectory(nanovdb)
+endif()
+
##########################################################################
add_custom_target(uninstall

View File

@@ -18,72 +18,12 @@
# <pep8 compliant> # <pep8 compliant>
import dataclasses
import json
import os import os
from pathlib import Path from pathlib import Path
from typing import Optional
import codesign.util as util import codesign.util as util
class ArchiveStateError(Exception):
message: str
def __init__(self, message):
self.message = message
super().__init__(self.message)
@dataclasses.dataclass
class ArchiveState:
"""
Additional information (state) of the archive
Includes information like expected file size of the archive file in the case
the archive file is expected to be successfully created.
If the archive can not be created, this state will contain error message
indicating details of error.
"""
# Size in bytes of the corresponding archive.
file_size: Optional[int] = None
# Non-empty value indicates that error has happenned.
error_message: str = ''
def has_error(self) -> bool:
"""
Check whether the archive is at error state
"""
return self.error_message
def serialize_to_string(self) -> str:
payload = dataclasses.asdict(self)
return json.dumps(payload, sort_keys=True, indent=4)
def serialize_to_file(self, filepath: Path) -> None:
string = self.serialize_to_string()
filepath.write_text(string)
@classmethod
def deserialize_from_string(cls, string: str) -> 'ArchiveState':
try:
object_as_dict = json.loads(string)
except json.decoder.JSONDecodeError:
raise ArchiveStateError('Error parsing JSON')
return cls(**object_as_dict)
@classmethod
def deserialize_from_file(cls, filepath: Path):
string = filepath.read_text()
return cls.deserialize_from_string(string)
class ArchiveWithIndicator: class ArchiveWithIndicator:
""" """
The idea of this class is to wrap around logic which takes care of keeping The idea of this class is to wrap around logic which takes care of keeping
@@ -139,19 +79,6 @@ class ArchiveWithIndicator:
if not self.ready_indicator_filepath.exists(): if not self.ready_indicator_filepath.exists():
return False return False
try:
archive_state = ArchiveState.deserialize_from_file(
self.ready_indicator_filepath)
except ArchiveStateError as error:
print(f'Error deserializing archive state: {error.message}')
return False
if archive_state.has_error():
# If the error did happen during codesign procedure there will be no
# corresponding archive file.
# The caller code will deal with the error check further.
return True
# Sometimes on macOS indicator file appears prior to the actual archive # Sometimes on macOS indicator file appears prior to the actual archive
# despite the order of creation and os.sync() used in tag_ready(). # despite the order of creation and os.sync() used in tag_ready().
# So consider archive not ready if there is an indicator without an # So consider archive not ready if there is an indicator without an
@@ -161,11 +88,23 @@ class ArchiveWithIndicator:
f'({self.archive_filepath}) to appear.') f'({self.archive_filepath}) to appear.')
return False return False
# Read archive size from indicator/
#
# Assume that file is either empty or is fully written. This is being checked
# by performing ValueError check since empty string will throw this exception
# when attempted to be converted to int.
expected_archive_size_str = self.ready_indicator_filepath.read_text()
try:
expected_archive_size = int(expected_archive_size_str)
except ValueError:
print(f'Invalid archive size "{expected_archive_size_str}"')
return False
# Wait for until archive is fully stored. # Wait for until archive is fully stored.
actual_archive_size = self.archive_filepath.stat().st_size actual_archive_size = self.archive_filepath.stat().st_size
if actual_archive_size != archive_state.file_size: if actual_archive_size != expected_archive_size:
print('Partial/invalid archive size (expected ' print('Partial/invalid archive size (expected '
f'{archive_state.file_size} got {actual_archive_size})') f'{expected_archive_size} got {actual_archive_size})')
return False return False
return True return True
@@ -190,7 +129,7 @@ class ArchiveWithIndicator:
print(f'Exception checking archive: {e}') print(f'Exception checking archive: {e}')
return False return False
def tag_ready(self, error_message='') -> None: def tag_ready(self) -> None:
""" """
Tag the archive as ready by creating the corresponding indication file. Tag the archive as ready by creating the corresponding indication file.
@@ -199,34 +138,13 @@ class ArchiveWithIndicator:
If it is violated, an assert will fail. If it is violated, an assert will fail.
""" """
assert not self.is_ready() assert not self.is_ready()
# Try the best to make sure everything is synced to the file system, # Try the best to make sure everything is synced to the file system,
# to avoid any possibility of stamp appearing on a network share prior to # to avoid any possibility of stamp appearing on a network share prior to
# an actual file. # an actual file.
if util.get_current_platform() != util.Platform.WINDOWS: if util.get_current_platform() != util.Platform.WINDOWS:
os.sync() os.sync()
archive_size = -1
if self.archive_filepath.exists():
archive_size = self.archive_filepath.stat().st_size archive_size = self.archive_filepath.stat().st_size
self.ready_indicator_filepath.write_text(str(archive_size))
archive_info = ArchiveState(
file_size=archive_size, error_message=error_message)
self.ready_indicator_filepath.write_text(
archive_info.serialize_to_string())
def get_state(self) -> ArchiveState:
"""
Get state object for this archive
The state is read from the corresponding state file.
"""
try:
return ArchiveState.deserialize_from_file(self.ready_indicator_filepath)
except ArchiveStateError as error:
return ArchiveState(error_message=f'Error in information format: {error}')
def clean(self) -> None: def clean(self) -> None:
""" """

View File

@@ -58,7 +58,6 @@ import codesign.util as util
from codesign.absolute_and_relative_filename import AbsoluteAndRelativeFileName from codesign.absolute_and_relative_filename import AbsoluteAndRelativeFileName
from codesign.archive_with_indicator import ArchiveWithIndicator from codesign.archive_with_indicator import ArchiveWithIndicator
from codesign.exception import CodeSignException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -221,15 +220,9 @@ class BaseCodeSigner(metaclass=abc.ABCMeta):
""" """
Wait until archive with signed files is available. Wait until archive with signed files is available.
Will only return if the archive with signed files is available. If there
was an error during code sign procedure the SystemExit exception is
raised, with the message set to the error reported by the codesign
server.
Will only wait for the configured time. If that time exceeds and there Will only wait for the configured time. If that time exceeds and there
is still no responce from the signing server the application will exit is still no responce from the signing server the application will exit
with a non-zero exit code. with a non-zero exit code.
""" """
signed_archive_info = self.signed_archive_info_for_request_id( signed_archive_info = self.signed_archive_info_for_request_id(
@@ -243,17 +236,9 @@ class BaseCodeSigner(metaclass=abc.ABCMeta):
time.sleep(1) time.sleep(1)
time_slept_in_seconds = time.monotonic() - time_start time_slept_in_seconds = time.monotonic() - time_start
if time_slept_in_seconds > timeout_in_seconds: if time_slept_in_seconds > timeout_in_seconds:
signed_archive_info.clean()
unsigned_archive_info.clean() unsigned_archive_info.clean()
raise SystemExit("Signing server didn't finish signing in " raise SystemExit("Signing server didn't finish signing in "
f'{timeout_in_seconds} seconds, dying :(') f"{timeout_in_seconds} seconds, dying :(")
archive_state = signed_archive_info.get_state()
if archive_state.has_error():
signed_archive_info.clean()
unsigned_archive_info.clean()
raise SystemExit(
f'Error happenned during codesign procedure: {archive_state.error_message}')
def copy_signed_files_to_directory( def copy_signed_files_to_directory(
self, signed_dir: Path, destination_dir: Path) -> None: self, signed_dir: Path, destination_dir: Path) -> None:
@@ -411,13 +396,7 @@ class BaseCodeSigner(metaclass=abc.ABCMeta):
temp_dir) temp_dir)
logger_server.info('Signing all requested files...') logger_server.info('Signing all requested files...')
try:
self.sign_all_files(files) self.sign_all_files(files)
except CodeSignException as error:
signed_archive_info.tag_ready(error_message=error.message)
unsigned_archive_info.clean()
logger_server.info('Signing is complete with errors.')
return
logger_server.info('Packing signed files...') logger_server.info('Packing signed files...')
pack_files(files=files, pack_files(files=files,

View File

@@ -1,26 +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.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
class CodeSignException(Exception):
message: str
def __init__(self, message):
self.message = message
super().__init__(self.message)

View File

@@ -33,7 +33,6 @@ from buildbot_utils import Builder
from codesign.absolute_and_relative_filename import AbsoluteAndRelativeFileName from codesign.absolute_and_relative_filename import AbsoluteAndRelativeFileName
from codesign.base_code_signer import BaseCodeSigner from codesign.base_code_signer import BaseCodeSigner
from codesign.exception import CodeSignException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger_server = logger.getChild('server') logger_server = logger.getChild('server')
@@ -46,10 +45,6 @@ EXTENSIONS_TO_BE_SIGNED = {'.dylib', '.so', '.dmg'}
NAME_PREFIXES_TO_BE_SIGNED = {'python'} NAME_PREFIXES_TO_BE_SIGNED = {'python'}
class NotarizationException(CodeSignException):
pass
def is_file_from_bundle(file: AbsoluteAndRelativeFileName) -> bool: def is_file_from_bundle(file: AbsoluteAndRelativeFileName) -> bool:
""" """
Check whether file is coming from an .app bundle Check whether file is coming from an .app bundle
@@ -191,7 +186,7 @@ class MacOSCodeSigner(BaseCodeSigner):
file.absolute_filepath] file.absolute_filepath]
self.run_command_or_mock(command, util.Platform.MACOS) self.run_command_or_mock(command, util.Platform.MACOS)
def codesign_all_files(self, files: List[AbsoluteAndRelativeFileName]) -> None: def codesign_all_files(self, files: List[AbsoluteAndRelativeFileName]) -> bool:
""" """
Run codesign tool on all eligible files in the given list. Run codesign tool on all eligible files in the given list.
@@ -230,6 +225,8 @@ class MacOSCodeSigner(BaseCodeSigner):
file_index + 1, num_signed_files, file_index + 1, num_signed_files,
signed_file.relative_filepath) signed_file.relative_filepath)
return True
def codesign_bundles( def codesign_bundles(
self, files: List[AbsoluteAndRelativeFileName]) -> None: self, files: List[AbsoluteAndRelativeFileName]) -> None:
""" """
@@ -276,6 +273,8 @@ class MacOSCodeSigner(BaseCodeSigner):
files.extend(extra_files) files.extend(extra_files)
return True
############################################################################ ############################################################################
# Notarization. # Notarization.
@@ -335,40 +334,7 @@ class MacOSCodeSigner(BaseCodeSigner):
logger_server.error('xcrun command did not report RequestUUID') logger_server.error('xcrun command did not report RequestUUID')
return None return None
def notarize_review_status(self, xcrun_output: str) -> bool: def notarize_wait_result(self, request_uuid: str) -> bool:
"""
Review status returned by xcrun's notarization info
Returns truth if the notarization process has finished.
If there are errors during notarization, a NotarizationException()
exception is thrown with status message from the notarial office.
"""
# Parse status and message
status = xcrun_field_value_from_output('Status', xcrun_output)
status_message = xcrun_field_value_from_output(
'Status Message', xcrun_output)
if status == 'success':
logger_server.info(
'Package successfully notarized: %s', status_message)
return True
if status == 'invalid':
logger_server.error(xcrun_output)
logger_server.error(
'Package notarization has failed: %s', status_message)
raise NotarizationException(status_message)
if status == 'in progress':
return False
logger_server.info(
'Unknown notarization status %s (%s)', status, status_message)
return False
def notarize_wait_result(self, request_uuid: str) -> None:
""" """
Wait for until notarial office have a reply Wait for until notarial office have a reply
""" """
@@ -385,11 +351,29 @@ class MacOSCodeSigner(BaseCodeSigner):
timeout_in_seconds = self.config.MACOS_NOTARIZE_TIMEOUT_IN_SECONDS timeout_in_seconds = self.config.MACOS_NOTARIZE_TIMEOUT_IN_SECONDS
while True: while True:
xcrun_output = self.check_output_or_mock( output = self.check_output_or_mock(
command, util.Platform.MACOS, allow_nonzero_exit_code=True) command, util.Platform.MACOS, allow_nonzero_exit_code=True)
# Parse status and message
status = xcrun_field_value_from_output('Status', output)
status_message = xcrun_field_value_from_output(
'Status Message', output)
if self.notarize_review_status(xcrun_output): # Review status.
break if status:
if status == 'success':
logger_server.info(
'Package successfully notarized: %s', status_message)
return True
elif status == 'invalid':
logger_server.error(output)
logger_server.error(
'Package notarization has failed: %s', status_message)
return False
elif status == 'in progress':
pass
else:
logger_server.info(
'Unknown notarization status %s (%s)', status, status_message)
logger_server.info('Keep waiting for notarization office.') logger_server.info('Keep waiting for notarization office.')
time.sleep(30) time.sleep(30)
@@ -410,6 +394,8 @@ class MacOSCodeSigner(BaseCodeSigner):
command = ['xcrun', 'stapler', 'staple', '-v', file.absolute_filepath] command = ['xcrun', 'stapler', 'staple', '-v', file.absolute_filepath]
self.check_output_or_mock(command, util.Platform.MACOS) self.check_output_or_mock(command, util.Platform.MACOS)
return True
def notarize_dmg(self, file: AbsoluteAndRelativeFileName) -> bool: def notarize_dmg(self, file: AbsoluteAndRelativeFileName) -> bool:
""" """
Run entire pipeline to get DMG notarized. Run entire pipeline to get DMG notarized.
@@ -428,7 +414,10 @@ class MacOSCodeSigner(BaseCodeSigner):
return False return False
# Staple. # Staple.
self.notarize_staple(file) if not self.notarize_staple(file):
return False
return True
def notarize_all_dmg( def notarize_all_dmg(
self, files: List[AbsoluteAndRelativeFileName]) -> bool: self, files: List[AbsoluteAndRelativeFileName]) -> bool:
@@ -443,7 +432,10 @@ class MacOSCodeSigner(BaseCodeSigner):
if not self.check_file_is_to_be_signed(file): if not self.check_file_is_to_be_signed(file):
continue continue
self.notarize_dmg(file) if not self.notarize_dmg(file):
return False
return True
############################################################################ ############################################################################
# Entry point. # Entry point.
@@ -451,6 +443,11 @@ class MacOSCodeSigner(BaseCodeSigner):
def sign_all_files(self, files: List[AbsoluteAndRelativeFileName]) -> None: def sign_all_files(self, files: List[AbsoluteAndRelativeFileName]) -> None:
# TODO(sergey): Handle errors somehow. # TODO(sergey): Handle errors somehow.
self.codesign_all_files(files) if not self.codesign_all_files(files):
self.codesign_bundles(files) return
self.notarize_all_dmg(files)
if not self.codesign_bundles(files):
return
if not self.notarize_all_dmg(files):
return

View File

@@ -29,7 +29,6 @@ from buildbot_utils import Builder
from codesign.absolute_and_relative_filename import AbsoluteAndRelativeFileName from codesign.absolute_and_relative_filename import AbsoluteAndRelativeFileName
from codesign.base_code_signer import BaseCodeSigner from codesign.base_code_signer import BaseCodeSigner
from codesign.exception import CodeSignException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger_server = logger.getChild('server') logger_server = logger.getChild('server')
@@ -41,9 +40,6 @@ BLACKLIST_FILE_PREFIXES = (
'api-ms-', 'concrt', 'msvcp', 'ucrtbase', 'vcomp', 'vcruntime') 'api-ms-', 'concrt', 'msvcp', 'ucrtbase', 'vcomp', 'vcruntime')
class SigntoolException(CodeSignException):
pass
class WindowsCodeSigner(BaseCodeSigner): class WindowsCodeSigner(BaseCodeSigner):
def check_file_is_to_be_signed( def check_file_is_to_be_signed(
self, file: AbsoluteAndRelativeFileName) -> bool: self, file: AbsoluteAndRelativeFileName) -> bool:
@@ -54,41 +50,12 @@ class WindowsCodeSigner(BaseCodeSigner):
return file.relative_filepath.suffix in EXTENSIONS_TO_BE_SIGNED return file.relative_filepath.suffix in EXTENSIONS_TO_BE_SIGNED
def get_sign_command_prefix(self) -> List[str]: def get_sign_command_prefix(self) -> List[str]:
return [ return [
'signtool', 'sign', '/v', 'signtool', 'sign', '/v',
'/f', self.config.WIN_CERTIFICATE_FILEPATH, '/f', self.config.WIN_CERTIFICATE_FILEPATH,
'/tr', self.config.WIN_TIMESTAMP_AUTHORITY_URL] '/tr', self.config.WIN_TIMESTAMP_AUTHORITY_URL]
def run_codesign_tool(self, filepath: Path) -> None:
command = self.get_sign_command_prefix() + [filepath]
codesign_output = self.check_output_or_mock(command, util.Platform.WINDOWS)
logger_server.info(f'signtool output:\n{codesign_output}')
got_number_of_success = False
for line in codesign_output.split('\n'):
line_clean = line.strip()
line_clean_lower = line_clean.lower()
if line_clean_lower.startswith('number of warnings') or \
line_clean_lower.startswith('number of errors'):
number = int(line_clean_lower.split(':')[1])
if number != 0:
raise SigntoolException('Non-clean success of signtool')
if line_clean_lower.startswith('number of files successfully signed'):
got_number_of_success = True
number = int(line_clean_lower.split(':')[1])
if number != 1:
raise SigntoolException('Signtool did not consider codesign a success')
if not got_number_of_success:
raise SigntoolException('Signtool did not report number of files signed')
def sign_all_files(self, files: List[AbsoluteAndRelativeFileName]) -> None: def sign_all_files(self, files: List[AbsoluteAndRelativeFileName]) -> None:
# NOTE: Sign files one by one to avoid possible command line length # NOTE: Sign files one by one to avoid possible command line length
# overflow (which could happen if we ever decide to sign every binary # overflow (which could happen if we ever decide to sign every binary
@@ -106,7 +73,12 @@ class WindowsCodeSigner(BaseCodeSigner):
file_index + 1, num_files, file.relative_filepath) file_index + 1, num_files, file.relative_filepath)
continue continue
command = self.get_sign_command_prefix()
command.append(file.absolute_filepath)
logger_server.info( logger_server.info(
'Running signtool command for file [%d/%d] %s...', 'Running signtool command for file [%d/%d] %s...',
file_index + 1, num_files, file.relative_filepath) file_index + 1, num_files, file.relative_filepath)
self.run_codesign_tool(file.absolute_filepath) # TODO(sergey): Check the status somehow. With a missing certificate
# the command still exists with a zero code.
self.run_command_or_mock(command, util.Platform.WINDOWS)
# TODO(sergey): Report number of signed and ignored files.

View File

@@ -43,10 +43,7 @@ find_program(CLANG_TIDY_EXECUTABLE
${_clang_tidy_SEARCH_DIRS} ${_clang_tidy_SEARCH_DIRS}
) )
if(CLANG_TIDY_EXECUTABLE AND NOT EXISTS ${CLANG_TIDY_EXECUTABLE}) if(CLANG_TIDY_EXECUTABLE)
message(WARNING "Cached or directly specified Clang-Tidy executable does not exist.")
set(CLANG_TIDY_FOUND FALSE)
elseif(CLANG_TIDY_EXECUTABLE)
# Mark clang-tidy as found. # Mark clang-tidy as found.
set(CLANG_TIDY_FOUND TRUE) set(CLANG_TIDY_FOUND TRUE)

View File

@@ -97,7 +97,6 @@ macro(BLENDER_SRC_GTEST_EX)
set_tests_properties(${TARGET_NAME} PROPERTIES ENVIRONMENT LSAN_OPTIONS=exitcode=0) set_tests_properties(${TARGET_NAME} PROPERTIES ENVIRONMENT LSAN_OPTIONS=exitcode=0)
endif() endif()
if(WIN32) if(WIN32)
set_target_properties(${TARGET_NAME} PROPERTIES VS_GLOBAL_VcpkgEnabled "false")
unset(MANIFEST) unset(MANIFEST)
endif() endif()
unset(TEST_INC) unset(TEST_INC)

View File

@@ -128,7 +128,7 @@ if(EXISTS ${SOURCE_DIR}/.git)
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT _git_changed_files STREQUAL "") if(NOT _git_changed_files STREQUAL "")
string(APPEND MY_WC_BRANCH " (modified)") set(MY_WC_BRANCH "${MY_WC_BRANCH} (modified)")
else() else()
# Unpushed commits are also considered local modifications # Unpushed commits are also considered local modifications
execute_process(COMMAND git log @{u}.. execute_process(COMMAND git log @{u}..
@@ -137,7 +137,7 @@ if(EXISTS ${SOURCE_DIR}/.git)
OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET) ERROR_QUIET)
if(NOT _git_unpushed_log STREQUAL "") if(NOT _git_unpushed_log STREQUAL "")
string(APPEND MY_WC_BRANCH " (modified)") set(MY_WC_BRANCH "${MY_WC_BRANCH} (modified)")
endif() endif()
unset(_git_unpushed_log) unset(_git_unpushed_log)
endif() endif()
@@ -161,7 +161,6 @@ file(WRITE buildinfo.h.txt
"#define BUILD_BRANCH \"${MY_WC_BRANCH}\"\n" "#define BUILD_BRANCH \"${MY_WC_BRANCH}\"\n"
"#define BUILD_DATE \"${BUILD_DATE}\"\n" "#define BUILD_DATE \"${BUILD_DATE}\"\n"
"#define BUILD_TIME \"${BUILD_TIME}\"\n" "#define BUILD_TIME \"${BUILD_TIME}\"\n"
"#include \"buildinfo_static.h\"\n"
) )
# cleanup # cleanup

View File

@@ -1,8 +0,0 @@
/* CMake expanded values that won't change between CMake execution (unlike date/time).
* This is included by `buildinfo.h` generated by `buildinfo.cmake`. */
#define BUILD_PLATFORM "@BUILD_PLATFORM@"
#define BUILD_TYPE "@BUILD_TYPE@"
#define BUILD_CFLAGS "@BUILD_CFLAGS@"
#define BUILD_CXXFLAGS "@BUILD_CXXFLAGS@"
#define BUILD_LINKFLAGS "@BUILD_LINKFLAGS@"
#define BUILD_SYSTEM "@BUILD_SYSTEM@"

View File

@@ -44,7 +44,6 @@ set(WITH_OPENMP ON CACHE BOOL "" FORCE)
set(WITH_OPENSUBDIV ON CACHE BOOL "" FORCE) set(WITH_OPENSUBDIV ON CACHE BOOL "" FORCE)
set(WITH_OPENVDB ON CACHE BOOL "" FORCE) set(WITH_OPENVDB ON CACHE BOOL "" FORCE)
set(WITH_OPENVDB_BLOSC ON CACHE BOOL "" FORCE) set(WITH_OPENVDB_BLOSC ON CACHE BOOL "" FORCE)
set(WITH_NANOVDB ON CACHE BOOL "" FORCE)
set(WITH_POTRACE ON CACHE BOOL "" FORCE) set(WITH_POTRACE ON CACHE BOOL "" FORCE)
set(WITH_PYTHON_INSTALL ON CACHE BOOL "" FORCE) set(WITH_PYTHON_INSTALL ON CACHE BOOL "" FORCE)
set(WITH_QUADRIFLOW ON CACHE BOOL "" FORCE) set(WITH_QUADRIFLOW ON CACHE BOOL "" FORCE)

View File

@@ -51,7 +51,6 @@ set(WITH_OPENIMAGEIO OFF CACHE BOOL "" FORCE)
set(WITH_OPENMP OFF CACHE BOOL "" FORCE) set(WITH_OPENMP OFF CACHE BOOL "" FORCE)
set(WITH_OPENSUBDIV OFF CACHE BOOL "" FORCE) set(WITH_OPENSUBDIV OFF CACHE BOOL "" FORCE)
set(WITH_OPENVDB OFF CACHE BOOL "" FORCE) set(WITH_OPENVDB OFF CACHE BOOL "" FORCE)
set(WITH_NANOVDB OFF CACHE BOOL "" FORCE)
set(WITH_QUADRIFLOW OFF CACHE BOOL "" FORCE) set(WITH_QUADRIFLOW OFF CACHE BOOL "" FORCE)
set(WITH_SDL OFF CACHE BOOL "" FORCE) set(WITH_SDL OFF CACHE BOOL "" FORCE)
set(WITH_TBB OFF CACHE BOOL "" FORCE) set(WITH_TBB OFF CACHE BOOL "" FORCE)

View File

@@ -45,7 +45,6 @@ set(WITH_OPENMP ON CACHE BOOL "" FORCE)
set(WITH_OPENSUBDIV ON CACHE BOOL "" FORCE) set(WITH_OPENSUBDIV ON CACHE BOOL "" FORCE)
set(WITH_OPENVDB ON CACHE BOOL "" FORCE) set(WITH_OPENVDB ON CACHE BOOL "" FORCE)
set(WITH_OPENVDB_BLOSC ON CACHE BOOL "" FORCE) set(WITH_OPENVDB_BLOSC ON CACHE BOOL "" FORCE)
set(WITH_NANOVDB ON CACHE BOOL "" FORCE)
set(WITH_POTRACE ON CACHE BOOL "" FORCE) set(WITH_POTRACE ON CACHE BOOL "" FORCE)
set(WITH_PYTHON_INSTALL ON CACHE BOOL "" FORCE) set(WITH_PYTHON_INSTALL ON CACHE BOOL "" FORCE)
set(WITH_QUADRIFLOW ON CACHE BOOL "" FORCE) set(WITH_QUADRIFLOW ON CACHE BOOL "" FORCE)

View File

@@ -28,7 +28,6 @@ set(WITH_OPENCOLLADA OFF CACHE BOOL "" FORCE)
set(WITH_INTERNATIONAL OFF CACHE BOOL "" FORCE) set(WITH_INTERNATIONAL OFF CACHE BOOL "" FORCE)
set(WITH_BULLET OFF CACHE BOOL "" FORCE) set(WITH_BULLET OFF CACHE BOOL "" FORCE)
set(WITH_OPENVDB OFF CACHE BOOL "" FORCE) set(WITH_OPENVDB OFF CACHE BOOL "" FORCE)
set(WITH_NANOVDB OFF CACHE BOOL "" FORCE)
set(WITH_ALEMBIC OFF CACHE BOOL "" FORCE) set(WITH_ALEMBIC OFF CACHE BOOL "" FORCE)
# Depends on Python install, do this to quiet warning. # Depends on Python install, do this to quiet warning.

View File

@@ -60,19 +60,6 @@ function(list_assert_duplicates
unset(_len_after) unset(_len_after)
endfunction() endfunction()
# Adds a native path separator to the end of the path:
#
# - 'example' -> 'example/'
# - '/example///' -> '/example/'
#
macro(path_ensure_trailing_slash
path_new path_input
)
file(TO_NATIVE_PATH "/" _path_sep)
string(REGEX REPLACE "[${_path_sep}]+$" "" ${path_new} ${path_input})
set(${path_new} "${${path_new}}${_path_sep}")
unset(_path_sep)
endmacro()
# foo_bar.spam --> foo_barMySuffix.spam # foo_bar.spam --> foo_barMySuffix.spam
macro(file_suffix macro(file_suffix
@@ -196,7 +183,7 @@ function(blender_user_header_search_paths
foreach(_INC ${includes}) foreach(_INC ${includes})
get_filename_component(_ABS_INC ${_INC} ABSOLUTE) get_filename_component(_ABS_INC ${_INC} ABSOLUTE)
# _ALL_INCS is a space-separated string of file paths in quotes. # _ALL_INCS is a space-separated string of file paths in quotes.
string(APPEND _ALL_INCS " \"${_ABS_INC}\"") set(_ALL_INCS "${_ALL_INCS} \"${_ABS_INC}\"")
endforeach() endforeach()
set_target_properties(${name} PROPERTIES XCODE_ATTRIBUTE_USER_HEADER_SEARCH_PATHS "${_ALL_INCS}") set_target_properties(${name} PROPERTIES XCODE_ATTRIBUTE_USER_HEADER_SEARCH_PATHS "${_ALL_INCS}")
endif() endif()
@@ -263,11 +250,11 @@ macro(add_cc_flags_custom_test
string(TOUPPER ${name} _name_upper) string(TOUPPER ${name} _name_upper)
if(DEFINED CMAKE_C_FLAGS_${_name_upper}) if(DEFINED CMAKE_C_FLAGS_${_name_upper})
message(STATUS "Using custom CFLAGS: CMAKE_C_FLAGS_${_name_upper} in \"${CMAKE_CURRENT_SOURCE_DIR}\"") message(STATUS "Using custom CFLAGS: CMAKE_C_FLAGS_${_name_upper} in \"${CMAKE_CURRENT_SOURCE_DIR}\"")
string(APPEND CMAKE_C_FLAGS " ${CMAKE_C_FLAGS_${_name_upper}}" ${ARGV1}) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${_name_upper}}" ${ARGV1})
endif() endif()
if(DEFINED CMAKE_CXX_FLAGS_${_name_upper}) if(DEFINED CMAKE_CXX_FLAGS_${_name_upper})
message(STATUS "Using custom CXXFLAGS: CMAKE_CXX_FLAGS_${_name_upper} in \"${CMAKE_CURRENT_SOURCE_DIR}\"") message(STATUS "Using custom CXXFLAGS: CMAKE_CXX_FLAGS_${_name_upper} in \"${CMAKE_CURRENT_SOURCE_DIR}\"")
string(APPEND CMAKE_CXX_FLAGS " ${CMAKE_CXX_FLAGS_${_name_upper}}" ${ARGV1}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${_name_upper}}" ${ARGV1})
endif() endif()
unset(_name_upper) unset(_name_upper)
@@ -688,14 +675,14 @@ endmacro()
macro(add_c_flag macro(add_c_flag
flag) flag)
string(APPEND CMAKE_C_FLAGS " ${flag}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}")
string(APPEND CMAKE_CXX_FLAGS " ${flag}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}")
endmacro() endmacro()
macro(add_cxx_flag macro(add_cxx_flag
flag) flag)
string(APPEND CMAKE_CXX_FLAGS " ${flag}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}")
endmacro() endmacro()
macro(remove_strict_flags) macro(remove_strict_flags)

View File

@@ -60,17 +60,6 @@ if(WITH_OPENAL)
endif() endif()
endif() endif()
if(WITH_JACK)
find_library(JACK_FRAMEWORK
NAMES jackmp
)
if(NOT JACK_FRAMEWORK)
set(WITH_JACK OFF)
else()
set(JACK_INCLUDE_DIRS ${JACK_FRAMEWORK}/headers)
endif()
endif()
if(NOT DEFINED LIBDIR) if(NOT DEFINED LIBDIR)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin) set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin)
# Prefer lib directory paths # Prefer lib directory paths
@@ -105,6 +94,17 @@ if(WITH_OPENSUBDIV)
find_package(OpenSubdiv) find_package(OpenSubdiv)
endif() endif()
if(WITH_JACK)
find_library(JACK_FRAMEWORK
NAMES jackmp
)
if(NOT JACK_FRAMEWORK)
set(WITH_JACK OFF)
else()
set(JACK_INCLUDE_DIRS ${JACK_FRAMEWORK}/headers)
endif()
endif()
if(WITH_CODEC_SNDFILE) if(WITH_CODEC_SNDFILE)
find_package(SndFile) find_package(SndFile)
find_library(_sndfile_FLAC_LIBRARY NAMES flac HINTS ${LIBDIR}/sndfile/lib) find_library(_sndfile_FLAC_LIBRARY NAMES flac HINTS ${LIBDIR}/sndfile/lib)
@@ -194,7 +194,7 @@ if(SYSTEMSTUBS_LIBRARY)
list(APPEND PLATFORM_LINKLIBS SystemStubs) list(APPEND PLATFORM_LINKLIBS SystemStubs)
endif() endif()
string(APPEND PLATFORM_CFLAGS " -pipe -funsigned-char -fno-strict-aliasing") set(PLATFORM_CFLAGS "${PLATFORM_CFLAGS} -pipe -funsigned-char")
set(PLATFORM_LINKFLAGS set(PLATFORM_LINKFLAGS
"-fexceptions -framework CoreServices -framework Foundation -framework IOKit -framework AppKit -framework Cocoa -framework Carbon -framework AudioUnit -framework AudioToolbox -framework CoreAudio -framework Metal -framework QuartzCore" "-fexceptions -framework CoreServices -framework Foundation -framework IOKit -framework AppKit -framework Cocoa -framework Carbon -framework AudioUnit -framework AudioToolbox -framework CoreAudio -framework Metal -framework QuartzCore"
) )
@@ -202,12 +202,12 @@ set(PLATFORM_LINKFLAGS
list(APPEND PLATFORM_LINKLIBS c++) list(APPEND PLATFORM_LINKLIBS c++)
if(WITH_JACK) if(WITH_JACK)
string(APPEND PLATFORM_LINKFLAGS " -F/Library/Frameworks -weak_framework jackmp") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -F/Library/Frameworks -weak_framework jackmp")
endif() endif()
if(WITH_PYTHON_MODULE OR WITH_PYTHON_FRAMEWORK) if(WITH_PYTHON_MODULE OR WITH_PYTHON_FRAMEWORK)
# force cmake to link right framework # force cmake to link right framework
string(APPEND PLATFORM_LINKFLAGS " /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python")
endif() endif()
if(WITH_OPENCOLLADA) if(WITH_OPENCOLLADA)
@@ -222,7 +222,7 @@ if(WITH_SDL)
find_package(SDL2) find_package(SDL2)
set(SDL_INCLUDE_DIR ${SDL2_INCLUDE_DIRS}) set(SDL_INCLUDE_DIR ${SDL2_INCLUDE_DIRS})
set(SDL_LIBRARY ${SDL2_LIBRARIES}) set(SDL_LIBRARY ${SDL2_LIBRARIES})
string(APPEND PLATFORM_LINKFLAGS " -framework ForceFeedback") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -framework ForceFeedback")
endif() endif()
set(PNG_ROOT ${LIBDIR}/png) set(PNG_ROOT ${LIBDIR}/png)
@@ -266,7 +266,7 @@ if(WITH_BOOST)
endif() endif()
if(WITH_INTERNATIONAL OR WITH_CODEC_FFMPEG) if(WITH_INTERNATIONAL OR WITH_CODEC_FFMPEG)
string(APPEND PLATFORM_LINKFLAGS " -liconv") # boost_locale and ffmpeg needs it ! set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -liconv") # boost_locale and ffmpeg needs it !
endif() endif()
if(WITH_OPENIMAGEIO) if(WITH_OPENIMAGEIO)
@@ -337,7 +337,7 @@ if(WITH_CYCLES_EMBREE)
find_package(Embree 3.8.0 REQUIRED) find_package(Embree 3.8.0 REQUIRED)
# Increase stack size for Embree, only works for executables. # Increase stack size for Embree, only works for executables.
if(NOT WITH_PYTHON_MODULE) if(NOT WITH_PYTHON_MODULE)
string(APPEND PLATFORM_LINKFLAGS " -Xlinker -stack_size -Xlinker 0x100000") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -Xlinker -stack_size -Xlinker 0x100000")
endif() endif()
# Embree static library linking can mix up SSE and AVX symbols, causing # Embree static library linking can mix up SSE and AVX symbols, causing
@@ -381,7 +381,7 @@ if(WITH_OPENMP)
set(OPENMP_FOUND ON) set(OPENMP_FOUND ON)
set(OpenMP_C_FLAGS "-Xclang -fopenmp -I'${LIBDIR}/openmp/include'") set(OpenMP_C_FLAGS "-Xclang -fopenmp -I'${LIBDIR}/openmp/include'")
set(OpenMP_CXX_FLAGS "-Xclang -fopenmp -I'${LIBDIR}/openmp/include'") set(OpenMP_CXX_FLAGS "-Xclang -fopenmp -I'${LIBDIR}/openmp/include'")
string(APPEND CMAKE_EXE_LINKER_FLAGS " -L'${LIBDIR}/openmp/lib' -lomp") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L'${LIBDIR}/openmp/lib' -lomp")
# Copy libomp.dylib to allow executables like datatoc and tests to work. # Copy libomp.dylib to allow executables like datatoc and tests to work.
# `@executable_path/../Resources/lib/` is a default dylib search path. # `@executable_path/../Resources/lib/` is a default dylib search path.
@@ -428,23 +428,23 @@ endif()
set(EXETYPE MACOSX_BUNDLE) set(EXETYPE MACOSX_BUNDLE)
set(CMAKE_C_FLAGS_DEBUG "-g") set(CMAKE_C_FLAGS_DEBUG "-fno-strict-aliasing -g")
set(CMAKE_CXX_FLAGS_DEBUG "-g") set(CMAKE_CXX_FLAGS_DEBUG "-fno-strict-aliasing -g")
if(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64" OR CMAKE_OSX_ARCHITECTURES MATCHES "i386") 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_CXX_FLAGS_RELEASE "-O2 -mdynamic-no-pic -msse -msse2 -msse3 -mssse3")
set(CMAKE_C_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_C_COMPILER_ID MATCHES "Clang") if(NOT CMAKE_C_COMPILER_ID MATCHES "Clang")
string(APPEND CMAKE_C_FLAGS_RELEASE " -ftree-vectorize -fvariable-expansion-in-unroller") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -ftree-vectorize -fvariable-expansion-in-unroller")
string(APPEND CMAKE_CXX_FLAGS_RELEASE " -ftree-vectorize -fvariable-expansion-in-unroller") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ftree-vectorize -fvariable-expansion-in-unroller")
endif() endif()
else() else()
set(CMAKE_C_FLAGS_RELEASE "-O2 -mdynamic-no-pic") set(CMAKE_C_FLAGS_RELEASE "-O2 -mdynamic-no-pic -fno-strict-aliasing")
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -mdynamic-no-pic") set(CMAKE_CXX_FLAGS_RELEASE "-O2 -mdynamic-no-pic -fno-strict-aliasing")
endif() endif()
if(${XCODE_VERSION} VERSION_EQUAL 5 OR ${XCODE_VERSION} VERSION_GREATER 5) if(${XCODE_VERSION} VERSION_EQUAL 5 OR ${XCODE_VERSION} VERSION_GREATER 5)
# Xcode 5 is always using CLANG, which has too low template depth of 128 for libmv # Xcode 5 is always using CLANG, which has too low template depth of 128 for libmv
string(APPEND CMAKE_CXX_FLAGS " -ftemplate-depth=1024") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth=1024")
endif() endif()
# Avoid conflicts with Luxrender, and other plug-ins that may use the same # Avoid conflicts with Luxrender, and other plug-ins that may use the same
@@ -453,8 +453,8 @@ set(PLATFORM_LINKFLAGS
"${PLATFORM_LINKFLAGS} -Xlinker -unexported_symbols_list -Xlinker '${CMAKE_SOURCE_DIR}/source/creator/osx_locals.map'" "${PLATFORM_LINKFLAGS} -Xlinker -unexported_symbols_list -Xlinker '${CMAKE_SOURCE_DIR}/source/creator/osx_locals.map'"
) )
string(APPEND CMAKE_CXX_FLAGS " -stdlib=libc++") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
string(APPEND PLATFORM_LINKFLAGS " -stdlib=libc++") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -stdlib=libc++")
# Suppress ranlib "has no symbols" warnings (workaround for T48250) # Suppress ranlib "has no symbols" warnings (workaround for T48250)
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>") set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")

View File

@@ -150,7 +150,7 @@ endif()
if(NOT ${CMAKE_GENERATOR} MATCHES "Xcode") if(NOT ${CMAKE_GENERATOR} MATCHES "Xcode")
# Force CMAKE_OSX_DEPLOYMENT_TARGET for makefiles, will not work else (CMake bug?) # Force CMAKE_OSX_DEPLOYMENT_TARGET for makefiles, will not work else (CMake bug?)
string(APPEND CMAKE_C_FLAGS " -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
string(APPEND CMAKE_CXX_FLAGS " -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
add_definitions("-DMACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}") add_definitions("-DMACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}")
endif() endif()

View File

@@ -73,7 +73,7 @@ if(EXISTS ${LIBDIR})
endif() endif()
if(WITH_STATIC_LIBS) if(WITH_STATIC_LIBS)
string(APPEND CMAKE_EXE_LINKER_FLAGS " -static-libstdc++") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libstdc++")
endif() endif()
# Wrapper to prefer static libraries # Wrapper to prefer static libraries
@@ -620,7 +620,7 @@ if(CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_C_FLAGS_RELEASE "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_RELEASE "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELWITHDEBINFO}") set(CMAKE_C_FLAGS_RELWITHDEBINFO "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELWITHDEBINFO}")
set(CMAKE_CXX_FLAGS_RELEASE "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_RELEASE "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}")
string(PREPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO "${GCC_EXTRA_FLAGS_RELEASE} ") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${GCC_EXTRA_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}")
unset(GCC_EXTRA_FLAGS_RELEASE) unset(GCC_EXTRA_FLAGS_RELEASE)
if(WITH_LINKER_GOLD) if(WITH_LINKER_GOLD)
@@ -628,8 +628,8 @@ if(CMAKE_COMPILER_IS_GNUCC)
COMMAND ${CMAKE_C_COMPILER} -fuse-ld=gold -Wl,--version COMMAND ${CMAKE_C_COMPILER} -fuse-ld=gold -Wl,--version
ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) ERROR_QUIET OUTPUT_VARIABLE LD_VERSION)
if("${LD_VERSION}" MATCHES "GNU gold") if("${LD_VERSION}" MATCHES "GNU gold")
string(APPEND CMAKE_C_FLAGS " -fuse-ld=gold") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fuse-ld=gold")
string(APPEND CMAKE_CXX_FLAGS " -fuse-ld=gold") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fuse-ld=gold")
else() else()
message(STATUS "GNU gold linker isn't available, using the default system linker.") message(STATUS "GNU gold linker isn't available, using the default system linker.")
endif() endif()
@@ -641,8 +641,8 @@ if(CMAKE_COMPILER_IS_GNUCC)
COMMAND ${CMAKE_C_COMPILER} -fuse-ld=lld -Wl,--version COMMAND ${CMAKE_C_COMPILER} -fuse-ld=lld -Wl,--version
ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) ERROR_QUIET OUTPUT_VARIABLE LD_VERSION)
if("${LD_VERSION}" MATCHES "LLD") if("${LD_VERSION}" MATCHES "LLD")
string(APPEND CMAKE_C_FLAGS " -fuse-ld=lld") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fuse-ld=lld")
string(APPEND CMAKE_CXX_FLAGS " -fuse-ld=lld") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fuse-ld=lld")
else() else()
message(STATUS "LLD linker isn't available, using the default system linker.") message(STATUS "LLD linker isn't available, using the default system linker.")
endif() endif()
@@ -667,12 +667,12 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Intel")
endif() endif()
mark_as_advanced(XILD) mark_as_advanced(XILD)
string(APPEND CMAKE_C_FLAGS " -fp-model precise -prec_div -parallel") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fp-model precise -prec_div -parallel")
string(APPEND CMAKE_CXX_FLAGS " -fp-model precise -prec_div -parallel") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fp-model precise -prec_div -parallel")
# string(APPEND PLATFORM_CFLAGS " -diag-enable sc3") # set(PLATFORM_CFLAGS "${PLATFORM_CFLAGS} -diag-enable sc3")
set(PLATFORM_CFLAGS "-pipe -fPIC -funsigned-char -fno-strict-aliasing") set(PLATFORM_CFLAGS "-pipe -fPIC -funsigned-char -fno-strict-aliasing")
string(APPEND PLATFORM_LINKFLAGS " -static-intel") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -static-intel")
endif() endif()
# Avoid conflicts with Mesa llvmpipe, Luxrender, and other plug-ins that may # Avoid conflicts with Mesa llvmpipe, Luxrender, and other plug-ins that may
@@ -685,5 +685,5 @@ set(PLATFORM_LINKFLAGS
# browsers can't properly detect blender as an executable then. Still enabled # browsers can't properly detect blender as an executable then. Still enabled
# for non-portable installs as typically used by Linux distributions. # for non-portable installs as typically used by Linux distributions.
if(WITH_INSTALL_PORTABLE) if(WITH_INSTALL_PORTABLE)
string(APPEND CMAKE_EXE_LINKER_FLAGS " -no-pie") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -no-pie")
endif() endif()

View File

@@ -49,7 +49,7 @@ if(CMAKE_C_COMPILER_ID MATCHES "Clang")
if(NOT EXISTS "${CLANG_OPENMP_DLL}") if(NOT EXISTS "${CLANG_OPENMP_DLL}")
message(FATAL_ERROR "Clang OpenMP library (${CLANG_OPENMP_DLL}) not found.") message(FATAL_ERROR "Clang OpenMP library (${CLANG_OPENMP_DLL}) not found.")
endif() endif()
string(APPEND CMAKE_EXE_LINKER_FLAGS " \"${CLANG_OPENMP_LIB}\"") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} \"${CLANG_OPENMP_LIB}\"")
endif() endif()
if(WITH_WINDOWS_STRIPPED_PDB) if(WITH_WINDOWS_STRIPPED_PDB)
message(WARNING "stripped pdb not supported with clang, disabling..") message(WARNING "stripped pdb not supported with clang, disabling..")
@@ -112,9 +112,9 @@ unset(_min_ver)
# needed for some MSVC installations # needed for some MSVC installations
# 4099 : PDB 'filename' was not found with 'object/library' # 4099 : PDB 'filename' was not found with 'object/library'
string(APPEND CMAKE_EXE_LINKER_FLAGS " /SAFESEH:NO /ignore:4099") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO /ignore:4099")
string(APPEND CMAKE_SHARED_LINKER_FLAGS " /SAFESEH:NO /ignore:4099") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SAFESEH:NO /ignore:4099")
string(APPEND CMAKE_MODULE_LINKER_FLAGS " /SAFESEH:NO /ignore:4099") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /SAFESEH:NO /ignore:4099")
list(APPEND PLATFORM_LINKLIBS list(APPEND PLATFORM_LINKLIBS
ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 Comctl32 version ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 Comctl32 version
@@ -154,18 +154,18 @@ if(WITH_WINDOWS_PDB)
endif() endif()
if(MSVC_CLANG) # Clangs version of cl doesn't support all flags if(MSVC_CLANG) # Clangs version of cl doesn't support all flags
string(APPEND CMAKE_CXX_FLAGS " ${CXX_WARN_FLAGS} /nologo /J /Gd /EHsc -Wno-unused-command-line-argument -Wno-microsoft-enum-forward-reference ") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_WARN_FLAGS} /nologo /J /Gd /EHsc -Wno-unused-command-line-argument -Wno-microsoft-enum-forward-reference ")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /nologo /J /Gd -Wno-unused-command-line-argument -Wno-microsoft-enum-forward-reference") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /nologo /J /Gd -Wno-unused-command-line-argument -Wno-microsoft-enum-forward-reference")
else() else()
string(APPEND CMAKE_CXX_FLAGS " /nologo /J /Gd /MP /EHsc /bigobj") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /nologo /J /Gd /MP /EHsc /bigobj")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /nologo /J /Gd /MP /bigobj") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /nologo /J /Gd /MP /bigobj")
endif() endif()
# C++ standards conformace (/permissive-) is available on msvc 15.5 (1912) and up # C++ standards conformace (/permissive-) is available on msvc 15.5 (1912) and up
if(MSVC_VERSION GREATER 1911 AND NOT MSVC_CLANG) if(MSVC_VERSION GREATER 1911 AND NOT MSVC_CLANG)
string(APPEND CMAKE_CXX_FLAGS " /permissive-") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /permissive-")
# Two-phase name lookup does not place nicely with OpenMP yet, so disable for now # Two-phase name lookup does not place nicely with OpenMP yet, so disable for now
string(APPEND CMAKE_CXX_FLAGS " /Zc:twoPhase-") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zc:twoPhase-")
endif() endif()
if(WITH_WINDOWS_SCCACHE AND CMAKE_VS_MSBUILD_COMMAND) if(WITH_WINDOWS_SCCACHE AND CMAKE_VS_MSBUILD_COMMAND)
@@ -183,33 +183,33 @@ else()
set(SYMBOL_FORMAT /ZI) set(SYMBOL_FORMAT /ZI)
endif() endif()
string(APPEND CMAKE_CXX_FLAGS_DEBUG " /MDd ${SYMBOL_FORMAT}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MDd ${SYMBOL_FORMAT}")
string(APPEND CMAKE_C_FLAGS_DEBUG " /MDd ${SYMBOL_FORMAT}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MDd ${SYMBOL_FORMAT}")
string(APPEND CMAKE_CXX_FLAGS_RELEASE " /MD ${PDB_INFO_OVERRIDE_FLAGS}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD ${PDB_INFO_OVERRIDE_FLAGS}")
string(APPEND CMAKE_C_FLAGS_RELEASE " /MD ${PDB_INFO_OVERRIDE_FLAGS}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MD ${PDB_INFO_OVERRIDE_FLAGS}")
string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL " /MD ${PDB_INFO_OVERRIDE_FLAGS}") set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /MD ${PDB_INFO_OVERRIDE_FLAGS}")
string(APPEND CMAKE_C_FLAGS_MINSIZEREL " /MD ${PDB_INFO_OVERRIDE_FLAGS}") set(CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL} /MD ${PDB_INFO_OVERRIDE_FLAGS}")
string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO " /MD ${SYMBOL_FORMAT}") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /MD ${SYMBOL_FORMAT}")
string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO " /MD ${SYMBOL_FORMAT}") set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} /MD ${SYMBOL_FORMAT}")
unset(SYMBOL_FORMAT) unset(SYMBOL_FORMAT)
# JMC is available on msvc 15.8 (1915) and up # JMC is available on msvc 15.8 (1915) and up
if(MSVC_VERSION GREATER 1914 AND NOT MSVC_CLANG) if(MSVC_VERSION GREATER 1914 AND NOT MSVC_CLANG)
string(APPEND CMAKE_CXX_FLAGS_DEBUG " /JMC") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /JMC")
endif() endif()
string(APPEND PLATFORM_LINKFLAGS " /SUBSYSTEM:CONSOLE /STACK:2097152") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /SUBSYSTEM:CONSOLE /STACK:2097152")
set(PLATFORM_LINKFLAGS_RELEASE "/NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libcmtd.lib /NODEFAULTLIB:msvcrtd.lib") set(PLATFORM_LINKFLAGS_RELEASE "/NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libcmtd.lib /NODEFAULTLIB:msvcrtd.lib")
string(APPEND PLATFORM_LINKFLAGS_DEBUG " /IGNORE:4099 /NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:libcmtd.lib") set(PLATFORM_LINKFLAGS_DEBUG "${PLATFORM_LINKFLAGS_DEBUG} /IGNORE:4099 /NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:libcmtd.lib")
# Ignore meaningless for us linker warnings. # Ignore meaningless for us linker warnings.
string(APPEND PLATFORM_LINKFLAGS " /ignore:4049 /ignore:4217 /ignore:4221") set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /ignore:4049 /ignore:4217 /ignore:4221")
set(PLATFORM_LINKFLAGS_RELEASE "${PLATFORM_LINKFLAGS} ${PDB_INFO_OVERRIDE_LINKER_FLAGS}") set(PLATFORM_LINKFLAGS_RELEASE "${PLATFORM_LINKFLAGS} ${PDB_INFO_OVERRIDE_LINKER_FLAGS}")
string(APPEND CMAKE_STATIC_LINKER_FLAGS " /ignore:4221") set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} /ignore:4221")
if(CMAKE_CL_64) if(CMAKE_CL_64)
string(PREPEND PLATFORM_LINKFLAGS "/MACHINE:X64 ") set(PLATFORM_LINKFLAGS "/MACHINE:X64 ${PLATFORM_LINKFLAGS}")
else() else()
string(PREPEND PLATFORM_LINKFLAGS "/MACHINE:IX86 /LARGEADDRESSAWARE ") set(PLATFORM_LINKFLAGS "/MACHINE:IX86 /LARGEADDRESSAWARE ${PLATFORM_LINKFLAGS}")
endif() endif()
if(NOT DEFINED LIBDIR) if(NOT DEFINED LIBDIR)

View File

@@ -31,7 +31,7 @@ if(WITH_WINDOWS_BUNDLE_CRT)
foreach(lib ${CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS}) foreach(lib ${CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS})
get_filename_component(filename ${lib} NAME) get_filename_component(filename ${lib} NAME)
file(SHA1 "${lib}" sha1_file) file(SHA1 "${lib}" sha1_file)
string(APPEND CRTLIBS " <file name=\"${filename}\" hash=\"${sha1_file}\" hashalg=\"SHA1\" />\n") set(CRTLIBS "${CRTLIBS} <file name=\"${filename}\" hash=\"${sha1_file}\" hashalg=\"SHA1\" />\n")
endforeach() endforeach()
configure_file(${CMAKE_SOURCE_DIR}/release/windows/manifest/blender.crt.manifest.in ${CMAKE_CURRENT_BINARY_DIR}/blender.crt.manifest @ONLY) configure_file(${CMAKE_SOURCE_DIR}/release/windows/manifest/blender.crt.manifest.in ${CMAKE_CURRENT_BINARY_DIR}/blender.crt.manifest @ONLY)
file(TOUCH ${manifest_trigger_file}) file(TOUCH ${manifest_trigger_file})

View File

@@ -423,7 +423,7 @@ set(LIB
if(CMAKE_COMPILER_IS_GNUCXX) if(CMAKE_COMPILER_IS_GNUCXX)
# needed for gcc 4.6+ # needed for gcc 4.6+
string(APPEND CMAKE_CXX_FLAGS " -fpermissive") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpermissive")
endif() endif()
if(MSVC) if(MSVC)

1137
extern/ceres/ChangeLog vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
Project: Ceres Solver Project: Ceres Solver
URL: http://ceres-solver.org/ URL: http://ceres-solver.org/
Upstream version 2.0.0 Upstream version 1.11 (aef9c9563b08d5f39eee1576af133a84749d1b48)
Local modifications: None Local modifications: None

View File

@@ -8,8 +8,8 @@ else
fi fi
repo="https://ceres-solver.googlesource.com/ceres-solver" repo="https://ceres-solver.googlesource.com/ceres-solver"
#branch="master" branch="master"
tag="2.0.0" tag=""
tmp=`mktemp -d` tmp=`mktemp -d`
checkout="$tmp/ceres" checkout="$tmp/ceres"

View File

@@ -153,44 +153,28 @@ template <typename CostFunctor,
int... Ns> // Number of parameters in each parameter block. int... Ns> // Number of parameters in each parameter block.
class AutoDiffCostFunction : public SizedCostFunction<kNumResiduals, Ns...> { class AutoDiffCostFunction : public SizedCostFunction<kNumResiduals, Ns...> {
public: public:
// Takes ownership of functor by default. Uses the template-provided // Takes ownership of functor. Uses the template-provided value for the
// value for the number of residuals ("kNumResiduals"). // number of residuals ("kNumResiduals").
explicit AutoDiffCostFunction(CostFunctor* functor, explicit AutoDiffCostFunction(CostFunctor* functor) : functor_(functor) {
Ownership ownership = TAKE_OWNERSHIP)
: functor_(functor), ownership_(ownership) {
static_assert(kNumResiduals != DYNAMIC, static_assert(kNumResiduals != DYNAMIC,
"Can't run the fixed-size constructor if the number of " "Can't run the fixed-size constructor if the number of "
"residuals is set to ceres::DYNAMIC."); "residuals is set to ceres::DYNAMIC.");
} }
// Takes ownership of functor by default. Ignores the template-provided // Takes ownership of functor. Ignores the template-provided
// kNumResiduals in favor of the "num_residuals" argument provided. // kNumResiduals in favor of the "num_residuals" argument provided.
// //
// This allows for having autodiff cost functions which return varying // This allows for having autodiff cost functions which return varying
// numbers of residuals at runtime. // numbers of residuals at runtime.
AutoDiffCostFunction(CostFunctor* functor, AutoDiffCostFunction(CostFunctor* functor, int num_residuals)
int num_residuals, : functor_(functor) {
Ownership ownership = TAKE_OWNERSHIP)
: functor_(functor), ownership_(ownership) {
static_assert(kNumResiduals == DYNAMIC, static_assert(kNumResiduals == DYNAMIC,
"Can't run the dynamic-size constructor if the number of " "Can't run the dynamic-size constructor if the number of "
"residuals is not ceres::DYNAMIC."); "residuals is not ceres::DYNAMIC.");
SizedCostFunction<kNumResiduals, Ns...>::set_num_residuals(num_residuals); SizedCostFunction<kNumResiduals, Ns...>::set_num_residuals(num_residuals);
} }
explicit AutoDiffCostFunction(AutoDiffCostFunction&& other) virtual ~AutoDiffCostFunction() {}
: functor_(std::move(other.functor_)), ownership_(other.ownership_) {}
virtual ~AutoDiffCostFunction() {
// Manually release pointer if configured to not take ownership rather than
// deleting only if ownership is taken.
// This is to stay maximally compatible to old user code which may have
// forgotten to implement a virtual destructor, from when the
// AutoDiffCostFunction always took ownership.
if (ownership_ == DO_NOT_TAKE_OWNERSHIP) {
functor_.release();
}
}
// Implementation details follow; clients of the autodiff cost function should // Implementation details follow; clients of the autodiff cost function should
// not have to examine below here. // not have to examine below here.
@@ -217,7 +201,6 @@ class AutoDiffCostFunction : public SizedCostFunction<kNumResiduals, Ns...> {
private: private:
std::unique_ptr<CostFunctor> functor_; std::unique_ptr<CostFunctor> functor_;
Ownership ownership_;
}; };
} // namespace ceres } // namespace ceres

View File

@@ -38,10 +38,8 @@
#ifndef CERES_PUBLIC_C_API_H_ #ifndef CERES_PUBLIC_C_API_H_
#define CERES_PUBLIC_C_API_H_ #define CERES_PUBLIC_C_API_H_
// clang-format off
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
#include "ceres/internal/disable_warnings.h" #include "ceres/internal/disable_warnings.h"
// clang-format on
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {

View File

@@ -144,7 +144,8 @@ class CostFunctionToFunctor {
// Extract parameter block pointers from params. // Extract parameter block pointers from params.
using Indices = using Indices =
std::make_integer_sequence<int, ParameterDims::kNumParameterBlocks>; std::make_integer_sequence<int,
ParameterDims::kNumParameterBlocks>;
std::array<const T*, ParameterDims::kNumParameterBlocks> parameter_blocks = std::array<const T*, ParameterDims::kNumParameterBlocks> parameter_blocks =
GetParameterPointers<T>(params, Indices()); GetParameterPointers<T>(params, Indices());

View File

@@ -51,7 +51,7 @@ class CovarianceImpl;
// ======= // =======
// It is very easy to use this class incorrectly without understanding // It is very easy to use this class incorrectly without understanding
// the underlying mathematics. Please read and understand the // the underlying mathematics. Please read and understand the
// documentation completely before attempting to use it. // documentation completely before attempting to use this class.
// //
// //
// This class allows the user to evaluate the covariance for a // This class allows the user to evaluate the covariance for a
@@ -73,7 +73,7 @@ class CovarianceImpl;
// the maximum likelihood estimate of x given observations y is the // the maximum likelihood estimate of x given observations y is the
// solution to the non-linear least squares problem: // solution to the non-linear least squares problem:
// //
// x* = arg min_x |f(x) - y|^2 // x* = arg min_x |f(x)|^2
// //
// And the covariance of x* is given by // And the covariance of x* is given by
// //
@@ -220,11 +220,11 @@ class CERES_EXPORT Covariance {
// 1. DENSE_SVD uses Eigen's JacobiSVD to perform the // 1. DENSE_SVD uses Eigen's JacobiSVD to perform the
// computations. It computes the singular value decomposition // computations. It computes the singular value decomposition
// //
// U * D * V' = J // U * S * V' = J
// //
// and then uses it to compute the pseudo inverse of J'J as // and then uses it to compute the pseudo inverse of J'J as
// //
// pseudoinverse[J'J] = V * pseudoinverse[D^2] * V' // pseudoinverse[J'J]^ = V * pseudoinverse[S] * V'
// //
// It is an accurate but slow method and should only be used // It is an accurate but slow method and should only be used
// for small to moderate sized problems. It can handle // for small to moderate sized problems. It can handle
@@ -235,7 +235,7 @@ class CERES_EXPORT Covariance {
// //
// Q * R = J // Q * R = J
// //
// [J'J]^-1 = [R'*R]^-1 // [J'J]^-1 = [R*R']^-1
// //
// SPARSE_QR is not capable of computing the covariance if the // SPARSE_QR is not capable of computing the covariance if the
// Jacobian is rank deficient. Depending on the value of // Jacobian is rank deficient. Depending on the value of

View File

@@ -40,7 +40,6 @@
#include "ceres/dynamic_cost_function.h" #include "ceres/dynamic_cost_function.h"
#include "ceres/internal/fixed_array.h" #include "ceres/internal/fixed_array.h"
#include "ceres/jet.h" #include "ceres/jet.h"
#include "ceres/types.h"
#include "glog/logging.h" #include "glog/logging.h"
namespace ceres { namespace ceres {
@@ -79,24 +78,10 @@ namespace ceres {
template <typename CostFunctor, int Stride = 4> template <typename CostFunctor, int Stride = 4>
class DynamicAutoDiffCostFunction : public DynamicCostFunction { class DynamicAutoDiffCostFunction : public DynamicCostFunction {
public: public:
// Takes ownership by default. explicit DynamicAutoDiffCostFunction(CostFunctor* functor)
DynamicAutoDiffCostFunction(CostFunctor* functor, : functor_(functor) {}
Ownership ownership = TAKE_OWNERSHIP)
: functor_(functor), ownership_(ownership) {}
explicit DynamicAutoDiffCostFunction(DynamicAutoDiffCostFunction&& other) virtual ~DynamicAutoDiffCostFunction() {}
: functor_(std::move(other.functor_)), ownership_(other.ownership_) {}
virtual ~DynamicAutoDiffCostFunction() {
// Manually release pointer if configured to not take ownership
// rather than deleting only if ownership is taken. This is to
// stay maximally compatible to old user code which may have
// forgotten to implement a virtual destructor, from when the
// AutoDiffCostFunction always took ownership.
if (ownership_ == DO_NOT_TAKE_OWNERSHIP) {
functor_.release();
}
}
bool Evaluate(double const* const* parameters, bool Evaluate(double const* const* parameters,
double* residuals, double* residuals,
@@ -166,9 +151,6 @@ class DynamicAutoDiffCostFunction : public DynamicCostFunction {
} }
} }
if (num_active_parameters == 0) {
return (*functor_)(parameters, residuals);
}
// When `num_active_parameters % Stride != 0` then it can be the case // When `num_active_parameters % Stride != 0` then it can be the case
// that `active_parameter_count < Stride` while parameter_cursor is less // that `active_parameter_count < Stride` while parameter_cursor is less
// than the total number of parameters and with no remaining non-constant // than the total number of parameters and with no remaining non-constant
@@ -266,7 +248,6 @@ class DynamicAutoDiffCostFunction : public DynamicCostFunction {
private: private:
std::unique_ptr<CostFunctor> functor_; std::unique_ptr<CostFunctor> functor_;
Ownership ownership_;
}; };
} // namespace ceres } // namespace ceres

View File

@@ -44,7 +44,6 @@
#include "ceres/internal/numeric_diff.h" #include "ceres/internal/numeric_diff.h"
#include "ceres/internal/parameter_dims.h" #include "ceres/internal/parameter_dims.h"
#include "ceres/numeric_diff_options.h" #include "ceres/numeric_diff_options.h"
#include "ceres/types.h"
#include "glog/logging.h" #include "glog/logging.h"
namespace ceres { namespace ceres {
@@ -85,10 +84,6 @@ class DynamicNumericDiffCostFunction : public DynamicCostFunction {
const NumericDiffOptions& options = NumericDiffOptions()) const NumericDiffOptions& options = NumericDiffOptions())
: functor_(functor), ownership_(ownership), options_(options) {} : functor_(functor), ownership_(ownership), options_(options) {}
explicit DynamicNumericDiffCostFunction(
DynamicNumericDiffCostFunction&& other)
: functor_(std::move(other.functor_)), ownership_(other.ownership_) {}
virtual ~DynamicNumericDiffCostFunction() { virtual ~DynamicNumericDiffCostFunction() {
if (ownership_ != TAKE_OWNERSHIP) { if (ownership_ != TAKE_OWNERSHIP) {
functor_.release(); functor_.release();

View File

@@ -62,8 +62,7 @@ class CERES_EXPORT GradientProblemSolver {
// Minimizer options ---------------------------------------- // Minimizer options ----------------------------------------
LineSearchDirectionType line_search_direction_type = LBFGS; LineSearchDirectionType line_search_direction_type = LBFGS;
LineSearchType line_search_type = WOLFE; LineSearchType line_search_type = WOLFE;
NonlinearConjugateGradientType nonlinear_conjugate_gradient_type = NonlinearConjugateGradientType nonlinear_conjugate_gradient_type = FLETCHER_REEVES;
FLETCHER_REEVES;
// The LBFGS hessian approximation is a low rank approximation to // The LBFGS hessian approximation is a low rank approximation to
// the inverse of the Hessian matrix. The rank of the // the inverse of the Hessian matrix. The rank of the

View File

@@ -198,7 +198,7 @@ struct Make1stOrderPerturbation {
template <int N, int Offset, typename T, typename JetT> template <int N, int Offset, typename T, typename JetT>
struct Make1stOrderPerturbation<N, N, Offset, T, JetT> { struct Make1stOrderPerturbation<N, N, Offset, T, JetT> {
public: public:
static void Apply(const T* src, JetT* dst) {} static void Apply(const T* /*src*/, JetT* /*dst*/) {}
}; };
// Calls Make1stOrderPerturbation for every parameter block. // Calls Make1stOrderPerturbation for every parameter block.
@@ -229,9 +229,7 @@ struct Make1stOrderPerturbations<std::integer_sequence<int, N, Ns...>,
// End of 'recursion'. Nothing more to do. // End of 'recursion'. Nothing more to do.
template <int ParameterIdx, int Total> template <int ParameterIdx, int Total>
struct Make1stOrderPerturbations<std::integer_sequence<int>, struct Make1stOrderPerturbations<std::integer_sequence<int>, ParameterIdx, Total> {
ParameterIdx,
Total> {
template <typename T, typename JetT> template <typename T, typename JetT>
static void Apply(T const* const* /* NOT USED */, JetT* /* NOT USED */) {} static void Apply(T const* const* /* NOT USED */, JetT* /* NOT USED */) {}
}; };

View File

@@ -36,22 +36,27 @@
namespace ceres { namespace ceres {
typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Vector; typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Vector;
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> typedef Eigen::Matrix<double,
Matrix; Eigen::Dynamic,
Eigen::Dynamic,
Eigen::RowMajor> Matrix;
typedef Eigen::Map<Vector> VectorRef; typedef Eigen::Map<Vector> VectorRef;
typedef Eigen::Map<Matrix> MatrixRef; typedef Eigen::Map<Matrix> MatrixRef;
typedef Eigen::Map<const Vector> ConstVectorRef; typedef Eigen::Map<const Vector> ConstVectorRef;
typedef Eigen::Map<const Matrix> ConstMatrixRef; typedef Eigen::Map<const Matrix> ConstMatrixRef;
// Column major matrices for DenseSparseMatrix/DenseQRSolver // Column major matrices for DenseSparseMatrix/DenseQRSolver
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> typedef Eigen::Matrix<double,
ColMajorMatrix; Eigen::Dynamic,
Eigen::Dynamic,
Eigen::ColMajor> ColMajorMatrix;
typedef Eigen::Map<ColMajorMatrix, 0, Eigen::Stride<Eigen::Dynamic, 1>> typedef Eigen::Map<ColMajorMatrix, 0,
ColMajorMatrixRef; Eigen::Stride<Eigen::Dynamic, 1>> ColMajorMatrixRef;
typedef Eigen::Map<const ColMajorMatrix, 0, Eigen::Stride<Eigen::Dynamic, 1>> typedef Eigen::Map<const ColMajorMatrix,
ConstColMajorMatrixRef; 0,
Eigen::Stride<Eigen::Dynamic, 1>> ConstColMajorMatrixRef;
// C++ does not support templated typdefs, thus the need for this // C++ does not support templated typdefs, thus the need for this
// struct so that we can support statically sized Matrix and Maps. // struct so that we can support statically sized Matrix and Maps.

View File

@@ -30,7 +30,6 @@
#ifndef CERES_PUBLIC_INTERNAL_FIXED_ARRAY_H_ #ifndef CERES_PUBLIC_INTERNAL_FIXED_ARRAY_H_
#define CERES_PUBLIC_INTERNAL_FIXED_ARRAY_H_ #define CERES_PUBLIC_INTERNAL_FIXED_ARRAY_H_
#include <Eigen/Core> // For Eigen::aligned_allocator
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <cstddef> #include <cstddef>
@@ -38,6 +37,8 @@
#include <tuple> #include <tuple>
#include <type_traits> #include <type_traits>
#include <Eigen/Core> // For Eigen::aligned_allocator
#include "ceres/internal/memory.h" #include "ceres/internal/memory.h"
#include "glog/logging.h" #include "glog/logging.h"

View File

@@ -62,8 +62,7 @@ struct SumImpl;
// Strip of and sum the first number. // Strip of and sum the first number.
template <typename T, T N, T... Ns> template <typename T, T N, T... Ns>
struct SumImpl<std::integer_sequence<T, N, Ns...>> { struct SumImpl<std::integer_sequence<T, N, Ns...>> {
static constexpr T Value = static constexpr T Value = N + SumImpl<std::integer_sequence<T, Ns...>>::Value;
N + SumImpl<std::integer_sequence<T, Ns...>>::Value;
}; };
// Strip of and sum the first two numbers. // Strip of and sum the first two numbers.
@@ -130,14 +129,10 @@ template <typename T, T Sum, typename SeqIn, typename SeqOut>
struct ExclusiveScanImpl; struct ExclusiveScanImpl;
template <typename T, T Sum, T N, T... Ns, T... Rs> template <typename T, T Sum, T N, T... Ns, T... Rs>
struct ExclusiveScanImpl<T, struct ExclusiveScanImpl<T, Sum, std::integer_sequence<T, N, Ns...>,
Sum,
std::integer_sequence<T, N, Ns...>,
std::integer_sequence<T, Rs...>> { std::integer_sequence<T, Rs...>> {
using Type = using Type =
typename ExclusiveScanImpl<T, typename ExclusiveScanImpl<T, Sum + N, std::integer_sequence<T, Ns...>,
Sum + N,
std::integer_sequence<T, Ns...>,
std::integer_sequence<T, Rs..., Sum>>::Type; std::integer_sequence<T, Rs..., Sum>>::Type;
}; };

View File

@@ -47,17 +47,15 @@
#include "ceres/types.h" #include "ceres/types.h"
#include "glog/logging.h" #include "glog/logging.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
// This is split from the main class because C++ doesn't allow partial template // This is split from the main class because C++ doesn't allow partial template
// specializations for member functions. The alternative is to repeat the main // specializations for member functions. The alternative is to repeat the main
// class for differing numbers of parameters, which is also unfortunate. // class for differing numbers of parameters, which is also unfortunate.
template <typename CostFunctor, template <typename CostFunctor, NumericDiffMethodType kMethod,
NumericDiffMethodType kMethod, int kNumResiduals, typename ParameterDims, int kParameterBlock,
int kNumResiduals,
typename ParameterDims,
int kParameterBlock,
int kParameterBlockSize> int kParameterBlockSize>
struct NumericDiff { struct NumericDiff {
// Mutates parameters but must restore them before return. // Mutates parameters but must restore them before return.
@@ -70,21 +68,21 @@ struct NumericDiff {
int parameter_block_size, int parameter_block_size,
double **parameters, double **parameters,
double *jacobian) { double *jacobian) {
using Eigen::ColMajor;
using Eigen::Map; using Eigen::Map;
using Eigen::Matrix; using Eigen::Matrix;
using Eigen::RowMajor; using Eigen::RowMajor;
using Eigen::ColMajor;
DCHECK(jacobian); DCHECK(jacobian);
const int num_residuals_internal = const int num_residuals_internal =
(kNumResiduals != ceres::DYNAMIC ? kNumResiduals : num_residuals); (kNumResiduals != ceres::DYNAMIC ? kNumResiduals : num_residuals);
const int parameter_block_index_internal = const int parameter_block_index_internal =
(kParameterBlock != ceres::DYNAMIC ? kParameterBlock (kParameterBlock != ceres::DYNAMIC ? kParameterBlock :
: parameter_block_index); parameter_block_index);
const int parameter_block_size_internal = const int parameter_block_size_internal =
(kParameterBlockSize != ceres::DYNAMIC ? kParameterBlockSize (kParameterBlockSize != ceres::DYNAMIC ? kParameterBlockSize :
: parameter_block_size); parameter_block_size);
typedef Matrix<double, kNumResiduals, 1> ResidualVector; typedef Matrix<double, kNumResiduals, 1> ResidualVector;
typedef Matrix<double, kParameterBlockSize, 1> ParameterVector; typedef Matrix<double, kParameterBlockSize, 1> ParameterVector;
@@ -99,17 +97,17 @@ struct NumericDiff {
(kParameterBlockSize == 1) ? ColMajor : RowMajor> (kParameterBlockSize == 1) ? ColMajor : RowMajor>
JacobianMatrix; JacobianMatrix;
Map<JacobianMatrix> parameter_jacobian( Map<JacobianMatrix> parameter_jacobian(jacobian,
jacobian, num_residuals_internal, parameter_block_size_internal); num_residuals_internal,
parameter_block_size_internal);
Map<ParameterVector> x_plus_delta( Map<ParameterVector> x_plus_delta(
parameters[parameter_block_index_internal], parameters[parameter_block_index_internal],
parameter_block_size_internal); parameter_block_size_internal);
ParameterVector x(x_plus_delta); ParameterVector x(x_plus_delta);
ParameterVector step_size = ParameterVector step_size = x.array().abs() *
x.array().abs() * ((kMethod == RIDDERS) ((kMethod == RIDDERS) ? options.ridders_relative_initial_step_size :
? options.ridders_relative_initial_step_size options.relative_step_size);
: options.relative_step_size);
// It is not a good idea to make the step size arbitrarily // It is not a good idea to make the step size arbitrarily
// small. This will lead to problems with round off and numerical // small. This will lead to problems with round off and numerical
@@ -120,8 +118,8 @@ struct NumericDiff {
// For Ridders' method, the initial step size is required to be large, // For Ridders' method, the initial step size is required to be large,
// thus ridders_relative_initial_step_size is used. // thus ridders_relative_initial_step_size is used.
if (kMethod == RIDDERS) { if (kMethod == RIDDERS) {
min_step_size = min_step_size = std::max(min_step_size,
std::max(min_step_size, options.ridders_relative_initial_step_size); options.ridders_relative_initial_step_size);
} }
// For each parameter in the parameter block, use finite differences to // For each parameter in the parameter block, use finite differences to
@@ -135,9 +133,7 @@ struct NumericDiff {
const double delta = std::max(min_step_size, step_size(j)); const double delta = std::max(min_step_size, step_size(j));
if (kMethod == RIDDERS) { if (kMethod == RIDDERS) {
if (!EvaluateRiddersJacobianColumn(functor, if (!EvaluateRiddersJacobianColumn(functor, j, delta,
j,
delta,
options, options,
num_residuals_internal, num_residuals_internal,
parameter_block_size_internal, parameter_block_size_internal,
@@ -150,9 +146,7 @@ struct NumericDiff {
return false; return false;
} }
} else { } else {
if (!EvaluateJacobianColumn(functor, if (!EvaluateJacobianColumn(functor, j, delta,
j,
delta,
num_residuals_internal, num_residuals_internal,
parameter_block_size_internal, parameter_block_size_internal,
x.data(), x.data(),
@@ -188,7 +182,8 @@ struct NumericDiff {
typedef Matrix<double, kParameterBlockSize, 1> ParameterVector; typedef Matrix<double, kParameterBlockSize, 1> ParameterVector;
Map<const ParameterVector> x(x_ptr, parameter_block_size); Map<const ParameterVector> x(x_ptr, parameter_block_size);
Map<ParameterVector> x_plus_delta(x_plus_delta_ptr, parameter_block_size); Map<ParameterVector> x_plus_delta(x_plus_delta_ptr,
parameter_block_size);
Map<ResidualVector> residuals(residuals_ptr, num_residuals); Map<ResidualVector> residuals(residuals_ptr, num_residuals);
Map<ResidualVector> temp_residuals(temp_residuals_ptr, num_residuals); Map<ResidualVector> temp_residuals(temp_residuals_ptr, num_residuals);
@@ -196,8 +191,9 @@ struct NumericDiff {
// Mutate 1 element at a time and then restore. // Mutate 1 element at a time and then restore.
x_plus_delta(parameter_index) = x(parameter_index) + delta; x_plus_delta(parameter_index) = x(parameter_index) + delta;
if (!VariadicEvaluate<ParameterDims>( if (!VariadicEvaluate<ParameterDims>(*functor,
*functor, parameters, residuals.data())) { parameters,
residuals.data())) {
return false; return false;
} }
@@ -210,8 +206,9 @@ struct NumericDiff {
// Compute the function on the other side of x(parameter_index). // Compute the function on the other side of x(parameter_index).
x_plus_delta(parameter_index) = x(parameter_index) - delta; x_plus_delta(parameter_index) = x(parameter_index) - delta;
if (!VariadicEvaluate<ParameterDims>( if (!VariadicEvaluate<ParameterDims>(*functor,
*functor, parameters, temp_residuals.data())) { parameters,
temp_residuals.data())) {
return false; return false;
} }
@@ -220,7 +217,8 @@ struct NumericDiff {
} else { } else {
// Forward difference only; reuse existing residuals evaluation. // Forward difference only; reuse existing residuals evaluation.
residuals -= residuals -=
Map<const ResidualVector>(residuals_at_eval_point, num_residuals); Map<const ResidualVector>(residuals_at_eval_point,
num_residuals);
} }
// Restore x_plus_delta. // Restore x_plus_delta.
@@ -256,17 +254,17 @@ struct NumericDiff {
double* x_plus_delta_ptr, double* x_plus_delta_ptr,
double* temp_residuals_ptr, double* temp_residuals_ptr,
double* residuals_ptr) { double* residuals_ptr) {
using Eigen::aligned_allocator;
using Eigen::Map; using Eigen::Map;
using Eigen::Matrix; using Eigen::Matrix;
using Eigen::aligned_allocator;
typedef Matrix<double, kNumResiduals, 1> ResidualVector; typedef Matrix<double, kNumResiduals, 1> ResidualVector;
typedef Matrix<double, kNumResiduals, Eigen::Dynamic> typedef Matrix<double, kNumResiduals, Eigen::Dynamic> ResidualCandidateMatrix;
ResidualCandidateMatrix;
typedef Matrix<double, kParameterBlockSize, 1> ParameterVector; typedef Matrix<double, kParameterBlockSize, 1> ParameterVector;
Map<const ParameterVector> x(x_ptr, parameter_block_size); Map<const ParameterVector> x(x_ptr, parameter_block_size);
Map<ParameterVector> x_plus_delta(x_plus_delta_ptr, parameter_block_size); Map<ParameterVector> x_plus_delta(x_plus_delta_ptr,
parameter_block_size);
Map<ResidualVector> residuals(residuals_ptr, num_residuals); Map<ResidualVector> residuals(residuals_ptr, num_residuals);
Map<ResidualVector> temp_residuals(temp_residuals_ptr, num_residuals); Map<ResidualVector> temp_residuals(temp_residuals_ptr, num_residuals);
@@ -277,16 +275,18 @@ struct NumericDiff {
// As the derivative is estimated, the step size decreases. // As the derivative is estimated, the step size decreases.
// By default, the step sizes are chosen so that the middle column // By default, the step sizes are chosen so that the middle column
// of the Romberg tableau uses the input delta. // of the Romberg tableau uses the input delta.
double current_step_size = double current_step_size = delta *
delta * pow(options.ridders_step_shrink_factor, pow(options.ridders_step_shrink_factor,
options.max_num_ridders_extrapolations / 2); options.max_num_ridders_extrapolations / 2);
// Double-buffering temporary differential candidate vectors // Double-buffering temporary differential candidate vectors
// from previous step size. // from previous step size.
ResidualCandidateMatrix stepsize_candidates_a( ResidualCandidateMatrix stepsize_candidates_a(
num_residuals, options.max_num_ridders_extrapolations); num_residuals,
options.max_num_ridders_extrapolations);
ResidualCandidateMatrix stepsize_candidates_b( ResidualCandidateMatrix stepsize_candidates_b(
num_residuals, options.max_num_ridders_extrapolations); num_residuals,
options.max_num_ridders_extrapolations);
ResidualCandidateMatrix* current_candidates = &stepsize_candidates_a; ResidualCandidateMatrix* current_candidates = &stepsize_candidates_a;
ResidualCandidateMatrix* previous_candidates = &stepsize_candidates_b; ResidualCandidateMatrix* previous_candidates = &stepsize_candidates_b;
@@ -304,9 +304,7 @@ struct NumericDiff {
// 3. Extrapolation becomes numerically unstable. // 3. Extrapolation becomes numerically unstable.
for (int i = 0; i < options.max_num_ridders_extrapolations; ++i) { for (int i = 0; i < options.max_num_ridders_extrapolations; ++i) {
// Compute the numerical derivative at this step size. // Compute the numerical derivative at this step size.
if (!EvaluateJacobianColumn(functor, if (!EvaluateJacobianColumn(functor, parameter_index, current_step_size,
parameter_index,
current_step_size,
num_residuals, num_residuals,
parameter_block_size, parameter_block_size,
x.data(), x.data(),
@@ -335,18 +333,17 @@ struct NumericDiff {
// the Richardson acceleration method. // the Richardson acceleration method.
current_candidates->col(k) = current_candidates->col(k) =
(richardson_factor * current_candidates->col(k - 1) - (richardson_factor * current_candidates->col(k - 1) -
previous_candidates->col(k - 1)) / previous_candidates->col(k - 1)) / (richardson_factor - 1.0);
(richardson_factor - 1.0);
richardson_factor *= options.ridders_step_shrink_factor * richardson_factor *= options.ridders_step_shrink_factor *
options.ridders_step_shrink_factor; options.ridders_step_shrink_factor;
// Compute the difference between the previous value and the current. // Compute the difference between the previous value and the current.
double candidate_error = std::max( double candidate_error = std::max(
(current_candidates->col(k) - current_candidates->col(k - 1)) (current_candidates->col(k) -
.norm(), current_candidates->col(k - 1)).norm(),
(current_candidates->col(k) - previous_candidates->col(k - 1)) (current_candidates->col(k) -
.norm()); previous_candidates->col(k - 1)).norm());
// If the error has decreased, update results. // If the error has decreased, update results.
if (candidate_error <= norm_error) { if (candidate_error <= norm_error) {
@@ -368,9 +365,8 @@ struct NumericDiff {
// Check to see if the current gradient estimate is numerically unstable. // Check to see if the current gradient estimate is numerically unstable.
// If so, bail out and return the last stable result. // If so, bail out and return the last stable result.
if (i > 0) { if (i > 0) {
double tableau_error = double tableau_error = (current_candidates->col(i) -
(current_candidates->col(i) - previous_candidates->col(i - 1)) previous_candidates->col(i - 1)).norm();
.norm();
// Compare current error to the chosen candidate's error. // Compare current error to the chosen candidate's error.
if (tableau_error >= 2 * norm_error) { if (tableau_error >= 2 * norm_error) {
@@ -486,18 +482,14 @@ struct EvaluateJacobianForParameterBlocks<ParameterDims,
// End of 'recursion'. Nothing more to do. // End of 'recursion'. Nothing more to do.
template <typename ParameterDims, int ParameterIdx> template <typename ParameterDims, int ParameterIdx>
struct EvaluateJacobianForParameterBlocks<ParameterDims, struct EvaluateJacobianForParameterBlocks<ParameterDims, std::integer_sequence<int>,
std::integer_sequence<int>,
ParameterIdx> { ParameterIdx> {
template <NumericDiffMethodType method, template <NumericDiffMethodType method, int kNumResiduals,
int kNumResiduals,
typename CostFunctor> typename CostFunctor>
static bool Apply(const CostFunctor* /* NOT USED*/, static bool Apply(const CostFunctor* /* NOT USED*/,
const double* /* NOT USED*/, const double* /* NOT USED*/,
const NumericDiffOptions& /* NOT USED*/, const NumericDiffOptions& /* NOT USED*/, int /* NOT USED*/,
int /* NOT USED*/, double** /* NOT USED*/, double** /* NOT USED*/) {
double** /* NOT USED*/,
double** /* NOT USED*/) {
return true; return true;
} }
}; };

View File

@@ -69,42 +69,22 @@
#endif #endif
// A macro to signal which functions and classes are exported when // A macro to signal which functions and classes are exported when
// building a shared library. // building a DLL with MSVC.
#if defined(_MSC_VER) //
#define CERES_API_SHARED_IMPORT __declspec(dllimport) // Note that the ordering here is important, CERES_BUILDING_SHARED_LIBRARY
#define CERES_API_SHARED_EXPORT __declspec(dllexport) // is only defined locally when Ceres is compiled, it is never exported to
#elif defined(__GNUC__) // users. However, in order that we do not have to configure config.h
#define CERES_API_SHARED_IMPORT __attribute__((visibility("default"))) // separately for building vs installing, if we are using MSVC and building
#define CERES_API_SHARED_EXPORT __attribute__((visibility("default"))) // a shared library, then both CERES_BUILDING_SHARED_LIBRARY and
// CERES_USING_SHARED_LIBRARY will be defined when Ceres is compiled.
// Hence it is important that the check for CERES_BUILDING_SHARED_LIBRARY
// happens first.
#if defined(_MSC_VER) && defined(CERES_BUILDING_SHARED_LIBRARY)
# define CERES_EXPORT __declspec(dllexport)
#elif defined(_MSC_VER) && defined(CERES_USING_SHARED_LIBRARY)
# define CERES_EXPORT __declspec(dllimport)
#else #else
#define CERES_API_SHARED_IMPORT
#define CERES_API_SHARED_EXPORT
#endif
// CERES_BUILDING_SHARED_LIBRARY is only defined locally when Ceres itself is
// compiled as a shared library, it is never exported to users. In order that
// we do not have to configure config.h separately when building Ceres as either
// a static or dynamic library, we define both CERES_USING_SHARED_LIBRARY and
// CERES_BUILDING_SHARED_LIBRARY when building as a shared library.
#if defined(CERES_USING_SHARED_LIBRARY)
#if defined(CERES_BUILDING_SHARED_LIBRARY)
// Compiling Ceres itself as a shared library.
#define CERES_EXPORT CERES_API_SHARED_EXPORT
#else
// Using Ceres as a shared library.
#define CERES_EXPORT CERES_API_SHARED_IMPORT
#endif
#else
// Ceres was compiled as a static library, export everything.
# define CERES_EXPORT # define CERES_EXPORT
#endif #endif
// Unit tests reach in and test internal functionality so we need a way to make
// those symbols visible
#ifdef CERES_EXPORT_INTERNAL_SYMBOLS
#define CERES_EXPORT_INTERNAL CERES_EXPORT
#else
#define CERES_EXPORT_INTERNAL
#endif
#endif // CERES_PUBLIC_INTERNAL_PORT_H_ #endif // CERES_PUBLIC_INTERNAL_PORT_H_

View File

@@ -46,10 +46,8 @@ namespace internal {
// For fixed size cost functors // For fixed size cost functors
template <typename Functor, typename T, int... Indices> template <typename Functor, typename T, int... Indices>
inline bool VariadicEvaluateImpl(const Functor& functor, inline bool VariadicEvaluateImpl(const Functor& functor, T const* const* input,
T const* const* input, T* output, std::false_type /*is_dynamic*/,
T* output,
std::false_type /*is_dynamic*/,
std::integer_sequence<int, Indices...>) { std::integer_sequence<int, Indices...>) {
static_assert(sizeof...(Indices), static_assert(sizeof...(Indices),
"Invalid number of parameter blocks. At least one parameter " "Invalid number of parameter blocks. At least one parameter "
@@ -59,31 +57,26 @@ inline bool VariadicEvaluateImpl(const Functor& functor,
// For dynamic sized cost functors // For dynamic sized cost functors
template <typename Functor, typename T> template <typename Functor, typename T>
inline bool VariadicEvaluateImpl(const Functor& functor, inline bool VariadicEvaluateImpl(const Functor& functor, T const* const* input,
T const* const* input, T* output, std::true_type /*is_dynamic*/,
T* output,
std::true_type /*is_dynamic*/,
std::integer_sequence<int>) { std::integer_sequence<int>) {
return functor(input, output); return functor(input, output);
} }
// For ceres cost functors (not ceres::CostFunction) // For ceres cost functors (not ceres::CostFunction)
template <typename ParameterDims, typename Functor, typename T> template <typename ParameterDims, typename Functor, typename T>
inline bool VariadicEvaluateImpl(const Functor& functor, inline bool VariadicEvaluateImpl(const Functor& functor, T const* const* input,
T const* const* input, T* output, const void* /* NOT USED */) {
T* output,
const void* /* NOT USED */) {
using ParameterBlockIndices = using ParameterBlockIndices =
std::make_integer_sequence<int, ParameterDims::kNumParameterBlocks>; std::make_integer_sequence<int, ParameterDims::kNumParameterBlocks>;
using IsDynamic = std::integral_constant<bool, ParameterDims::kIsDynamic>; using IsDynamic = std::integral_constant<bool, ParameterDims::kIsDynamic>;
return VariadicEvaluateImpl( return VariadicEvaluateImpl(functor, input, output, IsDynamic(),
functor, input, output, IsDynamic(), ParameterBlockIndices()); ParameterBlockIndices());
} }
// For ceres::CostFunction // For ceres::CostFunction
template <typename ParameterDims, typename Functor, typename T> template <typename ParameterDims, typename Functor, typename T>
inline bool VariadicEvaluateImpl(const Functor& functor, inline bool VariadicEvaluateImpl(const Functor& functor, T const* const* input,
T const* const* input,
T* output, T* output,
const CostFunction* /* NOT USED */) { const CostFunction* /* NOT USED */) {
return functor.Evaluate(input, output, nullptr); return functor.Evaluate(input, output, nullptr);
@@ -102,8 +95,7 @@ inline bool VariadicEvaluateImpl(const Functor& functor,
// blocks. The signature of the functor must have the following signature // blocks. The signature of the functor must have the following signature
// 'bool()(const T* i_1, const T* i_2, ... const T* i_n, T* output)'. // 'bool()(const T* i_1, const T* i_2, ... const T* i_n, T* output)'.
template <typename ParameterDims, typename Functor, typename T> template <typename ParameterDims, typename Functor, typename T>
inline bool VariadicEvaluate(const Functor& functor, inline bool VariadicEvaluate(const Functor& functor, T const* const* input,
T const* const* input,
T* output) { T* output) {
return VariadicEvaluateImpl<ParameterDims>(functor, input, output, &functor); return VariadicEvaluateImpl<ParameterDims>(functor, input, output, &functor);
} }

View File

@@ -73,7 +73,7 @@ struct CERES_EXPORT IterationSummary {
bool step_is_successful = false; bool step_is_successful = false;
// Value of the objective function. // Value of the objective function.
double cost = 0.0; double cost = 0.90;
// Change in the value of the objective function in this // Change in the value of the objective function in this
// iteration. This can be positive or negative. // iteration. This can be positive or negative.

View File

@@ -388,8 +388,6 @@ using std::cbrt;
using std::ceil; using std::ceil;
using std::cos; using std::cos;
using std::cosh; using std::cosh;
using std::erf;
using std::erfc;
using std::exp; using std::exp;
using std::exp2; using std::exp2;
using std::floor; using std::floor;
@@ -575,21 +573,6 @@ inline Jet<T, N> fmin(const Jet<T, N>& x, const Jet<T, N>& y) {
return y < x ? y : x; return y < x ? y : x;
} }
// erf is defined as an integral that cannot be expressed analyticaly
// however, the derivative is trivial to compute
// erf(x + h) = erf(x) + h * 2*exp(-x^2)/sqrt(pi)
template <typename T, int N>
inline Jet<T, N> erf(const Jet<T, N>& x) {
return Jet<T, N>(erf(x.a), x.v * M_2_SQRTPI * exp(-x.a * x.a));
}
// erfc(x) = 1-erf(x)
// erfc(x + h) = erfc(x) + h * (-2*exp(-x^2)/sqrt(pi))
template <typename T, int N>
inline Jet<T, N> erfc(const Jet<T, N>& x) {
return Jet<T, N>(erfc(x.a), -x.v * M_2_SQRTPI * exp(-x.a * x.a));
}
// Bessel functions of the first kind with integer order equal to 0, 1, n. // Bessel functions of the first kind with integer order equal to 0, 1, n.
// //
// Microsoft has deprecated the j[0,1,n]() POSIX Bessel functions in favour of // Microsoft has deprecated the j[0,1,n]() POSIX Bessel functions in favour of

View File

@@ -90,8 +90,8 @@ namespace ceres {
// //
// An example that occurs commonly in Structure from Motion problems // An example that occurs commonly in Structure from Motion problems
// is when camera rotations are parameterized using Quaternion. There, // is when camera rotations are parameterized using Quaternion. There,
// it is useful to only make updates orthogonal to that 4-vector // it is useful only make updates orthogonal to that 4-vector defining
// defining the quaternion. One way to do this is to let delta be a 3 // the quaternion. One way to do this is to let delta be a 3
// dimensional vector and define Plus to be // dimensional vector and define Plus to be
// //
// Plus(x, delta) = [cos(|delta|), sin(|delta|) delta / |delta|] * x // Plus(x, delta) = [cos(|delta|), sin(|delta|) delta / |delta|] * x
@@ -99,7 +99,7 @@ namespace ceres {
// The multiplication between the two 4-vectors on the RHS is the // The multiplication between the two 4-vectors on the RHS is the
// standard quaternion product. // standard quaternion product.
// //
// Given f and a point x, optimizing f can now be restated as // Given g and a point x, optimizing f can now be restated as
// //
// min f(Plus(x, delta)) // min f(Plus(x, delta))
// delta // delta
@@ -306,7 +306,6 @@ class CERES_EXPORT ProductParameterization : public LocalParameterization {
public: public:
ProductParameterization(const ProductParameterization&) = delete; ProductParameterization(const ProductParameterization&) = delete;
ProductParameterization& operator=(const ProductParameterization&) = delete; ProductParameterization& operator=(const ProductParameterization&) = delete;
virtual ~ProductParameterization() {}
// //
// NOTE: The constructor takes ownership of the input local // NOTE: The constructor takes ownership of the input local
// parameterizations. // parameterizations.
@@ -342,8 +341,7 @@ class CERES_EXPORT ProductParameterization : public LocalParameterization {
bool Plus(const double* x, bool Plus(const double* x,
const double* delta, const double* delta,
double* x_plus_delta) const override; double* x_plus_delta) const override;
bool ComputeJacobian(const double* x, bool ComputeJacobian(const double* x, double* jacobian) const override;
double* jacobian) const override;
int GlobalSize() const override { return global_size_; } int GlobalSize() const override { return global_size_; }
int LocalSize() const override { return local_size_; } int LocalSize() const override { return local_size_; }
@@ -356,8 +354,8 @@ class CERES_EXPORT ProductParameterization : public LocalParameterization {
} // namespace ceres } // namespace ceres
// clang-format off
#include "ceres/internal/reenable_warnings.h" #include "ceres/internal/reenable_warnings.h"
#include "ceres/internal/line_parameterization.h" #include "ceres/internal/line_parameterization.h"
#endif // CERES_PUBLIC_LOCAL_PARAMETERIZATION_H_ #endif // CERES_PUBLIC_LOCAL_PARAMETERIZATION_H_

View File

@@ -192,10 +192,7 @@ class NumericDiffCostFunction : public SizedCostFunction<kNumResiduals, Ns...> {
} }
} }
explicit NumericDiffCostFunction(NumericDiffCostFunction&& other) ~NumericDiffCostFunction() {
: functor_(std::move(other.functor_)), ownership_(other.ownership_) {}
virtual ~NumericDiffCostFunction() {
if (ownership_ != TAKE_OWNERSHIP) { if (ownership_ != TAKE_OWNERSHIP) {
functor_.release(); functor_.release();
} }

View File

@@ -453,15 +453,13 @@ class CERES_EXPORT Problem {
// problem.AddResidualBlock(new MyCostFunction, nullptr, &x); // problem.AddResidualBlock(new MyCostFunction, nullptr, &x);
// //
// double cost = 0.0; // double cost = 0.0;
// problem.Evaluate(Problem::EvaluateOptions(), &cost, // problem.Evaluate(Problem::EvaluateOptions(), &cost, nullptr, nullptr, nullptr);
// nullptr, nullptr, nullptr);
// //
// The cost is evaluated at x = 1. If you wish to evaluate the // The cost is evaluated at x = 1. If you wish to evaluate the
// problem at x = 2, then // problem at x = 2, then
// //
// x = 2; // x = 2;
// problem.Evaluate(Problem::EvaluateOptions(), &cost, // problem.Evaluate(Problem::EvaluateOptions(), &cost, nullptr, nullptr, nullptr);
// nullptr, nullptr, nullptr);
// //
// is the way to do so. // is the way to do so.
// //
@@ -511,41 +509,23 @@ class CERES_EXPORT Problem {
// apply_loss_function as the name implies allows the user to switch // apply_loss_function as the name implies allows the user to switch
// the application of the loss function on and off. // the application of the loss function on and off.
// //
// If an EvaluationCallback is associated with the problem, then its // WARNING: If an EvaluationCallback is associated with the problem
// PrepareForEvaluation method will be called every time this method // then it is the user's responsibility to call it before calling
// is called with new_point = true. This conservatively assumes that // this method.
// the user may have changed the parameter values since the previous //
// call to evaluate / solve. For improved efficiency, and only if // This is because, if the user calls this method multiple times, we
// you know that the parameter values have not changed between // cannot tell if the underlying parameter blocks have changed
// calls, see EvaluateResidualBlockAssumingParametersUnchanged(). // between calls or not. So if EvaluateResidualBlock was responsible
// for calling the EvaluationCallback, it will have to do it
// everytime it is called. Which makes the common case where the
// parameter blocks do not change, inefficient. So we leave it to
// the user to call the EvaluationCallback as needed.
bool EvaluateResidualBlock(ResidualBlockId residual_block_id, bool EvaluateResidualBlock(ResidualBlockId residual_block_id,
bool apply_loss_function, bool apply_loss_function,
double* cost, double* cost,
double* residuals, double* residuals,
double** jacobians) const; double** jacobians) const;
// Same as EvaluateResidualBlock except that if an
// EvaluationCallback is associated with the problem, then its
// PrepareForEvaluation method will be called every time this method
// is called with new_point = false.
//
// This means, if an EvaluationCallback is associated with the
// problem then it is the user's responsibility to call
// PrepareForEvaluation before calling this method if necessary,
// i.e. iff the parameter values have been changed since the last
// call to evaluate / solve.'
//
// This is because, as the name implies, we assume that the
// parameter blocks did not change since the last time
// PrepareForEvaluation was called (via Solve, Evaluate or
// EvaluateResidualBlock).
bool EvaluateResidualBlockAssumingParametersUnchanged(
ResidualBlockId residual_block_id,
bool apply_loss_function,
double* cost,
double* residuals,
double** jacobians) const;
private: private:
friend class Solver; friend class Solver;
friend class Covariance; friend class Covariance;

View File

@@ -320,8 +320,8 @@ inline void QuaternionToAngleAxis(const T* quaternion, T* angle_axis) {
} }
template <typename T> template <typename T>
void RotationMatrixToQuaternion(const T* R, T* quaternion) { void RotationMatrixToQuaternion(const T* R, T* angle_axis) {
RotationMatrixToQuaternion(ColumnMajorAdapter3x3(R), quaternion); RotationMatrixToQuaternion(ColumnMajorAdapter3x3(R), angle_axis);
} }
// This algorithm comes from "Quaternion Calculus and Fast Animation", // This algorithm comes from "Quaternion Calculus and Fast Animation",

View File

@@ -360,8 +360,7 @@ class CERES_EXPORT Solver {
// //
// If Solver::Options::preconditioner_type == SUBSET, then // If Solver::Options::preconditioner_type == SUBSET, then
// residual_blocks_for_subset_preconditioner must be non-empty. // residual_blocks_for_subset_preconditioner must be non-empty.
std::unordered_set<ResidualBlockId> std::unordered_set<ResidualBlockId> residual_blocks_for_subset_preconditioner;
residual_blocks_for_subset_preconditioner;
// Ceres supports using multiple dense linear algebra libraries // Ceres supports using multiple dense linear algebra libraries
// for dense matrix factorizations. Currently EIGEN and LAPACK are // for dense matrix factorizations. Currently EIGEN and LAPACK are
@@ -839,7 +838,7 @@ class CERES_EXPORT Solver {
int num_linear_solves = -1; int num_linear_solves = -1;
// Time (in seconds) spent evaluating the residual vector. // Time (in seconds) spent evaluating the residual vector.
double residual_evaluation_time_in_seconds = -1.0; double residual_evaluation_time_in_seconds = 1.0;
// Number of residual only evaluations. // Number of residual only evaluations.
int num_residual_evaluations = -1; int num_residual_evaluations = -1;

View File

@@ -50,7 +50,7 @@ namespace ceres {
// delete on it upon completion. // delete on it upon completion.
enum Ownership { enum Ownership {
DO_NOT_TAKE_OWNERSHIP, DO_NOT_TAKE_OWNERSHIP,
TAKE_OWNERSHIP, TAKE_OWNERSHIP
}; };
// TODO(keir): Considerably expand the explanations of each solver type. // TODO(keir): Considerably expand the explanations of each solver type.
@@ -185,19 +185,19 @@ enum SparseLinearAlgebraLibraryType {
enum DenseLinearAlgebraLibraryType { enum DenseLinearAlgebraLibraryType {
EIGEN, EIGEN,
LAPACK, LAPACK
}; };
// Logging options // Logging options
// The options get progressively noisier. // The options get progressively noisier.
enum LoggingType { enum LoggingType {
SILENT, SILENT,
PER_MINIMIZER_ITERATION, PER_MINIMIZER_ITERATION
}; };
enum MinimizerType { enum MinimizerType {
LINE_SEARCH, LINE_SEARCH,
TRUST_REGION, TRUST_REGION
}; };
enum LineSearchDirectionType { enum LineSearchDirectionType {
@@ -412,7 +412,7 @@ enum DumpFormatType {
// specified for the number of residuals. If specified, then the // specified for the number of residuals. If specified, then the
// number of residuas for that cost function can vary at runtime. // number of residuas for that cost function can vary at runtime.
enum DimensionType { enum DimensionType {
DYNAMIC = -1, DYNAMIC = -1
}; };
// The differentiation method used to compute numerical derivatives in // The differentiation method used to compute numerical derivatives in
@@ -433,7 +433,7 @@ enum NumericDiffMethodType {
enum LineSearchInterpolationType { enum LineSearchInterpolationType {
BISECTION, BISECTION,
QUADRATIC, QUADRATIC,
CUBIC, CUBIC
}; };
enum CovarianceAlgorithmType { enum CovarianceAlgorithmType {
@@ -448,7 +448,8 @@ enum CovarianceAlgorithmType {
// did not write to that memory location. // did not write to that memory location.
const double kImpossibleValue = 1e302; const double kImpossibleValue = 1e302;
CERES_EXPORT const char* LinearSolverTypeToString(LinearSolverType type); CERES_EXPORT const char* LinearSolverTypeToString(
LinearSolverType type);
CERES_EXPORT bool StringToLinearSolverType(std::string value, CERES_EXPORT bool StringToLinearSolverType(std::string value,
LinearSolverType* type); LinearSolverType* type);
@@ -458,23 +459,25 @@ CERES_EXPORT bool StringToPreconditionerType(std::string value,
CERES_EXPORT const char* VisibilityClusteringTypeToString( CERES_EXPORT const char* VisibilityClusteringTypeToString(
VisibilityClusteringType type); VisibilityClusteringType type);
CERES_EXPORT bool StringToVisibilityClusteringType( CERES_EXPORT bool StringToVisibilityClusteringType(std::string value,
std::string value, VisibilityClusteringType* type); VisibilityClusteringType* type);
CERES_EXPORT const char* SparseLinearAlgebraLibraryTypeToString( CERES_EXPORT const char* SparseLinearAlgebraLibraryTypeToString(
SparseLinearAlgebraLibraryType type); SparseLinearAlgebraLibraryType type);
CERES_EXPORT bool StringToSparseLinearAlgebraLibraryType( CERES_EXPORT bool StringToSparseLinearAlgebraLibraryType(
std::string value, SparseLinearAlgebraLibraryType* type); std::string value,
SparseLinearAlgebraLibraryType* type);
CERES_EXPORT const char* DenseLinearAlgebraLibraryTypeToString( CERES_EXPORT const char* DenseLinearAlgebraLibraryTypeToString(
DenseLinearAlgebraLibraryType type); DenseLinearAlgebraLibraryType type);
CERES_EXPORT bool StringToDenseLinearAlgebraLibraryType( CERES_EXPORT bool StringToDenseLinearAlgebraLibraryType(
std::string value, DenseLinearAlgebraLibraryType* type); std::string value,
DenseLinearAlgebraLibraryType* type);
CERES_EXPORT const char* TrustRegionStrategyTypeToString( CERES_EXPORT const char* TrustRegionStrategyTypeToString(
TrustRegionStrategyType type); TrustRegionStrategyType type);
CERES_EXPORT bool StringToTrustRegionStrategyType( CERES_EXPORT bool StringToTrustRegionStrategyType(std::string value,
std::string value, TrustRegionStrategyType* type); TrustRegionStrategyType* type);
CERES_EXPORT const char* DoglegTypeToString(DoglegType type); CERES_EXPORT const char* DoglegTypeToString(DoglegType type);
CERES_EXPORT bool StringToDoglegType(std::string value, DoglegType* type); CERES_EXPORT bool StringToDoglegType(std::string value, DoglegType* type);
@@ -484,39 +487,41 @@ CERES_EXPORT bool StringToMinimizerType(std::string value, MinimizerType* type);
CERES_EXPORT const char* LineSearchDirectionTypeToString( CERES_EXPORT const char* LineSearchDirectionTypeToString(
LineSearchDirectionType type); LineSearchDirectionType type);
CERES_EXPORT bool StringToLineSearchDirectionType( CERES_EXPORT bool StringToLineSearchDirectionType(std::string value,
std::string value, LineSearchDirectionType* type); LineSearchDirectionType* type);
CERES_EXPORT const char* LineSearchTypeToString(LineSearchType type); CERES_EXPORT const char* LineSearchTypeToString(LineSearchType type);
CERES_EXPORT bool StringToLineSearchType(std::string value, CERES_EXPORT bool StringToLineSearchType(std::string value, LineSearchType* type);
LineSearchType* type);
CERES_EXPORT const char* NonlinearConjugateGradientTypeToString( CERES_EXPORT const char* NonlinearConjugateGradientTypeToString(
NonlinearConjugateGradientType type); NonlinearConjugateGradientType type);
CERES_EXPORT bool StringToNonlinearConjugateGradientType( CERES_EXPORT bool StringToNonlinearConjugateGradientType(
std::string value, NonlinearConjugateGradientType* type); std::string value,
NonlinearConjugateGradientType* type);
CERES_EXPORT const char* LineSearchInterpolationTypeToString( CERES_EXPORT const char* LineSearchInterpolationTypeToString(
LineSearchInterpolationType type); LineSearchInterpolationType type);
CERES_EXPORT bool StringToLineSearchInterpolationType( CERES_EXPORT bool StringToLineSearchInterpolationType(
std::string value, LineSearchInterpolationType* type); std::string value,
LineSearchInterpolationType* type);
CERES_EXPORT const char* CovarianceAlgorithmTypeToString( CERES_EXPORT const char* CovarianceAlgorithmTypeToString(
CovarianceAlgorithmType type); CovarianceAlgorithmType type);
CERES_EXPORT bool StringToCovarianceAlgorithmType( CERES_EXPORT bool StringToCovarianceAlgorithmType(
std::string value, CovarianceAlgorithmType* type); std::string value,
CovarianceAlgorithmType* type);
CERES_EXPORT const char* NumericDiffMethodTypeToString( CERES_EXPORT const char* NumericDiffMethodTypeToString(
NumericDiffMethodType type); NumericDiffMethodType type);
CERES_EXPORT bool StringToNumericDiffMethodType(std::string value, CERES_EXPORT bool StringToNumericDiffMethodType(
std::string value,
NumericDiffMethodType* type); NumericDiffMethodType* type);
CERES_EXPORT const char* LoggingTypeToString(LoggingType type); CERES_EXPORT const char* LoggingTypeToString(LoggingType type);
CERES_EXPORT bool StringtoLoggingType(std::string value, LoggingType* type); CERES_EXPORT bool StringtoLoggingType(std::string value, LoggingType* type);
CERES_EXPORT const char* DumpFormatTypeToString(DumpFormatType type); CERES_EXPORT const char* DumpFormatTypeToString(DumpFormatType type);
CERES_EXPORT bool StringtoDumpFormatType(std::string value, CERES_EXPORT bool StringtoDumpFormatType(std::string value, DumpFormatType* type);
DumpFormatType* type);
CERES_EXPORT bool StringtoDumpFormatType(std::string value, LoggingType* type); CERES_EXPORT bool StringtoDumpFormatType(std::string value, LoggingType* type);
CERES_EXPORT const char* TerminationTypeToString(TerminationType type); CERES_EXPORT const char* TerminationTypeToString(TerminationType type);

View File

@@ -41,9 +41,8 @@
#define CERES_TO_STRING(x) CERES_TO_STRING_HELPER(x) #define CERES_TO_STRING(x) CERES_TO_STRING_HELPER(x)
// The Ceres version as a string; for example "1.9.0". // The Ceres version as a string; for example "1.9.0".
#define CERES_VERSION_STRING \ #define CERES_VERSION_STRING CERES_TO_STRING(CERES_VERSION_MAJOR) "." \
CERES_TO_STRING(CERES_VERSION_MAJOR) \ CERES_TO_STRING(CERES_VERSION_MINOR) "." \
"." CERES_TO_STRING(CERES_VERSION_MINOR) "." CERES_TO_STRING( \ CERES_TO_STRING(CERES_VERSION_REVISION)
CERES_VERSION_REVISION)
#endif // CERES_PUBLIC_VERSION_H_ #endif // CERES_PUBLIC_VERSION_H_

View File

@@ -33,19 +33,18 @@
#ifndef CERES_NO_ACCELERATE_SPARSE #ifndef CERES_NO_ACCELERATE_SPARSE
#include "ceres/accelerate_sparse.h"
#include <algorithm> #include <algorithm>
#include <string> #include <string>
#include <vector> #include <vector>
#include "ceres/accelerate_sparse.h"
#include "ceres/compressed_col_sparse_matrix_utils.h" #include "ceres/compressed_col_sparse_matrix_utils.h"
#include "ceres/compressed_row_sparse_matrix.h" #include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/triplet_sparse_matrix.h" #include "ceres/triplet_sparse_matrix.h"
#include "glog/logging.h" #include "glog/logging.h"
#define CASESTR(x) \ #define CASESTR(x) case x: return #x
case x: \
return #x
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -81,7 +80,8 @@ void* ResizeForAccelerateAlignment(const size_t required_size,
size_t size_from_aligned_start = workspace->size(); size_t size_from_aligned_start = workspace->size();
void* aligned_solve_workspace_start = void* aligned_solve_workspace_start =
reinterpret_cast<void*>(workspace->data()); reinterpret_cast<void*>(workspace->data());
aligned_solve_workspace_start = std::align(kAccelerateRequiredAlignment, aligned_solve_workspace_start =
std::align(kAccelerateRequiredAlignment,
required_size, required_size,
aligned_solve_workspace_start, aligned_solve_workspace_start,
size_from_aligned_start); size_from_aligned_start);
@@ -95,10 +95,10 @@ template <typename Scalar>
void AccelerateSparse<Scalar>::Solve(NumericFactorization* numeric_factor, void AccelerateSparse<Scalar>::Solve(NumericFactorization* numeric_factor,
DenseVector* rhs_and_solution) { DenseVector* rhs_and_solution) {
// From SparseSolve() documentation in Solve.h // From SparseSolve() documentation in Solve.h
const int required_size = numeric_factor->solveWorkspaceRequiredStatic + const int required_size =
numeric_factor->solveWorkspaceRequiredStatic +
numeric_factor->solveWorkspaceRequiredPerRHS; numeric_factor->solveWorkspaceRequiredPerRHS;
SparseSolve(*numeric_factor, SparseSolve(*numeric_factor, *rhs_and_solution,
*rhs_and_solution,
ResizeForAccelerateAlignment(required_size, &solve_workspace_)); ResizeForAccelerateAlignment(required_size, &solve_workspace_));
} }
@@ -153,14 +153,12 @@ template <typename Scalar>
void AccelerateSparse<Scalar>::Cholesky(ASSparseMatrix* A, void AccelerateSparse<Scalar>::Cholesky(ASSparseMatrix* A,
NumericFactorization* numeric_factor) { NumericFactorization* numeric_factor) {
// From SparseRefactor() documentation in Solve.h // From SparseRefactor() documentation in Solve.h
const int required_size = const int required_size = std::is_same<Scalar, double>::value
std::is_same<Scalar, double>::value
? numeric_factor->symbolicFactorization.workspaceSize_Double ? numeric_factor->symbolicFactorization.workspaceSize_Double
: numeric_factor->symbolicFactorization.workspaceSize_Float; : numeric_factor->symbolicFactorization.workspaceSize_Float;
return SparseRefactor( return SparseRefactor(*A, numeric_factor,
*A, ResizeForAccelerateAlignment(required_size,
numeric_factor, &factorization_workspace_));
ResizeForAccelerateAlignment(required_size, &factorization_workspace_));
} }
// Instantiate only for the specific template types required/supported s/t the // Instantiate only for the specific template types required/supported s/t the
@@ -169,8 +167,8 @@ template class AccelerateSparse<double>;
template class AccelerateSparse<float>; template class AccelerateSparse<float>;
template<typename Scalar> template<typename Scalar>
std::unique_ptr<SparseCholesky> AppleAccelerateCholesky<Scalar>::Create( std::unique_ptr<SparseCholesky>
OrderingType ordering_type) { AppleAccelerateCholesky<Scalar>::Create(OrderingType ordering_type) {
return std::unique_ptr<SparseCholesky>( return std::unique_ptr<SparseCholesky>(
new AppleAccelerateCholesky<Scalar>(ordering_type)); new AppleAccelerateCholesky<Scalar>(ordering_type));
} }
@@ -193,8 +191,9 @@ AppleAccelerateCholesky<Scalar>::StorageType() const {
} }
template<typename Scalar> template<typename Scalar>
LinearSolverTerminationType AppleAccelerateCholesky<Scalar>::Factorize( LinearSolverTerminationType
CompressedRowSparseMatrix* lhs, std::string* message) { AppleAccelerateCholesky<Scalar>::Factorize(CompressedRowSparseMatrix* lhs,
std::string* message) {
CHECK_EQ(lhs->storage_type(), StorageType()); CHECK_EQ(lhs->storage_type(), StorageType());
if (lhs == NULL) { if (lhs == NULL) {
*message = "Failure: Input lhs is NULL."; *message = "Failure: Input lhs is NULL.";
@@ -236,8 +235,10 @@ LinearSolverTerminationType AppleAccelerateCholesky<Scalar>::Factorize(
} }
template<typename Scalar> template<typename Scalar>
LinearSolverTerminationType AppleAccelerateCholesky<Scalar>::Solve( LinearSolverTerminationType
const double* rhs, double* solution, std::string* message) { AppleAccelerateCholesky<Scalar>::Solve(const double* rhs,
double* solution,
std::string* message) {
CHECK_EQ(numeric_factor_->status, SparseStatusOK) CHECK_EQ(numeric_factor_->status, SparseStatusOK)
<< "Solve called without a call to Factorize first (" << "Solve called without a call to Factorize first ("
<< SparseStatusToString(numeric_factor_->status) << ")."; << SparseStatusToString(numeric_factor_->status) << ").";
@@ -282,7 +283,7 @@ void AppleAccelerateCholesky<Scalar>::FreeNumericFactorization() {
template class AppleAccelerateCholesky<double>; template class AppleAccelerateCholesky<double>;
template class AppleAccelerateCholesky<float>; template class AppleAccelerateCholesky<float>;
} // namespace internal }
} // namespace ceres }
#endif // CERES_NO_ACCELERATE_SPARSE #endif // CERES_NO_ACCELERATE_SPARSE

View File

@@ -40,9 +40,9 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "Accelerate.h"
#include "ceres/linear_solver.h" #include "ceres/linear_solver.h"
#include "ceres/sparse_cholesky.h" #include "ceres/sparse_cholesky.h"
#include "Accelerate.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -51,7 +51,8 @@ class CompressedRowSparseMatrix;
class TripletSparseMatrix; class TripletSparseMatrix;
template<typename Scalar> template<typename Scalar>
struct SparseTypesTrait {}; struct SparseTypesTrait {
};
template<> template<>
struct SparseTypesTrait<double> { struct SparseTypesTrait<double> {
@@ -75,10 +76,8 @@ class AccelerateSparse {
using DenseVector = typename SparseTypesTrait<Scalar>::DenseVector; using DenseVector = typename SparseTypesTrait<Scalar>::DenseVector;
// Use ASSparseMatrix to avoid collision with ceres::internal::SparseMatrix. // Use ASSparseMatrix to avoid collision with ceres::internal::SparseMatrix.
using ASSparseMatrix = typename SparseTypesTrait<Scalar>::SparseMatrix; using ASSparseMatrix = typename SparseTypesTrait<Scalar>::SparseMatrix;
using SymbolicFactorization = using SymbolicFactorization = typename SparseTypesTrait<Scalar>::SymbolicFactorization;
typename SparseTypesTrait<Scalar>::SymbolicFactorization; using NumericFactorization = typename SparseTypesTrait<Scalar>::NumericFactorization;
using NumericFactorization =
typename SparseTypesTrait<Scalar>::NumericFactorization;
// Solves a linear system given its symbolic (reference counted within // Solves a linear system given its symbolic (reference counted within
// NumericFactorization) and numeric factorization. // NumericFactorization) and numeric factorization.
@@ -140,8 +139,8 @@ class AppleAccelerateCholesky : public SparseCholesky {
Eigen::Matrix<Scalar, Eigen::Dynamic, 1> scalar_rhs_and_solution_; Eigen::Matrix<Scalar, Eigen::Dynamic, 1> scalar_rhs_and_solution_;
}; };
} // namespace internal }
} // namespace ceres }
#endif // CERES_NO_ACCELERATE_SPARSE #endif // CERES_NO_ACCELERATE_SPARSE

View File

@@ -35,7 +35,6 @@
#include <cstddef> #include <cstddef>
#include <string> #include <string>
#include <vector> #include <vector>
#include "ceres/stringprintf.h" #include "ceres/stringprintf.h"
#include "ceres/types.h" #include "ceres/types.h"
namespace ceres { namespace ceres {
@@ -93,13 +92,14 @@ void AppendArrayToString(const int size, const double* x, string* result) {
void MapValuesToContiguousRange(const int size, int* array) { void MapValuesToContiguousRange(const int size, int* array) {
std::vector<int> unique_values(array, array + size); std::vector<int> unique_values(array, array + size);
std::sort(unique_values.begin(), unique_values.end()); std::sort(unique_values.begin(), unique_values.end());
unique_values.erase(std::unique(unique_values.begin(), unique_values.end()), unique_values.erase(std::unique(unique_values.begin(),
unique_values.end()),
unique_values.end()); unique_values.end());
for (int i = 0; i < size; ++i) { for (int i = 0; i < size; ++i) {
array[i] = array[i] = std::lower_bound(unique_values.begin(),
std::lower_bound(unique_values.begin(), unique_values.end(), array[i]) - unique_values.end(),
unique_values.begin(); array[i]) - unique_values.begin();
} }
} }

View File

@@ -44,7 +44,6 @@
#define CERES_INTERNAL_ARRAY_UTILS_H_ #define CERES_INTERNAL_ARRAY_UTILS_H_
#include <string> #include <string>
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
namespace ceres { namespace ceres {
@@ -52,22 +51,20 @@ namespace internal {
// Fill the array x with an impossible value that the user code is // Fill the array x with an impossible value that the user code is
// never expected to compute. // never expected to compute.
CERES_EXPORT_INTERNAL void InvalidateArray(int size, double* x); void InvalidateArray(int size, double* x);
// Check if all the entries of the array x are valid, i.e. all the // 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 // values in the array should be finite and none of them should be
// equal to the "impossible" value used by InvalidateArray. // equal to the "impossible" value used by InvalidateArray.
CERES_EXPORT_INTERNAL bool IsArrayValid(int size, const double* x); bool IsArrayValid(int size, const double* x);
// If the array contains an invalid value, return the index for it, // If the array contains an invalid value, return the index for it,
// otherwise return size. // otherwise return size.
CERES_EXPORT_INTERNAL int FindInvalidValue(const int size, const double* x); int FindInvalidValue(const int size, const double* x);
// Utility routine to print an array of doubles to a string. If the // 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. // array pointer is NULL, it is treated as an array of zeros.
CERES_EXPORT_INTERNAL void AppendArrayToString(const int size, void AppendArrayToString(const int size, const double* x, std::string* result);
const double* x,
std::string* result);
// This routine takes an array of integer values, sorts and uniques // This routine takes an array of integer values, sorts and uniques
// them and then maps each value in the array to its position in the // them and then maps each value in the array to its position in the
@@ -82,7 +79,7 @@ CERES_EXPORT_INTERNAL void AppendArrayToString(const int size,
// gets mapped to // gets mapped to
// //
// [1 0 2 3 0 1 3] // [1 0 2 3 0 1 3]
CERES_EXPORT_INTERNAL void MapValuesToContiguousRange(int size, int* array); void MapValuesToContiguousRange(int size, int* array);
} // namespace internal } // namespace internal
} // namespace ceres } // namespace ceres

View File

@@ -29,7 +29,6 @@
// Author: sameeragarwal@google.com (Sameer Agarwal) // Author: sameeragarwal@google.com (Sameer Agarwal)
#include "ceres/blas.h" #include "ceres/blas.h"
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
#include "glog/logging.h" #include "glog/logging.h"

View File

@@ -31,7 +31,6 @@
#include "ceres/block_evaluate_preparer.h" #include "ceres/block_evaluate_preparer.h"
#include <vector> #include <vector>
#include "ceres/block_sparse_matrix.h" #include "ceres/block_sparse_matrix.h"
#include "ceres/casts.h" #include "ceres/casts.h"
#include "ceres/parameter_block.h" #include "ceres/parameter_block.h"
@@ -54,8 +53,10 @@ void BlockEvaluatePreparer::Prepare(const ResidualBlock* residual_block,
double** jacobians) { double** jacobians) {
// If the overall jacobian is not available, use the scratch space. // If the overall jacobian is not available, use the scratch space.
if (jacobian == NULL) { if (jacobian == NULL) {
scratch_evaluate_preparer_.Prepare( scratch_evaluate_preparer_.Prepare(residual_block,
residual_block, residual_block_index, jacobian, jacobians); residual_block_index,
jacobian,
jacobians);
return; return;
} }

View File

@@ -30,9 +30,9 @@
#include "ceres/block_jacobi_preconditioner.h" #include "ceres/block_jacobi_preconditioner.h"
#include "ceres/block_random_access_diagonal_matrix.h"
#include "ceres/block_sparse_matrix.h" #include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h" #include "ceres/block_structure.h"
#include "ceres/block_random_access_diagonal_matrix.h"
#include "ceres/casts.h" #include "ceres/casts.h"
#include "ceres/internal/eigen.h" #include "ceres/internal/eigen.h"
@@ -65,11 +65,13 @@ bool BlockJacobiPreconditioner::UpdateImpl(const BlockSparseMatrix& A,
const int col_block_size = bs->cols[block_id].size; const int col_block_size = bs->cols[block_id].size;
int r, c, row_stride, col_stride; int r, c, row_stride, col_stride;
CellInfo* cell_info = CellInfo* cell_info = m_->GetCell(block_id, block_id,
m_->GetCell(block_id, block_id, &r, &c, &row_stride, &col_stride); &r, &c,
&row_stride, &col_stride);
MatrixRef m(cell_info->values, row_stride, col_stride); MatrixRef m(cell_info->values, row_stride, col_stride);
ConstMatrixRef b( ConstMatrixRef b(values + cells[j].position,
values + cells[j].position, row_block_size, col_block_size); row_block_size,
col_block_size);
m.block(r, c, col_block_size, col_block_size) += b.transpose() * b; m.block(r, c, col_block_size, col_block_size) += b.transpose() * b;
} }
} }
@@ -80,7 +82,9 @@ bool BlockJacobiPreconditioner::UpdateImpl(const BlockSparseMatrix& A,
for (int i = 0; i < bs->cols.size(); ++i) { for (int i = 0; i < bs->cols.size(); ++i) {
const int block_size = bs->cols[i].size; const int block_size = bs->cols[i].size;
int r, c, row_stride, col_stride; int r, c, row_stride, col_stride;
CellInfo* cell_info = m_->GetCell(i, i, &r, &c, &row_stride, &col_stride); CellInfo* cell_info = m_->GetCell(i, i,
&r, &c,
&row_stride, &col_stride);
MatrixRef m(cell_info->values, row_stride, col_stride); MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block_size, block_size).diagonal() += m.block(r, c, block_size, block_size).diagonal() +=
ConstVectorRef(D + position, block_size).array().square().matrix(); ConstVectorRef(D + position, block_size).array().square().matrix();

View File

@@ -32,9 +32,7 @@
#define CERES_INTERNAL_BLOCK_JACOBI_PRECONDITIONER_H_ #define CERES_INTERNAL_BLOCK_JACOBI_PRECONDITIONER_H_
#include <memory> #include <memory>
#include "ceres/block_random_access_diagonal_matrix.h" #include "ceres/block_random_access_diagonal_matrix.h"
#include "ceres/internal/port.h"
#include "ceres/preconditioner.h" #include "ceres/preconditioner.h"
namespace ceres { namespace ceres {
@@ -53,8 +51,7 @@ struct CompressedRowBlockStructure;
// update the matrix by running Update(A, D). The values of the matrix A are // update the matrix by running Update(A, D). The values of the matrix A are
// inspected to construct the preconditioner. The vector D is applied as the // inspected to construct the preconditioner. The vector D is applied as the
// D^TD diagonal term. // D^TD diagonal term.
class CERES_EXPORT_INTERNAL BlockJacobiPreconditioner class BlockJacobiPreconditioner : public BlockSparseMatrixPreconditioner {
: public BlockSparseMatrixPreconditioner {
public: public:
// A must remain valid while the BlockJacobiPreconditioner is. // A must remain valid while the BlockJacobiPreconditioner is.
explicit BlockJacobiPreconditioner(const BlockSparseMatrix& A); explicit BlockJacobiPreconditioner(const BlockSparseMatrix& A);

View File

@@ -32,11 +32,11 @@
#include "ceres/block_evaluate_preparer.h" #include "ceres/block_evaluate_preparer.h"
#include "ceres/block_sparse_matrix.h" #include "ceres/block_sparse_matrix.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/port.h"
#include "ceres/parameter_block.h" #include "ceres/parameter_block.h"
#include "ceres/program.h" #include "ceres/program.h"
#include "ceres/residual_block.h" #include "ceres/residual_block.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/port.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {

View File

@@ -39,7 +39,6 @@
#define CERES_INTERNAL_BLOCK_JACOBIAN_WRITER_H_ #define CERES_INTERNAL_BLOCK_JACOBIAN_WRITER_H_
#include <vector> #include <vector>
#include "ceres/evaluator.h" #include "ceres/evaluator.h"
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
@@ -53,7 +52,8 @@ class SparseMatrix;
// TODO(sameeragarwal): This class needs documemtation. // TODO(sameeragarwal): This class needs documemtation.
class BlockJacobianWriter { class BlockJacobianWriter {
public: public:
BlockJacobianWriter(const Evaluator::Options& options, Program* program); BlockJacobianWriter(const Evaluator::Options& options,
Program* program);
// JacobianWriter interface. // JacobianWriter interface.

View File

@@ -31,7 +31,6 @@
#include "ceres/block_random_access_dense_matrix.h" #include "ceres/block_random_access_dense_matrix.h"
#include <vector> #include <vector>
#include "ceres/internal/eigen.h" #include "ceres/internal/eigen.h"
#include "glog/logging.h" #include "glog/logging.h"
@@ -60,7 +59,8 @@ BlockRandomAccessDenseMatrix::BlockRandomAccessDenseMatrix(
// Assume that the user does not hold any locks on any cell blocks // Assume that the user does not hold any locks on any cell blocks
// when they are calling SetZero. // when they are calling SetZero.
BlockRandomAccessDenseMatrix::~BlockRandomAccessDenseMatrix() {} BlockRandomAccessDenseMatrix::~BlockRandomAccessDenseMatrix() {
}
CellInfo* BlockRandomAccessDenseMatrix::GetCell(const int row_block_id, CellInfo* BlockRandomAccessDenseMatrix::GetCell(const int row_block_id,
const int col_block_id, const int col_block_id,

View File

@@ -31,10 +31,11 @@
#ifndef CERES_INTERNAL_BLOCK_RANDOM_ACCESS_DENSE_MATRIX_H_ #ifndef CERES_INTERNAL_BLOCK_RANDOM_ACCESS_DENSE_MATRIX_H_
#define CERES_INTERNAL_BLOCK_RANDOM_ACCESS_DENSE_MATRIX_H_ #define CERES_INTERNAL_BLOCK_RANDOM_ACCESS_DENSE_MATRIX_H_
#include "ceres/block_random_access_matrix.h"
#include <memory> #include <memory>
#include <vector> #include <vector>
#include "ceres/block_random_access_matrix.h"
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
namespace ceres { namespace ceres {
@@ -50,8 +51,7 @@ namespace internal {
// pair. // pair.
// //
// ReturnCell is a nop. // ReturnCell is a nop.
class CERES_EXPORT_INTERNAL BlockRandomAccessDenseMatrix class BlockRandomAccessDenseMatrix : public BlockRandomAccessMatrix {
: public BlockRandomAccessMatrix {
public: public:
// blocks is a vector of block sizes. The resulting matrix has // blocks is a vector of block sizes. The resulting matrix has
// blocks.size() * blocks.size() cells. // blocks.size() * blocks.size() cells.

View File

@@ -63,8 +63,9 @@ BlockRandomAccessDiagonalMatrix::BlockRandomAccessDiagonalMatrix(
num_nonzeros += blocks_[i] * blocks_[i]; num_nonzeros += blocks_[i] * blocks_[i];
} }
VLOG(1) << "Matrix Size [" << num_cols << "," << num_cols << "] " VLOG(1) << "Matrix Size [" << num_cols
<< num_nonzeros; << "," << num_cols
<< "] " << num_nonzeros;
tsm_.reset(new TripletSparseMatrix(num_cols, num_cols, num_nonzeros)); tsm_.reset(new TripletSparseMatrix(num_cols, num_cols, num_nonzeros));
tsm_->set_num_nonzeros(num_nonzeros); tsm_->set_num_nonzeros(num_nonzeros);
@@ -115,7 +116,8 @@ CellInfo* BlockRandomAccessDiagonalMatrix::GetCell(int row_block_id,
// when they are calling SetZero. // when they are calling SetZero.
void BlockRandomAccessDiagonalMatrix::SetZero() { void BlockRandomAccessDiagonalMatrix::SetZero() {
if (tsm_->num_nonzeros()) { if (tsm_->num_nonzeros()) {
VectorRef(tsm_->mutable_values(), tsm_->num_nonzeros()).setZero(); VectorRef(tsm_->mutable_values(),
tsm_->num_nonzeros()).setZero();
} }
} }
@@ -124,8 +126,11 @@ void BlockRandomAccessDiagonalMatrix::Invert() {
for (int i = 0; i < blocks_.size(); ++i) { for (int i = 0; i < blocks_.size(); ++i) {
const int block_size = blocks_[i]; const int block_size = blocks_[i];
MatrixRef block(values, block_size, block_size); MatrixRef block(values, block_size, block_size);
block = block.selfadjointView<Eigen::Upper>().llt().solve( block =
Matrix::Identity(block_size, block_size)); block
.selfadjointView<Eigen::Upper>()
.llt()
.solve(Matrix::Identity(block_size, block_size));
values += block_size * block_size; values += block_size * block_size;
} }
} }

View File

@@ -46,13 +46,11 @@ namespace internal {
// A thread safe block diagonal matrix implementation of // A thread safe block diagonal matrix implementation of
// BlockRandomAccessMatrix. // BlockRandomAccessMatrix.
class CERES_EXPORT_INTERNAL BlockRandomAccessDiagonalMatrix class BlockRandomAccessDiagonalMatrix : public BlockRandomAccessMatrix {
: public BlockRandomAccessMatrix {
public: public:
// blocks is an array of block sizes. // blocks is an array of block sizes.
explicit BlockRandomAccessDiagonalMatrix(const std::vector<int>& blocks); explicit BlockRandomAccessDiagonalMatrix(const std::vector<int>& blocks);
BlockRandomAccessDiagonalMatrix(const BlockRandomAccessDiagonalMatrix&) = BlockRandomAccessDiagonalMatrix(const BlockRandomAccessDiagonalMatrix&) = delete;
delete;
void operator=(const BlockRandomAccessDiagonalMatrix&) = delete; void operator=(const BlockRandomAccessDiagonalMatrix&) = delete;
// The destructor is not thread safe. It assumes that no one is // The destructor is not thread safe. It assumes that no one is

View File

@@ -33,7 +33,8 @@
namespace ceres { namespace ceres {
namespace internal { namespace internal {
BlockRandomAccessMatrix::~BlockRandomAccessMatrix() {} BlockRandomAccessMatrix::~BlockRandomAccessMatrix() {
}
} // namespace internal } // namespace internal
} // namespace ceres } // namespace ceres

View File

@@ -35,8 +35,6 @@
#include <mutex> #include <mutex>
#include "ceres/internal/port.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -93,7 +91,7 @@ struct CellInfo {
std::mutex m; std::mutex m;
}; };
class CERES_EXPORT_INTERNAL BlockRandomAccessMatrix { class BlockRandomAccessMatrix {
public: public:
virtual ~BlockRandomAccessMatrix(); virtual ~BlockRandomAccessMatrix();

View File

@@ -50,8 +50,10 @@ using std::set;
using std::vector; using std::vector;
BlockRandomAccessSparseMatrix::BlockRandomAccessSparseMatrix( BlockRandomAccessSparseMatrix::BlockRandomAccessSparseMatrix(
const vector<int>& blocks, const set<pair<int, int>>& block_pairs) const vector<int>& blocks,
: kMaxRowBlocks(10 * 1000 * 1000), blocks_(blocks) { const set<pair<int, int>>& block_pairs)
: kMaxRowBlocks(10 * 1000 * 1000),
blocks_(blocks) {
CHECK_LT(blocks.size(), kMaxRowBlocks); CHECK_LT(blocks.size(), kMaxRowBlocks);
// Build the row/column layout vector and count the number of scalar // Build the row/column layout vector and count the number of scalar
@@ -73,8 +75,9 @@ BlockRandomAccessSparseMatrix::BlockRandomAccessSparseMatrix(
num_nonzeros += row_block_size * col_block_size; num_nonzeros += row_block_size * col_block_size;
} }
VLOG(1) << "Matrix Size [" << num_cols << "," << num_cols << "] " VLOG(1) << "Matrix Size [" << num_cols
<< num_nonzeros; << "," << num_cols
<< "] " << num_nonzeros;
tsm_.reset(new TripletSparseMatrix(num_cols, num_cols, num_nonzeros)); tsm_.reset(new TripletSparseMatrix(num_cols, num_cols, num_nonzeros));
tsm_->set_num_nonzeros(num_nonzeros); tsm_->set_num_nonzeros(num_nonzeros);
@@ -144,7 +147,8 @@ CellInfo* BlockRandomAccessSparseMatrix::GetCell(int row_block_id,
// when they are calling SetZero. // when they are calling SetZero.
void BlockRandomAccessSparseMatrix::SetZero() { void BlockRandomAccessSparseMatrix::SetZero() {
if (tsm_->num_nonzeros()) { if (tsm_->num_nonzeros()) {
VectorRef(tsm_->mutable_values(), tsm_->num_nonzeros()).setZero(); VectorRef(tsm_->mutable_values(),
tsm_->num_nonzeros()).setZero();
} }
} }
@@ -160,9 +164,7 @@ void BlockRandomAccessSparseMatrix::SymmetricRightMultiply(const double* x,
const int col_block_pos = block_positions_[col]; const int col_block_pos = block_positions_[col];
MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>( MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
cell_position_and_data.second, cell_position_and_data.second, row_block_size, col_block_size,
row_block_size,
col_block_size,
x + col_block_pos, x + col_block_pos,
y + row_block_pos); y + row_block_pos);
@@ -172,9 +174,7 @@ void BlockRandomAccessSparseMatrix::SymmetricRightMultiply(const double* x,
// triangular multiply also. // triangular multiply also.
if (row != col) { if (row != col) {
MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>( MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
cell_position_and_data.second, cell_position_and_data.second, row_block_size, col_block_size,
row_block_size,
col_block_size,
x + row_block_pos, x + row_block_pos,
y + col_block_pos); y + col_block_pos);
} }

View File

@@ -39,10 +39,10 @@
#include <vector> #include <vector>
#include "ceres/block_random_access_matrix.h" #include "ceres/block_random_access_matrix.h"
#include "ceres/internal/port.h"
#include "ceres/small_blas.h"
#include "ceres/triplet_sparse_matrix.h" #include "ceres/triplet_sparse_matrix.h"
#include "ceres/internal/port.h"
#include "ceres/types.h" #include "ceres/types.h"
#include "ceres/small_blas.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -51,8 +51,7 @@ namespace internal {
// BlockRandomAccessMatrix. Internally a TripletSparseMatrix is used // BlockRandomAccessMatrix. Internally a TripletSparseMatrix is used
// for doing the actual storage. This class augments this matrix with // for doing the actual storage. This class augments this matrix with
// an unordered_map that allows random read/write access. // an unordered_map that allows random read/write access.
class CERES_EXPORT_INTERNAL BlockRandomAccessSparseMatrix class BlockRandomAccessSparseMatrix : public BlockRandomAccessMatrix {
: public BlockRandomAccessMatrix {
public: public:
// blocks is an array of block sizes. block_pairs is a set of // blocks is an array of block sizes. block_pairs is a set of
// <row_block_id, col_block_id> pairs to identify the non-zero cells // <row_block_id, col_block_id> pairs to identify the non-zero cells

View File

@@ -30,10 +30,9 @@
#include "ceres/block_sparse_matrix.h" #include "ceres/block_sparse_matrix.h"
#include <algorithm>
#include <cstddef> #include <cstddef>
#include <algorithm>
#include <vector> #include <vector>
#include "ceres/block_structure.h" #include "ceres/block_structure.h"
#include "ceres/internal/eigen.h" #include "ceres/internal/eigen.h"
#include "ceres/random.h" #include "ceres/random.h"
@@ -78,8 +77,8 @@ BlockSparseMatrix::BlockSparseMatrix(
CHECK_GE(num_rows_, 0); CHECK_GE(num_rows_, 0);
CHECK_GE(num_cols_, 0); CHECK_GE(num_cols_, 0);
CHECK_GE(num_nonzeros_, 0); CHECK_GE(num_nonzeros_, 0);
VLOG(2) << "Allocating values array with " << num_nonzeros_ * sizeof(double) VLOG(2) << "Allocating values array with "
<< " bytes."; // NOLINT << num_nonzeros_ * sizeof(double) << " bytes."; // NOLINT
values_.reset(new double[num_nonzeros_]); values_.reset(new double[num_nonzeros_]);
max_num_nonzeros_ = num_nonzeros_; max_num_nonzeros_ = num_nonzeros_;
CHECK(values_ != nullptr); CHECK(values_ != nullptr);
@@ -102,9 +101,7 @@ void BlockSparseMatrix::RightMultiply(const double* x, double* y) const {
int col_block_size = block_structure_->cols[col_block_id].size; int col_block_size = block_structure_->cols[col_block_id].size;
int col_block_pos = block_structure_->cols[col_block_id].position; int col_block_pos = block_structure_->cols[col_block_id].position;
MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>( MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
values_.get() + cells[j].position, values_.get() + cells[j].position, row_block_size, col_block_size,
row_block_size,
col_block_size,
x + col_block_pos, x + col_block_pos,
y + row_block_pos); y + row_block_pos);
} }
@@ -124,9 +121,7 @@ void BlockSparseMatrix::LeftMultiply(const double* x, double* y) const {
int col_block_size = block_structure_->cols[col_block_id].size; int col_block_size = block_structure_->cols[col_block_id].size;
int col_block_pos = block_structure_->cols[col_block_id].position; int col_block_pos = block_structure_->cols[col_block_id].position;
MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>( MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
values_.get() + cells[j].position, values_.get() + cells[j].position, row_block_size, col_block_size,
row_block_size,
col_block_size,
x + row_block_pos, x + row_block_pos,
y + col_block_pos); y + col_block_pos);
} }
@@ -143,8 +138,8 @@ void BlockSparseMatrix::SquaredColumnNorm(double* x) const {
int col_block_id = cells[j].block_id; int col_block_id = cells[j].block_id;
int col_block_size = block_structure_->cols[col_block_id].size; int col_block_size = block_structure_->cols[col_block_id].size;
int col_block_pos = block_structure_->cols[col_block_id].position; int col_block_pos = block_structure_->cols[col_block_id].position;
const MatrixRef m( const MatrixRef m(values_.get() + cells[j].position,
values_.get() + cells[j].position, row_block_size, col_block_size); row_block_size, col_block_size);
VectorRef(x + col_block_pos, col_block_size) += m.colwise().squaredNorm(); VectorRef(x + col_block_pos, col_block_size) += m.colwise().squaredNorm();
} }
} }
@@ -160,8 +155,8 @@ void BlockSparseMatrix::ScaleColumns(const double* scale) {
int col_block_id = cells[j].block_id; int col_block_id = cells[j].block_id;
int col_block_size = block_structure_->cols[col_block_id].size; int col_block_size = block_structure_->cols[col_block_id].size;
int col_block_pos = block_structure_->cols[col_block_id].position; int col_block_pos = block_structure_->cols[col_block_id].position;
MatrixRef m( MatrixRef m(values_.get() + cells[j].position,
values_.get() + cells[j].position, row_block_size, col_block_size); row_block_size, col_block_size);
m *= ConstVectorRef(scale + col_block_pos, col_block_size).asDiagonal(); m *= ConstVectorRef(scale + col_block_pos, col_block_size).asDiagonal();
} }
} }
@@ -183,8 +178,8 @@ void BlockSparseMatrix::ToDenseMatrix(Matrix* dense_matrix) const {
int col_block_size = block_structure_->cols[col_block_id].size; int col_block_size = block_structure_->cols[col_block_id].size;
int col_block_pos = block_structure_->cols[col_block_id].position; int col_block_pos = block_structure_->cols[col_block_id].position;
int jac_pos = cells[j].position; int jac_pos = cells[j].position;
m.block(row_block_pos, col_block_pos, row_block_size, col_block_size) += m.block(row_block_pos, col_block_pos, row_block_size, col_block_size)
MatrixRef(values_.get() + jac_pos, row_block_size, col_block_size); += MatrixRef(values_.get() + jac_pos, row_block_size, col_block_size);
} }
} }
} }
@@ -220,7 +215,8 @@ void BlockSparseMatrix::ToTripletSparseMatrix(
// Return a pointer to the block structure. We continue to hold // Return a pointer to the block structure. We continue to hold
// ownership of the object though. // ownership of the object though.
const CompressedRowBlockStructure* BlockSparseMatrix::block_structure() const { const CompressedRowBlockStructure* BlockSparseMatrix::block_structure()
const {
return block_structure_.get(); return block_structure_.get();
} }
@@ -237,8 +233,7 @@ void BlockSparseMatrix::ToTextFile(FILE* file) const {
int jac_pos = cells[j].position; int jac_pos = cells[j].position;
for (int r = 0; r < row_block_size; ++r) { for (int r = 0; r < row_block_size; ++r) {
for (int c = 0; c < col_block_size; ++c) { for (int c = 0; c < col_block_size; ++c) {
fprintf(file, fprintf(file, "% 10d % 10d %17f\n",
"% 10d % 10d %17f\n",
row_block_pos + r, row_block_pos + r,
col_block_pos + c, col_block_pos + c,
values_[jac_pos++]); values_[jac_pos++]);
@@ -374,6 +369,7 @@ BlockSparseMatrix* BlockSparseMatrix::CreateRandomMatrix(
int row_block_position = 0; int row_block_position = 0;
int value_position = 0; int value_position = 0;
for (int r = 0; r < options.num_row_blocks; ++r) { for (int r = 0; r < options.num_row_blocks; ++r) {
const int delta_block_size = const int delta_block_size =
Uniform(options.max_row_block_size - options.min_row_block_size); Uniform(options.max_row_block_size - options.min_row_block_size);
const int row_block_size = options.min_row_block_size + delta_block_size; const int row_block_size = options.min_row_block_size + delta_block_size;

View File

@@ -35,11 +35,9 @@
#define CERES_INTERNAL_BLOCK_SPARSE_MATRIX_H_ #define CERES_INTERNAL_BLOCK_SPARSE_MATRIX_H_
#include <memory> #include <memory>
#include "ceres/block_structure.h" #include "ceres/block_structure.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/port.h"
#include "ceres/sparse_matrix.h" #include "ceres/sparse_matrix.h"
#include "ceres/internal/eigen.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -54,7 +52,7 @@ class TripletSparseMatrix;
// //
// internal/ceres/block_structure.h // internal/ceres/block_structure.h
// //
class CERES_EXPORT_INTERNAL BlockSparseMatrix : public SparseMatrix { class BlockSparseMatrix : public SparseMatrix {
public: public:
// Construct a block sparse matrix with a fully initialized // Construct a block sparse matrix with a fully initialized
// CompressedRowBlockStructure objected. The matrix takes over // CompressedRowBlockStructure objected. The matrix takes over
@@ -79,13 +77,11 @@ class CERES_EXPORT_INTERNAL BlockSparseMatrix : public SparseMatrix {
void ToDenseMatrix(Matrix* dense_matrix) const final; void ToDenseMatrix(Matrix* dense_matrix) const final;
void ToTextFile(FILE* file) const final; void ToTextFile(FILE* file) const final;
// clang-format off
int num_rows() const final { return num_rows_; } int num_rows() const final { return num_rows_; }
int num_cols() const final { return num_cols_; } int num_cols() const final { return num_cols_; }
int num_nonzeros() const final { return num_nonzeros_; } int num_nonzeros() const final { return num_nonzeros_; }
const double* values() const final { return values_.get(); } const double* values() const final { return values_.get(); }
double* mutable_values() final { return values_.get(); } double* mutable_values() final { return values_.get(); }
// clang-format on
void ToTripletSparseMatrix(TripletSparseMatrix* matrix) const; void ToTripletSparseMatrix(TripletSparseMatrix* matrix) const;
const CompressedRowBlockStructure* block_structure() const; const CompressedRowBlockStructure* block_structure() const;
@@ -98,7 +94,8 @@ class CERES_EXPORT_INTERNAL BlockSparseMatrix : public SparseMatrix {
void DeleteRowBlocks(int delta_row_blocks); void DeleteRowBlocks(int delta_row_blocks);
static BlockSparseMatrix* CreateDiagonalMatrix( static BlockSparseMatrix* CreateDiagonalMatrix(
const double* diagonal, const std::vector<Block>& column_blocks); const double* diagonal,
const std::vector<Block>& column_blocks);
struct RandomMatrixOptions { struct RandomMatrixOptions {
int num_row_blocks = 0; int num_row_blocks = 0;

View File

@@ -40,7 +40,6 @@
#include <cstdint> #include <cstdint>
#include <vector> #include <vector>
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
namespace ceres { namespace ceres {

View File

@@ -34,10 +34,9 @@
#include "ceres/c_api.h" #include "ceres/c_api.h"
#include <vector>
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <vector>
#include "ceres/cost_function.h" #include "ceres/cost_function.h"
#include "ceres/loss_function.h" #include "ceres/loss_function.h"
#include "ceres/problem.h" #include "ceres/problem.h"
@@ -71,7 +70,8 @@ class CallbackCostFunction : public ceres::CostFunction {
int num_residuals, int num_residuals,
int num_parameter_blocks, int num_parameter_blocks,
int* parameter_block_sizes) int* parameter_block_sizes)
: cost_function_(cost_function), user_data_(user_data) { : cost_function_(cost_function),
user_data_(user_data) {
set_num_residuals(num_residuals); set_num_residuals(num_residuals);
for (int i = 0; i < num_parameter_blocks; ++i) { for (int i = 0; i < num_parameter_blocks; ++i) {
mutable_parameter_block_sizes()->push_back(parameter_block_sizes[i]); mutable_parameter_block_sizes()->push_back(parameter_block_sizes[i]);
@@ -83,8 +83,10 @@ class CallbackCostFunction : public ceres::CostFunction {
bool Evaluate(double const* const* parameters, bool Evaluate(double const* const* parameters,
double* residuals, double* residuals,
double** jacobians) const final { double** jacobians) const final {
return (*cost_function_)( return (*cost_function_)(user_data_,
user_data_, const_cast<double**>(parameters), residuals, jacobians); const_cast<double**>(parameters),
residuals,
jacobians);
} }
private: private:
@@ -132,8 +134,8 @@ void ceres_free_stock_loss_function_data(void* loss_function_data) {
void ceres_stock_loss_function(void* user_data, void ceres_stock_loss_function(void* user_data,
double squared_norm, double squared_norm,
double out[3]) { double out[3]) {
reinterpret_cast<ceres::LossFunction*>(user_data)->Evaluate(squared_norm, reinterpret_cast<ceres::LossFunction*>(user_data)
out); ->Evaluate(squared_norm, out);
} }
ceres_residual_block_id_t* ceres_problem_add_residual_block( ceres_residual_block_id_t* ceres_problem_add_residual_block(
@@ -157,15 +159,16 @@ ceres_residual_block_id_t* ceres_problem_add_residual_block(
ceres::LossFunction* callback_loss_function = NULL; ceres::LossFunction* callback_loss_function = NULL;
if (loss_function != NULL) { if (loss_function != NULL) {
callback_loss_function = callback_loss_function = new CallbackLossFunction(loss_function,
new CallbackLossFunction(loss_function, loss_function_data); loss_function_data);
} }
std::vector<double*> parameter_blocks(parameters, std::vector<double*> parameter_blocks(parameters,
parameters + num_parameter_blocks); parameters + num_parameter_blocks);
return reinterpret_cast<ceres_residual_block_id_t*>( return reinterpret_cast<ceres_residual_block_id_t*>(
ceres_problem->AddResidualBlock( ceres_problem->AddResidualBlock(callback_cost_function,
callback_cost_function, callback_loss_function, parameter_blocks)); callback_loss_function,
parameter_blocks));
} }
void ceres_solve(ceres_problem_t* c_problem) { void ceres_solve(ceres_problem_t* c_problem) {

View File

@@ -28,10 +28,8 @@
// //
// Author: sameeragarwal@google.com (Sameer Agarwal) // Author: sameeragarwal@google.com (Sameer Agarwal)
#include "ceres/callbacks.h"
#include <iostream> // NO LINT #include <iostream> // NO LINT
#include "ceres/callbacks.h"
#include "ceres/program.h" #include "ceres/program.h"
#include "ceres/stringprintf.h" #include "ceres/stringprintf.h"
#include "glog/logging.h" #include "glog/logging.h"
@@ -78,7 +76,8 @@ CallbackReturnType GradientProblemSolverStateUpdatingCallback::operator()(
LoggingCallback::LoggingCallback(const MinimizerType minimizer_type, LoggingCallback::LoggingCallback(const MinimizerType minimizer_type,
const bool log_to_stdout) const bool log_to_stdout)
: minimizer_type(minimizer_type), log_to_stdout_(log_to_stdout) {} : minimizer_type(minimizer_type),
log_to_stdout_(log_to_stdout) {}
LoggingCallback::~LoggingCallback() {} LoggingCallback::~LoggingCallback() {}
@@ -100,13 +99,11 @@ CallbackReturnType LoggingCallback::operator()(
summary.iteration_time_in_seconds, summary.iteration_time_in_seconds,
summary.cumulative_time_in_seconds); summary.cumulative_time_in_seconds);
} else if (minimizer_type == TRUST_REGION) { } else if (minimizer_type == TRUST_REGION) {
// clang-format off
if (summary.iteration == 0) { if (summary.iteration == 0) {
output = "iter cost cost_change |gradient| |step| tr_ratio tr_radius ls_iter iter_time total_time\n"; // NOLINT output = "iter cost cost_change |gradient| |step| tr_ratio tr_radius ls_iter iter_time total_time\n"; // NOLINT
} }
const char* kReportRowFormat = const char* kReportRowFormat =
"% 4d % 8e % 3.2e % 3.2e % 3.2e % 3.2e % 3.2e % 4d % 3.2e % 3.2e"; // NOLINT "% 4d % 8e % 3.2e % 3.2e % 3.2e % 3.2e % 3.2e % 4d % 3.2e % 3.2e"; // NOLINT
// clang-format on
output += StringPrintf(kReportRowFormat, output += StringPrintf(kReportRowFormat,
summary.iteration, summary.iteration,
summary.cost, summary.cost,

View File

@@ -32,9 +32,8 @@
#define CERES_INTERNAL_CALLBACKS_H_ #define CERES_INTERNAL_CALLBACKS_H_
#include <string> #include <string>
#include "ceres/internal/port.h"
#include "ceres/iteration_callback.h" #include "ceres/iteration_callback.h"
#include "ceres/internal/port.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -48,7 +47,6 @@ class StateUpdatingCallback : public IterationCallback {
StateUpdatingCallback(Program* program, double* parameters); StateUpdatingCallback(Program* program, double* parameters);
virtual ~StateUpdatingCallback(); virtual ~StateUpdatingCallback();
CallbackReturnType operator()(const IterationSummary& summary) final; CallbackReturnType operator()(const IterationSummary& summary) final;
private: private:
Program* program_; Program* program_;
double* parameters_; double* parameters_;
@@ -63,7 +61,6 @@ class GradientProblemSolverStateUpdatingCallback : public IterationCallback {
double* user_parameters); double* user_parameters);
virtual ~GradientProblemSolverStateUpdatingCallback(); virtual ~GradientProblemSolverStateUpdatingCallback();
CallbackReturnType operator()(const IterationSummary& summary) final; CallbackReturnType operator()(const IterationSummary& summary) final;
private: private:
int num_parameters_; int num_parameters_;
const double* internal_parameters_; const double* internal_parameters_;

View File

@@ -31,8 +31,8 @@
#include "ceres/canonical_views_clustering.h" #include "ceres/canonical_views_clustering.h"
#include <unordered_map>
#include <unordered_set> #include <unordered_set>
#include <unordered_map>
#include "ceres/graph.h" #include "ceres/graph.h"
#include "ceres/map_util.h" #include "ceres/map_util.h"
@@ -126,7 +126,8 @@ void CanonicalViewsClustering::ComputeClustering(
// Add canonical view if quality improves, or if minimum is not // Add canonical view if quality improves, or if minimum is not
// yet met, otherwise break. // yet met, otherwise break.
if ((best_difference <= 0) && (centers->size() >= options_.min_views)) { if ((best_difference <= 0) &&
(centers->size() >= options_.min_views)) {
break; break;
} }
@@ -140,7 +141,8 @@ void CanonicalViewsClustering::ComputeClustering(
// Return the set of vertices of the graph which have valid vertex // Return the set of vertices of the graph which have valid vertex
// weights. // weights.
void CanonicalViewsClustering::FindValidViews(IntSet* valid_views) const { void CanonicalViewsClustering::FindValidViews(
IntSet* valid_views) const {
const IntSet& views = graph_->vertices(); const IntSet& views = graph_->vertices();
for (const auto& view : views) { for (const auto& view : views) {
if (graph_->VertexWeight(view) != WeightedGraph<int>::InvalidWeight()) { if (graph_->VertexWeight(view) != WeightedGraph<int>::InvalidWeight()) {
@@ -152,7 +154,8 @@ void CanonicalViewsClustering::FindValidViews(IntSet* valid_views) const {
// Computes the difference in the quality score if 'candidate' were // Computes the difference in the quality score if 'candidate' were
// added to the set of canonical views. // added to the set of canonical views.
double CanonicalViewsClustering::ComputeClusteringQualityDifference( double CanonicalViewsClustering::ComputeClusteringQualityDifference(
const int candidate, const vector<int>& centers) const { const int candidate,
const vector<int>& centers) const {
// View score. // View score.
double difference = double difference =
options_.view_score_weight * graph_->VertexWeight(candidate); options_.view_score_weight * graph_->VertexWeight(candidate);
@@ -189,7 +192,8 @@ void CanonicalViewsClustering::UpdateCanonicalViewAssignments(
for (const auto& neighbor : neighbors) { for (const auto& neighbor : neighbors) {
const double old_similarity = const double old_similarity =
FindWithDefault(view_to_canonical_view_similarity_, neighbor, 0.0); FindWithDefault(view_to_canonical_view_similarity_, neighbor, 0.0);
const double new_similarity = graph_->EdgeWeight(neighbor, canonical_view); const double new_similarity =
graph_->EdgeWeight(neighbor, canonical_view);
if (new_similarity > old_similarity) { if (new_similarity > old_similarity) {
view_to_canonical_view_[neighbor] = canonical_view; view_to_canonical_view_[neighbor] = canonical_view;
view_to_canonical_view_similarity_[neighbor] = new_similarity; view_to_canonical_view_similarity_[neighbor] = new_similarity;
@@ -199,7 +203,8 @@ void CanonicalViewsClustering::UpdateCanonicalViewAssignments(
// Assign a cluster id to each view. // Assign a cluster id to each view.
void CanonicalViewsClustering::ComputeClusterMembership( void CanonicalViewsClustering::ComputeClusterMembership(
const vector<int>& centers, IntMap* membership) const { const vector<int>& centers,
IntMap* membership) const {
CHECK(membership != nullptr); CHECK(membership != nullptr);
membership->clear(); membership->clear();

View File

@@ -45,7 +45,6 @@
#include <vector> #include <vector>
#include "ceres/graph.h" #include "ceres/graph.h"
#include "ceres/internal/port.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -95,13 +94,13 @@ struct CanonicalViewsClusteringOptions;
// It is possible depending on the configuration of the clustering // It is possible depending on the configuration of the clustering
// algorithm that some of the vertices may not be assigned to any // algorithm that some of the vertices may not be assigned to any
// cluster. In this case they are assigned to a cluster with id = -1; // cluster. In this case they are assigned to a cluster with id = -1;
CERES_EXPORT_INTERNAL void ComputeCanonicalViewsClustering( void ComputeCanonicalViewsClustering(
const CanonicalViewsClusteringOptions& options, const CanonicalViewsClusteringOptions& options,
const WeightedGraph<int>& graph, const WeightedGraph<int>& graph,
std::vector<int>* centers, std::vector<int>* centers,
std::unordered_map<int, int>* membership); std::unordered_map<int, int>* membership);
struct CERES_EXPORT_INTERNAL CanonicalViewsClusteringOptions { struct CanonicalViewsClusteringOptions {
// The minimum number of canonical views to compute. // The minimum number of canonical views to compute.
int min_views = 3; int min_views = 3;

View File

@@ -33,9 +33,8 @@
#include <algorithm> #include <algorithm>
#include <memory> #include <memory>
#include "ceres/internal/eigen.h"
#include "ceres/linear_operator.h" #include "ceres/linear_operator.h"
#include "ceres/internal/eigen.h"
namespace ceres { namespace ceres {
namespace internal { namespace internal {
@@ -81,7 +80,8 @@ class SparseMatrix;
class CgnrLinearOperator : public LinearOperator { class CgnrLinearOperator : public LinearOperator {
public: public:
CgnrLinearOperator(const LinearOperator& A, const double *D) CgnrLinearOperator(const LinearOperator& A, const double *D)
: A_(A), D_(D), z_(new double[A.num_rows()]) {} : A_(A), D_(D), z_(new double[A.num_rows()]) {
}
virtual ~CgnrLinearOperator() {} virtual ~CgnrLinearOperator() {}
void RightMultiply(const double* x, double* y) const final { void RightMultiply(const double* x, double* y) const final {
@@ -96,8 +96,8 @@ class CgnrLinearOperator : public LinearOperator {
// y = y + DtDx // y = y + DtDx
if (D_ != NULL) { if (D_ != NULL) {
int n = A_.num_cols(); int n = A_.num_cols();
VectorRef(y, n).array() += VectorRef(y, n).array() += ConstVectorRef(D_, n).array().square() *
ConstVectorRef(D_, n).array().square() * ConstVectorRef(x, n).array(); ConstVectorRef(x, n).array();
} }
} }

View File

@@ -32,7 +32,6 @@
#define CERES_INTERNAL_CGNR_SOLVER_H_ #define CERES_INTERNAL_CGNR_SOLVER_H_
#include <memory> #include <memory>
#include "ceres/linear_solver.h" #include "ceres/linear_solver.h"
namespace ceres { namespace ceres {
@@ -56,7 +55,8 @@ class CgnrSolver : public BlockSparseMatrixSolver {
void operator=(const CgnrSolver&) = delete; void operator=(const CgnrSolver&) = delete;
virtual ~CgnrSolver(); virtual ~CgnrSolver();
Summary SolveImpl(BlockSparseMatrix* A, Summary SolveImpl(
BlockSparseMatrix* A,
const double* b, const double* b,
const LinearSolver::PerSolveOptions& per_solve_options, const LinearSolver::PerSolveOptions& per_solve_options,
double* x) final; double* x) final;

View File

@@ -30,9 +30,8 @@
#include "ceres/compressed_col_sparse_matrix_utils.h" #include "ceres/compressed_col_sparse_matrix_utils.h"
#include <algorithm>
#include <vector> #include <vector>
#include <algorithm>
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
#include "glog/logging.h" #include "glog/logging.h"
@@ -41,7 +40,8 @@ namespace internal {
using std::vector; using std::vector;
void CompressedColumnScalarMatrixToBlockMatrix(const int* scalar_rows, void CompressedColumnScalarMatrixToBlockMatrix(
const int* scalar_rows,
const int* scalar_cols, const int* scalar_cols,
const vector<int>& row_blocks, const vector<int>& row_blocks,
const vector<int>& col_blocks, const vector<int>& col_blocks,
@@ -71,8 +71,10 @@ void CompressedColumnScalarMatrixToBlockMatrix(const int* scalar_rows,
for (int col_block = 0; col_block < num_col_blocks; ++col_block) { for (int col_block = 0; col_block < num_col_blocks; ++col_block) {
int column_size = 0; int column_size = 0;
for (int idx = scalar_cols[c]; idx < scalar_cols[c + 1]; ++idx) { for (int idx = scalar_cols[c]; idx < scalar_cols[c + 1]; ++idx) {
vector<int>::const_iterator it = std::lower_bound( vector<int>::const_iterator it =
row_block_starts.begin(), row_block_starts.end(), scalar_rows[idx]); std::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 // Since we are using lower_bound, it will return the row id
// where the row block starts. For everything but the first row // where the row block starts. For everything but the first row
// of the block, where these values will be the same, we can // of the block, where these values will be the same, we can

View File

@@ -32,7 +32,6 @@
#define CERES_INTERNAL_COMPRESSED_COL_SPARSE_MATRIX_UTILS_H_ #define CERES_INTERNAL_COMPRESSED_COL_SPARSE_MATRIX_UTILS_H_
#include <vector> #include <vector>
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
namespace ceres { namespace ceres {
@@ -48,7 +47,7 @@ namespace internal {
// and column block j, then it is expected that A contains at least // 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, // 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. // as that entry is used to detect the presence of a non-zero c_ij.
CERES_EXPORT_INTERNAL void CompressedColumnScalarMatrixToBlockMatrix( void CompressedColumnScalarMatrixToBlockMatrix(
const int* scalar_rows, const int* scalar_rows,
const int* scalar_cols, const int* scalar_cols,
const std::vector<int>& row_blocks, const std::vector<int>& row_blocks,
@@ -59,7 +58,7 @@ CERES_EXPORT_INTERNAL void CompressedColumnScalarMatrixToBlockMatrix(
// Given a set of blocks and a permutation of these blocks, compute // Given a set of blocks and a permutation of these blocks, compute
// the corresponding "scalar" ordering, where the scalar ordering of // the corresponding "scalar" ordering, where the scalar ordering of
// size sum(blocks). // size sum(blocks).
CERES_EXPORT_INTERNAL void BlockOrderingToScalarOrdering( void BlockOrderingToScalarOrdering(
const std::vector<int>& blocks, const std::vector<int>& blocks,
const std::vector<int>& block_ordering, const std::vector<int>& block_ordering,
std::vector<int>* scalar_ordering); std::vector<int>* scalar_ordering);

View File

@@ -44,21 +44,23 @@
namespace ceres { namespace ceres {
namespace internal { namespace internal {
using std::adjacent_find;
using std::make_pair; using std::make_pair;
using std::pair; using std::pair;
using std::vector; using std::vector;
using std::adjacent_find;
void CompressedRowJacobianWriter::PopulateJacobianRowAndColumnBlockVectors( void CompressedRowJacobianWriter::PopulateJacobianRowAndColumnBlockVectors(
const Program* program, CompressedRowSparseMatrix* jacobian) { const Program* program, CompressedRowSparseMatrix* jacobian) {
const vector<ParameterBlock*>& parameter_blocks = program->parameter_blocks(); const vector<ParameterBlock*>& parameter_blocks =
program->parameter_blocks();
vector<int>& col_blocks = *(jacobian->mutable_col_blocks()); vector<int>& col_blocks = *(jacobian->mutable_col_blocks());
col_blocks.resize(parameter_blocks.size()); col_blocks.resize(parameter_blocks.size());
for (int i = 0; i < parameter_blocks.size(); ++i) { for (int i = 0; i < parameter_blocks.size(); ++i) {
col_blocks[i] = parameter_blocks[i]->LocalSize(); col_blocks[i] = parameter_blocks[i]->LocalSize();
} }
const vector<ResidualBlock*>& residual_blocks = program->residual_blocks(); const vector<ResidualBlock*>& residual_blocks =
program->residual_blocks();
vector<int>& row_blocks = *(jacobian->mutable_row_blocks()); vector<int>& row_blocks = *(jacobian->mutable_row_blocks());
row_blocks.resize(residual_blocks.size()); row_blocks.resize(residual_blocks.size());
for (int i = 0; i < residual_blocks.size(); ++i) { for (int i = 0; i < residual_blocks.size(); ++i) {
@@ -70,7 +72,8 @@ void CompressedRowJacobianWriter::GetOrderedParameterBlocks(
const Program* program, const Program* program,
int residual_id, int residual_id,
vector<pair<int, int>>* evaluated_jacobian_blocks) { vector<pair<int, int>>* evaluated_jacobian_blocks) {
const ResidualBlock* residual_block = program->residual_blocks()[residual_id]; const ResidualBlock* residual_block =
program->residual_blocks()[residual_id];
const int num_parameter_blocks = residual_block->NumParameterBlocks(); const int num_parameter_blocks = residual_block->NumParameterBlocks();
for (int j = 0; j < num_parameter_blocks; ++j) { for (int j = 0; j < num_parameter_blocks; ++j) {
@@ -85,7 +88,8 @@ void CompressedRowJacobianWriter::GetOrderedParameterBlocks(
} }
SparseMatrix* CompressedRowJacobianWriter::CreateJacobian() const { SparseMatrix* CompressedRowJacobianWriter::CreateJacobian() const {
const vector<ResidualBlock*>& residual_blocks = program_->residual_blocks(); const vector<ResidualBlock*>& residual_blocks =
program_->residual_blocks();
int total_num_residuals = program_->NumResiduals(); int total_num_residuals = program_->NumResiduals();
int total_num_effective_parameters = program_->NumEffectiveParameters(); int total_num_effective_parameters = program_->NumEffectiveParameters();
@@ -108,7 +112,8 @@ SparseMatrix* CompressedRowJacobianWriter::CreateJacobian() const {
// Allocate more space than needed to store the jacobian so that when the LM // Allocate more space than needed to store the jacobian so that when the LM
// algorithm adds the diagonal, no reallocation is necessary. This reduces // algorithm adds the diagonal, no reallocation is necessary. This reduces
// peak memory usage significantly. // peak memory usage significantly.
CompressedRowSparseMatrix* jacobian = new CompressedRowSparseMatrix( CompressedRowSparseMatrix* jacobian =
new CompressedRowSparseMatrix(
total_num_residuals, total_num_residuals,
total_num_effective_parameters, total_num_effective_parameters,
num_jacobian_nonzeros + total_num_effective_parameters); num_jacobian_nonzeros + total_num_effective_parameters);
@@ -143,7 +148,8 @@ SparseMatrix* CompressedRowJacobianWriter::CreateJacobian() const {
std::string parameter_block_description; std::string parameter_block_description;
for (int j = 0; j < num_parameter_blocks; ++j) { for (int j = 0; j < num_parameter_blocks; ++j) {
ParameterBlock* parameter_block = residual_block->parameter_blocks()[j]; ParameterBlock* parameter_block = residual_block->parameter_blocks()[j];
parameter_block_description += parameter_block->ToString() + "\n"; parameter_block_description +=
parameter_block->ToString() + "\n";
} }
LOG(FATAL) << "Ceres internal error: " LOG(FATAL) << "Ceres internal error: "
<< "Duplicate parameter blocks detected in a cost function. " << "Duplicate parameter blocks detected in a cost function. "

View File

@@ -50,7 +50,8 @@ class CompressedRowJacobianWriter {
public: public:
CompressedRowJacobianWriter(Evaluator::Options /* ignored */, CompressedRowJacobianWriter(Evaluator::Options /* ignored */,
Program* program) Program* program)
: program_(program) {} : program_(program) {
}
// PopulateJacobianRowAndColumnBlockVectors sets col_blocks and // PopulateJacobianRowAndColumnBlockVectors sets col_blocks and
// row_blocks for a CompressedRowSparseMatrix, based on the // row_blocks for a CompressedRowSparseMatrix, based on the
@@ -63,7 +64,8 @@ class CompressedRowJacobianWriter {
// (Jacobian writers do not fall under any type hierarchy; they only // (Jacobian writers do not fall under any type hierarchy; they only
// have to provide an interface as specified in program_evaluator.h). // have to provide an interface as specified in program_evaluator.h).
static void PopulateJacobianRowAndColumnBlockVectors( static void PopulateJacobianRowAndColumnBlockVectors(
const Program* program, CompressedRowSparseMatrix* jacobian); const Program* program,
CompressedRowSparseMatrix* jacobian);
// It is necessary to determine the order of the jacobian blocks // It is necessary to determine the order of the jacobian blocks
// before copying them into a CompressedRowSparseMatrix (or derived // before copying them into a CompressedRowSparseMatrix (or derived

View File

@@ -33,7 +33,6 @@
#include <algorithm> #include <algorithm>
#include <numeric> #include <numeric>
#include <vector> #include <vector>
#include "ceres/crs_matrix.h" #include "ceres/crs_matrix.h"
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
#include "ceres/random.h" #include "ceres/random.h"

View File

@@ -32,7 +32,6 @@
#define CERES_INTERNAL_COMPRESSED_ROW_SPARSE_MATRIX_H_ #define CERES_INTERNAL_COMPRESSED_ROW_SPARSE_MATRIX_H_
#include <vector> #include <vector>
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
#include "ceres/sparse_matrix.h" #include "ceres/sparse_matrix.h"
#include "ceres/types.h" #include "ceres/types.h"
@@ -46,7 +45,7 @@ namespace internal {
class TripletSparseMatrix; class TripletSparseMatrix;
class CERES_EXPORT_INTERNAL CompressedRowSparseMatrix : public SparseMatrix { class CompressedRowSparseMatrix : public SparseMatrix {
public: public:
enum StorageType { enum StorageType {
UNSYMMETRIC, UNSYMMETRIC,

View File

@@ -152,6 +152,7 @@ class ConcurrentQueue {
bool wait_; bool wait_;
}; };
} // namespace internal } // namespace internal
} // namespace ceres } // namespace ceres

View File

@@ -68,8 +68,7 @@ ConditionedCostFunction::ConditionedCostFunction(
ConditionedCostFunction::~ConditionedCostFunction() { ConditionedCostFunction::~ConditionedCostFunction() {
if (ownership_ == TAKE_OWNERSHIP) { if (ownership_ == TAKE_OWNERSHIP) {
STLDeleteUniqueContainerPointers(conditioners_.begin(), STLDeleteUniqueContainerPointers(conditioners_.begin(), conditioners_.end());
conditioners_.end());
} else { } else {
wrapped_cost_function_.release(); wrapped_cost_function_.release();
} }
@@ -78,8 +77,8 @@ ConditionedCostFunction::~ConditionedCostFunction() {
bool ConditionedCostFunction::Evaluate(double const* const* parameters, bool ConditionedCostFunction::Evaluate(double const* const* parameters,
double* residuals, double* residuals,
double** jacobians) const { double** jacobians) const {
bool success = bool success = wrapped_cost_function_->Evaluate(parameters, residuals,
wrapped_cost_function_->Evaluate(parameters, residuals, jacobians); jacobians);
if (!success) { if (!success) {
return false; return false;
} }
@@ -103,8 +102,9 @@ bool ConditionedCostFunction::Evaluate(double const* const* parameters,
double unconditioned_residual = residuals[r]; double unconditioned_residual = residuals[r];
double* parameter_pointer = &unconditioned_residual; double* parameter_pointer = &unconditioned_residual;
success = conditioners_[r]->Evaluate( success = conditioners_[r]->Evaluate(&parameter_pointer,
&parameter_pointer, &residuals[r], conditioner_derivative_pointer2); &residuals[r],
conditioner_derivative_pointer2);
if (!success) { if (!success) {
return false; return false;
} }
@@ -117,8 +117,7 @@ bool ConditionedCostFunction::Evaluate(double const* const* parameters,
int parameter_block_size = int parameter_block_size =
wrapped_cost_function_->parameter_block_sizes()[i]; wrapped_cost_function_->parameter_block_sizes()[i];
VectorRef jacobian_row(jacobians[i] + r * parameter_block_size, VectorRef jacobian_row(jacobians[i] + r * parameter_block_size,
parameter_block_size, parameter_block_size, 1);
1);
jacobian_row *= conditioner_derivative; jacobian_row *= conditioner_derivative;
} }
} }

View File

@@ -41,7 +41,6 @@
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
#include "ceres/internal/eigen.h" #include "ceres/internal/eigen.h"
#include "ceres/linear_operator.h" #include "ceres/linear_operator.h"
#include "ceres/stringprintf.h" #include "ceres/stringprintf.h"
@@ -52,13 +51,16 @@ namespace ceres {
namespace internal { namespace internal {
namespace { namespace {
bool IsZeroOrInfinity(double x) { return ((x == 0.0) || std::isinf(x)); } bool IsZeroOrInfinity(double x) {
return ((x == 0.0) || std::isinf(x));
}
} // namespace } // namespace
ConjugateGradientsSolver::ConjugateGradientsSolver( ConjugateGradientsSolver::ConjugateGradientsSolver(
const LinearSolver::Options& options) const LinearSolver::Options& options)
: options_(options) {} : options_(options) {
}
LinearSolver::Summary ConjugateGradientsSolver::Solve( LinearSolver::Summary ConjugateGradientsSolver::Solve(
LinearOperator* A, LinearOperator* A,
@@ -135,10 +137,7 @@ LinearSolver::Summary ConjugateGradientsSolver::Solve(
summary.termination_type = LINEAR_SOLVER_FAILURE; summary.termination_type = LINEAR_SOLVER_FAILURE;
summary.message = StringPrintf( summary.message = StringPrintf(
"Numerical failure. beta = rho_n / rho_{n-1} = %e, " "Numerical failure. beta = rho_n / rho_{n-1} = %e, "
"rho_n = %e, rho_{n-1} = %e", "rho_n = %e, rho_{n-1} = %e", beta, rho, last_rho);
beta,
rho,
last_rho);
break; break;
} }
p = z + beta * p; p = z + beta * p;
@@ -153,20 +152,16 @@ LinearSolver::Summary ConjugateGradientsSolver::Solve(
summary.message = StringPrintf( summary.message = StringPrintf(
"Matrix is indefinite, no more progress can be made. " "Matrix is indefinite, no more progress can be made. "
"p'q = %e. |p| = %e, |q| = %e", "p'q = %e. |p| = %e, |q| = %e",
pq, pq, p.norm(), q.norm());
p.norm(),
q.norm());
break; break;
} }
const double alpha = rho / pq; const double alpha = rho / pq;
if (std::isinf(alpha)) { if (std::isinf(alpha)) {
summary.termination_type = LINEAR_SOLVER_FAILURE; summary.termination_type = LINEAR_SOLVER_FAILURE;
summary.message = StringPrintf( summary.message =
"Numerical failure. alpha = rho / pq = %e, rho = %e, pq = %e.", StringPrintf("Numerical failure. alpha = rho / pq = %e, "
alpha, "rho = %e, pq = %e.", alpha, rho, pq);
rho,
pq);
break; break;
} }

View File

@@ -34,7 +34,6 @@
#ifndef CERES_INTERNAL_CONJUGATE_GRADIENTS_SOLVER_H_ #ifndef CERES_INTERNAL_CONJUGATE_GRADIENTS_SOLVER_H_
#define CERES_INTERNAL_CONJUGATE_GRADIENTS_SOLVER_H_ #define CERES_INTERNAL_CONJUGATE_GRADIENTS_SOLVER_H_
#include "ceres/internal/port.h"
#include "ceres/linear_solver.h" #include "ceres/linear_solver.h"
namespace ceres { namespace ceres {
@@ -55,7 +54,7 @@ class LinearOperator;
// For more details see the documentation for // For more details see the documentation for
// LinearSolver::PerSolveOptions::r_tolerance and // LinearSolver::PerSolveOptions::r_tolerance and
// LinearSolver::PerSolveOptions::q_tolerance in linear_solver.h. // LinearSolver::PerSolveOptions::q_tolerance in linear_solver.h.
class CERES_EXPORT_INTERNAL ConjugateGradientsSolver : public LinearSolver { class ConjugateGradientsSolver : public LinearSolver {
public: public:
explicit ConjugateGradientsSolver(const LinearSolver::Options& options); explicit ConjugateGradientsSolver(const LinearSolver::Options& options);
Summary Solve(LinearOperator* A, Summary Solve(LinearOperator* A,

View File

@@ -34,6 +34,8 @@
namespace ceres { namespace ceres {
Context* Context::Create() { return new internal::ContextImpl(); } Context* Context::Create() {
return new internal::ContextImpl();
}
} // namespace ceres } // namespace ceres

View File

@@ -37,6 +37,7 @@ void ContextImpl::EnsureMinimumThreads(int num_threads) {
#ifdef CERES_USE_CXX_THREADS #ifdef CERES_USE_CXX_THREADS
thread_pool.Resize(num_threads); thread_pool.Resize(num_threads);
#endif // CERES_USE_CXX_THREADS #endif // CERES_USE_CXX_THREADS
} }
} // namespace internal } // namespace internal
} // namespace ceres } // namespace ceres

View File

@@ -32,9 +32,7 @@
#define CERES_INTERNAL_CONTEXT_IMPL_H_ #define CERES_INTERNAL_CONTEXT_IMPL_H_
// This include must come before any #ifndef check on Ceres compile options. // This include must come before any #ifndef check on Ceres compile options.
// clang-format off
#include "ceres/internal/port.h" #include "ceres/internal/port.h"
// clanf-format on
#include "ceres/context.h" #include "ceres/context.h"
@@ -45,7 +43,7 @@
namespace ceres { namespace ceres {
namespace internal { namespace internal {
class CERES_EXPORT_INTERNAL ContextImpl : public Context { class ContextImpl : public Context {
public: public:
ContextImpl() {} ContextImpl() {}
ContextImpl(const ContextImpl&) = delete; ContextImpl(const ContextImpl&) = delete;

View File

@@ -64,7 +64,8 @@ CoordinateDescentMinimizer::CoordinateDescentMinimizer(ContextImpl* context)
CHECK(context_ != nullptr); CHECK(context_ != nullptr);
} }
CoordinateDescentMinimizer::~CoordinateDescentMinimizer() {} CoordinateDescentMinimizer::~CoordinateDescentMinimizer() {
}
bool CoordinateDescentMinimizer::Init( bool CoordinateDescentMinimizer::Init(
const Program& program, const Program& program,
@@ -86,8 +87,8 @@ bool CoordinateDescentMinimizer::Init(
parameter_block_index[parameter_blocks_.back()] = parameter_block_index[parameter_blocks_.back()] =
parameter_blocks_.size() - 1; parameter_blocks_.size() - 1;
} }
independent_set_offsets_.push_back(independent_set_offsets_.back() + independent_set_offsets_.push_back(
elements.size()); independent_set_offsets_.back() + elements.size());
} }
// The ordering does not have to contain all parameter blocks, so // The ordering does not have to contain all parameter blocks, so
@@ -125,7 +126,8 @@ bool CoordinateDescentMinimizer::Init(
return true; return true;
} }
void CoordinateDescentMinimizer::Minimize(const Minimizer::Options& options, void CoordinateDescentMinimizer::Minimize(
const Minimizer::Options& options,
double* parameters, double* parameters,
Solver::Summary* summary) { Solver::Summary* summary) {
// Set the state and mark all parameter blocks constant. // Set the state and mark all parameter blocks constant.
@@ -249,10 +251,10 @@ bool CoordinateDescentMinimizer::IsOrderingValid(
// Verify that each group is an independent set // Verify that each group is an independent set
for (const auto& g_t_e : group_to_elements) { for (const auto& g_t_e : group_to_elements) {
if (!program.IsParameterBlockSetIndependent(g_t_e.second)) { if (!program.IsParameterBlockSetIndependent(g_t_e.second)) {
*message = StringPrintf( *message =
"The user-provided parameter_blocks_for_inner_iterations does not " StringPrintf("The user-provided "
"form an independent set. Group Id: %d", "parameter_blocks_for_inner_iterations does not "
g_t_e.first); "form an independent set. Group Id: %d", g_t_e.first);
return false; return false;
} }
} }

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