commit 9772673e43e74b931675081b2826f4acc91ba348 Author: Matt Pharr Date: Mon Aug 17 16:17:05 2020 -0700 Initial commit for public release. diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..e53238db --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +*~ +.#* +#*# +src/build +.DS_Store +.ipynb_checkpoints/ +build/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..c1e7e87e --- /dev/null +++ b/.gitmodules @@ -0,0 +1,19 @@ +[submodule "src/ext/zlib"] + path = src/ext/zlib + url = https://github.com/mitsuba-renderer/zlib +[submodule "src/ext/ptex"] + path = src/ext/ptex + url = https://github.com/wdas/ptex.git +[submodule "src/ext/double-conversion"] + path = src/ext/double-conversion + url = https://github.com/mmp/double-conversion +[submodule "src/ext/stb"] + path = src/ext/stb + url = https://github.com/nothings/stb.git +[submodule "src/ext/openexr"] + path = src/ext/openexr + url = https://github.com/mmp/openexr.git + branch = zlibstatic-export-workaround +[submodule "src/ext/filesystem"] + path = src/ext/filesystem + url = https://github.com/wjakob/filesystem.git diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..2211bcef --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,831 @@ +# pbrt-v4 top-level CMakeLists.txt + +cmake_minimum_required (VERSION 3.12) + +project (PBRT-V4 LANGUAGES CXX C) + +set (CMAKE_CXX_STANDARD 17) +set (CMAKE_CXX_STANDARD_REQUIRED ON) + +# For sanitizers +set (CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) + +# Configuration options + +option (PBRT_FLOAT_AS_DOUBLE "Use 64-bit floats" OFF) +option (PBRT_BUILD_NATIVE_EXECUTABLE "Build executable optimized for CPU architecture of system pbrt was built on" ON) +option (PBRT_NVTX "Insert NVTX annotations for NVIDIA Profiling and Debugging Tools" OFF) +set (PBRT_OPTIX7_PATH "" CACHE STRING "Path to OptiX 7 SDK") + +if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + message (STATUS "Setting build type to 'Release' as none was specified.") + set (CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) + set_property (CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" + "MinSizeRel" "RelWithDebInfo") +endif () + +function (CHECK_EXT NAME DIR HASH) + if (NOT IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/src/ext/${DIR}") + message (FATAL_ERROR "The ${NAME} submodule directory is missing! " + "You probably did not clone the project with --recursive. It is possible to recover by running:\n" + " \"git submodule update --init --recursive\"") + endif () + + find_package(Git) + if (GIT_FOUND) + execute_process( + COMMAND ${GIT_EXECUTABLE} branch --contains ${HASH} HEAD + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/src/ext/${DIR}" + RESULT_VARIABLE "git_return" + ERROR_QUIET + OUTPUT_QUIET) + if (NOT ${git_return} EQUAL 0) + message (FATAL_ERROR "The ${CMAKE_CURRENT_SOURCE_DIR}/src/ext/${DIR} " + "submodule isn't up to date. Please run:\n" + " \"git submodule update --recursive\"") + else() + #message(STATUS "${NAME}: includes git commit: ${HASH}") + endif() + else(GIT_FOUND) + message(STATUS "git not found: unable to verify revisions in submodules") + endif(GIT_FOUND) +endfunction() + +check_ext ("OpenEXR" "openexr/OpenEXR" 023e879e52e7486c4) +check_ext ("Ptex" "ptex/src" 82bd326) +check_ext ("double-conversion" "double-conversion/cmake" 9a8e518) +check_ext ("filesystem" "filesystem/filesystem" 4efd2628) +check_ext ("stb" "stb/tools" 1034f5) +check_ext ("zlib" "zlib/doc" 54d591e) + +if (CMAKE_BUILD_TYPE MATCHES Release) + add_definitions (-D NDEBUG) +endif () +# To build a release build with CHECKs enabled, comment-out the above +# 3 lines and un-comment out this one: +# SET(CMAKE_CXX_FLAGS_RELEASE "-O3") + +enable_testing () + +find_package ( Sanitizers ) +find_package ( Threads ) + +set_property(GLOBAL PROPERTY USE_FOLDERS ON) + +if (MSVC) + add_definitions (/D _CRT_SECURE_NO_WARNINGS) + set(PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_IS_MSVC) + list (APPEND PBRT_CXX_FLAGS /wd4305) # double constant assigned to float + list (APPEND PBRT_CXX_FLAGS /wd4244) # int -> float conversion + list (APPEND PBRT_CXX_FLAGS /wd4843) # double -> float conversion + list (APPEND PBRT_CXX_FLAGS /wd4267) # size_t -> int conversion + list (APPEND PBRT_CXX_FLAGS /wd4838) # double -> int conversion + list (APPEND PBRT_CXX_FLAGS /wd26495) # uninitialized member variable + list (APPEND PBRT_CXX_FLAGS /wd26451) # arithmetic on 4-byte value, then cast to 8-byte +endif () + +####################################### +## ext + +set (BUILD_SHARED_LIBS OFF) + +add_subdirectory (${CMAKE_CURRENT_SOURCE_DIR}/src/ext) + +######################################### +## CUDA / OptiX + +include (CheckLanguage) + +check_language(CUDA) + +if (CMAKE_CUDA_COMPILER) + find_package (CUDA REQUIRED) + + # This seems to be necessary starting with 3.17.1, but gives an error + # about 17 being an unsupported version earlier... + if (${CMAKE_VERSION} VERSION_GREATER "3.17.0") + set (CMAKE_CUDA_STANDARD 17) + endif () + + message (STATUS "Found CUDA: ${CMAKE_CUDA_COMPILER_VERSION}") + if ("${PBRT_OPTIX7_PATH}" STREQUAL "") + message (WARNING "Found CUDA but PBRT_OPTIX7_PATH is not set. Disabling GPU compilation.") + else () + enable_language (CUDA) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_BUILD_GPU_RENDERER) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} NVTX) + set (PBRT_CUDA_ENABLED ON) + + # FIXME + include_directories (${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) # for regular c++ compiles + + # http://www.ssl.berkeley.edu/~jimm/grizzly_docs/SSL/opt/intel/cc/9.0/lib/locale/en_US/mcpcom.msg + set (PBRT_CUDA_DIAG_FLAGS "") + #set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} -Xptxas --warn-on-double-precision-use") + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} -Xcudafe --diag_suppress=partial_override") + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} -Xcudafe --diag_suppress=virtual_function_decl_hidden") + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} -Xcudafe --diag_suppress=integer_sign_change") + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} -Xcudafe --diag_suppress=declared_but_not_referenced") + # WAR invalid warnings about this with "if constexpr" + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} -Xcudafe --diag_suppress=implicit_return_from_non_void_function") + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} --expt-relaxed-constexpr") + set (PBRT_CUDA_DIAG_FLAGS "${PBRT_CUDA_DIAG_FLAGS} --extended-lambda") + set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} ${PBRT_CUDA_DIAG_FLAGS}") + + # Willie hears yeh.. + set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Xnvlink -suppress-stack-size-warning") + + # https://wagonhelm.github.io/articles/2018-03/detecting-cuda-capability-with-cmake + # Get CUDA compute capability + set (OUTPUTFILE ${CMAKE_BINARY_DIR}/checkcuda) + execute_process (COMMAND nvcc -lcuda ${CMAKE_SOURCE_DIR}/cmake/checkcuda.cu -o ${OUTPUTFILE}) + execute_process (COMMAND ${OUTPUTFILE} + RESULT_VARIABLE CUDA_RETURN_CODE + OUTPUT_VARIABLE ARCH) + + set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --std=c++17") + if (CMAKE_BUILD_TYPE MATCHES Release) + set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --use_fast_math -lineinfo --maxrregcount 128") + else() + set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --use_fast_math -G -g") + endif () + + if (NOT ${CUDA_RETURN_CODE} EQUAL 0) + message (SEND_ERROR "Unable to determine GPU's compute capability") + else () + message (STATUS "CUDA Architecture: ${ARCH}") + set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --gpu-architecture=${ARCH}") + endif () + + set (PBRT_CUDA_LIB cuda) + + # optix + # FIXME + include_directories (${PBRT_OPTIX7_PATH}/include) + # FIXME. Sigh. I'm not sure how else to pass this through to cuda_compile_ptx... + include_directories (src) + include_directories (${CMAKE_BINARY_DIR}) + + # from Ingo's configure_optix.cmake (Apache licensed) + find_program (BIN2C bin2c DOC "Path to the CUDA SDK bin2c executable.") + + # this macro defines cmake rules that execute the following four steps: + # 1) compile the given cuda file ${cuda_file} to an intermediary PTX file + # 2) use the 'bin2c' tool (that comes with CUDA) to + # create a second intermediary (.c-)file which defines a const string variable + # (named '${c_var_name}') whose (constant) value is the PTX output + # from the previous step. + # 3) compile the given .c file to an intermediary object file (why thus has + # that PTX string 'embedded' as a global constant. + # 4) assign the name of the intermediary .o file to the cmake variable + # 'output_var', which can then be added to cmake targets. + macro (cuda_compile_and_embed output_var cuda_file) + set (c_var_name ${output_var}) + cuda_compile_ptx (ptx_files ${cuda_file} + OPTIONS --std=c++17 -O3 ${PBRT_CUDA_DIAG_FLAGS} -DNDEBUG --use_fast_math + # disable "extern declaration... is treated as a static definition" warning + -Xcudafe=--display_error_number -Xcudafe=--diag_suppress=3089 + --gpu-architecture=${ARCH} -D PBRT_BUILD_GPU_RENDERER) + list (GET ptx_files 0 ptx_file) + set (embedded_file ${ptx_file}_embedded.c) + add_custom_command ( + OUTPUT ${embedded_file} + COMMAND ${BIN2C} -c --padd 0 --type char --name ${c_var_name} ${ptx_file} > ${embedded_file} + DEPENDS ${ptx_file} + COMMENT "compiling (and embedding ptx from) ${cuda_file}" + ) + set (${output_var} ${embedded_file}) + endmacro () + endif () +else () + message (STATUS "CUDA not found") +endif () + +if (PBRT_FLOAT_AS_DOUBLE) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_FLOAT_AS_DOUBLE) +endif () + +########################################################################### +# Annoying compiler-specific details + +INCLUDE(CheckCXXCompilerFlag) + +# TODO: how to specify this on windows? +check_cxx_compiler_flag ("-march=native" COMPILER_SUPPORTS_MARCH_NATIVE) +if (COMPILER_SUPPORTS_MARCH_NATIVE AND PBRT_BUILD_NATIVE_EXECUTABLE AND NOT PBRT_CUDA_ENABLED) + list (APPEND PBRT_CXX_FLAGS -march=native) +endif () + +if (CMAKE_CXX_COMPILER_ID STREQUAL "Intel") + list(APPEND PBRT_CXX_FLAGS -std=c++17) + + FIND_PROGRAM(XIAR xiar) + IF(XIAR) + SET(CMAKE_AR "${XIAR}") + ENDIF(XIAR) + MARK_AS_ADVANCED(XIAR) + + FIND_PROGRAM(XILD xild) + IF(XILD) + SET(CMAKE_LINKER "${XILD}") + ENDIF(XILD) + MARK_AS_ADVANCED(XILD) + + # ICC will default to -fp-model fast=1, which performs value-unsafe optimizations which will + # cause pbrt_test to fail. For safety, -fp-model precise is explicitly set here by default. + set(FP_MODEL "precise" CACHE STRING "The floating point model to compile with.") + set_property(CACHE FP_MODEL PROPERTY STRINGS "precise" "fast=1" "fast=2") + + list (APPEND PBRT_CXX_FLAGS "-fp-model ${FP_MODEL}") +endif () + +########################################################################### +# Check for various C++ features and set preprocessor variables or +# define workarounds. + +include (CheckCXXSourceCompiles) + +check_cxx_source_compiles (" +#include +#include +#include +#include +int main() { + int fd = open(\"foo\", O_RDONLY); + struct stat s; + fstat(fd, &s); + size_t len = s.st_size; + void *ptr = mmap(0, len, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0); + munmap(ptr, len); +} +" HAVE_MMAP) + +if (HAVE_MMAP) + set(PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_HAVE_MMAP) +ENDIF () + +include (CheckIncludeFiles) + +check_cxx_source_compiles (" +#include +int main() { + unsigned long lz = 0, v = 1234; + if (_BitScanReverse(&lz, v)) return lz; + return 0; +} " HAS_INTRIN_H) + +if (HAS_INTRIN_H) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_HAS_INTRIN_H) +endif () + +######################################## +# os/compiler-specific stuff + +if (CMAKE_SYSTEM_NAME STREQUAL Windows) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_IS_WINDOWS NOMINMAX) +elseif (CMAKE_SYSTEM_NAME STREQUAL Darwin) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_IS_OSX) +elseif (CMAKE_SYSTEM_NAME STREQUAL Linux) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_IS_LINUX) + # -rdynamic so we can get backtrace symbols... + # --no-as-needed so libprofiler sticks around + set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -rdynamic -Wl,--no-as-needed") +else () + message (SEND_ERROR "Unknown system name: " + CMAKE_SYSTEM_NAME) +endif() + +# libgoogle-perftools-dev +find_library (PROFILE_LIB profiler) +if (NOT PROFILE_LIB) + message (STATUS "Unable to find -lprofiler") +else () + message (STATUS "Found -lprofiler: ${PROFILE_LIB}") +endif () + +######################################## +# noinline + +check_cxx_source_compiles ( +"__declspec(noinline) void foo() { } +int main() { }" +HAVE_DECLSPEC_NOINLINE) + +check_cxx_source_compiles ( +"__attribute__((noinline)) void foo() { } +int main() { }" +HAVE_ATTRIBUTE_NOINLINE) + +if (HAVE_ATTRIBUTE_NOINLINE) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} "PBRT_NOINLINE=__attribute__((noinline))") +elseif (HAVE_DECLSPEC_NOINLINE) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} "PBRT_NOINLINE=__declspec(noinline)") +else () + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_NOINLINE) +endif () + +######################################## +# Aligned memory allocation + +check_cxx_source_compiles ( " +#include +int main() { void * ptr = _aligned_malloc(1024, 32); } +" HAVE__ALIGNED_MALLOC ) + +check_cxx_source_compiles ( " +#include +int main() { + void *ptr; + posix_memalign(&ptr, 32, 1024); +} " HAVE_POSIX_MEMALIGN ) + +if (HAVE__ALIGNED_MALLOC) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_HAVE__ALIGNED_MALLOC) +elseif (HAVE_POSIX_MEMALIGN) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_HAVE_POSIX_MEMALIGN) +else () + message (SEND_ERROR "Unable to find a way to allocate aligned memory") +endif () + +######################################## +# are long and int64_t the same + +check_cxx_source_compiles (" +#include +#include +static_assert(!std::is_same::value && !std::is_same::value); +int main() { } +" INT64_IS_OWN_TYPE) + +if (INT64_IS_OWN_TYPE) + set (PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PBRT_INT64_IS_OWN_TYPE) + +endif () +if (PBRT_NVTX) + add_definitions( -D NVTX ) +endif() + +########################################################################### +# On to pbrt... + +set (PBRT_SOURCE + src/pbrt/bsdf.cpp + src/pbrt/bssrdf.cpp + src/pbrt/bxdfs.cpp + src/pbrt/cameras.cpp + src/pbrt/film.cpp + src/pbrt/filters.cpp + src/pbrt/interaction.cpp + src/pbrt/lights.cpp + src/pbrt/lightsamplers.cpp + src/pbrt/materials.cpp + src/pbrt/media.cpp + src/pbrt/options.cpp + src/pbrt/paramdict.cpp + src/pbrt/parsedscene.cpp + src/pbrt/parser.cpp + src/pbrt/pbrt.cpp + src/pbrt/ray.cpp + src/pbrt/samplers.cpp + src/pbrt/shapes.cpp + src/pbrt/textures.cpp + + src/pbrt/cpu/accelerators.cpp + src/pbrt/cpu/integrators.cpp + src/pbrt/cpu/primitive.cpp + src/pbrt/cpu/render.cpp + ) + +set (PBRT_SOURCE_HEADERS + src/pbrt/bsdf.h + src/pbrt/bssrdf.h + src/pbrt/bxdfs.h + src/pbrt/cameras.h + src/pbrt/film.h + src/pbrt/filters.h + src/pbrt/interaction.h + src/pbrt/lightsamplers.h + src/pbrt/lights.h + src/pbrt/materials.h + src/pbrt/media.h + src/pbrt/options.h + src/pbrt/paramdict.h + src/pbrt/parsedscene.h + src/pbrt/parser.h + src/pbrt/pbrt.h + src/pbrt/pbrt.soa + src/pbrt/ray.h + src/pbrt/samplers.h + src/pbrt/shapes.h + src/pbrt/textures.h + ) + +SET (PBRT_UTIL_SOURCE + src/pbrt/util/bluenoise.cpp + src/pbrt/util/check.cpp + src/pbrt/util/color.cpp + src/pbrt/util/colorspace.cpp + src/pbrt/util/display.cpp + src/pbrt/util/error.cpp + src/pbrt/util/file.cpp + src/pbrt/util/float.cpp + src/pbrt/util/image.cpp + src/pbrt/util/log.cpp + src/pbrt/util/loopsubdiv.cpp + src/pbrt/util/lowdiscrepancy.cpp + src/pbrt/util/math.cpp + src/pbrt/util/memory.cpp + src/pbrt/util/mesh.cpp + src/pbrt/util/mipmap.cpp + src/pbrt/util/parallel.cpp + src/pbrt/util/pmj02tables.cpp + src/pbrt/util/primes.cpp + src/pbrt/util/print.cpp + src/pbrt/util/progressreporter.cpp + src/pbrt/util/pstd.cpp + src/pbrt/util/rng.cpp + src/pbrt/util/sampling.cpp + src/pbrt/util/scattering.cpp + src/pbrt/util/sobolmatrices.cpp + src/pbrt/util/spectrum.cpp + src/pbrt/util/stats.cpp + src/pbrt/util/stbimage.cpp + src/pbrt/util/string.cpp + src/pbrt/util/transform.cpp + src/pbrt/util/vecmath.cpp +) + +SET (PBRT_UTIL_SOURCE_HEADERS + src/pbrt/util/args.h + src/pbrt/util/bits.h + src/pbrt/util/bluenoise.h + src/pbrt/util/buffercache.h + src/pbrt/util/check.h + src/pbrt/util/color.h + src/pbrt/util/colorspace.h + src/pbrt/util/containers.h + src/pbrt/util/display.h + src/pbrt/util/error.h + src/pbrt/util/file.h + src/pbrt/util/float.h + src/pbrt/util/hash.h + src/pbrt/util/image.h + src/pbrt/util/log.h + src/pbrt/util/loopsubdiv.h + src/pbrt/util/lowdiscrepancy.h + src/pbrt/util/math.h + src/pbrt/util/memory.h + src/pbrt/util/mesh.h + src/pbrt/util/mipmap.h + src/pbrt/util/parallel.h + src/pbrt/util/pmj02tables.h + src/pbrt/util/primes.h + src/pbrt/util/print.h + src/pbrt/util/progressreporter.h + src/pbrt/util/pstd.h + src/pbrt/util/rng.h + src/pbrt/util/sampling.h + src/pbrt/util/scattering.h + src/pbrt/util/shuffle.h + src/pbrt/util/soa.h + src/pbrt/util/sobolmatrices.h + src/pbrt/util/spectrum.h + src/pbrt/util/splines.h + src/pbrt/util/stats.h + src/pbrt/util/string.h + src/pbrt/util/taggedptr.h + src/pbrt/util/transform.h + src/pbrt/util/vecmath.h + ) + +if (PBRT_CUDA_ENABLED) + set (PBRT_GPU_SOURCE + src/pbrt/gpu/accel.cpp + src/pbrt/gpu/camera.cpp + src/pbrt/gpu/film.cpp + src/pbrt/gpu/init.cpp + src/pbrt/gpu/launch.cpp + src/pbrt/gpu/media.cpp + src/pbrt/gpu/pathintegrator.cpp + src/pbrt/gpu/samples.cpp + src/pbrt/gpu/subsurface.cpp + src/pbrt/gpu/surfscatter.cpp + ) + set (PBRT_GPU_SOURCE_HEADERS + src/pbrt/gpu/accel.h + src/pbrt/gpu/init.h + src/pbrt/gpu/launch.h + src/pbrt/gpu/optix.h + src/pbrt/gpu/pathintegrator.h + src/pbrt/gpu/workitems.h + src/pbrt/gpu/workitems.soa + src/pbrt/gpu/workqueue.h + ) + + set_source_files_properties ( + src/pbrt/bsdf.cpp + src/pbrt/bssrdf.cpp + src/pbrt/bxdfs.cpp + src/pbrt/cameras.cpp + src/pbrt/film.cpp + src/pbrt/filters.cpp +# src/pbrt/genscene.cpp + src/pbrt/interaction.cpp + src/pbrt/lights.cpp + src/pbrt/lightsamplers.cpp + src/pbrt/materials.cpp +# src/pbrt/media.cpp + src/pbrt/options.cpp +# src/pbrt/paramdict.cpp +# src/pbrt/parser.cpp + src/pbrt/pbrt.cpp + src/pbrt/samplers.cpp + src/pbrt/shapes.cpp + src/pbrt/textures.cpp + + src/pbrt/util/bluenoise.cpp + src/pbrt/util/check.cpp + src/pbrt/util/color.cpp + src/pbrt/util/colorspace.cpp + src/pbrt/util/error.cpp +# src/pbrt/util/file.cpp +# src/pbrt/util/float.cpp +# src/pbrt/util/image.cpp + src/pbrt/util/log.cpp +# src/pbrt/util/loopsubdiv.cpp + src/pbrt/util/lowdiscrepancy.cpp + src/pbrt/util/math.cpp +# src/pbrt/util/memory.cpp + src/pbrt/util/mesh.cpp +# src/pbrt/util/mipmap.cpp +# src/pbrt/util/parallel.cpp + src/pbrt/util/pmj02tables.cpp + src/pbrt/util/primes.cpp +# src/pbrt/util/print.cpp +# src/pbrt/util/progressreporter.cpp + src/pbrt/util/pstd.cpp + src/pbrt/util/rng.cpp + src/pbrt/util/sampling.cpp + src/pbrt/util/scattering.cpp + src/pbrt/util/sobolmatrices.cpp + src/pbrt/util/spectrum.cpp + src/pbrt/util/stats.cpp +# src/pbrt/util/stbimage.cpp +# src/pbrt/util/string.cpp + src/pbrt/util/transform.cpp + src/pbrt/util/vecmath.cpp + + ${PBRT_GPU_SOURCE} + + PROPERTIES LANGUAGE CUDA + ) + + cuda_compile_and_embed (PBRT_EMBEDDED_PTX src/pbrt/gpu/optix.cu) +endif () + +source_group("Source Files" FILES ${PBRT_SOURCE}) +source_group("Header Files" FILES ${PBRT_SOURCE_HEADERS}) +source_group("Source Files/util" FILES ${PBRT_UTIL_SOURCE}) +source_group("Header Files/util" FILES ${PBRT_UTIL_SOURCE_HEADERS}) +if (PBRT_CUDA_ENABLED) + source_group("Source Files/gpu" FILES ${PBRT_GPU_SOURCE}) + source_group("Header Files/gpu" FILES ${PBRT_GPU_SOURCE_HEADERS}) +endif () + +########################################################################### +# pbrt libraries and executables + +set(PBRT_DEFINITIONS ${PBRT_DEFINITIONS} PTEX_STATIC) + +###################### +# soac + +add_executable (soac src/pbrt/cmd/soac.cpp) +add_executable (pbrt::soac ALIAS soac) + +target_compile_definitions (soac PRIVATE ${PBRT_DEFINITIONS}) +target_compile_options (soac PUBLIC ${PBRT_CXX_FLAGS}) + +set_target_properties (soac PROPERTIES OUTPUT_NAME soac) + +add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/pbrt_soa.h + COMMAND soac ${CMAKE_SOURCE_DIR}/src/pbrt/pbrt.soa > ${CMAKE_CURRENT_BINARY_DIR}/pbrt_soa.h + DEPENDS soac ${CMAKE_SOURCE_DIR}/src/pbrt/pbrt.soa) +set (PBRT_SOA_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/pbrt_soa.h) + +if (PBRT_CUDA_ENABLED) + add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/gpu_workitems_soa.h + COMMAND soac ${CMAKE_SOURCE_DIR}/src/pbrt/gpu/workitems.soa > ${CMAKE_CURRENT_BINARY_DIR}/gpu_workitems_soa.h + DEPENDS soac ${CMAKE_SOURCE_DIR}/src/pbrt/gpu/workitems.soa) + set (PBRT_SOA_GENERATED ${PBRT_SOA_GENERATED} ${CMAKE_CURRENT_BINARY_DIR}/gpu_workitems_soa.h) +endif () + +###################### +# pbrt_lib + +add_library (pbrt_lib STATIC + ${PBRT_SOA_GENERATED} + ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_srgb.cpp + ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_dci_p3.cpp + ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_rec2020.cpp + ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_aces.cpp + ${PBRT_SOURCE} + ${PBRT_UTIL_SOURCE} + ${PBRT_GPU_SOURCE} + + src/ext/gtest/gtest-all.cc + src/ext/lodepng/lodepng.cpp + src/ext/rply/rply.cpp + ) +add_library (pbrt::pbrt_lib ALIAS pbrt_lib) + +target_compile_definitions (pbrt_lib PRIVATE ${PBRT_DEFINITIONS}) + +target_include_directories (pbrt_lib PUBLIC + src + src/ext + ${STB_INCLUDE} + ${OPENEXR_INCLUDE} + ${ZLIB_INCLUDE_DIRS} + ${FILESYSTEM_INCLUDE} + ${PTEX_INCLUDE} + ${DOUBLE_CONVERSION_INCLUDE} + ${CMAKE_CURRENT_BINARY_DIR} +) + +target_compile_options (pbrt_lib PUBLIC ${PBRT_CXX_FLAGS}) + +add_sanitizers (pbrt_lib) + +if (WIN32) + # Avoid a name clash when building on Visual Studio + set_target_properties (pbrt_lib PROPERTIES OUTPUT_NAME libpbrt) +endif() + +set (ALL_PBRT_LIBS + pbrt_lib + ${CMAKE_THREAD_LIBS_INIT} + ${OPENEXR_LIBS} + Ptex_static + ${ZLIB_LIBRARIES} + double-conversion + ${PBRT_CUDA_LIB} +) + +if (PBRT_CUDA_ENABLED) + set_property (TARGET pbrt_lib PROPERTY CUDA_SEPARABLE_COMPILATION ON) + add_library (pbrt_embedded_ptx_lib STATIC + ${PBRT_EMBEDDED_PTX} + ) + set (ALL_PBRT_LIBS ${ALL_PBRT_LIBS} pbrt_embedded_ptx_lib) +endif() + + +if (WIN32) + set (ALL_PBRT_LIBS ${ALL_PBRT_LIBS} dbghelp wsock32 ws2_32) +endif () + +if (PROFILE_LIB) + set(ALL_PBRT_LIBS ${ALL_PBRT_LIBS} ${PROFILE_LIB}) +endif () + +###################### +## rgb2spec_opt + +add_executable (rgb2spec_opt src/pbrt/cmd/rgb2spec_opt.cpp) +add_executable (pbrt::rgb2spec_opt ALIAS rgb2spec_opt) + +target_compile_definitions (rgb2spec_opt PRIVATE ${PBRT_DEFINITIONS}) +target_compile_options (rgb2spec_opt PUBLIC ${PBRT_CXX_FLAGS}) +target_link_libraries (rgb2spec_opt ${CMAKE_THREAD_LIBS_INIT}) + +add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_aces.cpp + COMMAND rgb2spec_opt 64 ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_aces.cpp ACES2065_1 + DEPENDS rgb2spec_opt) + +add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_dci_p3.cpp + COMMAND rgb2spec_opt 64 ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_dci_p3.cpp DCI_P3 + DEPENDS rgb2spec_opt) + +add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_rec2020.cpp + COMMAND rgb2spec_opt 64 ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_rec2020.cpp REC2020 + DEPENDS rgb2spec_opt) + +add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_srgb.cpp + COMMAND rgb2spec_opt 64 ${CMAKE_CURRENT_BINARY_DIR}/rgbspectrum_srgb.cpp sRGB + DEPENDS rgb2spec_opt) + +###################### +# Main renderer + +add_executable (pbrt_exe src/pbrt/cmd/pbrt.cpp) +add_executable (pbrt::pbrt_exe ALIAS pbrt_exe) + +target_compile_definitions (pbrt_exe PRIVATE ${PBRT_DEFINITIONS}) +target_compile_options (pbrt_exe PRIVATE ${PBRT_CXX_FLAGS}) +target_include_directories (pbrt_exe PRIVATE src src/ext) +target_link_libraries (pbrt_exe PRIVATE ${ALL_PBRT_LIBS}) + +set_target_properties (pbrt_exe PROPERTIES OUTPUT_NAME pbrt) + +add_sanitizers (pbrt_exe) + +###################### +# imgtool + +add_executable (imgtool src/pbrt/cmd/imgtool.cpp) +add_executable (pbrt::imgtool ALIAS imgtool) + +add_library (sky_lib STATIC src/ext/skymodel/ArHosekSkyModel.c) +set_property (TARGET sky_lib PROPERTY FOLDER "ext") + +target_compile_definitions (imgtool PRIVATE ${PBRT_DEFINITIONS}) +target_compile_options (imgtool PRIVATE ${PBRT_CXX_FLAGS}) +target_include_directories (imgtool PRIVATE src src/ext) +target_link_libraries (imgtool PRIVATE ${ALL_PBRT_LIBS} sky_lib) + +add_sanitizers (imgtool) + +###################### +# obj2pbrt + +add_executable (obj2pbrt src/pbrt/cmd/obj2pbrt.cpp) + +target_compile_definitions (obj2pbrt PRIVATE ${PBRT_DEFINITIONS}) +target_compile_options (obj2pbrt PRIVATE ${PBRT_CXX_FLAGS}) + +add_sanitizers (obj2pbrt) + +###################### +# cyhair2pbrt + +add_executable (cyhair2pbrt src/pbrt/cmd/cyhair2pbrt.cpp) + +target_compile_definitions (cyhair2pbrt PRIVATE ${PBRT_DEFINITIONS}) +target_compile_options (cyhair2pbrt PRIVATE ${PBRT_CXX_FLAGS}) + +add_sanitizers (cyhair2pbrt) + +################## +# Unit tests + +set (PBRT_TEST_SOURCE + src/pbrt/bsdfs_test.cpp + src/pbrt/filters_test.cpp + src/pbrt/lights_test.cpp + src/pbrt/lightsamplers_test.cpp + src/pbrt/media_test.cpp + src/pbrt/parser_test.cpp + src/pbrt/samplers_test.cpp + src/pbrt/shapes_test.cpp + + src/pbrt/cpu/integrators_test.cpp + + src/pbrt/util/args_test.cpp + src/pbrt/util/bits_test.cpp + src/pbrt/util/color_test.cpp + src/pbrt/util/containers_test.cpp + src/pbrt/util/file_test.cpp + src/pbrt/util/float_test.cpp + src/pbrt/util/hash_test.cpp + src/pbrt/util/image_test.cpp + src/pbrt/util/math_test.cpp + src/pbrt/util/parallel_test.cpp + src/pbrt/util/print_test.cpp + src/pbrt/util/pstd_test.cpp + src/pbrt/util/rng_test.cpp + src/pbrt/util/sampling_test.cpp + src/pbrt/util/spectrum_test.cpp + src/pbrt/util/splines_test.cpp + src/pbrt/util/taggedptr_test.cpp + src/pbrt/util/transform_test.cpp + src/pbrt/util/vecmath_test.cpp + ) + +add_executable (pbrt_test src/pbrt/cmd/pbrt_test.cpp ${PBRT_TEST_SOURCE}) + +target_link_libraries (pbrt_test PRIVATE ${ALL_PBRT_LIBS}) +target_compile_definitions (pbrt_test PRIVATE ${PBRT_DEFINITIONS}) +target_include_directories (pbrt_test PRIVATE src src/ext ${DOUBLE_CONVERSION_INCLUDE}) +target_compile_options(pbrt_test PUBLIC ${PBRT_CXX_FLAGS}) + +add_sanitizers (pbrt_test) + +add_test (pbrt_unit_test pbrt_test) + +############################### +# Installation + +install (TARGETS + pbrt_exe + imgtool + obj2pbrt + cyhair2pbrt + DESTINATION + bin + ) + +install (TARGETS + pbrt_lib + DESTINATION + lib + ) diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 00000000..f55e35b4 --- /dev/null +++ b/README.md @@ -0,0 +1,189 @@ +pbrt, Version 4 (Early Release) +=============================== + +This is an early release of pbrt-v4, the rendering system that will be +described in the (eventually) forthcoming fourth edition of *Physically +Based Rendering: From Theory to Implementation*. (We hope to have an +online version of the book posted late in 2020 and printed books available +in Spring 2021.) + +We are making this code available for hardy adventurers; it's not yet +extensively documented, but if you're familiar with previous versions of +pbrt, you should be able to make your away around it. Our hope is that the +system will be useful to some people in its current form and that any bugs +in the current implementation might be found now, allowing us to correct +them before the book is final. + +A number of scenes for pbrt-v4 are [available in a git repository](TODO). + +Features +-------- + +pbrt-v4 represents a substantial update to the previous version of pbrt-v3. +Major changes include: + +* Spectral rendering + * Rendering computations are always performed using + point-sampled spectra; the use of RGB color is limited to the scene + description (e.g., image texture maps), and final image output. +* Modernized volumetric scattering + * An all-new `VolPathIntegrator` based on the null-scattering path + integral formulation of [Miller et + al. 2019](https://cs.dartmouth.edu/~wjarosz/publications/miller19null.html) + has been added. + * Tighter majorants are used for null-scattering with the `GridDensityMedium` + via a separate low-resolution grid of majorants. + * Emissive volumes are now supported. +* Support for rendering on GPUs is available on systems that have CUDA and OptiX. + * The GPU path provides all of the functionality of the CPU-based + `VolPathIntegrator`, including volumetric scattering, subsurface + scattering, all of pbrt's cameras, samplers, shapes, lights, materials + and BxDFs, etc. + * Performance is substantially faster than rendering on the CPU. +* New BxDFs and Materials + * The provided BxDFs and Materials have been redesigned to be more + closely tied to physical scattering processes, along the lines of + Mitsuba's materials. (Among other things, the kitchen-sink UberMaterial + is now gone.) + * Measured BRDFs are now represented using [Dupuy and Jakob's + approach](https://rgl.epfl.ch/publications/Dupuy2018Adaptive). + * Scattering from layered materials is accurately simulated using Monte + Carlo random walks (after [Guo et al. 2018](https://shuangz.com/projects/layered-sa18/).) +* A variety of light sampling improvements have been implemented. + * "Many-light" sampling is available via light BVHs ([Conty and Kulla 2018](http://aconty.com/pdf/many-lights-hpg2018.pdf)). + * Solid angle sampling is used for triangle + ([Arvo1995](https://dl.acm.org/doi/10.1145/218380.218500)) and + quadrilateral ([Ureña et al. 2013](https://www.arnoldrenderer.com/research/egsr2013_spherical_rectangle.pdf)) + light sources. + * A single ray is now traced for both indirect lighting and BSDF-sampled direct-lighting. + * Warp product sampling is used for approximate cosine-weighted solid angle + sampling ([Hart et al. 2019](https://onlinelibrary.wiley.com/doi/abs/10.1111/cgf.14060)). + * An implementation of Bitterli et al's environment light [portal sampling](https://benedikt-bitterli.me/pmems.html) + technique is included. +* And also... + * Various improvements have been made to the `Sampler` classes, including + better randomization and a new sampler that implements pmj02bn sampling ([Christensen et + al. 2018](https://graphics.pixar.com/library/ProgressiveMultiJitteredSampling/)). + * A new `GBufferFilm` that provides position, normal, albedo, etc., at + each pixel is now available. (This is particularly useful for denoising and ML training.) + * Path regularization (optionally). + * A bilinear patch primitive has been added ([Reshetov 2019](https://link.springer.com/chapter/10.1007/978-1-4842-4427-2_8)). + * Accurate modeling of film response in cameras and photometric lighting controls thanks to a contribution from Anders Langlands and Luca Fascione. + * Various improvements to ray--shape intersection precision. + * Most of the low-level sampling code has been factored out into + stand-alone functions for easier reuse. Also, functions that invert + many sampling techniques are provided. + * Unit tests have been substantially increased. + +We have also made a refactoring pass throughout the entire system, cleaning +up various APIs and data types to improve both readability and usability. + +Finally, pbrt-v4 can work together with the +[tev](https://github.com/Tom94/tev) image viewer to display the image as +it's being rendered. As of recent versions, *tev* can display images +provided to it via a network socket; by default, it listens to port 14158, +though this can be changed via its ``--hostname`` command-line option. If +you have an instance of *tev* running, you can run pbrt like: +```bash +$ pbrt --display-server localhost:14158 scene.pbrt +``` +In that case, the image will be progressively displayed as it renders. + +Building the code +----------------- + +As before, pbrt uses git submodules for a number of third-party libraries +that it depends on. Therefore, be sure to use the `--recursive` flag when +cloning the repository: +```bash +$ git clone --recursive https://github.com/mmp/pbrt-v4.git +``` + +If you accidentally clone pbrt without using ``--recursive`` (or to update +the pbrt source tree after a new submodule has been added, run the +following command to also fetch the dependencies: +```bash +$ git submodule update --init --recursive +``` + +pbrt uses [cmake](http://www.cmake.org/) for its build system. Note that a +release build is the default; provide `-DCMAKE_BUILD_TYPE=Debug` to cmake +for a debug build. + +pbrt should build on any system that has C++ compiler with support for +C++17. We welcome PRs that make it build on more systems. + +Bug Reports and PRs +------------------- + +Please use the [pbrt-v4 github issue +tracker](https://github.com/mmp/pbrt-v4/issues) to report bugs in pbrt-v4. +(We have pre-populated it with a number of issues corresponding to known +bugs in the initial release.) + +We are always happy to receive pull requests that fix bugs, including any +bugs you find yourself or open issues in the issue tracker. + +Note, however, that in the interests of finishing the book in a finite +amount of time, the functionality of pbrt-v4 is basically fixed at this +point. We therefore will not be merging PRs that make major changes to the +system's operation or structure (but feel free to keep them in your own +forks!). Also, don't bother sending PRs for anything marked "TODO" or +"FIXME" in the source code; we'll take care of those as we finish polishing +things up. + +Updating pbrt-v3 scenes +----------------------- + +There are a variety of changes to the input file format and, as noted +above, the new format is not yet documented. However, pbrt-v4 partially +makes up for that by providing an automatic upgrade mechanism: +```bash +$ pbrt --upgrade old.pbrt > new.pbrt +``` + +Most scene files can be automatically updated. In some cases manual +intervention is required; an error message will be printed in this case. + +The environment map parameterization has also changed (from equi-rect to an +equi-area mapping); you can upgrade environment maps using +```bash +$ imgtool makeenv old.exr --outfile new.exr +``` + +Using pbrt on the GPU +--------------------- + +To run on the GPU, pbrt requires: + +* C++17 support on the GPU, including kernel launch with C++ lambdas. +* Unified memory so that the CPU can allocate and initialize data + structures for code that runs on the GPU. +* An API for ray-object intersections on the GPU. + +These requirements are effectively what makes it possible to bring pbrt to +the GPU with limited changes to the core system. As a practical matter, +these capabilities are only available via CUDA and OptiX on NVIDIA GPUs +today, though we'd be happy to see pbrt running on any other GPUs that +provide those capabilities. + +pbrt's GPU path specifically requires CUDA 11.0 and OptiX 7.1. The build +scripts will automatically attempt to find a CUDA compiler, looking in the +usual places; the cmake output will indicate whether it was successful. It +is necessary to set the cmake `PBRT_OPTIX7_PATH` configuration option to +point at an OptiX 7.1 install. + +Even when compiled with GPU support, pbrt uses the CPU by default unless +the `--gpu` command-line option is given. Note that when rendering with +the GPU, the `--spp` command-line flag can be helpful to easily crank up +the number of samples per pixel. Also, it's extra fun to use *tev* to watch +rendering progress. + + +To denoise images using the OptiX denoiser, set the scene's "Film" type to +be "gbuffer" when rendering and use EXR for the image format; a "deep" +image will be generated with auxilary channels like albedo and normal that +are useful for the denoiser. The resulting EXR can be denoised using +```bash +$ imgtool denoise-optix noisy.exr --outfile denoised.exr +``` diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 00000000..b13e2764 --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,27 @@ + +pbrt-v4 makes use of the following third-party libraries and data. Thanks +to all of the developers who have made these available! + +* [double-conversion](https://github.com/google/double-conversion) +* [filesystem](https://github.com/wjakob/filesystem) +* [googletest](https://github.com/google/googletest) +* [lodepng](https://lodev.org/lodepng/) +* [OpenEXR](http:://www.openexr.com) +* [Ptex](http://ptex.us/) +* [rply](http://w3.impa.br/~diego/software/rply/) +* [skymodel](https://cgg.mff.cuni.cz/projects/SkylightModelling/) +* [stb](https://github.com/nothings/stb) +* [tinyobjloader](https://github.com/tinyobjloader/tinyobjloader) +* [zlib](https://zlib.net/) + +Thanks also to Anders Langlands, who provided the Sensor implementation +used in the film model and Syoyo Fujita for the cyhair converter. + +pbrt-v4 also includes spectral data from the following sources: + +* Glass refractive index tables from https://refractiveindex.info, public + domain CC0. +* Camera sensor measurement data from https://github.com/ampas/rawtoaces, + Copyright © 2017 Academy of Motion Picture Arts and Sciences. + + diff --git a/cmake/FindASan.cmake b/cmake/FindASan.cmake new file mode 100644 index 00000000..fcebb437 --- /dev/null +++ b/cmake/FindASan.cmake @@ -0,0 +1,59 @@ +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +option(SANITIZE_ADDRESS "Enable AddressSanitizer for sanitized targets." Off) + +set(FLAG_CANDIDATES + # Clang 3.2+ use this version. The no-omit-frame-pointer option is optional. + "-g -fsanitize=address -fno-omit-frame-pointer" + "-g -fsanitize=address" + + # Older deprecated flag for ASan + "-g -faddress-sanitizer" +) + + +if (SANITIZE_ADDRESS AND (SANITIZE_THREAD OR SANITIZE_MEMORY)) + message(FATAL_ERROR "AddressSanitizer is not compatible with " + "ThreadSanitizer or MemorySanitizer.") +endif () + + +include(sanitize-helpers) + +if (SANITIZE_ADDRESS) + sanitizer_check_compiler_flags("${FLAG_CANDIDATES}" "AddressSanitizer" + "ASan") + + find_program(ASan_WRAPPER "asan-wrapper" PATHS ${CMAKE_MODULE_PATH}) + mark_as_advanced(ASan_WRAPPER) +endif () + +function (add_sanitize_address TARGET) + if (NOT SANITIZE_ADDRESS) + return() + endif () + + saitizer_add_flags(${TARGET} "AddressSanitizer" "ASan") +endfunction () diff --git a/cmake/FindMSan.cmake b/cmake/FindMSan.cmake new file mode 100644 index 00000000..3b0a4add --- /dev/null +++ b/cmake/FindMSan.cmake @@ -0,0 +1,57 @@ +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +option(SANITIZE_MEMORY "Enable MemorySanitizer for sanitized targets." Off) + +set(FLAG_CANDIDATES + "-g -fsanitize=memory" +) + + +include(sanitize-helpers) + +if (SANITIZE_MEMORY) + if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Linux") + message(WARNING "MemorySanitizer disabled for target ${TARGET} because " + "MemorySanitizer is supported for Linux systems only.") + set(SANITIZE_MEMORY Off CACHE BOOL + "Enable MemorySanitizer for sanitized targets." FORCE) + elseif (NOT ${CMAKE_SIZEOF_VOID_P} EQUAL 8) + message(WARNING "MemorySanitizer disabled for target ${TARGET} because " + "MemorySanitizer is supported for 64bit systems only.") + set(SANITIZE_MEMORY Off CACHE BOOL + "Enable MemorySanitizer for sanitized targets." FORCE) + else () + sanitizer_check_compiler_flags("${FLAG_CANDIDATES}" "MemorySanitizer" + "MSan") + endif () +endif () + +function (add_sanitize_memory TARGET) + if (NOT SANITIZE_MEMORY) + return() + endif () + + saitizer_add_flags(${TARGET} "MemorySanitizer" "MSan") +endfunction () diff --git a/cmake/FindSanitizers.cmake b/cmake/FindSanitizers.cmake new file mode 100644 index 00000000..627ee243 --- /dev/null +++ b/cmake/FindSanitizers.cmake @@ -0,0 +1,62 @@ +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# If any of the used compiler is a GNU compiler, add a second option to static +# link against the sanitizers. +option(SANITIZE_LINK_STATIC "Try to link static against sanitizers." Off) + + + + +set(FIND_QUIETLY_FLAG "") +if (DEFINED Sanitizers_FIND_QUIETLY) + set(FIND_QUIETLY_FLAG "QUIET") +endif () + +find_package(ASan ${FIND_QUIETLY_FLAG}) +find_package(TSan ${FIND_QUIETLY_FLAG}) +find_package(MSan ${FIND_QUIETLY_FLAG}) +find_package(UBSan ${FIND_QUIETLY_FLAG}) + + + + +function(sanitizer_add_blacklist_file FILE) + if(NOT IS_ABSOLUTE ${FILE}) + set(FILE "${CMAKE_CURRENT_SOURCE_DIR}/${FILE}") + endif() + get_filename_component(FILE "${FILE}" REALPATH) + + sanitizer_check_compiler_flags("-fsanitize-blacklist=${FILE}" + "SanitizerBlacklist" "SanBlist") +endfunction() + +function(add_sanitizers ...) + foreach (TARGET ${ARGV}) + add_sanitize_address(${TARGET}) + add_sanitize_thread(${TARGET}) + add_sanitize_memory(${TARGET}) + add_sanitize_undefined(${TARGET}) + endforeach () +endfunction(add_sanitizers) diff --git a/cmake/FindTSan.cmake b/cmake/FindTSan.cmake new file mode 100644 index 00000000..0e80f29b --- /dev/null +++ b/cmake/FindTSan.cmake @@ -0,0 +1,64 @@ +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +option(SANITIZE_THREAD "Enable ThreadSanitizer for sanitized targets." Off) + +set(FLAG_CANDIDATES + "-g -fsanitize=thread" +) + + +# ThreadSanitizer is not compatible with MemorySanitizer. +if (SANITIZE_THREAD AND SANITIZE_MEMORY) + message(FATAL_ERROR "ThreadSanitizer is not compatible with " + "MemorySanitizer.") +endif () + + +include(sanitize-helpers) + +if (SANITIZE_THREAD) + if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Linux") + message(WARNING "ThreadSanitizer disabled for target ${TARGET} because " + "ThreadSanitizer is supported for Linux systems only.") + set(SANITIZE_THREAD Off CACHE BOOL + "Enable ThreadSanitizer for sanitized targets." FORCE) + elseif (NOT ${CMAKE_SIZEOF_VOID_P} EQUAL 8) + message(WARNING "ThreadSanitizer disabled for target ${TARGET} because " + "ThreadSanitizer is supported for 64bit systems only.") + set(SANITIZE_THREAD Off CACHE BOOL + "Enable ThreadSanitizer for sanitized targets." FORCE) + else () + sanitizer_check_compiler_flags("${FLAG_CANDIDATES}" "ThreadSanitizer" + "TSan") + endif () +endif () + +function (add_sanitize_thread TARGET) + if (NOT SANITIZE_THREAD) + return() + endif () + + saitizer_add_flags(${TARGET} "ThreadSanitizer" "TSan") +endfunction () diff --git a/cmake/FindUBSan.cmake b/cmake/FindUBSan.cmake new file mode 100644 index 00000000..69486742 --- /dev/null +++ b/cmake/FindUBSan.cmake @@ -0,0 +1,46 @@ +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +option(SANITIZE_UNDEFINED + "Enable UndefinedBehaviorSanitizer for sanitized targets." Off) + +set(FLAG_CANDIDATES + "-g -fsanitize=undefined" +) + + +include(sanitize-helpers) + +if (SANITIZE_UNDEFINED) + sanitizer_check_compiler_flags("${FLAG_CANDIDATES}" + "UndefinedBehaviorSanitizer" "UBSan") +endif () + +function (add_sanitize_undefined TARGET) + if (NOT SANITIZE_UNDEFINED) + return() + endif () + + saitizer_add_flags(${TARGET} "UndefinedBehaviorSanitizer" "UBSan") +endfunction () diff --git a/cmake/asan-wrapper b/cmake/asan-wrapper new file mode 100755 index 00000000..5d541033 --- /dev/null +++ b/cmake/asan-wrapper @@ -0,0 +1,55 @@ +#!/bin/sh + +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# This script is a wrapper for AddressSanitizer. In some special cases you need +# to preload AddressSanitizer to avoid error messages - e.g. if you're +# preloading another library to your application. At the moment this script will +# only do something, if we're running on a Linux platform. OSX might not be +# affected. + + +# Exit immediately, if platform is not Linux. +if [ "$(uname)" != "Linux" ] +then + exec $@ +fi + + +# Get the used libasan of the application ($1). If a libasan was found, it will +# be prepended to LD_PRELOAD. +libasan=$(ldd $1 | grep libasan | sed "s/^[[:space:]]//" | cut -d' ' -f1) +if [ -n "$libasan" ] +then + if [ -n "$LD_PRELOAD" ] + then + export LD_PRELOAD="$libasan:$LD_PRELOAD" + else + export LD_PRELOAD="$libasan" + fi +fi + +# Execute the application. +exec $@ diff --git a/cmake/checkcuda.cu b/cmake/checkcuda.cu new file mode 100644 index 00000000..b07d8077 --- /dev/null +++ b/cmake/checkcuda.cu @@ -0,0 +1,24 @@ +// https://wagonhelm.github.io/articles/2018-03/detecting-cuda-capability-with-cmake +// Justin Francis + +#include + +int main(int argc, char **argv){ + cudaDeviceProp dP; + float min_cc = 5.0; // TODO: figure out what this should be. + + int rc = cudaGetDeviceProperties(&dP, 0); + if(rc != cudaSuccess) { + cudaError_t error = cudaGetLastError(); + printf("CUDA error: %s", cudaGetErrorString(error)); + return rc; /* Failure */ + } + if((dP.major+(dP.minor/10)) < min_cc) { + printf("Min Compute Capability of %2.1f required: %d.%d found\n Not Building CUDA Code", + min_cc, dP.major, dP.minor); + return 1; /* Failure */ + } else { + printf("sm_%d%d", dP.major, dP.minor); + return 0; /* Success */ + } +} diff --git a/cmake/sanitize-helpers.cmake b/cmake/sanitize-helpers.cmake new file mode 100644 index 00000000..88da66ea --- /dev/null +++ b/cmake/sanitize-helpers.cmake @@ -0,0 +1,173 @@ +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# Helper function to get the language of a source file. +function (sanitizer_lang_of_source FILE RETURN_VAR) + get_filename_component(FILE_EXT "${FILE}" EXT) + string(TOLOWER "${FILE_EXT}" FILE_EXT) + string(SUBSTRING "${FILE_EXT}" 1 -1 FILE_EXT) + + get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES) + foreach (LANG ${ENABLED_LANGUAGES}) + list(FIND CMAKE_${LANG}_SOURCE_FILE_EXTENSIONS "${FILE_EXT}" TEMP) + if (NOT ${TEMP} EQUAL -1) + set(${RETURN_VAR} "${LANG}" PARENT_SCOPE) + return() + endif () + endforeach() + + set(${RETURN_VAR} "" PARENT_SCOPE) +endfunction () + + +# Helper function to get compilers used by a target. +function (sanitizer_target_compilers TARGET RETURN_VAR) + # Check if all sources for target use the same compiler. If a target uses + # e.g. C and Fortran mixed and uses different compilers (e.g. clang and + # gfortran) this can trigger huge problems, because different compilers may + # use different implementations for sanitizers. + set(BUFFER "") + get_target_property(TSOURCES ${TARGET} SOURCES) + foreach (FILE ${TSOURCES}) + # If expression was found, FILE is a generator-expression for an object + # library. Object libraries will be ignored. + string(REGEX MATCH "TARGET_OBJECTS:([^ >]+)" _file ${FILE}) + if ("${_file}" STREQUAL "") + sanitizer_lang_of_source(${FILE} LANG) + if (LANG) + list(APPEND BUFFER ${CMAKE_${LANG}_COMPILER_ID}) + endif () + endif () + endforeach () + + list(REMOVE_DUPLICATES BUFFER) + set(${RETURN_VAR} "${BUFFER}" PARENT_SCOPE) +endfunction () + + +# Helper function to check compiler flags for language compiler. +function (sanitizer_check_compiler_flag FLAG LANG VARIABLE) + if (${LANG} STREQUAL "C") + include(CheckCCompilerFlag) + check_c_compiler_flag("${FLAG}" ${VARIABLE}) + + elseif (${LANG} STREQUAL "CXX") + include(CheckCXXCompilerFlag) + check_cxx_compiler_flag("${FLAG}" ${VARIABLE}) + + elseif (${LANG} STREQUAL "Fortran") + # CheckFortranCompilerFlag was introduced in CMake 3.x. To be compatible + # with older Cmake versions, we will check if this module is present + # before we use it. Otherwise we will define Fortran coverage support as + # not available. + include(CheckFortranCompilerFlag OPTIONAL RESULT_VARIABLE INCLUDED) + if (INCLUDED) + check_fortran_compiler_flag("${FLAG}" ${VARIABLE}) + elseif (NOT CMAKE_REQUIRED_QUIET) + message(STATUS "Performing Test ${VARIABLE}") + message(STATUS "Performing Test ${VARIABLE}" + " - Failed (Check not supported)") + endif () + endif() +endfunction () + + +# Helper function to test compiler flags. +function (sanitizer_check_compiler_flags FLAG_CANDIDATES NAME PREFIX) + set(CMAKE_REQUIRED_QUIET ${${PREFIX}_FIND_QUIETLY}) + + get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES) + foreach (LANG ${ENABLED_LANGUAGES}) + # Sanitizer flags are not dependend on language, but the used compiler. + # So instead of searching flags foreach language, search flags foreach + # compiler used. + set(COMPILER ${CMAKE_${LANG}_COMPILER_ID}) + if (NOT DEFINED ${PREFIX}_${COMPILER}_FLAGS) + foreach (FLAG ${FLAG_CANDIDATES}) + if(NOT CMAKE_REQUIRED_QUIET) + message(STATUS "Try ${COMPILER} ${NAME} flag = [${FLAG}]") + endif() + + set(CMAKE_REQUIRED_FLAGS "${FLAG}") + unset(${PREFIX}_FLAG_DETECTED CACHE) + sanitizer_check_compiler_flag("${FLAG}" ${LANG} + ${PREFIX}_FLAG_DETECTED) + + if (${PREFIX}_FLAG_DETECTED) + # If compiler is a GNU compiler, search for static flag, if + # SANITIZE_LINK_STATIC is enabled. + if (SANITIZE_LINK_STATIC AND (${COMPILER} STREQUAL "GNU")) + string(TOLOWER ${PREFIX} PREFIX_lower) + sanitizer_check_compiler_flag( + "-static-lib${PREFIX_lower}" ${LANG} + ${PREFIX}_STATIC_FLAG_DETECTED) + + if (${PREFIX}_STATIC_FLAG_DETECTED) + set(FLAG "-static-lib${PREFIX_lower} ${FLAG}") + endif () + endif () + + set(${PREFIX}_${COMPILER}_FLAGS "${FLAG}" CACHE STRING + "${NAME} flags for ${COMPILER} compiler.") + mark_as_advanced(${PREFIX}_${COMPILER}_FLAGS) + break() + endif () + endforeach () + + if (NOT ${PREFIX}_FLAG_DETECTED) + set(${PREFIX}_${COMPILER}_FLAGS "" CACHE STRING + "${NAME} flags for ${COMPILER} compiler.") + mark_as_advanced(${PREFIX}_${COMPILER}_FLAGS) + endif () + endif () + endforeach () +endfunction () + + +# Helper to assign sanitizer flags for TARGET. +function (saitizer_add_flags TARGET NAME PREFIX) + # Get list of compilers used by target and check, if target can be checked + # by sanitizer. + sanitizer_target_compilers(${TARGET} TARGET_COMPILER) + list(LENGTH TARGET_COMPILER NUM_COMPILERS) + if (NUM_COMPILERS GREATER 1) + message(WARNING "${NAME} disabled for target ${TARGET} because it will " + "be compiled by different compilers.") + return() + + elseif ((NUM_COMPILERS EQUAL 0) OR + ("${${PREFIX}_${TARGET_COMPILER}_FLAGS}" STREQUAL "")) + message(WARNING "${NAME} disabled for target ${TARGET} because there is" + " no sanitizer available for target sources.") + return() + endif() + + # Set compile- and link-flags for target. + set_property(TARGET ${TARGET} APPEND_STRING + PROPERTY COMPILE_FLAGS " ${${PREFIX}_${TARGET_COMPILER}_FLAGS}") + set_property(TARGET ${TARGET} APPEND_STRING + PROPERTY COMPILE_FLAGS " ${SanBlist_${TARGET_COMPILER}_FLAGS}") + set_property(TARGET ${TARGET} APPEND_STRING + PROPERTY LINK_FLAGS " ${${PREFIX}_${TARGET_COMPILER}_FLAGS}") +endfunction () diff --git a/exporters/cinema4d/PBRT Export/pbrt.pyp b/exporters/cinema4d/PBRT Export/pbrt.pyp new file mode 100644 index 00000000..9ac17af8 --- /dev/null +++ b/exporters/cinema4d/PBRT Export/pbrt.pyp @@ -0,0 +1,1557 @@ +import c4d, os, subprocess, tempfile, array, logging, threading, datetime, time, math, shutil + +PBRT_EXPORT_ID = 1032340 + +DLG_PBRT = 60000 +IDS_PBRT = 60001 +IDC_PBRT_START = 60002 +IDC_PBRT_LOG = 60003 +IDC_PBRT_EXE = 60004 +IDC_PBRT_MODE = 60005 +IDC_PBRT_MODE_EXPORT = 60006 +IDC_PBRT_MODE_EXPORT_AND_RENDER = 60007 +IDC_PBRT_MODE_RENDER = 60008 +IDC_PBRT_SAMPLES = 60009 +IDC_PBRT_ABORT = 60010 +IDC_BUTTON_GROUP = 60011 +IDC_PBRT_LOGLEVEL = 60012 +IDC_PBRT_LOGLEVEL_DEBUG = 60013 +IDC_PBRT_LOGLEVEL_INFO = 60014 +IDC_PBRT_LOGLEVEL_WARNING = 60015 +IDC_PBRT_LOGLEVEL_ERROR = 60016 +IDC_PBRT_INTENSITY = 60017 + +#IDC_TEMP_BAKE_LINK = 60011 # temporary location to store the link to the bake texture tag + +IDS_PBRT_START = 60100 +IDS_PBRT_ABORT = 60101 + +# treeview column ids +TREEVIEW_COLUMN_ID_TIME = 123 +TREEVIEW_COLUMN_ID_LEVEL = 234 +TREEVIEW_COLUMN_ID_DESCRIPTION = 345 + +MSG_PBRT_UPDATE_LOG = 1000002 +MSG_PBRT_FINISHED = 1000003 +MSG_PBRT_BAKETEXTURE = 1000004 + +logpipe = None +g_bmp = None +g_thread = None + +# although we only need a reference to the bake tag we also save a global reference to the document +# to keep the tag alive - without this the document would be deleted when out of scope. +g_bakeDoc = None +g_bakeTag = None +g_bakeTextureFile = None # when a baked environment is created, store the resulting file here +g_nLightSourcesExported = 0 # to determine whether to use auto light or not + +""" The ErrorHandler inserts informations about errors and warning into this lists which will be displayed in the treeview """ +g_errorlist = [] # example element{'time': '00:04:01', 'level':'Info', 'msg':'Oh my god!'} +g_errorRoot = None + +g_levelMap = { 'DEBUG':logging.DEBUG, 'INFO':logging.INFO, 'WARNING':logging.WARNING, 'ERROR':logging.ERROR} +g_level = logging.INFO # filter level selected in dialog + +logger = logging.getLogger(__name__) + + +"""Wrapper class which can be used to write to a logfile during a subprocess.call + +http://codereview.stackexchange.com/questions/6567/how-to-redirect-a-subprocesses-output-stdout-and-stderr-to-logging-module +""" +class LogPipe(threading.Thread): + def __init__(self): + """Setup the object with a logger and a loglevel + and start the thread + """ + threading.Thread.__init__(self) + self.daemon = False + self.fdRead, self.fdWrite = os.pipe() + self.pipeReader = os.fdopen(self.fdRead) + self.start() + + def fileno(self): + """Return the write file descriptor of the pipe + """ + return self.fdWrite + + def run(self): + """Run the thread, logging everything. + """ + for line in iter(self.pipeReader.readline, ''): + line = line.rstrip('\r\n') + if len(line) > 0: + # check if this message comes from the publish subprocess (LEVEL: msg..) + tokens = line.split(':') + if tokens > 0 and g_levelMap.has_key(tokens[0]): + level = tokens[0] + msg = line[len(tokens[0])+1:].strip() + # log this message with the correct level + # we are using warning and error explicetely because log() + # does not support our counting of warnings and errors + if level == 'WARNING': + logger.warning(msg) + elif level == 'ERROR': + logger.error(msg) + else: + logger.log(g_levelMap[level], msg) + else: + if self.handleAsError(line): + logging.error(line) + elif self.handleAsInfo(line): + logging.info(line) + # ignore memory leak outputs + elif not 'Bytes' in line: + logging.debug(line) + + self.pipeReader.close() + + def close(self): + """Close the write end of the pipe. + """ + try: + os.close(self.fdWrite) + except: + pass + + def handleAsInfo(self, msg): + if ('rendering') in msg.lower(): + return True + return False + + def handleAsError(self, msg): + """Specifies if the given message should be handled + as an error. + """ + if ('failed') in msg.lower(): + return True + if ('unable') in msg.lower(): + return True + if ('wrong') in msg.lower(): + return True + return False + + def __del__(self): + """delete object, call close + """ + self.close() + + +class ErrorItem(object): + def __init__(self, time="", level="", msg=""): + super(ErrorItem, self).__init__() + self.children = [] + self.parent = None + + self.time = time + self.level = level + self.msg = msg + + self.is_selected = False + + def GetChildren(self): + return self.children + + def AddChild(self, child): + if not isinstance(child, ErrorItem): + raise TypeError('expected TreeViewItem instance.') + self.children.append(child) + child.parent = self + + def GetNext(self): + if not self.parent: + return None + try: + i = self.parent.children.index(self) + return self.parent.children[i + 1] + except (ValueError, IndexError): + return None + + def GetPred(self): + if not self.parent: + return None + i = self.parent.children.index(self) + if i > 0: + return self.parent.children[i - 1] + return None + + def GetUp(self): + return self.parent + + def GetDown(self): + try: + return self.children[0] + except IndexError: + return None + + def GetRoot(self): + curr = self + while curr.parent: + curr = curr.parent + return curr + + def DeselectAll(self): + self.is_selected = False + for child in self.children: + child.DeselectAll() + + def GetSelected(self): + if self.is_selected: + yield self + for child in self.children: + for selected in child.GetSelected(): + yield selected + + def Select(self, selected=True): + self.is_selected = selected + + def IsSelected(self): + return self.is_selected + + def Format(self, i=0): + print i * ' ' + '' + for child in self.children: + child.format(i + 1) + + def Sort(self, key=lambda x: int(x.data['id'])): + for child in self.children: + child.sort(key) + self.children.sort(key=key) + + def Find(self, key): + if key(self): + return self + for child in self.children: + r = child.find(key) + if r: return r + return None + +class RootItem(ErrorItem): + + def __init__(self): + super(RootItem, self).__init__() + + def GetSelected(self): + return False + + def GetSelectedChildren(self): + for child in self.children: + for selected in child.GetSelected(): + yield selected + + def __str__(self): + return "root" + + def Clear(self): + self.children = [] + + def GetLastChild(self): + try: + return self.children[-1] + except IndexError: + print "Ahaaaaa fu" + return None + +class ErrorHandler(logging.Handler): + + def __init__(self): + # run the regular Handler __init__ + logging.Handler.__init__(self) + del g_errorlist[:] + + def emit(self, record): + now = datetime.datetime.now() + time = datetime.datetime.strftime(now, '%H:%M:%S') # for more options see http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior + g_errorlist.append(ErrorItem(time, record.levelname, record.msg)) + UpdateErrorList() + UpdateTreeView() + +class ErrorList(c4d.gui.TreeViewFunctions): + + def GetFirst(self, root, userdata): + """Return the first element of the hierarchy""" + return root.GetDown() + + def GetNext(self, root, userdata, obj): + """Return the next element of the passed object""" + return obj.GetNext() + + def GetPred(self, root, userdata, obj): + """Return the previous element of the passed object""" + return obj.GetPred() + + def GetDown(self, data, userdata, obj): + return obj.GetDown() + + def GetName(self, data, userdata, obj): + return str(obj) + + def IsSelected(self, data, userdata, issue): + return issue.is_selected + + def Select(self, data, userdata, obj, mode): + if mode == c4d.SELECTION_SUB: + obj.Select(False) + elif mode == c4d.SELECTION_NEW: + obj.GetRoot().DeselectAll() + obj.Select() + elif mode == c4d.SELECTION_ADD: + bj.GetRoot().DeselectAll() # remove this to support multi selection + obj.Select() + + def DrawCell(self, root, userdata, obj, col, drawinfo, bgColor): + "Draw the cell" + if col == TREEVIEW_COLUMN_ID_TIME: + text = obj.time + elif col == TREEVIEW_COLUMN_ID_LEVEL: + text = obj.level.title() + else: + text = obj.msg + + area = drawinfo["frame"] + + # multiply text color with red or yellow depending on warning level (LAUBWERKCINEMA-524) + textColor = area.GetColorRGB(c4d.COLOR_TEXT) + textColor = dict((k, v / 255.0) for k, v in textColor.items()) + if obj.level == 'WARNING': + # yellow + textColor['b'] = textColor['b'] * 0.0 + elif obj.level == 'ERROR': + # multiply with red (pure red is barely readable) + textColor['r'] = 1.0#textColor['r'] * 0.7 + textColor['g'] = 0.0#textColor['g'] * 0.1 + textColor['b'] = 0.0#textColor['b'] * 0.1 + + area.DrawSetTextCol(c4d.Vector(textColor['r'], textColor['g'], textColor['b']), bgColor) + area.DrawText(text, drawinfo["xpos"], drawinfo["ypos"], flags = c4d.DRAWTEXT_VALIGN_MASK) + + def GetLineHeight(self, root, userdata, obj, col, area): + return 16 + + def GetHeaderColumnWidth(self, root, userdata, col, area): + width = 100 + if col == TREEVIEW_COLUMN_ID_TIME: + width = 40 + elif col == TREEVIEW_COLUMN_ID_LEVEL: + width = 50 + elif col == TREEVIEW_COLUMN_ID_DESCRIPTION: + width = -1 + return width + + def GetColumnWidth(self, root, userdata, obj, col, area): + width = 100 + if col == TREEVIEW_COLUMN_ID_TIME: + width = 50 + elif col == TREEVIEW_COLUMN_ID_LEVEL: + width = 60 + elif col == TREEVIEW_COLUMN_ID_DESCRIPTION: + def lenMsg(x): + return len(str(x.msg)) + width = area.DrawGetTextWidth(max(g_errorRoot.GetChildren(), key=lenMsg)) + return width + +def UpdateErrorList(): + global g_errorRoot + g_errorRoot.Clear() + for error in g_errorlist: + if g_levelMap[error.level] >= g_level: + g_errorRoot.AddChild(error) + +def UpdateTreeView(): + c4d.SpecialEventAdd(MSG_PBRT_UPDATE_LOG) + +# +# helper functions to iterate through the object tree starting at a certain object +# +def iter_tree(obj, include_first=True): + if include_first: + yield obj + cache = obj.GetCache() + while cache: + for o in iter_tree(cache, True): + yield o + cache = cache.GetNext() + + for child in obj.GetChildren(): + for o in iter_tree(child, True): + yield o + +# +# helper functions to iterate through all object trees in a document +# +def iter_all(doc): + for obj in doc.GetObjects(): + for o in iter_tree(obj): + yield o + +# +# takes a name and an optional list of existing names +# the name is first forced to conform to a number of conditions (ascii only, etc.), then checked if +# it already exists and modified until it is unique +# +def SanitizeObjectName(name, nameList=None): + # todo + return name + +def FindNamedObject(object, namedObjects): + for namedObject in namedObjects: + if object == namedObject[0]: + return namedObject + return None + +# +# The GenerateTexturePath() function only exists in the C++ API, so we have to roll our own here... +# +def GenerateTexturePath(docpath, file): + if os.path.isabs(file): + if os.path.isfile(file): + return file + else: + return '' + + if os.path.isfile(os.path.join(docpath, file)): + return os.path.join(docpath, file) + + if os.path.isfile(os.path.join(docpath, 'tex', file)): + return os.path.join(docpath, 'tex', file) + + # TODO: include texture paths from preferences (Edit->Preferences->Files einstellen) + + return '' + + +# +# This function walks up to the parents and collects all texture tags. It starts at the topmost parent +# object and grabs all tags, then goes back through the hierarchy and replaces all tags that are +# superceded. +# The order of the tags is inverted over the order on the objects, so the tags with the highest +# precedence come first. This means, as soon as a tag is found that will be applied to tthe piece of +# geometry we are looking at, we don't have to look any further +# +def GetTextureTagsRec(obj): + parentTags = [] + parent = obj.GetUp() + if parent: + parentTags = GetTextureTagsRec(parent) + else: + parent = obj.GetCacheParent() + if parent: + parentTags = GetTextureTagsRec(parent) + + objectTags = [] # here we will collect all tags that will be added from the current object + for tag in reversed(obj.GetTags()): + # every texture tag that comes after one that has no restriction, can be ignored + if tag.GetType() == c4d.Ttexture: + # if there is no material associated, ignore this tag + if not tag.GetMaterial(): + continue + + # if this texture tag has no restriction, it just overrides everything from parent objects + # and also no other tag from the current object will be taken into account. + restriction = tag[c4d.TEXTURETAG_RESTRICTION] + if not restriction or len(restriction) == 0: + objectTags.append(tag) + parentTags = [] + break + + objectTags.append(tag) + + def hasRestriction(tag, restriction): + if restriction == tag[c4d.TEXTURETAG_RESTRICTION]: + return True + else: + return False + + # check if a tag with the identical restriction exists in parentTags and remove it + parentTags = [parentTag for parentTag in parentTags if not hasRestriction(parentTag, restriction)] + + # insert the new tags at the beginning of the list + objectTags.extend(parentTags) + return objectTags + +EPSILON = 0.00001 + +# +# depending on the mode, either just pass the texture name through or copy it to the target directory and return just the basename. +# add the texture to the textureList, so it can be cleared later +# +def ManageTexture(filename, doc, directory = None, textureList = None): + filePath = GenerateTexturePath(doc.GetDocumentPath(), filename) + if not os.path.isfile(filePath): + logger.warning(filename + ' not found!') + return filename + + if directory: + # make sure dir really only contains the folder + if not os.path.isdir(directory): + raise ValueError(str(directory) + ' is not a directory!') + + # copy texture file to target path + myFilename = os.path.basename(filePath) + myDstPath = os.path.join(directory, myFilename) + shutil.copyfile(filePath, myDstPath) + + # add (absolute!) destination path to texture list + if textureList: + textureList.append(myDstPath) + + # return just the base file name + return myFilename + else: + return filePath + + +def makePbrtAttributeFloat(attrib, val): + return '"float ' + attrib +'" [' + str(val) + ']' + +def makePbrtAttributeColor(attrib, color, transform=True): + color = c4d.utils.TransformColor(color, c4d.COLORSPACETRANSFORMATION_SRGB_TO_LINEAR) if transform else color + return '"rgb ' + attrib + '" [' + str(color.x) + ' ' + str(color.y) + ' ' + str(color.z) +']' + +def makePbrtAttributeTexture(attrib, tex): + return '"texture ' + attrib + '" "' + tex + '"' + +def makePbrtAttribute(attrib, val, transform=True): + attribType = type(val) + if attribType == float: + return makePbrtAttributeFloat(attrib, val) + elif attribType == c4d.Vector: + return makePbrtAttributeColor(attrib, val, transform) + elif attribType == str: + return makePbrtAttributeTexture(attrib, val) + +def makePbrtTexture(filename, texAbbrev, texType='spectrum', useGamma=True): + extension = os.path.splitext(filename)[1] + gamma = 1.0 if extension != '.exr' else 2.2 + if not (extension == '.exr' or extension == '.tga' or extension == '.pfm' or extension == '.png'): + logger.warning('Texture file "' + os.path.basename(filename) + '" uses unsupported texture file format') + bumpTextureName = os.path.splitext(os.path.basename(filename))[0] + '_' + texAbbrev + bumTextureString = 'Texture "' + bumpTextureName + '" "' + texType + '" "imagemap" "string filename" "' + filename.replace('\\','\\\\') + '"' + if not c4d.utils.CompareFloatTolerant(gamma, 1.0): + bumTextureString += ' ' + makePbrtAttributeFloat('gamma', gamma) + return bumpTextureName, bumTextureString + +# +# export the given object as a polygon object +# since in pbrt an object can only have a single object, this may actually export as +# several pbrt objects +# +def ExportPolygonObject(pbrtGeometry, pbrtMaterials, exportedMaterials, obj, indent=""): + if obj.GetType() != c4d.Opolygon: + raise TypeError("Expected a BaseObject of type Opolygon!") + + doc = obj.GetDocument() + pbrtDir = os.path.dirname(os.path.abspath(pbrtGeometry.name)) + + # + # TODO: + # to split up, do the following + # walk through polygons, for each vertex check if there is already a vertex that has: + # (1) the same vertex index + # (2) the same normal (within a limit) + # (3) the same uv coordinate (within a limit) + # this process will create a map that for each vertex has a list of taget vertices with different uvs and normals + # To accomodate for different primitives, we may either want to do this for each + # material selection (potentially killing runtime behavior) or update the mapping with + # new target vertex indices in for each material (probably more sensible). + # when writing the polygons + # That data structure will contain some information that lets us look up the original + # data for comparison. An efficient way is probably to not copy the original data, but + # point to the polygon that this data is stored with. + # The number of different material assignements should be determined beforehand. Take + # into consideration that this might be nontrivial to figure out based on material + # sidedness, selections and material application order. Since we're making a 'grungy' + # exporter, we should probably ignore a few of the intricacies for now. + # + # Also keep in mind that PBRT likes to get the texture passed directly to the mesh for + # clipping via the alpha texture parameter. + # + + # grab phong normals and uvw tag. The uvw tag can be different depending on which material we are writing + tmpPhongNormals = obj.CreatePhongNormals() + uvwTag = obj.GetTag(c4d.Tuvw) + + # keep a list of polygons already exported with a particular material, so we can stop when all polygons have been written + # and also make sure all polygons get written even if there is no material assigned + touchedPolygons = obj.GetPolygonS().GetClone() + touchedPolygons.DeselectAll() + + # for all potentially applied materials, check if there are any selections and export a trianglemesh per selection + # we append an empty texturetag entry at the end, so there is an iteration that would write all polygons with the default material + textureTags = GetTextureTagsRec(obj) + textureTags.append(c4d.BaseTag(c4d.Ttexture)) + for textureTag in textureTags: + + # create a list of just polygon selection tags + def isPolygonSelectionTag(tag): + if tag.GetType() == c4d.Tpolygonselection: + return True + else: + return False + + selectionTags = [tag for tag in obj.GetTags() if isPolygonSelectionTag(tag)] + restriction = textureTag[c4d.TEXTURETAG_RESTRICTION] + currentSelection = None + for selectionTag in selectionTags: + if selectionTag.GetName() == restriction: + currentSelection = selectionTag.GetBaseSelect() + break + + if not currentSelection and restriction and len(restriction) > 0: + #print "ignored due to no matching selection" + continue + + if currentSelection and currentSelection.GetCount() == 0: + #print "ignored due to empty selection" + continue + + innerAttributeBlock = False + alphaTextureName = None + material = textureTag.GetMaterial() + if material: + # DEBUG + #print material.GetName() + +# if material.GetType() != c4d.Mmaterial and material.GetType() != c4d.BaseMaterial: +# logger.warning(material.GetName()) +# logger.warning("Unidentified material type encountered and ignored!") +# logger.warning(material) +# continue + + pbrtGeometry.write(indent + 'AttributeBegin\n') + indent += "\t" + pbrtGeometry.write(indent + 'NamedMaterial "' + str(material.GetName()) + '"\n') + innerAttributeBlock = True + + # translate material + if not material.GetName() in exportedMaterials: + exportedMaterials[material.GetName()] = 1 + baseColor = c4d.Vector(0, 0, 0) + colorTextureName = None + if material[c4d.MATERIAL_USE_COLOR]: + baseColor = material[c4d.MATERIAL_COLOR_COLOR] * material[c4d.MATERIAL_COLOR_BRIGHTNESS] + colorShader = material[c4d.MATERIAL_COLOR_SHADER] + if colorShader and colorShader.GetType() == c4d.Xbitmap: + try: + colorTextureFile = ManageTexture(colorShader[c4d.BITMAPSHADER_FILENAME], doc, pbrtDir, None) + colorTextureName, colorTextureString = makePbrtTexture(colorTextureFile, 'color') + except (RuntimeError, ValueError) as err: + logger.error(err) + else: + pbrtMaterials.write(colorTextureString + '\n') + + alphaTextureName = None + if material[c4d.MATERIAL_USE_ALPHA]: + alphaShader = material[c4d.MATERIAL_ALPHA_SHADER] + if alphaShader and alphaShader.GetType() == c4d.Xbitmap: + try: + alphaTextureFile = ManageTexture(alphaShader[c4d.BITMAPSHADER_FILENAME], doc, pbrtDir, None) + # alpha is stored as linear by default so we ignore gamma here + alphaTextureName, alphaTextureString = makePbrtTexture(alphaTextureFile, 'alpha', 'float', False) + except (RuntimeError, ValueError) as err: + logger.error(err) + else: + pbrtMaterials.write(alphaTextureString + '\n') + + bumpTextureName = None + if material[c4d.MATERIAL_USE_BUMP]: + bumpShader = material[c4d.MATERIAL_BUMP_SHADER] + if bumpShader and bumpShader.GetType() == c4d.Xbitmap: + try: + bumpTextureFile = ManageTexture(bumpShader[c4d.BITMAPSHADER_FILENAME], doc, pbrtDir, None) + bumpTextureName, bumpTextureString = makePbrtTexture(bumpTextureFile, 'bump', 'float', False) + except (RuntimeError, ValueError) as err: + logger.error(err) + else: + pbrtMaterials.write(bumpTextureString + '\n') + + glossyColor = c4d.Vector(0.0) + reflectivityColor = c4d.Vector(0.0) + roughness = 0.1 + ior = 1.333 + specularTextureName = None + if material[c4d.MATERIAL_USE_REFLECTION]: + reflectDataId = c4d.REFLECTION_LAYER_LAYER_DATA + c4d.REFLECTION_LAYER_LAYER_SIZE * 4 # 4 = default layer id + roughness = material[reflectDataId + c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS] + specularColor = material[reflectDataId + c4d.REFLECTION_LAYER_COLOR_COLOR] + specularColorBrightness = material[reflectDataId + c4d.REFLECTION_LAYER_COLOR_BRIGHTNESS] + specularStrength = material[reflectDataId + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] + + reflectType = material[reflectDataId + c4d.REFLECTION_LAYER_MAIN_DISTRIBUTION] + reflectionStrength = 0.25 + if reflectType == c4d.REFLECTION_DISTRIBUTION_GGX: + reflectionStrength = material[reflectDataId + c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION] + if material[reflectDataId + c4d.REFLECTION_LAYER_FRESNEL_MODE] == c4d.REFLECTION_FRESNEL_DIELECTRIC: + ior = material[reflectDataId + c4d.REFLECTION_LAYER_FRESNEL_VALUE_IOR] + elif reflectType == c4d.REFLECTION_DISTRIBUTION_SPECULAR_BLINN: + reflectionStrength = material[reflectDataId + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] + + glossyColor = specularColor * specularColorBrightness * specularStrength + reflectivityColor = specularColor * specularColorBrightness * reflectionStrength + + specularColorShader = material[reflectDataId + c4d.REFLECTION_LAYER_COLOR_TEXTURE] + if specularColorShader is not None and specularColorShader.GetType() == c4d.Xbitmap: + specularTextureFile = ManageTexture(specularColorShader[c4d.BITMAPSHADER_FILENAME], doc, pbrtDir, None) + try: + specularTextureName, specularTextureString = makePbrtTexture(specularTextureFile, 'specular') + except RuntimeError as err: + logger.error(err) + else: + pbrtMaterials.write(specularTextureString + '\n') + + useTranslucency = False + if material[c4d.MATERIAL_USE_LUMINANCE]: + luminanceShader = material[c4d.MATERIAL_LUMINANCE_SHADER] + if luminanceShader is not None: + if luminanceShader.GetType() == c4d.Xfusion: + if luminanceShader[c4d.SLA_FUSION_BASE_CHANNEL] is not None: + if luminanceShader[c4d.SLA_FUSION_BASE_CHANNEL].GetType() == c4d.Xtranslucency: + useTranslucency = True + elif luminanceShader.GetType() == c4d.Xlayer: + shader = luminanceShader.GetDown() + while shader != None: + if shader.GetType() == c4d.Xtranslucency: + useTranslucency = True + break + shader = shader.GetNext() + + opacityColor = c4d.Vector(1.0) + if material[c4d.MATERIAL_USE_TRANSPARENCY]: + opacityColor = (material[c4d.MATERIAL_TRANSPARENCY_COLOR] * material[c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS]) + transmissivityColor = c4d.Vector(1.0) - opacityColor + + # create named material if material is translucent so we can reference it from Mix material + if useTranslucency: + prefix = 'MakeNamedMaterial "' + material.GetName() + '_front" "string type"' + else: + prefix = 'MakeNamedMaterial "' + material.GetName() + '" "string type"' + + if not c4d.utils.CompareFloatTolerant(transmissivityColor.GetLength(), 0.0): + pbrtMaterials.write(prefix +' "glass" ' + makePbrtAttributeFloat('index', ior)) + pbrtMaterials.write(' ' + makePbrtAttribute('Kr', reflectivityColor if specularTextureName is None else specularTextureName)) + pbrtMaterials.write(' ' + makePbrtAttribute('Kt', transmissivityColor, False)) + else: + pbrtMaterials.write(prefix +' "uber" ' + makePbrtAttributeFloat('index', ior)) + pbrtMaterials.write(' ' + makePbrtAttribute('Kd', baseColor if colorTextureName is None else colorTextureName)) + pbrtMaterials.write(' ' + makePbrtAttribute('Ks', glossyColor if specularTextureName is None else specularTextureName)) + pbrtMaterials.write(' ' + makePbrtAttribute('Kr', reflectivityColor if specularTextureName is None else specularTextureName)) + pbrtMaterials.write(' ' + makePbrtAttributeFloat('roughness', roughness)) + #pbrtMaterials.write(' ' + makePbrtAttributeColor('opacity', opacityColor, False)) + + if useTranslucency: + # create translucent material + pbrtMaterials.write('\n') + pbrtMaterials.write('MakeNamedMaterial "' + material.GetName() + '_back" "string type" "translucent" "rgb reflect" [0.0 0.0 0.0] "rgb transmit" [1.0 1.0 1.0] ') + pbrtMaterials.write(' ' + makePbrtAttribute('Kd', baseColor if colorTextureName is None else colorTextureName)) + # create mix material + pbrtMaterials.write('\n') + pbrtMaterials.write('Material "mix" "color amount" [0.4 0.4 0.4] "string namedmaterial1" "' + material.GetName() + '_front" "string namedmaterial2" "' + material.GetName() + '_back"') + + # all materials take a texture that can be used to specify a bump map + # (commented this line because it produces a warning when used with mixed material and duplicated it instead whereever it s used) + if bumpTextureName: + pbrtMaterials.write(' ' + makePbrtAttribute('bumpmap', bumpTextureName)) + pbrtMaterials.write('\n') + + # these are the point, uv, normal and index lists to be filled + # and written to the upcoming triangle mesh + points = [] + uvs = None + if (uvwTag): + uvs = [] + normals = None + if tmpPhongNormals: + normals = [] + indices = [] + + + # for each original vertex index store a list of target vertices. With these vertices we store the new index, the uv texture coordinate and the normal + vertexMap = dict() + for iPolygon, polygon in zip(range(obj.GetPolygonCount()), obj.GetAllPolygons()): + if (currentSelection and not currentSelection.IsSelected(iPolygon)) or touchedPolygons.IsSelected(iPolygon): + continue + + touchedPolygons.Select(iPolygon) + + # add this polygon to the list of touched polygons + + # for each vertex, get the index, uv coordinate and phong normal and check if it already exists + if uvwTag: + uvwdict = uvwTag.GetSlow(iPolygon) + else: + uvwdict = {"a" : None, "b" : None, "c" : None, "d" : None} + + # helper function that checks whether a point that references the same original mesh + # point and has the same texture coordinates and normal already exists. If it exists, + # its index is returned. If it doesn't, it is created and the new index is returned. + # This is necessary, because pbrt stores normals and texture coordinates per point and + # never per vertex, so we effectively have to split up points that have discontinuous + # texture coordinates or normals into multiple points. + def checkVertex(index, uvw, normal): + newIndex = len(points) + if vertexMap.has_key(index): + for entry in vertexMap[index]: + if (not uvw or (math.fabs(entry[0].x - uvw.x) < EPSILON and math.fabs(entry[0].y - uvw.y) < EPSILON and math.fabs(entry[0].z - uvw.z) < EPSILON)) and \ + (not normal or (math.fabs(entry[1].x - normal.x) < EPSILON and math.fabs(entry[1].y - normal.y) < EPSILON and math.fabs(entry[1].z - normal.z) < EPSILON)): + return entry[2] + + vertexMap[index].append([uvw, normal, newIndex]) + else: + vertexMap[index] = [[uvw, normal, newIndex]] + + # we only get here if there is no matching entry for the new vertex already, so go ahead and make one + # store a new vertx entry, since there is either no entry for this index or uvw or normal were different + points.append(obj.GetPoint(index)) + if uvw != None and uvs != None: + uvs.append(uvw) + if normals != None: + normals.append(normal) + + return newIndex + + # vertex a + newIndexA = checkVertex(polygon.a, uvwdict["a"], None if not tmpPhongNormals else tmpPhongNormals[iPolygon*4+0]) + indices.append(newIndexA) + + # vertex b + indices.append(checkVertex(polygon.b, uvwdict["b"], None if not tmpPhongNormals else tmpPhongNormals[iPolygon*4+1])) + + # vertex c + newIndexC = checkVertex(polygon.c, uvwdict["c"], None if not tmpPhongNormals else tmpPhongNormals[iPolygon*4+2]) + indices.append(newIndexC) + + if polygon.c != polygon.d: + indices.append(newIndexC) + + # vertex d + indices.append(checkVertex(polygon.d, uvwdict["d"], None if not tmpPhongNormals else tmpPhongNormals[iPolygon*4+3])) + + indices.append(newIndexA) + + if len(indices) > 0: + pbrtGeometry.write(indent + 'Shape "trianglemesh" "integer indices" [') + # write indices + for index in indices: + pbrtGeometry.write(str(index) + ' ') + # write points + pbrtGeometry.write('] "point P" [') + #for point in obj.GetAllPoints(): + for point in points: + pbrtGeometry.write(str(point.x) + ' ' + str(point.y) + ' ' + str(point.z) + ' ') + # write uv coordinates, apply texture tag scaling settings + if uvs: + offsetx = textureTag[c4d.TEXTURETAG_OFFSETX] + offsety = textureTag[c4d.TEXTURETAG_OFFSETY] + lengthx = textureTag[c4d.TEXTURETAG_LENGTHX] + lengthy = textureTag[c4d.TEXTURETAG_LENGTHY] + pbrtGeometry.write('] "float uv" [') + for uv in uvs: + pbrtGeometry.write(str((uv.x - offsetx) / lengthx) + ' ' + str((-uv.y + offsety) / lengthy) + ' ') + # write normals + if normals: + pbrtGeometry.write('] "normal N" [') + for normal in normals: + pbrtGeometry.write(str(normal.x) + ' ' + str(normal.y) + ' ' + str(normal.z) + ' ') + # close array + pbrtGeometry.write(']') + if alphaTextureName: + pbrtGeometry.write('"texture alpha" "' + alphaTextureName + '"') + pbrtGeometry.write('\n') + + if innerAttributeBlock: + indent = indent[0:-1] + pbrtGeometry.write(indent + 'AttributeEnd\n') + + if touchedPolygons.GetCount() == obj.GetPolygonCount(): + break + + +# +# Run through the scene recursively and call the passed function for every object. +# The passed function is supposed to return a bool, when that bool is False, it should not walk +# into the object that was just processed. +# The function will stack AttributeBegin/AttributeEnd blocks like they are in the scene hierarchy +# The function expects an c4d.BaseObject or c4d.BaseDocument as second parameter +# +# The root object is mainly passed to stop traversing up the tree for visibility detection +# this is important when writing object trees which are instanced and therefore don't take +# upstream visibility settings into account +# +def WalkObjectTree(pbrtGeometry, pbrtMaterials, obj, exportedMaterials, functionToCall, namedObjects = [], indent = "", rootObj = None): + if type(obj) != c4d.documents.BaseDocument: + # call the function that does the actual thing + # when this function returns False, no further traversal into children should be done + result = functionToCall(pbrtGeometry, pbrtMaterials, obj, exportedMaterials, namedObjects, indent, rootObj) + if result: + cache = obj.GetDeformCache() + if cache == None: + cache = obj.GetCache() + while cache: + pbrtGeometry.write(indent + "AttributeBegin\n") + indent += "\t" + pbrtGeometry.write(indent + "# " + cache.GetName() + "\n") + ml = cache.GetMl() + if ml != c4d.Matrix(): + pbrtGeometry.write(indent + 'ConcatTransform [' + str(ml.v1.x) + ' ' + str(ml.v1.y) + ' ' + str(ml.v1.z) + ' 0 ' + str(ml.v2.x) + ' ' + str(ml.v2.y) + ' ' + str(ml.v2.z) + ' 0 ' + str(ml.v3.x) + ' ' + str(ml.v3.y) + ' ' + str(ml.v3.z) + ' 0 ' + str(ml.off.x) + ' ' + str(ml.off.y) + ' ' + str(ml.off.z) + ' 1]\n') + WalkObjectTree(pbrtGeometry, pbrtMaterials, cache, exportedMaterials, functionToCall, namedObjects, indent, rootObj) + indent = indent[0:-1] + pbrtGeometry.write(indent + "AttributeEnd\n") + cache = cache.GetNext() + + for child in obj.GetChildren(): + pbrtGeometry.write(indent + "AttributeBegin\n") + indent += "\t" + pbrtGeometry.write(indent + "# " + child.GetName() + "\n") + ml = child.GetMl() + if ml != c4d.Matrix(): + pbrtGeometry.write(indent + 'ConcatTransform [' + str(ml.v1.x) + ' ' + str(ml.v1.y) + ' ' + str(ml.v1.z) + ' 0 ' + str(ml.v2.x) + ' ' + str(ml.v2.y) + ' ' + str(ml.v2.z) + ' 0 ' + str(ml.v3.x) + ' ' + str(ml.v3.y) + ' ' + str(ml.v3.z) + ' 0 ' + str(ml.off.x) + ' ' + str(ml.off.y) + ' ' + str(ml.off.z) + ' 1]\n') + WalkObjectTree(pbrtGeometry, pbrtMaterials, child, exportedMaterials, functionToCall, namedObjects, indent, rootObj) + indent = indent[0:-1] + pbrtGeometry.write(indent + "AttributeEnd\n") + + else: + for o in obj.GetObjects(): + pbrtGeometry.write(indent + "AttributeBegin\n") + indent += "\t" + pbrtGeometry.write(indent + "# " + o.GetName() + "\n") + ml = o.GetMl() + if ml != c4d.Matrix(): + pbrtGeometry.write(indent + 'ConcatTransform [' + str(ml.v1.x) + ' ' + str(ml.v1.y) + ' ' + str(ml.v1.z) + ' 0 ' + str(ml.v2.x) + ' ' + str(ml.v2.y) + ' ' + str(ml.v2.z) + ' 0 ' + str(ml.v3.x) + ' ' + str(ml.v3.y) + ' ' + str(ml.v3.z) + ' 0 ' + str(ml.off.x) + ' ' + str(ml.off.y) + ' ' + str(ml.off.z) + ' 1]\n') + WalkObjectTree(pbrtGeometry, pbrtMaterials, o, exportedMaterials, functionToCall, namedObjects, indent, rootObj) + indent = indent[0:-1] + pbrtGeometry.write(indent + "AttributeEnd\n") + +def IsProcessRunning(): + global g_thread + return g_thread is not None and g_thread.IsRunning() + +def TerminateProcess(): + global g_thread + if g_thread is not None: + g_thread.TerminateRenderer() + g_thread.End() + g_thread = None + +def GetRenderModeRec(obj, rootObj=None): + renderMode = obj.GetRenderMode() + if renderMode is c4d.MODE_UNDEF and obj != rootObj: + parent = obj.GetUp() + if parent: + renderMode = GetRenderModeRec(parent, rootObj) + else: + parent = obj.GetCacheParent() + if parent: + renderMode = GetRenderModeRec(parent, rootObj) + + return renderMode + + +class PbrtThread(c4d.threading.C4DThread): + def __init__(self, doc, mode, data, exe, path): + super(c4d.threading.C4DThread, self).__init__() + self.doc = doc.GetClone(c4d.COPYFLAGS_DOCUMENT) + self.mode = mode + self.data = data + self.exe = exe + self.path = path + self.pbrtProcess = None + + + def Main(self): + # reset global variables + global g_bakeDoc + global g_bakeTag + global g_bakeTextureFile + global g_nLightSourcesExported + g_bakeDoc = None + g_bakeTag = None + g_bakeTextureFile = None + g_nLightSourcesExported = 0 + + logger.info("Evaluating Document Copy...") + self.doc.ExecutePasses(self.Get(), True, True, True, c4d.BUILDFLAGS_EXTERNALRENDERER) + + logger.info("Starting Export...") + pbrtFilename, imageFilename = self.ExportDocumentToPbrt(self.doc, self.data, self.path) + + # if an environment file was created... + if g_bakeTextureFile: + # ...first wait until the file actually shows up... + for i in range(60): + if os.path.exists(g_bakeTextureFile): + break + logger.info("Waiting for Environment Baking to finish...") + time.sleep(1) + + # ...then wait until it is can be opened for reading + for i in range(240): + try: + bakeFileTmp = open(g_bakeTextureFile, 'r') + bakeFileTmp.close() + break + except: + logger.info("Waiting for Environment Baking to finish...") + time.sleep(1) + + # also don't forget to free the tag and document + g_bakeTag = None + g_bakeDoc = None + + # if an output filename is defined and the gui is set to start the rendering, go ahead + if imageFilename is not None and self.mode != IDC_PBRT_MODE_EXPORT: + global g_bmp + logger.info("Start External Rendering...") + g_bmp = self.ExecuteRenderer(pbrtFilename, imageFilename) + + c4d.SpecialEventAdd(MSG_PBRT_FINISHED) + + + # + # export the current document as pbrt file, return the path of the resulting file and the output image file + # + def ExportDocumentToPbrt(self, doc, data, dest=""): + bc = doc.GetActiveRenderData().GetData() + + docFilename = doc.GetDocumentName() + docPath = doc.GetDocumentPath() + globalLightScale = data.GetFloat(IDC_PBRT_INTENSITY) + + # generate a temporary location and filename for the exported file image + if len(dest) > 0: + pbrtFilename = dest + else: + pbrtFilename = os.path.join(tempfile.gettempdir(), os.path.splitext(docFilename)[0] + ".pbrt") + + pbrt = open(pbrtFilename, 'w') + + pbrtMaterialsFilename = os.path.splitext(pbrtFilename)[0] + '_materials' + os.path.splitext(pbrtFilename)[1] + pbrtGeometryFilename = os.path.splitext(pbrtFilename)[0] + '_geometry' + os.path.splitext(pbrtFilename)[1] + + # + # output scene options that are derived from the camera/viewport + # + camera = doc.GetRenderBaseDraw() + mi = camera.GetMi() + cameraObject = camera.GetSceneCamera(doc) + if (cameraObject): + mi = ~cameraObject.GetMg() + pbrt.write('Transform [' + str(mi.v1.x) + ' ' + str(mi.v1.y) + ' ' + str(mi.v1.z) + ' 0 ' + str(mi.v2.x) + ' ' + str(mi.v2.y) + ' ' + str(mi.v2.z) + ' 0 ' + str(mi.v3.x) + ' ' + str(mi.v3.y) + ' ' + str(mi.v3.z) + ' 0 ' + str(mi.off.x) + ' ' + str(mi.off.y) + ' ' + str(mi.off.z) + ' 1]\n') + + # we need render settings for dof, so they are initialized here already + renderData = doc.GetActiveRenderData() + renderDataBc = renderData.GetDataInstance() + + # Pbrt expects the camera fov to be the spread angle of the viewing frustum along the narrower + # of the images width and height. CINEMA 4D provides both, so we just grab the smaller of the + # two. + cameraFov = cameraObject[c4d.CAMERAOBJECT_FOV] + cameraVerticalFov = cameraObject[c4d.CAMERAOBJECT_FOV_VERTICAL] + if cameraFov > cameraVerticalFov: + cameraFov = cameraVerticalFov + if cameraObject == None: + pbrt.write('Camera "perspective" "float fov" [' + str(c4d.utils.Deg(cameraFov)) + ']\n') + else: + focalLength = cameraObject.GetDataInstance()[c4d.CAMERAOBJECT_TARGETDISTANCE] + lensRadius = 0 # default to pinhole camera + vp = renderData.GetFirstVideoPost() + while vp: + if vp.GetType() == 1023342 and not vp.GetBit(c4d.BIT_VPDISABLED) and vp.GetDataInstance()[c4d.VP_XMB_DOF]: + # Formula to compute the lens diameter from f-stop and focal length from here: + # http://www.punitsinha.com/resource/aperture_focal_length.html + # consider document scale, because focal length is always given in mm + # divide result by 2 because pbrt expects lens radius + mmUnitScale = c4d.UnitScaleData() + mmUnitScale.SetUnitScale(1, c4d.DOCUMENT_UNIT_MM) + scale = c4d.utils.CalculateTranslationScale(mmUnitScale, doc.GetSettingsInstance(c4d.DOCUMENTSETTINGS_DOCUMENT)[c4d.DOCUMENT_DOCUNIT]) + lensRadius = (cameraObject.GetDataInstance()[c4d.CAMERA_FOCUS] * scale) / cameraObject.GetDataInstance()[c4d.CAMERAOBJECT_FNUMBER_VALUE] / 2 + vp = vp.GetNext() + pbrt.write('Camera "perspective" "float fov" [' + str(c4d.utils.Deg(cameraFov)) + '] "float focaldistance" [' + str(focalLength) + '] "float lensradius" [' + str(lensRadius) + ']\n') + + # + # output scene options that are derived from the render settings + # + pbrt.write('Sampler "halton" "integer pixelsamples" [' + str(data.GetInt32(IDC_PBRT_SAMPLES)) + ']\n') + + # generate a temporary location and filename for the output image + # TODO: Also make the filename random + if len(dest) > 0: + destFile = os.path.basename(dest) + imageFilename = os.path.splitext(destFile)[0] + '.exr' + else: + imageFilename = os.path.join(tempfile.gettempdir(), 'simple.exr') + pbrt.write('Film "image" "string filename" ["' + imageFilename.replace('\\','\\\\') + '"] "integer xresolution" [' + str(int(renderDataBc[c4d.RDATA_XRES])) +'] "integer yresolution" [' + str(int(renderDataBc[c4d.RDATA_YRES])) + ']\n') + + # search for a global illumination post effect to decide which surfaceintegrator to use + renderVideoPost = renderData.GetFirstVideoPost() + while renderVideoPost: + if renderVideoPost.GetType() == 1021096 and not renderVideoPost.GetBit(c4d.BIT_VPDISABLED): + logger.info('Using Integrator "path" Due To Global Illumination Effect Present.') + pbrt.write('Integrator "path" "integer maxdepth" [5]\n') + break + renderVideoPost = renderVideoPost.GetNext() + + if not renderVideoPost: + logger.info('Using Integrator "directlighting" Due To Global Illumination Effect Not Present.') + pbrt.write('Integrator "directlighting" "integer maxdepth" [5] "string strategy" "all"\n') + + pbrt.write('WorldBegin\n') + indent = "\t" + + # + # set default material + # + pbrt.write(indent + '# Default Material\n') + defaultMaterialColor = doc[c4d.DOCUMENT_DEFAULTMATERIAL_COLOR] + linearDefaultMaterialColor = c4d.utils.TransformColor(defaultMaterialColor, c4d.COLORSPACETRANSFORMATION_SRGB_TO_LINEAR) + pbrt.write(indent + 'Material "uber" "rgb Kd" [' + str(linearDefaultMaterialColor.x) + ' ' + str(linearDefaultMaterialColor.y) + ' ' + str(linearDefaultMaterialColor.z) +'] "float index" [1.333]\n') + + """ + define an export function to be passed to WalkObjectTree as callback + TODO: should identify (physical) sky objects, bake them to a texture and define them as a light source + """ + def MyExportFunction(pbrtGeometry, pbrtMaterials, obj, exportedMaterials, namedObjects = [], indent="", rootObj=None): + # walk through all the possible reasons to not export this object + # if a reason is found, still return true, because this doesn't mean the subtree shouldn't be traversed + if not obj.GetDeformMode(): + return True + + renderMode = GetRenderModeRec(obj, rootObj) + if renderMode == c4d.MODE_OFF: + return True + + # take care of render instances and instanced objcts + if obj.GetType() == c4d.Oinstance and obj[c4d.INSTANCEOBJECT_RENDERINSTANCE] == True: + # make sure this instance is not used as input object for generator (LAUBWERKCINEMA-769) + # while this flag is always true for normal instances this check will work for render instances + if not obj.GetBit(c4d.BIT_CONTROLOBJECT) and not obj.GetBit(c4d.BIT_IGNOREDRAW): + namedObject = FindNamedObject(obj.GetDataInstance().GetObjectLink(c4d.INSTANCEOBJECT_LINK), namedObjects) + if namedObject: + pbrtGeometry.write(indent + 'ObjectInstance "' + namedObject[1] + '"\n') + # if this object has been inserted as an object instance, we return False to notify WalkObjectTree that it should not traverse the hierarchy below this object + return False + elif FindNamedObject(obj, namedObjects): + namedObject = FindNamedObject(obj, namedObjects) + if namedObject: + pbrtGeometry.write(indent + 'ObjectInstance "' + namedObject[1] + '"\n') + # if this object has been inserted as an object instance, we return False to notify WalkObjectTree that it should not traverse the hierarchy below this object + return False + + # this needs to be checked after the check whether this is an instanced object, + # because generator objects also return True here + if obj.GetBit(c4d.BIT_CONTROLOBJECT): + return True + + # this object is visible, write it to file + if obj.GetType() == c4d.Olight: + global g_nLightSourcesExported + g_nLightSourcesExported += 1 + # export this object as a light + lightColor = obj[c4d.LIGHT_COLOR] + lightBrightness = obj[c4d.LIGHT_BRIGHTNESS] + #lightBrightness *= 100 + if obj[c4d.LIGHT_TYPE] == c4d.LIGHT_TYPE_OMNI: + lightScale = obj[c4d.LIGHT_DETAILS_OUTERRADIUS] * globalLightScale + pbrtGeometry.write(indent + 'LightSource "point" "rgb I" [' + str(lightColor.x * lightBrightness) + ' ' + str(lightColor.y * lightBrightness) + ' ' + str(lightColor.z * lightBrightness) + '] "point from" [0 0 0] "rgb scale" [' + str(lightScale) + ' ' + str(lightScale) + ' ' + str(lightScale) + '] \n') + elif obj[c4d.LIGHT_TYPE] == c4d.LIGHT_TYPE_SPOT: + pass + elif obj[c4d.LIGHT_TYPE] == c4d.LIGHT_TYPE_DISTANT: + pbrtGeometry.write(indent + 'LightSource "distant" "rgb L" [' + str(lightColor.x * lightBrightness) + ' ' + str(lightColor.y * lightBrightness) + ' ' + str(lightColor.z * lightBrightness) + '] "point from" [0 0 0] "point to" [0 0 1]') + if not c4d.utils.CompareFloatTolerant(globalLightScale, 1.0): + pbrtGeometry.write(' ' + makePbrtAttributeColor('scale', c4d.Vector(globalLightScale), False)) + pbrtGeometry.write('\n') + else: + logger.warning("Light Source " + obj.GetName() + " ignored due to unknown Light Type Setting!") + + elif obj.GetType() == c4d.Osky: + # in case of a sky object present, we copy that object into a separate scene, bake it into a texture and apply that texture as infinite light to the scene + # see LAUBWERKCINEMA-697 + parent = obj.GetCacheParent() + #print parent + #print parent.GetName() + #print parent.GetType() + if parent and parent.GetType() == 1011146: + + global g_bakeTextureFile + if not g_bakeTextureFile: + global g_bakeDoc + g_bakeDoc = c4d.documents.IsolateObjects(parent.GetDocument(), [parent]) + if c4d.documents.MergeDocument(doc=g_bakeDoc, name=os.path.join(os.path.dirname(__file__), "res", "pbrt-env-bake.c4d"), loadflags=c4d.SCENEFILTER_OBJECTS|c4d.SCENEFILTER_MATERIALS, thread=self.Get()): + + #c4d.documents.SaveDocument(doc=g_bakeDoc, name='C:\\bakeDoc.c4d', saveflags=c4d.SAVEDOCUMENTFLAGS_0, format=c4d.FORMAT_C4DEXPORT) + + global g_bakeTag + g_bakeTag = g_bakeDoc.GetFirstObject().GetFirstTag() + + # set the output file in the bake tag, so the texture gets written to the correct location + bakeTagTexturename = os.path.join(os.path.dirname(pbrtFilename), "environment_") + g_bakeTag[c4d.BAKETEXTURE_NAME] = bakeTagTexturename + + # the tag will append "Reflection" and the extension + # store the filename globally, so we can later check how it's progressing + g_bakeTextureFile = os.path.join(os.path.dirname(pbrtFilename), "environment_Reflection.exr") + + # if the file already exists, remove it to prevent the bake command to trigger a dialog popup + if os.path.exists(g_bakeTextureFile): + try: + os.remove(g_bakeTextureFile) + except: + os.error("Unable to remove previous baked environment texture!") + + # trigger the texture bake event, so the environment texture gets written + # we have to use a message, because we can't call into another thread directly + c4d.SpecialEventAdd(MSG_PBRT_BAKETEXTURE) + + # rotate the light so it matches the CINEMA 4D Physical Sky environment + pbrtGeometry.write(indent + 'Rotate 90 -1 0 0\n') + pbrtGeometry.write(indent + 'Scale 1 -1 1\n') + + # write the infinite light to the scene + pbrtGeometry.write(indent + 'LightSource "infinite" "string mapname" ["' + os.path.basename(g_bakeTextureFile) + '"] "color L" [1 1 1] "integer nsamples" [128]') + if not c4d.utils.CompareFloatTolerant(globalLightScale, 1.0): + pbrtGeometry.write(' ' + makePbrtAttributeColor('scale', c4d.Vector(globalLightScale), False)) + pbrtGeometry.write('\n') + else: + logger.error("Unable to merge environment bake template!") + + else: + logger.warning("More than one Physical Sky object found for baking, ignored!") + + elif obj.GetType() == c4d.Opolygon: + # this is a regular polygon object, export as such + logger.debug("Exporting Polygon Object: " + obj.GetName()) + ExportPolygonObject(pbrtGeometry, pbrtMaterials, exportedMaterials, obj, indent) + + return True + + + # + # define named objects + # + namedObjects = [] + for obj in iter_all(doc): + if self.TestBreak(): + return None, None + + # find visible render instance objects + if obj.GetType() == c4d.Oinstance: + if not obj[c4d.INSTANCEOBJECT_RENDERINSTANCE]: + continue + + if GetRenderModeRec(obj, None) != c4d.MODE_OFF: + instancedObject = obj.GetDataInstance().GetObjectLink(c4d.INSTANCEOBJECT_LINK) + if instancedObject and not FindNamedObject(instancedObject, namedObjects): + # make the name of the named object + objectName = SanitizeObjectName(instancedObject.GetName()) + # append to list of named objects + namedObjects.append([instancedObject, objectName]) + + # create separate file for content + pbrtMaterials = open(pbrtMaterialsFilename, 'w') + pbrtGeometry = open(pbrtGeometryFilename, 'w') + exportedMaterials = dict() + for namedObject in namedObjects: + pbrtGeometry.write('ObjectBegin "' + namedObject[1] + '"\n') + logger.info("Exporting " + namedObject[0].GetName() + " as Instance...") + WalkObjectTree(pbrtGeometry, pbrtMaterials, namedObject[0], exportedMaterials, MyExportFunction, indent=indent, rootObj=namedObject[0]) + pbrtGeometry.write('ObjectEnd\n') + + # main scene export run + WalkObjectTree(pbrtGeometry, pbrtMaterials, doc, exportedMaterials, MyExportFunction, namedObjects) + pbrtMaterials.close() + pbrtGeometry.close() + + # in case of no light sources in the scene and the corresponding option being set, + # export default light + global g_nLightSourcesExported + if renderData[c4d.RDATA_AUTOLIGHT] and g_nLightSourcesExported == 0: + lightVector = (~mi).MulV(-camera[c4d.BASEDRAW_DATA_LIGHTVECTOR]) + pbrt.write(indent + 'LightSource "distant" "rgb L" [1 1 1] "point from" [0 0 0] "point to" [' + str(lightVector.x) + ' ' + str(lightVector.y) + ' ' + str(lightVector.z) + ']') + if not c4d.utils.CompareFloatTolerant(globalLightScale, 1.0): + pbrt.write(' ' + makePbrtAttributeColor('scale', c4d.Vector(globalLightScale), False)) + pbrt.write('\n') + + pbrt.write(indent + 'Include "' + os.path.basename(pbrtMaterialsFilename) + '"\n'); + pbrt.write(indent + 'Include "' + os.path.basename(pbrtGeometryFilename) + '"\n'); + + """ + pbrt.write('AttributeBegin\n') + pbrt.write(' Rotate 135 1 0 0\n') + pbrt.write(' Texture "checks" "spectrum" "checkerboard" "float uscale" [4] "float vscale" [4] "rgb tex1" [1 0 0] "rgb tex2" [0 0 1]\n') + pbrt.write(' Material "matte" "texture Kd" "checks"\n') + pbrt.write(' Shape "disk" "float radius" [20] "float height" [-1]\n') + pbrt.write('AttributeEnd\n') + """ + + indent = "" + pbrt.write('WorldEnd\n') + + pbrt.close() + + return pbrtFilename, imageFilename + + def TerminateRenderer(self): + if self.pbrtProcess is not None and self.pbrtProcess.poll() is None: + self.pbrtProcess.terminate() + + # + # executes the actual renderer and returns the rendered image + # + def ExecuteRenderer(self, pbrtFilename, imageFilename): + # call pbrt for rendering + try: + self.pbrtProcess = subprocess.Popen([os.path.join(os.path.dirname(__file__), 'pbrt', 'bin', 'pbrt.exe'), pbrtFilename], cwd=os.path.dirname(pbrtFilename)) + except subprocess.CalledProcessError as err: + logger.error("Failed to render image: " + str(err)) + return None + else: + # wait until rendering is finished or user aborts the process + self.pbrtProcess.wait() + + # check if the return code of the renderer indicates that it ran through without error + bmp = None + if self.pbrtProcess.poll() == 0: + # display resulting image + bmp = c4d.bitmaps.BaseBitmap() + result, ismovie = bmp.InitWith(imageFilename) + + # if we're only rendering, clean up the files + if self.data.GetInt32(IDC_PBRT_MODE) == IDC_PBRT_MODE_RENDER: + # remove exported pbrt file + try: + os.remove(pbrtFilename) + except OSError as err: + logger.error('Unable to remove "' + pbrtFilename + '": ' + str(err)) + + # if the image wasn't supposed to be saved, the temp image file can now be deleted + try: + if os.path.exists(imageFilename): + os.remove(imageFilename) + except OSError as err: + logger.error('Unable to remove "' + imageFilename + '": ' + str(err)) + + return bmp + + +class ExportToPbrtDialog(c4d.gui.GeDialog): + def __init__(self): + super(c4d.gui.GeDialog, self).__init__() + self._data = None + self.treeview = None + self.lastScrollPos = 0 + self.autoscroll = True + + # called when the dialog is opened - load or generate the GUI here + def CreateLayout(self): + res = self.LoadDialogResource(DLG_PBRT) + return res + + @property + def data(self): + self._data = c4d.plugins.GetWorldPluginData(PBRT_EXPORT_ID) + if self._data is None: + self._data = c4d.BaseContainer() + self._data.SetFilename(IDC_PBRT_EXE, "") + self._data.SetInt32(IDC_PBRT_MODE, IDC_PBRT_MODE_RENDER) + self._data.SetInt32(IDC_PBRT_SAMPLES, 32) + self._data.SetFloat(IDC_PBRT_INTENSITY, 1.0) + self._data.SetInt32(IDC_PBRT_LOGLEVEL, IDC_PBRT_LOGLEVEL_INFO) + c4d.plugins.SetWorldPluginData(PBRT_EXPORT_ID, self._data) + return self._data + + def EnableControls(self, enable): + self.Enable(IDC_PBRT_MODE, enable) + self.Enable(IDC_PBRT_EXE, enable) + self.Enable(IDC_PBRT_SAMPLES, enable) + self.Enable(IDC_PBRT_INTENSITY, enable) + + def UpdateGui(self): + self.LayoutFlushGroup(IDC_BUTTON_GROUP) + + if not IsProcessRunning(): + self.EnableControls(True) + self.AddButton(IDC_PBRT_START, c4d.BFH_LEFT|c4d.BFH_SCALEFIT, name=c4d.plugins.GeLoadString(IDS_PBRT_START)) + else: + self.EnableControls(False) + self.AddButton(IDC_PBRT_ABORT, c4d.BFH_LEFT|c4d.BFH_SCALEFIT, name=c4d.plugins.GeLoadString(IDS_PBRT_ABORT)) + + self.LayoutChanged(IDC_BUTTON_GROUP) + + def InitValues(self): + self.SetInt32(IDC_PBRT_MODE, self.data.GetInt32(IDC_PBRT_MODE, IDC_PBRT_MODE_RENDER)) + self.SetFilename(IDC_PBRT_EXE, self.data.GetFilename(IDC_PBRT_EXE, "")) + self.SetInt32(IDC_PBRT_SAMPLES, self.data.GetInt32(IDC_PBRT_SAMPLES, 32), 0, 4096) + self.SetFloat(IDC_PBRT_INTENSITY, self.data.GetFloat(IDC_PBRT_INTENSITY, 1.0), 0.0, 1.0e12, 0.01, c4d.FORMAT_PERCENT) + self.SetInt32(IDC_PBRT_LOGLEVEL, self.data.GetInt32(IDC_PBRT_LOGLEVEL, IDC_PBRT_LOGLEVEL_INFO)) + + data = c4d.BaseContainer() + data.SetInt32(TREEVIEW_COLUMN_ID_TIME, c4d.LV_USER) + data.SetInt32(TREEVIEW_COLUMN_ID_LEVEL, c4d.LV_USER) + data.SetInt32(TREEVIEW_COLUMN_ID_DESCRIPTION, c4d.LV_USER) + + self.treeview = self.FindCustomGui(IDC_PBRT_LOG, c4d.CUSTOMGUI_TREEVIEW) + if self.treeview is None: + return False + + self.treeview.SetLayout(3, data) + self.treeview.SetHeaderText(TREEVIEW_COLUMN_ID_TIME, "Time") + self.treeview.SetHeaderText(TREEVIEW_COLUMN_ID_LEVEL, "Level") + self.treeview.SetHeaderText(TREEVIEW_COLUMN_ID_DESCRIPTION, "Description") + self.treeview.Refresh() + + global g_errorRoot + g_errorRoot = RootItem() + self.treeview.SetRoot(g_errorRoot, ErrorList(self.treeview), None) + + self.UpdateGui() + return True + + def Command(self, id, msg): + if id == IDC_PBRT_START: + self.autoscroll = True + self.lastScrollPos = 0 + logger.setLevel(logging.DEBUG) + logger.handlers = [] + logger.addHandler(ErrorHandler()) + doc = c4d.documents.GetActiveDocument() + if doc is not None: + mode = self.GetInt32(IDC_PBRT_MODE) + exe = self.GetFilename(IDC_PBRT_EXE) + if mode != IDC_PBRT_MODE_EXPORT and len(exe) == 0: + c4d.gui.MessageDialog("Please provide the path to the pbrt renderer executable!") + return False + path = "" + if mode != IDC_PBRT_MODE_RENDER: + defPath = os.path.join(doc.GetDocumentPath(), doc.GetDocumentName()) + path = c4d.storage.SaveDialog(title="Select the destination for your export", force_suffix="pbrt", def_path=defPath) + # check if the user did not cancel here + if path is not None: + global g_thread + g_thread = PbrtThread(doc, mode, self.data, exe, path) + g_thread.Start() + self.UpdateGui() + + return True + elif id == IDC_PBRT_ABORT: + TerminateProcess() + self.UpdateGui() + elif id >= IDC_PBRT_EXE and id <= IDC_PBRT_SAMPLES or id == IDC_PBRT_INTENSITY: + if id == IDC_PBRT_MODE: + self.data.SetInt32(IDC_PBRT_MODE, self.GetInt32(IDC_PBRT_MODE)) + elif id == IDC_PBRT_EXE: + self.data.SetFilename(IDC_PBRT_EXE, self.GetFilename(IDC_PBRT_EXE)) + elif id == IDC_PBRT_SAMPLES: + self.data.SetInt32(IDC_PBRT_SAMPLES, self.GetInt32(IDC_PBRT_SAMPLES)) + elif id == IDC_PBRT_INTENSITY: + self.data.SetFloat(IDC_PBRT_INTENSITY, self.GetFloat(IDC_PBRT_INTENSITY)) + elif id == IDC_PBRT_LOGLEVEL: + self.data.SetInt32(IDC_PBRT_LOGLEVEL, self.GetInt32(IDC_PBRT_LOGLEVEL)) + c4d.plugins.SetWorldPluginData(PBRT_EXPORT_ID, self.data) + elif id == IDC_PBRT_LOGLEVEL: + # if the message level filter changed update the treeview + value = self.GetInt32(IDC_PBRT_LOGLEVEL) + global g_level + if value == IDC_PBRT_LOGLEVEL_DEBUG: + g_level = logging.DEBUG + elif value == IDC_PBRT_LOGLEVEL_INFO: + g_level = logging.INFO + elif value == IDC_PBRT_LOGLEVEL_WARNING: + g_level = logging.WARNING + elif value == IDC_PBRT_LOGLEVEL_ERROR: + g_level = logging.ERROR + else: + g_level = logging.INFO + UpdateErrorList() + UpdateTreeView() + return True + return False + + def CoreMessage(self, id, bc): + if id == MSG_PBRT_UPDATE_LOG: + if self.treeview: + self.treeview.Refresh() + if self.autoscroll: + self.treeview.MakeVisible(g_errorRoot.GetLastChild()) + return True + + elif id == MSG_PBRT_FINISHED: + global g_thread + if g_thread is not None: + logger.info("Finished") + + if g_bmp is not None: + # it's not allowed to call ShowBitmap() in a thread + c4d.bitmaps.ShowBitmap(g_bmp) + else: + logger.error("Cancelled") + g_thread = None + self.UpdateGui() + return True + + elif id == MSG_PBRT_BAKETEXTURE: + # this triggers a bake texture tag + # The actual baking process will run in a separate thread + global g_bakeDoc + global g_bakeTag + if g_bakeTag is not None and g_bakeDoc is not None: + c4d.CallButton(g_bakeTag, c4d.BAKETEXTURE_BAKE) + else: + logger.error("Bake texture thread can't find Bake Texture Tag!") + return True + + return c4d.gui.GeDialog.CoreMessage(self, id, bc) + + def Message(self, msg, result): + id = msg.GetId() + if id == c4d.BFM_SCROLLGROUP_SCROLLED: + scrollPos = msg.GetInt32(3) # vertical scroll pos + if self.autoscroll: + # if the user scrolled up stop scrolling down automatically + if scrollPos > self.lastScrollPos: + self.autoscroll = False + # save last scroll pos + self.lastScrollPos = scrollPos + return c4d.gui.GeDialog.Message(self, msg, result) + + +# this class is the basic plugin +class ExportToPbrtCommand(c4d.plugins.CommandData): + + _dialog = None + + @property + def dialog(self): + if not self._dialog: + self._dialog = ExportToPbrtDialog() + return self._dialog + + # we could also just execute some code here - the dialog is optional + def Execute(self, doc): + self.dialog.Open(c4d.DLG_TYPE_ASYNC, PBRT_EXPORT_ID, -1, -1, 260, 400) + return True + + # needed to restore minimized dialogs and for startup layout integration + def RestoreLayout(self, sec_ref): + return self.dialog.Restore(PBRT_EXPORT_ID, sec_ref) + +def PluginMessage(id, data): + """Make sure to clean up when C4D ends. + """ + if id == c4d.C4DPL_ENDACTIVITY: + if IsProcessRunning(): + TerminateProcess() + return True + return False + +#register the plugin +if __name__ == "__main__": + # only load if r16 or higher (LAUBWERKCINEMA-683) + if c4d.GetC4DVersion() >= 16000: + # load an icon from the 'res' folder + icon = c4d.bitmaps.BaseBitmap() + icon.InitWith(os.path.join(os.path.dirname(__file__), "res", "icon.tif")) + + # get the plugin title from the string resource + title = "Export to PBRT..."#c4d.plugins.GeLoadString(IDS_SUBMIT) + # c4d.plugins.RegisterMessagePlugin(TREEVIEWUPDATETIMER_COMMAND_ID, "TreeviewUpdateTimer", 0, TreeviewUpdateTimer()) + c4d.plugins.RegisterCommandPlugin(PBRT_EXPORT_ID, title, 0, icon, title, ExportToPbrtCommand()) diff --git a/exporters/cinema4d/PBRT Export/res/c4d_symbols.h b/exporters/cinema4d/PBRT Export/res/c4d_symbols.h new file mode 100644 index 00000000..63871c60 --- /dev/null +++ b/exporters/cinema4d/PBRT Export/res/c4d_symbols.h @@ -0,0 +1,23 @@ +enum +{ + DLG_PBRT = 60000, + IDS_PBRT, + IDC_PBRT_START, + IDC_PBRT_LOG, + IDC_PBRT_EXE, + IDC_PBRT_MODE, + IDC_PBRT_MODE_EXPORT, + IDC_PBRT_MODE_EXPORT_AND_RENDER, + IDC_PBRT_MODE_RENDER, + IDC_PBRT_SAMPLES, + IDC_PBRT_ABORT, + IDC_BUTTON_GROUP, + IDC_PBRT_LOGLEVEL, + IDC_PBRT_LOGLEVEL_DEBUG, + IDC_PBRT_LOGLEVEL_INFO, + IDC_PBRT_LOGLEVEL_WARNING, + IDC_PBRT_LOGLEVEL_ERROR, + IDC_PBRT_INTENSITY, + IDS_PBRT_START = 60100, + IDS_PBRT_ABORT, +}; diff --git a/exporters/cinema4d/PBRT Export/res/dialogs/dlg_pbrt.res b/exporters/cinema4d/PBRT Export/res/dialogs/dlg_pbrt.res new file mode 100644 index 00000000..eeda396e --- /dev/null +++ b/exporters/cinema4d/PBRT Export/res/dialogs/dlg_pbrt.res @@ -0,0 +1,62 @@ +// C4D-DialogResource +DIALOG DLG_PBRT +{ + NAME IDS_PBRT; + SCALE_V; SCALE_H; + GROUP + { + SCALE_V; SCALE_H; + COLUMNS 1; + + GROUP + { + SCALE_H; + COLUMNS 2; + BORDERSIZE 4, 4, 4, 4; + + STATICTEXT 0 { NAME IDS_PBRT_MODE; ALIGN_LEFT; } + COMBOBOX IDC_PBRT_MODE + { + //SIZE 100; + SCALE_H; + CHILDS + { + IDC_PBRT_MODE_EXPORT_AND_RENDER, IDS_PBRT_MODE_EXPORT_AND_RENDER; + IDC_PBRT_MODE_EXPORT, IDS_PBRT_MODE_EXPORT; + IDC_PBRT_MODE_RENDER, IDS_PBRT_MODE_RENDER; + } + } + + STATICTEXT 0 { NAME IDS_PBRT_EXE; ALIGN_LEFT; } + FILENAME IDC_PBRT_EXE { SCALE_H; } + + STATICTEXT 0 { NAME IDS_PBRT_SAMPLES; ALIGN_LEFT; } + EDITNUMBERARROWS IDC_PBRT_SAMPLES { SCALE_H; } + + STATICTEXT 0 { NAME IDS_PBRT_INTENSITY; ALIGN_LEFT; } + EDITNUMBERARROWS IDC_PBRT_INTENSITY { SCALE_H; } + + STATICTEXT 0 { NAME IDS_PBRT_LOGLEVEL; ALIGN_LEFT; } + COMBOBOX IDC_PBRT_LOGLEVEL + { + SCALE_H; + CHILDS + { + IDC_PBRT_LOGLEVEL_DEBUG, IDS_PBRT_LOGLEVEL_DEBUG; + IDC_PBRT_LOGLEVEL_INFO, IDS_PBRT_LOGLEVEL_INFO; + IDC_PBRT_LOGLEVEL_WARNING, IDS_PBRT_LOGLEVEL_WARNING; + IDC_PBRT_LOGLEVEL_ERROR, IDS_PBRT_LOGLEVEL_ERROR; + } + } + + STATICTEXT 0 { } + GROUP IDC_BUTTON_GROUP + { + SCALE_H; + COLUMNS 1; + } + } + + TREEVIEW IDC_PBRT_LOG { HAS_HEADER; ALTERNATE_BG; FIXED_LAYOUT; RESIZE_HEADER; SCALE_V; SCALE_H; BORDER; } + } +} \ No newline at end of file diff --git a/exporters/cinema4d/PBRT Export/res/pbrt-env-bake.c4d b/exporters/cinema4d/PBRT Export/res/pbrt-env-bake.c4d new file mode 100644 index 00000000..9ac644be Binary files /dev/null and b/exporters/cinema4d/PBRT Export/res/pbrt-env-bake.c4d differ diff --git a/exporters/cinema4d/PBRT Export/res/strings_us/c4d_strings.str b/exporters/cinema4d/PBRT Export/res/strings_us/c4d_strings.str new file mode 100644 index 00000000..c1b31f45 --- /dev/null +++ b/exporters/cinema4d/PBRT Export/res/strings_us/c4d_strings.str @@ -0,0 +1,8 @@ +// C4D-StringResource +// Identifier Text + +STRINGTABLE +{ + IDS_PBRT_START "Start"; + IDS_PBRT_ABORT "Abort"; +} diff --git a/exporters/cinema4d/PBRT Export/res/strings_us/dialogs/dlg_pbrt.str b/exporters/cinema4d/PBRT Export/res/strings_us/dialogs/dlg_pbrt.str new file mode 100644 index 00000000..223f7ea1 --- /dev/null +++ b/exporters/cinema4d/PBRT Export/res/strings_us/dialogs/dlg_pbrt.str @@ -0,0 +1,18 @@ +// C4D-DialogResource + +DIALOGSTRINGS DLG_PBRT +{ + IDS_PBRT "Export to PBRT"; + IDS_PBRT_EXE "Renderer"; + IDS_PBRT_MODE "Mode"; + IDS_PBRT_MODE_EXPORT "Export"; + IDS_PBRT_MODE_EXPORT_AND_RENDER "Export and Render"; + IDS_PBRT_MODE_RENDER "Render"; + IDS_PBRT_SAMPLES "Samples"; + IDS_PBRT_INTENSITY "Light Intensity"; + IDS_PBRT_LOGLEVEL "Logging Level"; + IDS_PBRT_LOGLEVEL_DEBUG "Debug"; + IDS_PBRT_LOGLEVEL_INFO "Info"; + IDS_PBRT_LOGLEVEL_WARNING "Warning"; + IDS_PBRT_LOGLEVEL_ERROR "Error"; +} diff --git a/exporters/cinema4d/readme.md b/exporters/cinema4d/readme.md new file mode 100644 index 00000000..d88ddc71 --- /dev/null +++ b/exporters/cinema4d/readme.md @@ -0,0 +1,27 @@ + +# PBRT Exporter for Cinema 4D + +## Compatibility + +This version of the PBRT Exporter for Cinema 4D has been tested with PBRT v3 and Cinema 4D R16. It will probably also work with earlier and later Cinema 4D versions. It will definitely not work with different versions than PBRT v3. + +## Installation + +To install the exporter, just copy the 'PBRT Export' folder into the plugins folder of your Cinema 4D Installation. It will then show up in the Plugins menu the next time you start Cinema 4D. + +## Operation + +Choosing 'Export to PBRT...' from the Plugins menu will open the export dialog. The export mode controls where PBRT files are written and whether the renderer is started. The 'Render' mode will export the scene to a temporary location, start pbrt and open the resulting image in the Picture Viewer once the rendering is done. 'Export' will ask you for a location the pbrt scene should be written to. 'Export and Render' will ask you where the scene should be written and will start a rendering. For 'Render' and 'Export and Render' is important to let the plugin know where your pbrt executable is located. This can be specified using the 'Renderer' input field. 'Samples' allows you to specify the number of Samples per Pixel to be used. 'Light Intensity' lets you globally scale the intensity of all exported light sources in the scene. During export, a detailed log is created. The 'Logging Level' lets you choose how much detail you want to see in the log window at the bottom of the export dialog. + +By default, the 'directlighting' integrator is used. When a Global Illumination effect is added to the regular Cinema 4D render settings, the 'path' integrator is used instead. + +## Supported Features + +- Omni and Distant Light sources are exported +- The Physical Sky object will have appropriate light sources added and the background is baked into an environment texture and added as infinite light. +- All geometric objects that create polygons are exported. +- The plugin attempts to move basic material attributes (base color, specularity, bump). Furthermore it detects translucency setups using the Backlight shader and attempts to translate those. + +## Copyright + +This plugin has been created by Burak Kahraman and Timm Dapper of Laubwerk GmbH (www.laubwerk.com). It is distributed under the same license as the rest of the PBRT repository. diff --git a/src/ext/CMakeLists.txt b/src/ext/CMakeLists.txt new file mode 100644 index 00000000..67835751 --- /dev/null +++ b/src/ext/CMakeLists.txt @@ -0,0 +1,98 @@ + +cmake_minimum_required (VERSION 3.12) + +########################################################################### +# stb + +set (STB_INCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/stb PARENT_SCOPE) + +########################################################################### +# filesystem + +set (FILESYSTEM_INCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/filesystem PARENT_SCOPE) + +########################################################################### +# zlib + +find_package (ZLIB) +if (NOT ZLIB_FOUND) + # Build zlib + set (ZLIB_BUILD_STATIC_LIBS ON CACHE BOOL " " FORCE) + set (ZLIB_BUILD_SHARED_LIBS OFF CACHE BOOL " " FORCE) + add_subdirectory (zlib) + + set (ZLIB_LIBRARIES zlibstatic) + set (ZLIB_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/zlib ${CMAKE_CURRENT_BINARY_DIR}/zlib) + + # try to make openexr happy about this... + set (ZLIB_LIBRARY zlibstatic) + set (ZLIB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/zlib ${CMAKE_CURRENT_BINARY_DIR}/zlib) + set (ZLIB_FOUND TRUE) + + set_property (TARGET zlibstatic PROPERTY FOLDER "ext") + + add_library (ZLIB::ZLIB ALIAS zlibstatic) + include_directories(${ZLIB_INCLUDE_DIRS}) # yuck, but so openexr/ptex can find zlib.h... +endif () + +set (ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE_DIRS} PARENT_SCOPE) +set (ZLIB_LIBRARIES ${ZLIB_LIBARIES} PARENT_SCOPE) + +########################################################################### +# OpenEXR + +set (ILMBASE_NAMESPACE_VERSIONING OFF CACHE BOOL " " FORCE) +set (OPENEXR_NAMESPACE_VERSIONING OFF CACHE BOOL " " FORCE) +set (OPENEXR_BUILD_SHARED_LIBS OFF CACHE BOOL " " FORCE) +set (ILMBASE_BUILD_SHARED_LIBS OFF CACHE BOOL " " FORCE) +set (PYILMBASE_ENABLE OFF CACHE BOOL " " FORCE) +set (OPENEXR_BUILD_UTILS OFF CACHE BOOL " " FORCE) + +add_subdirectory (openexr) + +set_property (TARGET IexMath IlmThread Half + Iex Imath IlmImf HalfTest IexTest + IlmImfExamples IlmImfTest IlmImfUtil IlmImfUtilTest ImathTest + PROPERTY FOLDER "ext/OpenEXR") + +set (OPENEXR_INCLUDE + ${CMAKE_CURRENT_SOURCE_DIR}/openexr/IlmBase/Imath + ${CMAKE_CURRENT_SOURCE_DIR}/openexr/IlmBase/Half + ${CMAKE_CURRENT_SOURCE_DIR}/openexr/IlmBase/Iex + ${CMAKE_CURRENT_SOURCE_DIR}/openexr/OpenEXR/IlmImf + ${CMAKE_CURRENT_BINARY_DIR}/openexr/IlmBase/config + ${CMAKE_CURRENT_BINARY_DIR}/openexr/OpenEXR/config +PARENT_SCOPE +) + +if (WIN32) + set (OPENEXR_LIBS OpenEXR::IlmImf IlmBase::Imath IlmBase::Half ${ZLIB_LIBRARY} PARENT_SCOPE) +else () + set (OPENEXR_LIBS OpenEXR::IlmImf IlmBase::Imath IlmBase::Half PARENT_SCOPE) +endif () + +########################################################################### +# ptex + +set (PTEX_BUILD_SHARED_LIBS OFF CACHE BOOL " " FORCE) + +set (CMAKE_MACOSX_RPATH 1) +if (WIN32) + add_definitions (/D PTEX_STATIC) +endif () + +add_subdirectory (ptex) + +set_property (TARGET Ptex_static ptxinfo halftest ftest rtest wtest PROPERTY FOLDER "ext/ptex") + +set (PTEX_INCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/ptex/src/ptex PARENT_SCOPE) + +########################################################################### +# double-conversion + +add_subdirectory (double-conversion) + +set (DOUBLE_CONVERSION_INCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/double-conversion PARENT_SCOPE) + +set_property (TARGET double-conversion cctest PROPERTY FOLDER "ext") + diff --git a/src/ext/double-conversion b/src/ext/double-conversion new file mode 160000 index 00000000..cc1f75a1 --- /dev/null +++ b/src/ext/double-conversion @@ -0,0 +1 @@ +Subproject commit cc1f75a114aca8d2af69f73a5a959aecbab0e87a diff --git a/src/ext/filesystem b/src/ext/filesystem new file mode 160000 index 00000000..f45da753 --- /dev/null +++ b/src/ext/filesystem @@ -0,0 +1 @@ +Subproject commit f45da753728cde9b1c380b343e41c8b1ca6498d7 diff --git a/src/ext/gtest/gtest-all.cc b/src/ext/gtest/gtest-all.cc new file mode 100644 index 00000000..f99c9615 --- /dev/null +++ b/src/ext/gtest/gtest-all.cc @@ -0,0 +1,9592 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// +// Google C++ Testing Framework (Google Test) +// +// Sometimes it's desirable to build Google Test by compiling a single file. +// This file serves this purpose. + +// This line ensures that gtest.h can be compiled on its own, even +// when it's fused. +#include + +// The following lines pull in the real gtest *.cc files. +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) + +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Utilities for testing Google Test itself and code that uses Google Test +// (e.g. frameworks built on top of Google Test). + +#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ +#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ + + +namespace testing { + +// This helper class can be used to mock out Google Test failure reporting +// so that we can test Google Test or code that builds on Google Test. +// +// An object of this class appends a TestPartResult object to the +// TestPartResultArray object given in the constructor whenever a Google Test +// failure is reported. It can either intercept only failures that are +// generated in the same thread that created this object or it can intercept +// all generated failures. The scope of this mock object can be controlled with +// the second argument to the two arguments constructor. +class GTEST_API_ ScopedFakeTestPartResultReporter + : public TestPartResultReporterInterface { + public: + // The two possible mocking modes of this object. + enum InterceptMode { + INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. + INTERCEPT_ALL_THREADS // Intercepts all failures. + }; + + // The c'tor sets this object as the test part result reporter used + // by Google Test. The 'result' parameter specifies where to report the + // results. This reporter will only catch failures generated in the current + // thread. DEPRECATED + explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); + + // Same as above, but you can choose the interception scope of this object. + ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, + TestPartResultArray* result); + + // The d'tor restores the previous test part result reporter. + virtual ~ScopedFakeTestPartResultReporter(); + + // Appends the TestPartResult object to the TestPartResultArray + // received in the constructor. + // + // This method is from the TestPartResultReporterInterface + // interface. + virtual void ReportTestPartResult(const TestPartResult& result); + private: + void Init(); + + const InterceptMode intercept_mode_; + TestPartResultReporterInterface* old_reporter_; + TestPartResultArray* const result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); +}; + +namespace internal { + +// A helper class for implementing EXPECT_FATAL_FAILURE() and +// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given +// TestPartResultArray contains exactly one failure that has the given +// type and contains the given substring. If that's not the case, a +// non-fatal failure will be generated. +class GTEST_API_ SingleFailureChecker { + public: + // The constructor remembers the arguments. + SingleFailureChecker(const TestPartResultArray* results, + TestPartResult::Type type, + const string& substr); + ~SingleFailureChecker(); + private: + const TestPartResultArray* const results_; + const TestPartResult::Type type_; + const string substr_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); +}; + +} // namespace internal + +} // namespace testing + +// A set of macros for testing Google Test assertions or code that's expected +// to generate Google Test fatal failures. It verifies that the given +// statement will cause exactly one fatal Google Test failure with 'substr' +// being part of the failure message. +// +// There are two different versions of this macro. EXPECT_FATAL_FAILURE only +// affects and considers failures generated in the current thread and +// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. +// +// The verification of the assertion is done correctly even when the statement +// throws an exception or aborts the current function. +// +// Known restrictions: +// - 'statement' cannot reference local non-static variables or +// non-static members of the current object. +// - 'statement' cannot return a value. +// - You cannot stream a failure message to this macro. +// +// Note that even though the implementations of the following two +// macros are much alike, we cannot refactor them to use a common +// helper macro, due to some peculiarity in how the preprocessor +// works. The AcceptsMacroThatExpandsToUnprotectedComma test in +// gtest_unittest.cc will fail to compile if we do that. +#define EXPECT_FATAL_FAILURE(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper {\ + public:\ + static void Execute() { statement; }\ + };\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ + GTestExpectFatalFailureHelper::Execute();\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper {\ + public:\ + static void Execute() { statement; }\ + };\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ALL_THREADS, >est_failures);\ + GTestExpectFatalFailureHelper::Execute();\ + }\ + } while (::testing::internal::AlwaysFalse()) + +// A macro for testing Google Test assertions or code that's expected to +// generate Google Test non-fatal failures. It asserts that the given +// statement will cause exactly one non-fatal Google Test failure with 'substr' +// being part of the failure message. +// +// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only +// affects and considers failures generated in the current thread and +// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. +// +// 'statement' is allowed to reference local variables and members of +// the current object. +// +// The verification of the assertion is done correctly even when the statement +// throws an exception or aborts the current function. +// +// Known restrictions: +// - You cannot stream a failure message to this macro. +// +// Note that even though the implementations of the following two +// macros are much alike, we cannot refactor them to use a common +// helper macro, due to some peculiarity in how the preprocessor +// works. If we do that, the code won't compile when the user gives +// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that +// expands to code containing an unprotected comma. The +// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc +// catches that. +// +// For the same reason, we have to write +// if (::testing::internal::AlwaysTrue()) { statement; } +// instead of +// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) +// to avoid an MSVC warning on unreachable code. +#define EXPECT_NONFATAL_FAILURE(statement, substr) \ + do {\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ + if (::testing::internal::AlwaysTrue()) { statement; }\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do {\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ + >est_failures);\ + if (::testing::internal::AlwaysTrue()) { statement; }\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include // NOLINT +#include +#include + +#if GTEST_OS_LINUX + +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +# define GTEST_HAS_GETTIMEOFDAY_ 1 + +# include // NOLINT +# include // NOLINT +# include // NOLINT +// Declares vsnprintf(). This header is not available on Windows. +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include + +#elif GTEST_OS_SYMBIAN +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT + +#elif GTEST_OS_ZOS +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT + +// On z/OS we additionally need strings.h for strcasecmp. +# include // NOLINT + +#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. + +# include // NOLINT + +#elif GTEST_OS_WINDOWS // We are on Windows proper. + +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT + +# if GTEST_OS_WINDOWS_MINGW +// MinGW has gettimeofday() but not _ftime64(). +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +// TODO(kenton@google.com): There are other ways to get the time on +// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW +// supports these. consider using them instead. +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT +# endif // GTEST_OS_WINDOWS_MINGW + +// cpplint thinks that the header is already included, so we want to +// silence it. +# include // NOLINT + +#else + +// Assume other platforms have gettimeofday(). +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +# define GTEST_HAS_GETTIMEOFDAY_ 1 + +// cpplint thinks that the header is already included, so we want to +// silence it. +# include // NOLINT +# include // NOLINT + +#endif // GTEST_OS_LINUX + +#if GTEST_HAS_EXCEPTIONS +# include +#endif + +#if GTEST_CAN_STREAM_RESULTS_ +# include // NOLINT +# include // NOLINT +#endif + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Utility functions and classes used by the Google C++ testing framework. +// +// Author: wan@google.com (Zhanyong Wan) +// +// This file contains purely Google Test's internal implementation. Please +// DO NOT #INCLUDE IT IN A USER PROGRAM. + +#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ +#define GTEST_SRC_GTEST_INTERNAL_INL_H_ + +// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is +// part of Google Test's implementation; otherwise it's undefined. +#if !GTEST_IMPLEMENTATION_ +// A user is trying to include this from his code - just say no. +# error "gtest-internal-inl.h is part of Google Test's internal implementation." +# error "It must not be included except by Google Test itself." +#endif // GTEST_IMPLEMENTATION_ + +#ifndef _WIN32_WCE +# include +#endif // !_WIN32_WCE +#include +#include // For strtoll/_strtoul64/malloc/free. +#include // For memmove. + +#include +#include +#include + + +#if GTEST_CAN_STREAM_RESULTS_ +# include // NOLINT +# include // NOLINT +#endif + +#if GTEST_OS_WINDOWS +# include // NOLINT +#endif // GTEST_OS_WINDOWS + + +namespace testing { + +// Declares the flags. +// +// We don't want the users to modify this flag in the code, but want +// Google Test's own unit tests to be able to access it. Therefore we +// declare it here as opposed to in gtest.h. +GTEST_DECLARE_bool_(death_test_use_fork); + +namespace internal { + +// The value of GetTestTypeId() as seen from within the Google Test +// library. This is solely for testing GetTestTypeId(). +GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; + +// Names of the flags (needed for parsing Google Test flags). +const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; +const char kBreakOnFailureFlag[] = "break_on_failure"; +const char kCatchExceptionsFlag[] = "catch_exceptions"; +const char kColorFlag[] = "color"; +const char kFilterFlag[] = "filter"; +const char kListTestsFlag[] = "list_tests"; +const char kOutputFlag[] = "output"; +const char kPrintTimeFlag[] = "print_time"; +const char kRandomSeedFlag[] = "random_seed"; +const char kRepeatFlag[] = "repeat"; +const char kShuffleFlag[] = "shuffle"; +const char kStackTraceDepthFlag[] = "stack_trace_depth"; +const char kStreamResultToFlag[] = "stream_result_to"; +const char kThrowOnFailureFlag[] = "throw_on_failure"; + +// A valid random seed must be in [1, kMaxRandomSeed]. +const int kMaxRandomSeed = 99999; + +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +GTEST_API_ extern bool g_help_flag; + +// Returns the current time in milliseconds. +GTEST_API_ TimeInMillis GetTimeInMillis(); + +// Returns true iff Google Test should use colors in the output. +GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); + +// Formats the given time in milliseconds as seconds. +GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); + +// Converts the given time in milliseconds to a date string in the ISO 8601 +// format, without the timezone information. N.B.: due to the use the +// non-reentrant localtime() function, this function is not thread safe. Do +// not use it in any code that can be called from multiple threads. +GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); + +// Parses a string for an Int32 flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +GTEST_API_ bool ParseInt32Flag( + const char* str, const char* flag, Int32* value); + +// Returns a random seed in range [1, kMaxRandomSeed] based on the +// given --gtest_random_seed flag value. +inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { + const unsigned int raw_seed = (random_seed_flag == 0) ? + static_cast(GetTimeInMillis()) : + static_cast(random_seed_flag); + + // Normalizes the actual seed to range [1, kMaxRandomSeed] such that + // it's easy to type. + const int normalized_seed = + static_cast((raw_seed - 1U) % + static_cast(kMaxRandomSeed)) + 1; + return normalized_seed; +} + +// Returns the first valid random seed after 'seed'. The behavior is +// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is +// considered to be 1. +inline int GetNextRandomSeed(int seed) { + GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) + << "Invalid random seed " << seed << " - must be in [1, " + << kMaxRandomSeed << "]."; + const int next_seed = seed + 1; + return (next_seed > kMaxRandomSeed) ? 1 : next_seed; +} + +// This class saves the values of all Google Test flags in its c'tor, and +// restores them in its d'tor. +class GTestFlagSaver { + public: + // The c'tor. + GTestFlagSaver() { + also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); + break_on_failure_ = GTEST_FLAG(break_on_failure); + catch_exceptions_ = GTEST_FLAG(catch_exceptions); + color_ = GTEST_FLAG(color); + death_test_style_ = GTEST_FLAG(death_test_style); + death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); + filter_ = GTEST_FLAG(filter); + internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); + list_tests_ = GTEST_FLAG(list_tests); + output_ = GTEST_FLAG(output); + print_time_ = GTEST_FLAG(print_time); + random_seed_ = GTEST_FLAG(random_seed); + repeat_ = GTEST_FLAG(repeat); + shuffle_ = GTEST_FLAG(shuffle); + stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); + stream_result_to_ = GTEST_FLAG(stream_result_to); + throw_on_failure_ = GTEST_FLAG(throw_on_failure); + } + + // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. + ~GTestFlagSaver() { + GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; + GTEST_FLAG(break_on_failure) = break_on_failure_; + GTEST_FLAG(catch_exceptions) = catch_exceptions_; + GTEST_FLAG(color) = color_; + GTEST_FLAG(death_test_style) = death_test_style_; + GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; + GTEST_FLAG(filter) = filter_; + GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; + GTEST_FLAG(list_tests) = list_tests_; + GTEST_FLAG(output) = output_; + GTEST_FLAG(print_time) = print_time_; + GTEST_FLAG(random_seed) = random_seed_; + GTEST_FLAG(repeat) = repeat_; + GTEST_FLAG(shuffle) = shuffle_; + GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; + GTEST_FLAG(stream_result_to) = stream_result_to_; + GTEST_FLAG(throw_on_failure) = throw_on_failure_; + } + + private: + // Fields for saving the original values of flags. + bool also_run_disabled_tests_; + bool break_on_failure_; + bool catch_exceptions_; + std::string color_; + std::string death_test_style_; + bool death_test_use_fork_; + std::string filter_; + std::string internal_run_death_test_; + bool list_tests_; + std::string output_; + bool print_time_; + internal::Int32 random_seed_; + internal::Int32 repeat_; + bool shuffle_; + internal::Int32 stack_trace_depth_; + std::string stream_result_to_; + bool throw_on_failure_; +} GTEST_ATTRIBUTE_UNUSED_; + +// Converts a Unicode code point to a narrow string in UTF-8 encoding. +// code_point parameter is of type UInt32 because wchar_t may not be +// wide enough to contain a code point. +// If the code_point is not a valid Unicode code point +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); + +// Converts a wide string to a narrow string in UTF-8 encoding. +// The wide string is assumed to have the following encoding: +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-32 if sizeof(wchar_t) == 4 (on Linux) +// Parameter str points to a null-terminated wide string. +// Parameter num_chars may additionally limit the number +// of wchar_t characters processed. -1 is used when the entire string +// should be processed. +// If the string contains code points that are not valid Unicode code points +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding +// and contains invalid UTF-16 surrogate pairs, values in those pairs +// will be encoded as individual Unicode characters from Basic Normal Plane. +GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); + +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file +// if the variable is present. If a file already exists at this location, this +// function will write over it. If the variable is present, but the file cannot +// be created, prints an error and exits. +void WriteToShardStatusFileIfNeeded(); + +// Checks whether sharding is enabled by examining the relevant +// environment variable values. If the variables are present, +// but inconsistent (e.g., shard_index >= total_shards), prints +// an error and exits. If in_subprocess_for_death_test, sharding is +// disabled because it must only be applied to the original test +// process. Otherwise, we could filter out death tests we intended to execute. +GTEST_API_ bool ShouldShard(const char* total_shards_str, + const char* shard_index_str, + bool in_subprocess_for_death_test); + +// Parses the environment variable var as an Int32. If it is unset, +// returns default_val. If it is not an Int32, prints an error and +// and aborts. +GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); + +// Given the total number of shards, the shard index, and the test id, +// returns true iff the test should be run on this shard. The test id is +// some arbitrary but unique non-negative integer assigned to each test +// method. Assumes that 0 <= shard_index < total_shards. +GTEST_API_ bool ShouldRunTestOnShard( + int total_shards, int shard_index, int test_id); + +// STL container utilities. + +// Returns the number of elements in the given container that satisfy +// the given predicate. +template +inline int CountIf(const Container& c, Predicate predicate) { + // Implemented as an explicit loop since std::count_if() in libCstd on + // Solaris has a non-standard signature. + int count = 0; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { + if (predicate(*it)) + ++count; + } + return count; +} + +// Applies a function/functor to each element in the container. +template +void ForEach(const Container& c, Functor functor) { + std::for_each(c.begin(), c.end(), functor); +} + +// Returns the i-th element of the vector, or default_value if i is not +// in range [0, v.size()). +template +inline E GetElementOr(const std::vector& v, int i, E default_value) { + return (i < 0 || i >= static_cast(v.size())) ? default_value : v[i]; +} + +// Performs an in-place shuffle of a range of the vector's elements. +// 'begin' and 'end' are element indices as an STL-style range; +// i.e. [begin, end) are shuffled, where 'end' == size() means to +// shuffle to the end of the vector. +template +void ShuffleRange(internal::Random* random, int begin, int end, + std::vector* v) { + const int size = static_cast(v->size()); + GTEST_CHECK_(0 <= begin && begin <= size) + << "Invalid shuffle range start " << begin << ": must be in range [0, " + << size << "]."; + GTEST_CHECK_(begin <= end && end <= size) + << "Invalid shuffle range finish " << end << ": must be in range [" + << begin << ", " << size << "]."; + + // Fisher-Yates shuffle, from + // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle + for (int range_width = end - begin; range_width >= 2; range_width--) { + const int last_in_range = begin + range_width - 1; + const int selected = begin + random->Generate(range_width); + std::swap((*v)[selected], (*v)[last_in_range]); + } +} + +// Performs an in-place shuffle of the vector's elements. +template +inline void Shuffle(internal::Random* random, std::vector* v) { + ShuffleRange(random, 0, static_cast(v->size()), v); +} + +// A function for deleting an object. Handy for being used as a +// functor. +template +static void Delete(T* x) { + delete x; +} + +// A predicate that checks the key of a TestProperty against a known key. +// +// TestPropertyKeyIs is copyable. +class TestPropertyKeyIs { + public: + // Constructor. + // + // TestPropertyKeyIs has NO default constructor. + explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} + + // Returns true iff the test name of test property matches on key_. + bool operator()(const TestProperty& test_property) const { + return test_property.key() == key_; + } + + private: + std::string key_; +}; + +// Class UnitTestOptions. +// +// This class contains functions for processing options the user +// specifies when running the tests. It has only static members. +// +// In most cases, the user can specify an option using either an +// environment variable or a command line flag. E.g. you can set the +// test filter using either GTEST_FILTER or --gtest_filter. If both +// the variable and the flag are present, the latter overrides the +// former. +class GTEST_API_ UnitTestOptions { + public: + // Functions for processing the gtest_output flag. + + // Returns the output format, or "" for normal printed output. + static std::string GetOutputFormat(); + + // Returns the absolute path of the requested output file, or the + // default (test_detail.xml in the original working directory) if + // none was explicitly specified. + static std::string GetAbsolutePathToOutputFile(); + + // Functions for processing the gtest_filter flag. + + // Returns true iff the wildcard pattern matches the string. The + // first ':' or '\0' character in pattern marks the end of it. + // + // This recursive algorithm isn't very efficient, but is clear and + // works well enough for matching test names, which are short. + static bool PatternMatchesString(const char *pattern, const char *str); + + // Returns true iff the user-specified filter matches the test case + // name and the test name. + static bool FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name); + +#if GTEST_OS_WINDOWS + // Function for supporting the gtest_catch_exception flag. + + // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the + // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. + // This function is useful as an __except condition. + static int GTestShouldProcessSEH(DWORD exception_code); +#endif // GTEST_OS_WINDOWS + + // Returns true if "name" matches the ':' separated list of glob-style + // filters in "filter". + static bool MatchesFilter(const std::string& name, const char* filter); +}; + +// Returns the current application's name, removing directory path if that +// is present. Used by UnitTestOptions::GetOutputFile. +GTEST_API_ FilePath GetCurrentExecutableName(); + +// The role interface for getting the OS stack trace as a string. +class OsStackTraceGetterInterface { + public: + OsStackTraceGetterInterface() {} + virtual ~OsStackTraceGetterInterface() {} + + // Returns the current OS stack trace as an std::string. Parameters: + // + // max_depth - the maximum number of stack frames to be included + // in the trace. + // skip_count - the number of top frames to be skipped; doesn't count + // against max_depth. + virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; + + // UponLeavingGTest() should be called immediately before Google Test calls + // user code. It saves some information about the current stack that + // CurrentStackTrace() will use to find and hide Google Test stack frames. + virtual void UponLeavingGTest() = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); +}; + +// A working implementation of the OsStackTraceGetterInterface interface. +class OsStackTraceGetter : public OsStackTraceGetterInterface { + public: + OsStackTraceGetter() : caller_frame_(NULL) {} + + virtual string CurrentStackTrace(int max_depth, int skip_count) + GTEST_LOCK_EXCLUDED_(mutex_); + + virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_); + + // This string is inserted in place of stack frames that are part of + // Google Test's implementation. + static const char* const kElidedFramesMarker; + + private: + Mutex mutex_; // protects all internal state + + // We save the stack frame below the frame that calls user code. + // We do this because the address of the frame immediately below + // the user code changes between the call to UponLeavingGTest() + // and any calls to CurrentStackTrace() from within the user code. + void* caller_frame_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); +}; + +// Information about a Google Test trace point. +struct TraceInfo { + const char* file; + int line; + std::string message; +}; + +// This is the default global test part result reporter used in UnitTestImpl. +// This class should only be used by UnitTestImpl. +class DefaultGlobalTestPartResultReporter + : public TestPartResultReporterInterface { + public: + explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); + // Implements the TestPartResultReporterInterface. Reports the test part + // result in the current test. + virtual void ReportTestPartResult(const TestPartResult& result); + + private: + UnitTestImpl* const unit_test_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); +}; + +// This is the default per thread test part result reporter used in +// UnitTestImpl. This class should only be used by UnitTestImpl. +class DefaultPerThreadTestPartResultReporter + : public TestPartResultReporterInterface { + public: + explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); + // Implements the TestPartResultReporterInterface. The implementation just + // delegates to the current global test part result reporter of *unit_test_. + virtual void ReportTestPartResult(const TestPartResult& result); + + private: + UnitTestImpl* const unit_test_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); +}; + +// The private implementation of the UnitTest class. We don't protect +// the methods under a mutex, as this class is not accessible by a +// user and the UnitTest class that delegates work to this class does +// proper locking. +class GTEST_API_ UnitTestImpl { + public: + explicit UnitTestImpl(UnitTest* parent); + virtual ~UnitTestImpl(); + + // There are two different ways to register your own TestPartResultReporter. + // You can register your own repoter to listen either only for test results + // from the current thread or for results from all threads. + // By default, each per-thread test result repoter just passes a new + // TestPartResult to the global test result reporter, which registers the + // test part result for the currently running test. + + // Returns the global test part result reporter. + TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); + + // Sets the global test part result reporter. + void SetGlobalTestPartResultReporter( + TestPartResultReporterInterface* reporter); + + // Returns the test part result reporter for the current thread. + TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); + + // Sets the test part result reporter for the current thread. + void SetTestPartResultReporterForCurrentThread( + TestPartResultReporterInterface* reporter); + + // Gets the number of successful test cases. + int successful_test_case_count() const; + + // Gets the number of failed test cases. + int failed_test_case_count() const; + + // Gets the number of all test cases. + int total_test_case_count() const; + + // Gets the number of all test cases that contain at least one test + // that should run. + int test_case_to_run_count() const; + + // Gets the number of successful tests. + int successful_test_count() const; + + // Gets the number of failed tests. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Gets the number of all tests. + int total_test_count() const; + + // Gets the number of tests that should run. + int test_to_run_count() const; + + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const { return start_timestamp_; } + + // Gets the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns true iff the unit test passed (i.e. all test cases passed). + bool Passed() const { return !Failed(); } + + // Returns true iff the unit test failed (i.e. some test case failed + // or something outside of all tests failed). + bool Failed() const { + return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); + } + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + const TestCase* GetTestCase(int i) const { + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[i]; + } + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + TestCase* GetMutableTestCase(int i) { + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[index]; + } + + // Provides access to the event listener list. + TestEventListeners* listeners() { return &listeners_; } + + // Returns the TestResult for the test that's currently running, or + // the TestResult for the ad hoc test if no test is running. + TestResult* current_test_result(); + + // Returns the TestResult for the ad hoc test. + const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } + + // Sets the OS stack trace getter. + // + // Does nothing if the input and the current OS stack trace getter + // are the same; otherwise, deletes the old getter and makes the + // input the current getter. + void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); + + // Returns the current OS stack trace getter if it is not NULL; + // otherwise, creates an OsStackTraceGetter, makes it the current + // getter, and returns it. + OsStackTraceGetterInterface* os_stack_trace_getter(); + + // Returns the current OS stack trace as an std::string. + // + // The maximum number of stack frames to be included is specified by + // the gtest_stack_trace_depth flag. The skip_count parameter + // specifies the number of top frames to be skipped, which doesn't + // count against the number of frames to be included. + // + // For example, if Foo() calls Bar(), which in turn calls + // CurrentOsStackTraceExceptTop(1), Foo() will be included in the + // trace but Bar() and CurrentOsStackTraceExceptTop() won't. + std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; + + // Finds and returns a TestCase with the given name. If one doesn't + // exist, creates one and returns it. + // + // Arguments: + // + // test_case_name: name of the test case + // type_param: the name of the test's type parameter, or NULL if + // this is not a typed or a type-parameterized test. + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + TestCase* GetTestCase(const char* test_case_name, + const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc); + + // Adds a TestInfo to the unit test. + // + // Arguments: + // + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + // test_info: the TestInfo object + void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, + TestInfo* test_info) { + // In order to support thread-safe death tests, we need to + // remember the original working directory when the test program + // was first invoked. We cannot do this in RUN_ALL_TESTS(), as + // the user may have changed the current directory before calling + // RUN_ALL_TESTS(). Therefore we capture the current directory in + // AddTestInfo(), which is called to register a TEST or TEST_F + // before main() is reached. + if (original_working_dir_.IsEmpty()) { + original_working_dir_.Set(FilePath::GetCurrentDir()); + GTEST_CHECK_(!original_working_dir_.IsEmpty()) + << "Failed to get the current working directory."; + } + + GetTestCase(test_info->test_case_name(), + test_info->type_param(), + set_up_tc, + tear_down_tc)->AddTestInfo(test_info); + } + +#if GTEST_HAS_PARAM_TEST + // Returns ParameterizedTestCaseRegistry object used to keep track of + // value-parameterized tests and instantiate and register them. + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { + return parameterized_test_registry_; + } +#endif // GTEST_HAS_PARAM_TEST + + // Sets the TestCase object for the test that's currently running. + void set_current_test_case(TestCase* a_current_test_case) { + current_test_case_ = a_current_test_case; + } + + // Sets the TestInfo object for the test that's currently running. If + // current_test_info is NULL, the assertion results will be stored in + // ad_hoc_test_result_. + void set_current_test_info(TestInfo* a_current_test_info) { + current_test_info_ = a_current_test_info; + } + + // Registers all parameterized tests defined using TEST_P and + // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter + // combination. This method can be called more then once; it has guards + // protecting from registering the tests more then once. If + // value-parameterized tests are disabled, RegisterParameterizedTests is + // present but does nothing. + void RegisterParameterizedTests(); + + // Runs all tests in this UnitTest object, prints the result, and + // returns true if all tests are successful. If any exception is + // thrown during a test, this test is considered to be failed, but + // the rest of the tests will still be run. + bool RunAllTests(); + + // Clears the results of all tests, except the ad hoc tests. + void ClearNonAdHocTestResult() { + ForEach(test_cases_, TestCase::ClearTestCaseResult); + } + + // Clears the results of ad-hoc test assertions. + void ClearAdHocTestResult() { + ad_hoc_test_result_.Clear(); + } + + // Adds a TestProperty to the current TestResult object when invoked in a + // context of a test or a test case, or to the global property set. If the + // result already contains a property with the same key, the value will be + // updated. + void RecordProperty(const TestProperty& test_property); + + enum ReactionToSharding { + HONOR_SHARDING_PROTOCOL, + IGNORE_SHARDING_PROTOCOL + }; + + // Matches the full name of each test against the user-specified + // filter to decide whether the test should run, then records the + // result in each TestCase and TestInfo object. + // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests + // based on sharding variables in the environment. + // Returns the number of tests that should run. + int FilterTests(ReactionToSharding shard_tests); + + // Prints the names of the tests matching the user-specified filter flag. + void ListTestsMatchingFilter(); + + const TestCase* current_test_case() const { return current_test_case_; } + TestInfo* current_test_info() { return current_test_info_; } + const TestInfo* current_test_info() const { return current_test_info_; } + + // Returns the vector of environments that need to be set-up/torn-down + // before/after the tests are run. + std::vector& environments() { return environments_; } + + // Getters for the per-thread Google Test trace stack. + std::vector& gtest_trace_stack() { + return *(gtest_trace_stack_.pointer()); + } + const std::vector& gtest_trace_stack() const { + return gtest_trace_stack_.get(); + } + +#if GTEST_HAS_DEATH_TEST + void InitDeathTestSubprocessControlInfo() { + internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); + } + // Returns a pointer to the parsed --gtest_internal_run_death_test + // flag, or NULL if that flag was not specified. + // This information is useful only in a death test child process. + // Must not be called before a call to InitGoogleTest. + const InternalRunDeathTestFlag* internal_run_death_test_flag() const { + return internal_run_death_test_flag_.get(); + } + + // Returns a pointer to the current death test factory. + internal::DeathTestFactory* death_test_factory() { + return death_test_factory_.get(); + } + + void SuppressTestEventsIfInSubprocess(); + + friend class ReplaceDeathTestFactory; +#endif // GTEST_HAS_DEATH_TEST + + // Initializes the event listener performing XML output as specified by + // UnitTestOptions. Must not be called before InitGoogleTest. + void ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Initializes the event listener for streaming test results to a socket. + // Must not be called before InitGoogleTest. + void ConfigureStreamingOutput(); +#endif + + // Performs initialization dependent upon flag values obtained in + // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to + // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest + // this function is also called from RunAllTests. Since this function can be + // called more than once, it has to be idempotent. + void PostFlagParsingInit(); + + // Gets the random seed used at the start of the current test iteration. + int random_seed() const { return random_seed_; } + + // Gets the random number generator. + internal::Random* random() { return &random_; } + + // Shuffles all test cases, and the tests within each test case, + // making sure that death tests are still run first. + void ShuffleTests(); + + // Restores the test cases and tests to their order before the first shuffle. + void UnshuffleTests(); + + // Returns the value of GTEST_FLAG(catch_exceptions) at the moment + // UnitTest::Run() starts. + bool catch_exceptions() const { return catch_exceptions_; } + + private: + friend class ::testing::UnitTest; + + // Used by UnitTest::Run() to capture the state of + // GTEST_FLAG(catch_exceptions) at the moment it starts. + void set_catch_exceptions(bool value) { catch_exceptions_ = value; } + + // The UnitTest object that owns this implementation object. + UnitTest* const parent_; + + // The working directory when the first TEST() or TEST_F() was + // executed. + internal::FilePath original_working_dir_; + + // The default test part result reporters. + DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; + DefaultPerThreadTestPartResultReporter + default_per_thread_test_part_result_reporter_; + + // Points to (but doesn't own) the global test part result reporter. + TestPartResultReporterInterface* global_test_part_result_repoter_; + + // Protects read and write access to global_test_part_result_reporter_. + internal::Mutex global_test_part_result_reporter_mutex_; + + // Points to (but doesn't own) the per-thread test part result reporter. + internal::ThreadLocal + per_thread_test_part_result_reporter_; + + // The vector of environments that need to be set-up/torn-down + // before/after the tests are run. + std::vector environments_; + + // The vector of TestCases in their original order. It owns the + // elements in the vector. + std::vector test_cases_; + + // Provides a level of indirection for the test case list to allow + // easy shuffling and restoring the test case order. The i-th + // element of this vector is the index of the i-th test case in the + // shuffled order. + std::vector test_case_indices_; + +#if GTEST_HAS_PARAM_TEST + // ParameterizedTestRegistry object used to register value-parameterized + // tests. + internal::ParameterizedTestCaseRegistry parameterized_test_registry_; + + // Indicates whether RegisterParameterizedTests() has been called already. + bool parameterized_tests_registered_; +#endif // GTEST_HAS_PARAM_TEST + + // Index of the last death test case registered. Initially -1. + int last_death_test_case_; + + // This points to the TestCase for the currently running test. It + // changes as Google Test goes through one test case after another. + // When no test is running, this is set to NULL and Google Test + // stores assertion results in ad_hoc_test_result_. Initially NULL. + TestCase* current_test_case_; + + // This points to the TestInfo for the currently running test. It + // changes as Google Test goes through one test after another. When + // no test is running, this is set to NULL and Google Test stores + // assertion results in ad_hoc_test_result_. Initially NULL. + TestInfo* current_test_info_; + + // Normally, a user only writes assertions inside a TEST or TEST_F, + // or inside a function called by a TEST or TEST_F. Since Google + // Test keeps track of which test is current running, it can + // associate such an assertion with the test it belongs to. + // + // If an assertion is encountered when no TEST or TEST_F is running, + // Google Test attributes the assertion result to an imaginary "ad hoc" + // test, and records the result in ad_hoc_test_result_. + TestResult ad_hoc_test_result_; + + // The list of event listeners that can be used to track events inside + // Google Test. + TestEventListeners listeners_; + + // The OS stack trace getter. Will be deleted when the UnitTest + // object is destructed. By default, an OsStackTraceGetter is used, + // but the user can set this field to use a custom getter if that is + // desired. + OsStackTraceGetterInterface* os_stack_trace_getter_; + + // True iff PostFlagParsingInit() has been called. + bool post_flag_parse_init_performed_; + + // The random number seed used at the beginning of the test run. + int random_seed_; + + // Our random number generator. + internal::Random random_; + + // The time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp_; + + // How long the test took to run, in milliseconds. + TimeInMillis elapsed_time_; + +#if GTEST_HAS_DEATH_TEST + // The decomposed components of the gtest_internal_run_death_test flag, + // parsed when RUN_ALL_TESTS is called. + internal::scoped_ptr internal_run_death_test_flag_; + internal::scoped_ptr death_test_factory_; +#endif // GTEST_HAS_DEATH_TEST + + // A per-thread stack of traces created by the SCOPED_TRACE() macro. + internal::ThreadLocal > gtest_trace_stack_; + + // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() + // starts. + bool catch_exceptions_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); +}; // class UnitTestImpl + +// Convenience function for accessing the global UnitTest +// implementation object. +inline UnitTestImpl* GetUnitTestImpl() { + return UnitTest::GetInstance()->impl(); +} + +#if GTEST_USES_SIMPLE_RE + +// Internal helper functions for implementing the simple regular +// expression matcher. +GTEST_API_ bool IsInSet(char ch, const char* str); +GTEST_API_ bool IsAsciiDigit(char ch); +GTEST_API_ bool IsAsciiPunct(char ch); +GTEST_API_ bool IsRepeat(char ch); +GTEST_API_ bool IsAsciiWhiteSpace(char ch); +GTEST_API_ bool IsAsciiWordChar(char ch); +GTEST_API_ bool IsValidEscape(char ch); +GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); +GTEST_API_ bool ValidateRegex(const char* regex); +GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead( + bool escaped, char ch, char repeat, const char* regex, const char* str); +GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); + +#endif // GTEST_USES_SIMPLE_RE + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); + +#if GTEST_HAS_DEATH_TEST + +// Returns the message describing the last system error, regardless of the +// platform. +GTEST_API_ std::string GetLastErrnoDescription(); + +# if GTEST_OS_WINDOWS +// Provides leak-safe Windows kernel handle ownership. +class AutoHandle { + public: + AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} + explicit AutoHandle(HANDLE handle) : handle_(handle) {} + + ~AutoHandle() { Reset(); } + + HANDLE Get() const { return handle_; } + void Reset() { Reset(INVALID_HANDLE_VALUE); } + void Reset(HANDLE handle) { + if (handle != handle_) { + if (handle_ != INVALID_HANDLE_VALUE) + ::CloseHandle(handle_); + handle_ = handle; + } + } + + private: + HANDLE handle_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); +}; +# endif // GTEST_OS_WINDOWS + +// Attempts to parse a string into a positive integer pointed to by the +// number parameter. Returns true if that is possible. +// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use +// it here. +template +bool ParseNaturalNumber(const ::std::string& str, Integer* number) { + // Fail fast if the given string does not begin with a digit; + // this bypasses strtoXXX's "optional leading whitespace and plus + // or minus sign" semantics, which are undesirable here. + if (str.empty() || !IsDigit(str[0])) { + return false; + } + errno = 0; + + char* end; + // BiggestConvertible is the largest integer type that system-provided + // string-to-number conversion routines can return. + +# if GTEST_OS_WINDOWS && !defined(__GNUC__) + + // MSVC and C++ Builder define __int64 instead of the standard long long. + typedef unsigned __int64 BiggestConvertible; + const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); + +# else + + typedef unsigned long long BiggestConvertible; // NOLINT + const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); + +# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) + + const bool parse_success = *end == '\0' && errno == 0; + + // TODO(vladl@google.com): Convert this to compile time assertion when it is + // available. + GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); + + const Integer result = static_cast(parsed); + if (parse_success && static_cast(result) == parsed) { + *number = result; + return true; + } + return false; +} +#endif // GTEST_HAS_DEATH_TEST + +// TestResult contains some private methods that should be hidden from +// Google Test user but are required for testing. This class allow our tests +// to access them. +// +// This class is supplied only for the purpose of testing Google Test's own +// constructs. Do not use it in user tests, either directly or indirectly. +class TestResultAccessor { + public: + static void RecordProperty(TestResult* test_result, + const std::string& xml_element, + const TestProperty& property) { + test_result->RecordProperty(xml_element, property); + } + + static void ClearTestPartResults(TestResult* test_result) { + test_result->ClearTestPartResults(); + } + + static const std::vector& test_part_results( + const TestResult& test_result) { + return test_result.test_part_results(); + } +}; + +#if GTEST_CAN_STREAM_RESULTS_ + +// Streams test results to the given port on the given host machine. +class StreamingListener : public EmptyTestEventListener { + public: + // Abstract base class for writing strings to a socket. + class AbstractSocketWriter { + public: + virtual ~AbstractSocketWriter() {} + + // Sends a string to the socket. + virtual void Send(const string& message) = 0; + + // Closes the socket. + virtual void CloseConnection() {} + + // Sends a string and a newline to the socket. + void SendLn(const string& message) { + Send(message + "\n"); + } + }; + + // Concrete class for actually writing strings to a socket. + class SocketWriter : public AbstractSocketWriter { + public: + SocketWriter(const string& host, const string& port) + : sockfd_(-1), host_name_(host), port_num_(port) { + MakeConnection(); + } + + virtual ~SocketWriter() { + if (sockfd_ != -1) + CloseConnection(); + } + + // Sends a string to the socket. + virtual void Send(const string& message) { + GTEST_CHECK_(sockfd_ != -1) + << "Send() can be called only when there is a connection."; + + const int len = static_cast(message.length()); + if (write(sockfd_, message.c_str(), len) != len) { + GTEST_LOG_(WARNING) + << "stream_result_to: failed to stream to " + << host_name_ << ":" << port_num_; + } + } + + private: + // Creates a client socket and connects to the server. + void MakeConnection(); + + // Closes the socket. + void CloseConnection() { + GTEST_CHECK_(sockfd_ != -1) + << "CloseConnection() can be called only when there is a connection."; + + close(sockfd_); + sockfd_ = -1; + } + + int sockfd_; // socket file descriptor + const string host_name_; + const string port_num_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); + }; // class SocketWriter + + // Escapes '=', '&', '%', and '\n' characters in str as "%xx". + static string UrlEncode(const char* str); + + StreamingListener(const string& host, const string& port) + : socket_writer_(new SocketWriter(host, port)) { Start(); } + + explicit StreamingListener(AbstractSocketWriter* socket_writer) + : socket_writer_(socket_writer) { Start(); } + + void OnTestProgramStart(const UnitTest& /* unit_test */) { + SendLn("event=TestProgramStart"); + } + + void OnTestProgramEnd(const UnitTest& unit_test) { + // Note that Google Test current only report elapsed time for each + // test iteration, not for the entire test program. + SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); + + // Notify the streaming server to stop. + socket_writer_->CloseConnection(); + } + + void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { + SendLn("event=TestIterationStart&iteration=" + + StreamableToString(iteration)); + } + + void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { + SendLn("event=TestIterationEnd&passed=" + + FormatBool(unit_test.Passed()) + "&elapsed_time=" + + StreamableToString(unit_test.elapsed_time()) + "ms"); + } + + void OnTestCaseStart(const TestCase& test_case) { + SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); + } + + void OnTestCaseEnd(const TestCase& test_case) { + SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + + "ms"); + } + + void OnTestStart(const TestInfo& test_info) { + SendLn(std::string("event=TestStart&name=") + test_info.name()); + } + + void OnTestEnd(const TestInfo& test_info) { + SendLn("event=TestEnd&passed=" + + FormatBool((test_info.result())->Passed()) + + "&elapsed_time=" + + StreamableToString((test_info.result())->elapsed_time()) + "ms"); + } + + void OnTestPartResult(const TestPartResult& test_part_result) { + const char* file_name = test_part_result.file_name(); + if (file_name == NULL) + file_name = ""; + SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + + "&line=" + StreamableToString(test_part_result.line_number()) + + "&message=" + UrlEncode(test_part_result.message())); + } + + private: + // Sends the given message and a newline to the socket. + void SendLn(const string& message) { socket_writer_->SendLn(message); } + + // Called at the start of streaming to notify the receiver what + // protocol we are using. + void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } + + string FormatBool(bool value) { return value ? "1" : "0"; } + + const scoped_ptr socket_writer_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); +}; // class StreamingListener + +#endif // GTEST_CAN_STREAM_RESULTS_ + +} // namespace internal +} // namespace testing + +#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ +#undef GTEST_IMPLEMENTATION_ + +#if GTEST_OS_WINDOWS +# define vsnprintf _vsnprintf +#endif // GTEST_OS_WINDOWS + +namespace testing { + +using internal::CountIf; +using internal::ForEach; +using internal::GetElementOr; +using internal::Shuffle; + +// Constants. + +// A test whose test case name or test name matches this filter is +// disabled and not run. +static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; + +// A test case whose name matches this filter is considered a death +// test case and will be run before test cases whose name doesn't +// match this filter. +static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; + +// A test filter that matches everything. +static const char kUniversalFilter[] = "*"; + +// The default output file for XML output. +static const char kDefaultOutputFile[] = "test_detail.xml"; + +// The environment variable name for the test shard index. +static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; +// The environment variable name for the total number of test shards. +static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; +// The environment variable name for the test shard status file. +static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; + +namespace internal { + +// The text used in failure messages to indicate the start of the +// stack trace. +const char kStackTraceMarker[] = "\nStack trace:\n"; + +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +bool g_help_flag = false; + +} // namespace internal + +static const char* GetDefaultFilter() { + return kUniversalFilter; +} + +GTEST_DEFINE_bool_( + also_run_disabled_tests, + internal::BoolFromGTestEnv("also_run_disabled_tests", false), + "Run disabled tests too, in addition to the tests normally being run."); + +GTEST_DEFINE_bool_( + break_on_failure, + internal::BoolFromGTestEnv("break_on_failure", false), + "True iff a failed assertion should be a debugger break-point."); + +GTEST_DEFINE_bool_( + catch_exceptions, + internal::BoolFromGTestEnv("catch_exceptions", true), + "True iff " GTEST_NAME_ + " should catch exceptions and treat them as test failures."); + +GTEST_DEFINE_string_( + color, + internal::StringFromGTestEnv("color", "auto"), + "Whether to use colors in the output. Valid values: yes, no, " + "and auto. 'auto' means to use colors if the output is " + "being sent to a terminal and the TERM environment variable " + "is set to a terminal type that supports colors."); + +GTEST_DEFINE_string_( + filter, + internal::StringFromGTestEnv("filter", GetDefaultFilter()), + "A colon-separated list of glob (not regex) patterns " + "for filtering the tests to run, optionally followed by a " + "'-' and a : separated list of negative patterns (tests to " + "exclude). A test is run if it matches one of the positive " + "patterns and does not match any of the negative patterns."); + +GTEST_DEFINE_bool_(list_tests, false, + "List all tests without running them."); + +GTEST_DEFINE_string_( + output, + internal::StringFromGTestEnv("output", ""), + "A format (currently must be \"xml\"), optionally followed " + "by a colon and an output file name or directory. A directory " + "is indicated by a trailing pathname separator. " + "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " + "If a directory is specified, output files will be created " + "within that directory, with file-names based on the test " + "executable's name and, if necessary, made unique by adding " + "digits."); + +GTEST_DEFINE_bool_( + print_time, + internal::BoolFromGTestEnv("print_time", true), + "True iff " GTEST_NAME_ + " should display elapsed time in text output."); + +GTEST_DEFINE_int32_( + random_seed, + internal::Int32FromGTestEnv("random_seed", 0), + "Random number seed to use when shuffling test orders. Must be in range " + "[1, 99999], or 0 to use a seed based on the current time."); + +GTEST_DEFINE_int32_( + repeat, + internal::Int32FromGTestEnv("repeat", 1), + "How many times to repeat each test. Specify a negative number " + "for repeating forever. Useful for shaking out flaky tests."); + +GTEST_DEFINE_bool_( + show_internal_stack_frames, false, + "True iff " GTEST_NAME_ " should include internal stack frames when " + "printing test failure stack traces."); + +GTEST_DEFINE_bool_( + shuffle, + internal::BoolFromGTestEnv("shuffle", false), + "True iff " GTEST_NAME_ + " should randomize tests' order on every run."); + +GTEST_DEFINE_int32_( + stack_trace_depth, + internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), + "The maximum number of stack frames to print when an " + "assertion fails. The valid range is 0 through 100, inclusive."); + +GTEST_DEFINE_string_( + stream_result_to, + internal::StringFromGTestEnv("stream_result_to", ""), + "This flag specifies the host name and the port number on which to stream " + "test results. Example: \"localhost:555\". The flag is effective only on " + "Linux."); + +GTEST_DEFINE_bool_( + throw_on_failure, + internal::BoolFromGTestEnv("throw_on_failure", false), + "When this flag is specified, a failed assertion will throw an exception " + "if exceptions are enabled or exit the program with a non-zero code " + "otherwise."); + +namespace internal { + +// Generates a random number from [0, range), using a Linear +// Congruential Generator (LCG). Crashes if 'range' is 0 or greater +// than kMaxRange. +UInt32 Random::Generate(UInt32 range) { + // These constants are the same as are used in glibc's rand(3). + state_ = (1103515245U*state_ + 12345U) % kMaxRange; + + GTEST_CHECK_(range > 0) + << "Cannot generate a number in the range [0, 0)."; + GTEST_CHECK_(range <= kMaxRange) + << "Generation of a number in [0, " << range << ") was requested, " + << "but this can only generate numbers in [0, " << kMaxRange << ")."; + + // Converting via modulus introduces a bit of downward bias, but + // it's simple, and a linear congruential generator isn't too good + // to begin with. + return state_ % range; +} + +// GTestIsInitialized() returns true iff the user has initialized +// Google Test. Useful for catching the user mistake of not initializing +// Google Test before calling RUN_ALL_TESTS(). +// +// A user must call testing::InitGoogleTest() to initialize Google +// Test. g_init_gtest_count is set to the number of times +// InitGoogleTest() has been called. We don't protect this variable +// under a mutex as it is only accessed in the main thread. +GTEST_API_ int g_init_gtest_count = 0; +static bool GTestIsInitialized() { return g_init_gtest_count != 0; } + +// Iterates over a vector of TestCases, keeping a running sum of the +// results of calling a given int-returning method on each. +// Returns the sum. +static int SumOverTestCaseList(const std::vector& case_list, + int (TestCase::*method)() const) { + int sum = 0; + for (size_t i = 0; i < case_list.size(); i++) { + sum += (case_list[i]->*method)(); + } + return sum; +} + +// Returns true iff the test case passed. +static bool TestCasePassed(const TestCase* test_case) { + return test_case->should_run() && test_case->Passed(); +} + +// Returns true iff the test case failed. +static bool TestCaseFailed(const TestCase* test_case) { + return test_case->should_run() && test_case->Failed(); +} + +// Returns true iff test_case contains at least one test that should +// run. +static bool ShouldRunTestCase(const TestCase* test_case) { + return test_case->should_run(); +} + +// AssertHelper constructor. +AssertHelper::AssertHelper(TestPartResult::Type type, + const char* file, + int line, + const char* message) + : data_(new AssertHelperData(type, file, line, message)) { +} + +AssertHelper::~AssertHelper() { + delete data_; +} + +// Message assignment, for assertion streaming support. +void AssertHelper::operator=(const Message& message) const { + UnitTest::GetInstance()-> + AddTestPartResult(data_->type, data_->file, data_->line, + AppendUserMessage(data_->message, message), + UnitTest::GetInstance()->impl() + ->CurrentOsStackTraceExceptTop(1) + // Skips the stack frame for this function itself. + ); // NOLINT +} + +// Mutex for linked pointers. +GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); + +// Application pathname gotten in InitGoogleTest. +std::string g_executable_path; + +// Returns the current application's name, removing directory path if that +// is present. +FilePath GetCurrentExecutableName() { + FilePath result; + +#if GTEST_OS_WINDOWS + result.Set(FilePath(g_executable_path).RemoveExtension("exe")); +#else + result.Set(FilePath(g_executable_path)); +#endif // GTEST_OS_WINDOWS + + return result.RemoveDirectoryName(); +} + +// Functions for processing the gtest_output flag. + +// Returns the output format, or "" for normal printed output. +std::string UnitTestOptions::GetOutputFormat() { + const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + if (gtest_output_flag == NULL) return std::string(""); + + const char* const colon = strchr(gtest_output_flag, ':'); + return (colon == NULL) ? + std::string(gtest_output_flag) : + std::string(gtest_output_flag, colon - gtest_output_flag); +} + +// Returns the name of the requested output file, or the default if none +// was explicitly specified. +std::string UnitTestOptions::GetAbsolutePathToOutputFile() { + const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + if (gtest_output_flag == NULL) + return ""; + + const char* const colon = strchr(gtest_output_flag, ':'); + if (colon == NULL) + return internal::FilePath::ConcatPaths( + internal::FilePath( + UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(kDefaultOutputFile)).string(); + + internal::FilePath output_name(colon + 1); + if (!output_name.IsAbsolutePath()) + // TODO(wan@google.com): on Windows \some\path is not an absolute + // path (as its meaning depends on the current drive), yet the + // following logic for turning it into an absolute path is wrong. + // Fix it. + output_name = internal::FilePath::ConcatPaths( + internal::FilePath(UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(colon + 1)); + + if (!output_name.IsDirectory()) + return output_name.string(); + + internal::FilePath result(internal::FilePath::GenerateUniqueFileName( + output_name, internal::GetCurrentExecutableName(), + GetOutputFormat().c_str())); + return result.string(); +} + +// Returns true iff the wildcard pattern matches the string. The +// first ':' or '\0' character in pattern marks the end of it. +// +// This recursive algorithm isn't very efficient, but is clear and +// works well enough for matching test names, which are short. +bool UnitTestOptions::PatternMatchesString(const char *pattern, + const char *str) { + switch (*pattern) { + case '\0': + case ':': // Either ':' or '\0' marks the end of the pattern. + return *str == '\0'; + case '?': // Matches any single character. + return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); + case '*': // Matches any string (possibly empty) of characters. + return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || + PatternMatchesString(pattern + 1, str); + default: // Non-special character. Matches itself. + return *pattern == *str && + PatternMatchesString(pattern + 1, str + 1); + } +} + +bool UnitTestOptions::MatchesFilter( + const std::string& name, const char* filter) { + const char *cur_pattern = filter; + for (;;) { + if (PatternMatchesString(cur_pattern, name.c_str())) { + return true; + } + + // Finds the next pattern in the filter. + cur_pattern = strchr(cur_pattern, ':'); + + // Returns if no more pattern can be found. + if (cur_pattern == NULL) { + return false; + } + + // Skips the pattern separater (the ':' character). + cur_pattern++; + } +} + +// Returns true iff the user-specified filter matches the test case +// name and the test name. +bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name) { + const std::string& full_name = test_case_name + "." + test_name.c_str(); + + // Split --gtest_filter at '-', if there is one, to separate into + // positive filter and negative filter portions + const char* const p = GTEST_FLAG(filter).c_str(); + const char* const dash = strchr(p, '-'); + std::string positive; + std::string negative; + if (dash == NULL) { + positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter + negative = ""; + } else { + positive = std::string(p, dash); // Everything up to the dash + negative = std::string(dash + 1); // Everything after the dash + if (positive.empty()) { + // Treat '-test1' as the same as '*-test1' + positive = kUniversalFilter; + } + } + + // A filter is a colon-separated list of patterns. It matches a + // test if any pattern in it matches the test. + return (MatchesFilter(full_name, positive.c_str()) && + !MatchesFilter(full_name, negative.c_str())); +} + +#if GTEST_HAS_SEH +// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the +// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. +// This function is useful as an __except condition. +int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { + // Google Test should handle a SEH exception if: + // 1. the user wants it to, AND + // 2. this is not a breakpoint exception, AND + // 3. this is not a C++ exception (VC++ implements them via SEH, + // apparently). + // + // SEH exception code for C++ exceptions. + // (see http://support.microsoft.com/kb/185294 for more information). + const DWORD kCxxExceptionCode = 0xe06d7363; + + bool should_handle = true; + + if (!GTEST_FLAG(catch_exceptions)) + should_handle = false; + else if (exception_code == EXCEPTION_BREAKPOINT) + should_handle = false; + else if (exception_code == kCxxExceptionCode) + should_handle = false; + + return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; +} +#endif // GTEST_HAS_SEH + +} // namespace internal + +// The c'tor sets this object as the test part result reporter used by +// Google Test. The 'result' parameter specifies where to report the +// results. Intercepts only failures from the current thread. +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( + TestPartResultArray* result) + : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), + result_(result) { + Init(); +} + +// The c'tor sets this object as the test part result reporter used by +// Google Test. The 'result' parameter specifies where to report the +// results. +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( + InterceptMode intercept_mode, TestPartResultArray* result) + : intercept_mode_(intercept_mode), + result_(result) { + Init(); +} + +void ScopedFakeTestPartResultReporter::Init() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + if (intercept_mode_ == INTERCEPT_ALL_THREADS) { + old_reporter_ = impl->GetGlobalTestPartResultReporter(); + impl->SetGlobalTestPartResultReporter(this); + } else { + old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); + impl->SetTestPartResultReporterForCurrentThread(this); + } +} + +// The d'tor restores the test part result reporter used by Google Test +// before. +ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + if (intercept_mode_ == INTERCEPT_ALL_THREADS) { + impl->SetGlobalTestPartResultReporter(old_reporter_); + } else { + impl->SetTestPartResultReporterForCurrentThread(old_reporter_); + } +} + +// Increments the test part result count and remembers the result. +// This method is from the TestPartResultReporterInterface interface. +void ScopedFakeTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + result_->Append(result); +} + +namespace internal { + +// Returns the type ID of ::testing::Test. We should always call this +// instead of GetTypeId< ::testing::Test>() to get the type ID of +// testing::Test. This is to work around a suspected linker bug when +// using Google Test as a framework on Mac OS X. The bug causes +// GetTypeId< ::testing::Test>() to return different values depending +// on whether the call is from the Google Test framework itself or +// from user test code. GetTestTypeId() is guaranteed to always +// return the same value, as it always calls GetTypeId<>() from the +// gtest.cc, which is within the Google Test framework. +TypeId GetTestTypeId() { + return GetTypeId(); +} + +// The value of GetTestTypeId() as seen from within the Google Test +// library. This is solely for testing GetTestTypeId(). +extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); + +// This predicate-formatter checks that 'results' contains a test part +// failure of the given type and that the failure message contains the +// given substring. +AssertionResult HasOneFailure(const char* /* results_expr */, + const char* /* type_expr */, + const char* /* substr_expr */, + const TestPartResultArray& results, + TestPartResult::Type type, + const string& substr) { + const std::string expected(type == TestPartResult::kFatalFailure ? + "1 fatal failure" : + "1 non-fatal failure"); + Message msg; + if (results.size() != 1) { + msg << "Expected: " << expected << "\n" + << " Actual: " << results.size() << " failures"; + for (int i = 0; i < results.size(); i++) { + msg << "\n" << results.GetTestPartResult(i); + } + return AssertionFailure() << msg; + } + + const TestPartResult& r = results.GetTestPartResult(0); + if (r.type() != type) { + return AssertionFailure() << "Expected: " << expected << "\n" + << " Actual:\n" + << r; + } + + if (strstr(r.message(), substr.c_str()) == NULL) { + return AssertionFailure() << "Expected: " << expected << " containing \"" + << substr << "\"\n" + << " Actual:\n" + << r; + } + + return AssertionSuccess(); +} + +// The constructor of SingleFailureChecker remembers where to look up +// test part results, what type of failure we expect, and what +// substring the failure message should contain. +SingleFailureChecker:: SingleFailureChecker( + const TestPartResultArray* results, + TestPartResult::Type type, + const string& substr) + : results_(results), + type_(type), + substr_(substr) {} + +// The destructor of SingleFailureChecker verifies that the given +// TestPartResultArray contains exactly one failure that has the given +// type and contains the given substring. If that's not the case, a +// non-fatal failure will be generated. +SingleFailureChecker::~SingleFailureChecker() { + EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); +} + +DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( + UnitTestImpl* unit_test) : unit_test_(unit_test) {} + +void DefaultGlobalTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + unit_test_->current_test_result()->AddTestPartResult(result); + unit_test_->listeners()->repeater()->OnTestPartResult(result); +} + +DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( + UnitTestImpl* unit_test) : unit_test_(unit_test) {} + +void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); +} + +// Returns the global test part result reporter. +TestPartResultReporterInterface* +UnitTestImpl::GetGlobalTestPartResultReporter() { + internal::MutexLock lock(&global_test_part_result_reporter_mutex_); + return global_test_part_result_repoter_; +} + +// Sets the global test part result reporter. +void UnitTestImpl::SetGlobalTestPartResultReporter( + TestPartResultReporterInterface* reporter) { + internal::MutexLock lock(&global_test_part_result_reporter_mutex_); + global_test_part_result_repoter_ = reporter; +} + +// Returns the test part result reporter for the current thread. +TestPartResultReporterInterface* +UnitTestImpl::GetTestPartResultReporterForCurrentThread() { + return per_thread_test_part_result_reporter_.get(); +} + +// Sets the test part result reporter for the current thread. +void UnitTestImpl::SetTestPartResultReporterForCurrentThread( + TestPartResultReporterInterface* reporter) { + per_thread_test_part_result_reporter_.set(reporter); +} + +// Gets the number of successful test cases. +int UnitTestImpl::successful_test_case_count() const { + return CountIf(test_cases_, TestCasePassed); +} + +// Gets the number of failed test cases. +int UnitTestImpl::failed_test_case_count() const { + return CountIf(test_cases_, TestCaseFailed); +} + +// Gets the number of all test cases. +int UnitTestImpl::total_test_case_count() const { + return static_cast(test_cases_.size()); +} + +// Gets the number of all test cases that contain at least one test +// that should run. +int UnitTestImpl::test_case_to_run_count() const { + return CountIf(test_cases_, ShouldRunTestCase); +} + +// Gets the number of successful tests. +int UnitTestImpl::successful_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); +} + +// Gets the number of failed tests. +int UnitTestImpl::failed_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); +} + +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTestImpl::reportable_disabled_test_count() const { + return SumOverTestCaseList(test_cases_, + &TestCase::reportable_disabled_test_count); +} + +// Gets the number of disabled tests. +int UnitTestImpl::disabled_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); +} + +// Gets the number of tests to be printed in the XML report. +int UnitTestImpl::reportable_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); +} + +// Gets the number of all tests. +int UnitTestImpl::total_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); +} + +// Gets the number of tests that should run. +int UnitTestImpl::test_to_run_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); +} + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// CurrentOsStackTraceExceptTop(1), Foo() will be included in the +// trace but Bar() and CurrentOsStackTraceExceptTop() won't. +std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { + (void)skip_count; + return ""; +} + +// Returns the current time in milliseconds. +TimeInMillis GetTimeInMillis() { +#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) + // Difference between 1970-01-01 and 1601-01-01 in milliseconds. + // http://analogous.blogspot.com/2005/04/epoch.html + const TimeInMillis kJavaEpochToWinFileTimeDelta = + static_cast(116444736UL) * 100000UL; + const DWORD kTenthMicrosInMilliSecond = 10000; + + SYSTEMTIME now_systime; + FILETIME now_filetime; + ULARGE_INTEGER now_int64; + // TODO(kenton@google.com): Shouldn't this just use + // GetSystemTimeAsFileTime()? + GetSystemTime(&now_systime); + if (SystemTimeToFileTime(&now_systime, &now_filetime)) { + now_int64.LowPart = now_filetime.dwLowDateTime; + now_int64.HighPart = now_filetime.dwHighDateTime; + now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - + kJavaEpochToWinFileTimeDelta; + return now_int64.QuadPart; + } + return 0; +#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ + __timeb64 now; + +# ifdef _MSC_VER + + // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 + // (deprecated function) there. + // TODO(kenton@google.com): Use GetTickCount()? Or use + // SystemTimeToFileTime() +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4996) // Temporarily disables warning 4996. + _ftime64(&now); +# pragma warning(pop) // Restores the warning state. +# else + + _ftime64(&now); + +# endif // _MSC_VER + + return static_cast(now.time) * 1000 + now.millitm; +#elif GTEST_HAS_GETTIMEOFDAY_ + struct timeval now; + gettimeofday(&now, NULL); + return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; +#else +# error "Don't know how to get the current time on your system." +#endif +} + +// Utilities + +// class String. + +#if GTEST_OS_WINDOWS_MOBILE +// Creates a UTF-16 wide string from the given ANSI string, allocating +// memory using new. The caller is responsible for deleting the return +// value using delete[]. Returns the wide string, or NULL if the +// input is NULL. +LPCWSTR String::AnsiToUtf16(const char* ansi) { + if (!ansi) return NULL; + const int length = strlen(ansi); + const int unicode_length = + MultiByteToWideChar(CP_ACP, 0, ansi, length, + NULL, 0); + WCHAR* unicode = new WCHAR[unicode_length + 1]; + MultiByteToWideChar(CP_ACP, 0, ansi, length, + unicode, unicode_length); + unicode[unicode_length] = 0; + return unicode; +} + +// Creates an ANSI string from the given wide string, allocating +// memory using new. The caller is responsible for deleting the return +// value using delete[]. Returns the ANSI string, or NULL if the +// input is NULL. +const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { + if (!utf16_str) return NULL; + const int ansi_length = + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, + NULL, 0, NULL, NULL); + char* ansi = new char[ansi_length + 1]; + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, + ansi, ansi_length, NULL, NULL); + ansi[ansi_length] = 0; + return ansi; +} + +#endif // GTEST_OS_WINDOWS_MOBILE + +// Compares two C strings. Returns true iff they have the same content. +// +// Unlike strcmp(), this function can handle NULL argument(s). A NULL +// C string is considered different to any non-NULL C string, +// including the empty string. +bool String::CStringEquals(const char * lhs, const char * rhs) { + if ( lhs == NULL ) return rhs == NULL; + + if ( rhs == NULL ) return false; + + return strcmp(lhs, rhs) == 0; +} + +#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING + +// Converts an array of wide chars to a narrow string using the UTF-8 +// encoding, and streams the result to the given Message object. +static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, + Message* msg) { + for (size_t i = 0; i != length; ) { // NOLINT + if (wstr[i] != L'\0') { + *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); + while (i != length && wstr[i] != L'\0') + i++; + } else { + *msg << '\0'; + i++; + } + } +} + +#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING + +} // namespace internal + +// Constructs an empty Message. +// We allocate the stringstream separately because otherwise each use of +// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's +// stack frame leading to huge stack frames in some cases; gcc does not reuse +// the stack space. +Message::Message() : ss_(new ::std::stringstream) { + // By default, we want there to be enough precision when printing + // a double to a Message. + *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); +} + +// These two overloads allow streaming a wide C string to a Message +// using the UTF-8 encoding. +Message& Message::operator <<(const wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} +Message& Message::operator <<(wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} + +#if GTEST_HAS_STD_WSTRING +// Converts the given wide string to a narrow string using the UTF-8 +// encoding, and streams the result to this Message object. +Message& Message::operator <<(const ::std::wstring& wstr) { + internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); + return *this; +} +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_GLOBAL_WSTRING +// Converts the given wide string to a narrow string using the UTF-8 +// encoding, and streams the result to this Message object. +Message& Message::operator <<(const ::wstring& wstr) { + internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); + return *this; +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +// Gets the text streamed to this object so far as an std::string. +// Each '\0' character in the buffer is replaced with "\\0". +std::string Message::GetString() const { + return internal::StringStreamToString(ss_.get()); +} + +// AssertionResult constructors. +// Used in EXPECT_TRUE/FALSE(assertion_result). +AssertionResult::AssertionResult(const AssertionResult& other) + : success_(other.success_), + message_(other.message_.get() != NULL ? + new ::std::string(*other.message_) : + static_cast< ::std::string*>(NULL)) { +} + +// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. +AssertionResult AssertionResult::operator!() const { + AssertionResult negation(!success_); + if (message_.get() != NULL) + negation << *message_; + return negation; +} + +// Makes a successful assertion result. +AssertionResult AssertionSuccess() { + return AssertionResult(true); +} + +// Makes a failed assertion result. +AssertionResult AssertionFailure() { + return AssertionResult(false); +} + +// Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << message. +AssertionResult AssertionFailure(const Message& message) { + return AssertionFailure() << message; +} + +namespace internal { + +// Constructs and returns the message for an equality assertion +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. +// +// The first four parameters are the expressions used in the assertion +// and their values, as strings. For example, for ASSERT_EQ(foo, bar) +// where foo is 5 and bar is 6, we have: +// +// expected_expression: "foo" +// actual_expression: "bar" +// expected_value: "5" +// actual_value: "6" +// +// The ignoring_case parameter is true iff the assertion is a +// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will +// be inserted into the message. +AssertionResult EqFailure(const char* expected_expression, + const char* actual_expression, + const std::string& expected_value, + const std::string& actual_value, + bool ignoring_case) { + Message msg; + msg << "Value of: " << actual_expression; + if (actual_value != actual_expression) { + msg << "\n Actual: " << actual_value; + } + + msg << "\nExpected: " << expected_expression; + if (ignoring_case) { + msg << " (ignoring case)"; + } + if (expected_value != expected_expression) { + msg << "\nWhich is: " << expected_value; + } + + return AssertionFailure() << msg; +} + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value) { + const char* actual_message = assertion_result.message(); + Message msg; + msg << "Value of: " << expression_text + << "\n Actual: " << actual_predicate_value; + if (actual_message[0] != '\0') + msg << " (" << actual_message << ")"; + msg << "\nExpected: " << expected_predicate_value; + return msg.GetString(); +} + +// Helper function for implementing ASSERT_NEAR. +AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error) { + const double diff = fabs(val1 - val2); + if (diff <= abs_error) return AssertionSuccess(); + + // TODO(wan): do not print the value of an expression if it's + // already a literal. + return AssertionFailure() + << "The difference between " << expr1 << " and " << expr2 + << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" + << expr1 << " evaluates to " << val1 << ",\n" + << expr2 << " evaluates to " << val2 << ", and\n" + << abs_error_expr << " evaluates to " << abs_error << "."; +} + + +// Helper template for implementing FloatLE() and DoubleLE(). +template +AssertionResult FloatingPointLE(const char* expr1, + const char* expr2, + RawType val1, + RawType val2) { + // Returns success if val1 is less than val2, + if (val1 < val2) { + return AssertionSuccess(); + } + + // or if val1 is almost equal to val2. + const FloatingPoint lhs(val1), rhs(val2); + if (lhs.AlmostEquals(rhs)) { + return AssertionSuccess(); + } + + // Note that the above two checks will both fail if either val1 or + // val2 is NaN, as the IEEE floating-point standard requires that + // any predicate involving a NaN must return false. + + ::std::stringstream val1_ss; + val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << val1; + + ::std::stringstream val2_ss; + val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << val2; + + return AssertionFailure() + << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); +} + +} // namespace internal + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2) { + return internal::FloatingPointLE(expr1, expr2, val1, val2); +} + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2) { + return internal::FloatingPointLE(expr1, expr2, val1, val2); +} + +namespace internal { + +// The helper function for {ASSERT|EXPECT}_EQ with int or enum +// arguments. +AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual) { + if (expected == actual) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + FormatForComparisonFailureMessage(expected, actual), + FormatForComparisonFailureMessage(actual, expected), + false); +} + +// A macro for implementing the helper functions needed to implement +// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here +// just to avoid copy-and-paste of similar code. +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + BiggestInt val1, BiggestInt val2) {\ + if (val1 op val2) {\ + return AssertionSuccess();\ + } else {\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ + << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ + << " vs " << FormatForComparisonFailureMessage(val2, val1);\ + }\ +} + +// Implements the helper function for {ASSERT|EXPECT}_NE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(NE, !=) +// Implements the helper function for {ASSERT|EXPECT}_LE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(LE, <=) +// Implements the helper function for {ASSERT|EXPECT}_LT with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(LT, < ) +// Implements the helper function for {ASSERT|EXPECT}_GE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(GE, >=) +// Implements the helper function for {ASSERT|EXPECT}_GT with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(GT, > ) + +#undef GTEST_IMPL_CMP_HELPER_ + +// The helper function for {ASSERT|EXPECT}_STREQ. +AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual) { + if (String::CStringEquals(expected, actual)) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + PrintToString(expected), + PrintToString(actual), + false); +} + +// The helper function for {ASSERT|EXPECT}_STRCASEEQ. +AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual) { + if (String::CaseInsensitiveCStringEquals(expected, actual)) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + PrintToString(expected), + PrintToString(actual), + true); +} + +// The helper function for {ASSERT|EXPECT}_STRNE. +AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2) { + if (!String::CStringEquals(s1, s2)) { + return AssertionSuccess(); + } else { + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; + } +} + +// The helper function for {ASSERT|EXPECT}_STRCASENE. +AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2) { + if (!String::CaseInsensitiveCStringEquals(s1, s2)) { + return AssertionSuccess(); + } else { + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" + << s2_expression << ") (ignoring case), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; + } +} + +} // namespace internal + +namespace { + +// Helper functions for implementing IsSubString() and IsNotSubstring(). + +// This group of overloaded functions return true iff needle is a +// substring of haystack. NULL is considered a substring of itself +// only. + +bool IsSubstringPred(const char* needle, const char* haystack) { + if (needle == NULL || haystack == NULL) + return needle == haystack; + + return strstr(haystack, needle) != NULL; +} + +bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { + if (needle == NULL || haystack == NULL) + return needle == haystack; + + return wcsstr(haystack, needle) != NULL; +} + +// StringType here can be either ::std::string or ::std::wstring. +template +bool IsSubstringPred(const StringType& needle, + const StringType& haystack) { + return haystack.find(needle) != StringType::npos; +} + +// This function implements either IsSubstring() or IsNotSubstring(), +// depending on the value of the expected_to_be_substring parameter. +// StringType here can be const char*, const wchar_t*, ::std::string, +// or ::std::wstring. +template +AssertionResult IsSubstringImpl( + bool expected_to_be_substring, + const char* needle_expr, const char* haystack_expr, + const StringType& needle, const StringType& haystack) { + if (IsSubstringPred(needle, haystack) == expected_to_be_substring) + return AssertionSuccess(); + + const bool is_wide_string = sizeof(needle[0]) > 1; + const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; + return AssertionFailure() + << "Value of: " << needle_expr << "\n" + << " Actual: " << begin_string_quote << needle << "\"\n" + << "Expected: " << (expected_to_be_substring ? "" : "not ") + << "a substring of " << haystack_expr << "\n" + << "Which is: " << begin_string_quote << haystack << "\""; +} + +} // namespace + +// IsSubstring() and IsNotSubstring() check whether needle is a +// substring of haystack (NULL is considered a substring of itself +// only), and return an appropriate error message when they fail. + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +#if GTEST_HAS_STD_WSTRING +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} +#endif // GTEST_HAS_STD_WSTRING + +namespace internal { + +#if GTEST_OS_WINDOWS + +namespace { + +// Helper function for IsHRESULT{SuccessFailure} predicates +AssertionResult HRESULTFailureHelper(const char* expr, + const char* expected, + long hr) { // NOLINT +# if GTEST_OS_WINDOWS_MOBILE + + // Windows CE doesn't support FormatMessage. + const char error_text[] = ""; + +# else + + // Looks up the human-readable system message for the HRESULT code + // and since we're not passing any params to FormatMessage, we don't + // want inserts expanded. + const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS; + const DWORD kBufSize = 4096; + // Gets the system's human readable message string for this HRESULT. + char error_text[kBufSize] = { '\0' }; + DWORD message_length = ::FormatMessageA(kFlags, + 0, // no source, we're asking system + hr, // the error + 0, // no line width restrictions + error_text, // output buffer + kBufSize, // buf size + NULL); // no arguments for inserts + // Trims tailing white space (FormatMessage leaves a trailing CR-LF) + for (; message_length && IsSpace(error_text[message_length - 1]); + --message_length) { + error_text[message_length - 1] = '\0'; + } + +# endif // GTEST_OS_WINDOWS_MOBILE + + const std::string error_hex("0x" + String::FormatHexInt(hr)); + return ::testing::AssertionFailure() + << "Expected: " << expr << " " << expected << ".\n" + << " Actual: " << error_hex << " " << error_text << "\n"; +} + +} // namespace + +AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT + if (SUCCEEDED(hr)) { + return AssertionSuccess(); + } + return HRESULTFailureHelper(expr, "succeeds", hr); +} + +AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT + if (FAILED(hr)) { + return AssertionSuccess(); + } + return HRESULTFailureHelper(expr, "fails", hr); +} + +#endif // GTEST_OS_WINDOWS + +// Utility functions for encoding Unicode text (wide strings) in +// UTF-8. + +// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 +// like this: +// +// Code-point length Encoding +// 0 - 7 bits 0xxxxxxx +// 8 - 11 bits 110xxxxx 10xxxxxx +// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx +// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + +// The maximum code-point a one-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; + +// The maximum code-point a two-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; + +// The maximum code-point a three-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; + +// The maximum code-point a four-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; + +// Chops off the n lowest bits from a bit pattern. Returns the n +// lowest bits. As a side effect, the original bit pattern will be +// shifted to the right by n bits. +inline UInt32 ChopLowBits(UInt32* bits, int n) { + const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); + *bits >>= n; + return low_bits; +} + +// Converts a Unicode code point to a narrow string in UTF-8 encoding. +// code_point parameter is of type UInt32 because wchar_t may not be +// wide enough to contain a code point. +// If the code_point is not a valid Unicode code point +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +std::string CodePointToUtf8(UInt32 code_point) { + if (code_point > kMaxCodePoint4) { + return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; + } + + char str[5]; // Big enough for the largest valid code point. + if (code_point <= kMaxCodePoint1) { + str[1] = '\0'; + str[0] = static_cast(code_point); // 0xxxxxxx + } else if (code_point <= kMaxCodePoint2) { + str[2] = '\0'; + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xC0 | code_point); // 110xxxxx + } else if (code_point <= kMaxCodePoint3) { + str[3] = '\0'; + str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xE0 | code_point); // 1110xxxx + } else { // code_point <= kMaxCodePoint4 + str[4] = '\0'; + str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xF0 | code_point); // 11110xxx + } + return str; +} + +// The following two functions only make sense if the the system +// uses UTF-16 for wide string encoding. All supported systems +// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. + +// Determines if the arguments constitute UTF-16 surrogate pair +// and thus should be combined into a single Unicode code point +// using CreateCodePointFromUtf16SurrogatePair. +inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { + return sizeof(wchar_t) == 2 && + (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; +} + +// Creates a Unicode code point from UTF16 surrogate pair. +inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, + wchar_t second) { + const UInt32 mask = (1 << 10) - 1; + return (sizeof(wchar_t) == 2) ? + (((first & mask) << 10) | (second & mask)) + 0x10000 : + // This function should not be called when the condition is + // false, but we provide a sensible default in case it is. + static_cast(first); +} + +// Converts a wide string to a narrow string in UTF-8 encoding. +// The wide string is assumed to have the following encoding: +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-32 if sizeof(wchar_t) == 4 (on Linux) +// Parameter str points to a null-terminated wide string. +// Parameter num_chars may additionally limit the number +// of wchar_t characters processed. -1 is used when the entire string +// should be processed. +// If the string contains code points that are not valid Unicode code points +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding +// and contains invalid UTF-16 surrogate pairs, values in those pairs +// will be encoded as individual Unicode characters from Basic Normal Plane. +std::string WideStringToUtf8(const wchar_t* str, int num_chars) { + if (num_chars == -1) + num_chars = static_cast(wcslen(str)); + + ::std::stringstream stream; + for (int i = 0; i < num_chars; ++i) { + UInt32 unicode_code_point; + + if (str[i] == L'\0') { + break; + } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { + unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], + str[i + 1]); + i++; + } else { + unicode_code_point = static_cast(str[i]); + } + + stream << CodePointToUtf8(unicode_code_point); + } + return StringStreamToString(&stream); +} + +// Converts a wide C string to an std::string using the UTF-8 encoding. +// NULL will be converted to "(null)". +std::string String::ShowWideCString(const wchar_t * wide_c_str) { + if (wide_c_str == NULL) return "(null)"; + + return internal::WideStringToUtf8(wide_c_str, -1); +} + +// Compares two wide C strings. Returns true iff they have the same +// content. +// +// Unlike wcscmp(), this function can handle NULL argument(s). A NULL +// C string is considered different to any non-NULL C string, +// including the empty string. +bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { + if (lhs == NULL) return rhs == NULL; + + if (rhs == NULL) return false; + + return wcscmp(lhs, rhs) == 0; +} + +// Helper function for *_STREQ on wide strings. +AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const wchar_t* expected, + const wchar_t* actual) { + if (String::WideCStringEquals(expected, actual)) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + PrintToString(expected), + PrintToString(actual), + false); +} + +// Helper function for *_STRNE on wide strings. +AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2) { + if (!String::WideCStringEquals(s1, s2)) { + return AssertionSuccess(); + } + + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: " + << PrintToString(s1) + << " vs " << PrintToString(s2); +} + +// Compares two C strings, ignoring case. Returns true iff they have +// the same content. +// +// Unlike strcasecmp(), this function can handle NULL argument(s). A +// NULL C string is considered different to any non-NULL C string, +// including the empty string. +bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { + if (lhs == NULL) + return rhs == NULL; + if (rhs == NULL) + return false; + return posix::StrCaseCmp(lhs, rhs) == 0; +} + + // Compares two wide C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike wcscasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL wide C string, + // including the empty string. + // NB: The implementations on different platforms slightly differ. + // On windows, this method uses _wcsicmp which compares according to LC_CTYPE + // environment variable. On GNU platform this method uses wcscasecmp + // which compares according to LC_CTYPE category of the current locale. + // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the + // current locale. +bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, + const wchar_t* rhs) { + if (lhs == NULL) return rhs == NULL; + + if (rhs == NULL) return false; + +#if GTEST_OS_WINDOWS + return _wcsicmp(lhs, rhs) == 0; +#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID + return wcscasecmp(lhs, rhs) == 0; +#else + // Android, Mac OS X and Cygwin don't define wcscasecmp. + // Other unknown OSes may not define it either. + wint_t left, right; + do { + left = towlower(*lhs++); + right = towlower(*rhs++); + } while (left && left == right); + return left == right; +#endif // OS selector +} + +// Returns true iff str ends with the given suffix, ignoring case. +// Any string is considered to end with an empty suffix. +bool String::EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix) { + const size_t str_len = str.length(); + const size_t suffix_len = suffix.length(); + return (str_len >= suffix_len) && + CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, + suffix.c_str()); +} + +// Formats an int value as "%02d". +std::string String::FormatIntWidth2(int value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << value; + return ss.str(); +} + +// Formats an int value as "%X". +std::string String::FormatHexInt(int value) { + std::stringstream ss; + ss << std::hex << std::uppercase << value; + return ss.str(); +} + +// Formats a byte as "%02X". +std::string String::FormatByte(unsigned char value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase + << static_cast(value); + return ss.str(); +} + +// Converts the buffer in a stringstream to an std::string, converting NUL +// bytes to "\\0" along the way. +std::string StringStreamToString(::std::stringstream* ss) { + const ::std::string& str = ss->str(); + const char* const start = str.c_str(); + const char* const end = start + str.length(); + + std::string result; + result.reserve(2 * (end - start)); + for (const char* ch = start; ch != end; ++ch) { + if (*ch == '\0') { + result += "\\0"; // Replaces NUL with "\\0"; + } else { + result += *ch; + } + } + + return result; +} + +// Appends the user-supplied message to the Google-Test-generated message. +std::string AppendUserMessage(const std::string& gtest_msg, + const Message& user_msg) { + // Appends the user message if it's non-empty. + const std::string user_msg_string = user_msg.GetString(); + if (user_msg_string.empty()) { + return gtest_msg; + } + + return gtest_msg + "\n" + user_msg_string; +} + +} // namespace internal + +// class TestResult + +// Creates an empty TestResult. +TestResult::TestResult() + : death_test_count_(0), + elapsed_time_(0) { +} + +// D'tor. +TestResult::~TestResult() { +} + +// Returns the i-th test part result among all the results. i can +// range from 0 to total_part_count() - 1. If i is not in that range, +// aborts the program. +const TestPartResult& TestResult::GetTestPartResult(int i) const { + if (i < 0 || i >= total_part_count()) + internal::posix::Abort(); + return test_part_results_.at(i); +} + +// Returns the i-th test property. i can range from 0 to +// test_property_count() - 1. If i is not in that range, aborts the +// program. +const TestProperty& TestResult::GetTestProperty(int i) const { + if (i < 0 || i >= test_property_count()) + internal::posix::Abort(); + return test_properties_.at(i); +} + +// Clears the test part results. +void TestResult::ClearTestPartResults() { + test_part_results_.clear(); +} + +// Adds a test part result to the list. +void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { + test_part_results_.push_back(test_part_result); +} + +// Adds a test property to the list. If a property with the same key as the +// supplied property is already represented, the value of this test_property +// replaces the old value for that key. +void TestResult::RecordProperty(const std::string& xml_element, + const TestProperty& test_property) { + if (!ValidateTestProperty(xml_element, test_property)) { + return; + } + internal::MutexLock lock(&test_properites_mutex_); + const std::vector::iterator property_with_matching_key = + std::find_if(test_properties_.begin(), test_properties_.end(), + internal::TestPropertyKeyIs(test_property.key())); + if (property_with_matching_key == test_properties_.end()) { + test_properties_.push_back(test_property); + return; + } + property_with_matching_key->SetValue(test_property.value()); +} + +// The list of reserved attributes used in the element of XML +// output. +static const char* const kReservedTestSuitesAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "random_seed", + "tests", + "time", + "timestamp" +}; + +// The list of reserved attributes used in the element of XML +// output. +static const char* const kReservedTestSuiteAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "tests", + "time" +}; + +// The list of reserved attributes used in the element of XML output. +static const char* const kReservedTestCaseAttributes[] = { + "classname", + "name", + "status", + "time", + "type_param", + "value_param" +}; + +template +std::vector ArrayAsVector(const char* const (&array)[kSize]) { + return std::vector(array, array + kSize); +} + +static std::vector GetReservedAttributesForElement( + const std::string& xml_element) { + if (xml_element == "testsuites") { + return ArrayAsVector(kReservedTestSuitesAttributes); + } else if (xml_element == "testsuite") { + return ArrayAsVector(kReservedTestSuiteAttributes); + } else if (xml_element == "testcase") { + return ArrayAsVector(kReservedTestCaseAttributes); + } else { + GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; + } + // This code is unreachable but some compilers may not realizes that. + return std::vector(); +} + +static std::string FormatWordList(const std::vector& words) { + Message word_list; + for (size_t i = 0; i < words.size(); ++i) { + if (i > 0 && words.size() > 2) { + word_list << ", "; + } + if (i == words.size() - 1) { + word_list << "and "; + } + word_list << "'" << words[i] << "'"; + } + return word_list.GetString(); +} + +bool ValidateTestPropertyName(const std::string& property_name, + const std::vector& reserved_names) { + if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != + reserved_names.end()) { + ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name + << " (" << FormatWordList(reserved_names) + << " are reserved by " << GTEST_NAME_ << ")"; + return false; + } + return true; +} + +// Adds a failure if the key is a reserved attribute of the element named +// xml_element. Returns true if the property is valid. +bool TestResult::ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property) { + return ValidateTestPropertyName(test_property.key(), + GetReservedAttributesForElement(xml_element)); +} + +// Clears the object. +void TestResult::Clear() { + test_part_results_.clear(); + test_properties_.clear(); + death_test_count_ = 0; + elapsed_time_ = 0; +} + +// Returns true iff the test failed. +bool TestResult::Failed() const { + for (int i = 0; i < total_part_count(); ++i) { + if (GetTestPartResult(i).failed()) + return true; + } + return false; +} + +// Returns true iff the test part fatally failed. +static bool TestPartFatallyFailed(const TestPartResult& result) { + return result.fatally_failed(); +} + +// Returns true iff the test fatally failed. +bool TestResult::HasFatalFailure() const { + return CountIf(test_part_results_, TestPartFatallyFailed) > 0; +} + +// Returns true iff the test part non-fatally failed. +static bool TestPartNonfatallyFailed(const TestPartResult& result) { + return result.nonfatally_failed(); +} + +// Returns true iff the test has a non-fatal failure. +bool TestResult::HasNonfatalFailure() const { + return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; +} + +// Gets the number of all test parts. This is the sum of the number +// of successful test parts and the number of failed test parts. +int TestResult::total_part_count() const { + return static_cast(test_part_results_.size()); +} + +// Returns the number of the test properties. +int TestResult::test_property_count() const { + return static_cast(test_properties_.size()); +} + +// class Test + +// Creates a Test object. + +// The c'tor saves the values of all Google Test flags. +Test::Test() + : gtest_flag_saver_(new internal::GTestFlagSaver) { +} + +// The d'tor restores the values of all Google Test flags. +Test::~Test() { + delete gtest_flag_saver_; +} + +// Sets up the test fixture. +// +// A sub-class may override this. +void Test::SetUp() { +} + +// Tears down the test fixture. +// +// A sub-class may override this. +void Test::TearDown() { +} + +// Allows user supplied key value pairs to be recorded for later output. +void Test::RecordProperty(const std::string& key, const std::string& value) { + UnitTest::GetInstance()->RecordProperty(key, value); +} + +// Allows user supplied key value pairs to be recorded for later output. +void Test::RecordProperty(const std::string& key, int value) { + Message value_message; + value_message << value; + RecordProperty(key, value_message.GetString().c_str()); +} + +namespace internal { + +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, + const std::string& message) { + // This function is a friend of UnitTest and as such has access to + // AddTestPartResult. + UnitTest::GetInstance()->AddTestPartResult( + result_type, + NULL, // No info about the source file where the exception occurred. + -1, // We have no info on which line caused the exception. + message, + ""); // No stack trace, either. +} + +} // namespace internal + +// Google Test requires all tests in the same test case to use the same test +// fixture class. This function checks if the current test has the +// same fixture class as the first test in the current test case. If +// yes, it returns true; otherwise it generates a Google Test failure and +// returns false. +bool Test::HasSameFixtureClass() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + const TestCase* const test_case = impl->current_test_case(); + + // Info about the first test in the current test case. + const TestInfo* const first_test_info = test_case->test_info_list()[0]; + const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; + const char* const first_test_name = first_test_info->name(); + + // Info about the current test. + const TestInfo* const this_test_info = impl->current_test_info(); + const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; + const char* const this_test_name = this_test_info->name(); + + if (this_fixture_id != first_fixture_id) { + // Is the first test defined using TEST? + const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); + // Is this test defined using TEST? + const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); + + if (first_is_TEST || this_is_TEST) { + // The user mixed TEST and TEST_F in this test case - we'll tell + // him/her how to fix it. + + // Gets the name of the TEST and the name of the TEST_F. Note + // that first_is_TEST and this_is_TEST cannot both be true, as + // the fixture IDs are different for the two tests. + const char* const TEST_name = + first_is_TEST ? first_test_name : this_test_name; + const char* const TEST_F_name = + first_is_TEST ? this_test_name : first_test_name; + + ADD_FAILURE() + << "All tests in the same test case must use the same test fixture\n" + << "class, so mixing TEST_F and TEST in the same test case is\n" + << "illegal. In test case " << this_test_info->test_case_name() + << ",\n" + << "test " << TEST_F_name << " is defined using TEST_F but\n" + << "test " << TEST_name << " is defined using TEST. You probably\n" + << "want to change the TEST to TEST_F or move it to another test\n" + << "case."; + } else { + // The user defined two fixture classes with the same name in + // two namespaces - we'll tell him/her how to fix it. + ADD_FAILURE() + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " + << this_test_info->test_case_name() << ",\n" + << "you defined test " << first_test_name + << " and test " << this_test_name << "\n" + << "using two different test fixture classes. This can happen if\n" + << "the two classes are from different namespaces or translation\n" + << "units and have the same name. You should probably rename one\n" + << "of the classes to put the tests into different test cases."; + } + return false; + } + + return true; +} + +#if GTEST_HAS_SEH + +// Adds an "exception thrown" fatal failure to the current test. This +// function returns its result via an output parameter pointer because VC++ +// prohibits creation of objects with destructors on stack in functions +// using __try (see error C2712). +static std::string* FormatSehExceptionMessage(DWORD exception_code, + const char* location) { + Message message; + message << "SEH exception with code 0x" << std::setbase(16) << + exception_code << std::setbase(10) << " thrown in " << location << "."; + + return new std::string(message.GetString()); +} + +#endif // GTEST_HAS_SEH + +namespace internal { + +#if GTEST_HAS_EXCEPTIONS + +// Adds an "exception thrown" fatal failure to the current test. +static std::string FormatCxxExceptionMessage(const char* description, + const char* location) { + Message message; + if (description != NULL) { + message << "C++ exception with description \"" << description << "\""; + } else { + message << "Unknown C++ exception"; + } + message << " thrown in " << location << "."; + + return message.GetString(); +} + +static std::string PrintTestPartResultToString( + const TestPartResult& test_part_result); + +GoogleTestFailureException::GoogleTestFailureException( + const TestPartResult& failure) + : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} + +#endif // GTEST_HAS_EXCEPTIONS + +// We put these helper functions in the internal namespace as IBM's xlC +// compiler rejects the code if they were declared static. + +// Runs the given method and handles SEH exceptions it throws, when +// SEH is supported; returns the 0-value for type Result in case of an +// SEH exception. (Microsoft compilers cannot handle SEH and C++ +// exceptions in the same function. Therefore, we provide a separate +// wrapper function for handling SEH exceptions.) +template +Result HandleSehExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { +#if GTEST_HAS_SEH + __try { + return (object->*method)(); + } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT + GetExceptionCode())) { + // We create the exception message on the heap because VC++ prohibits + // creation of objects with destructors on stack in functions using __try + // (see error C2712). + std::string* exception_message = FormatSehExceptionMessage( + GetExceptionCode(), location); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, + *exception_message); + delete exception_message; + return static_cast(0); + } +#else + (void)location; + return (object->*method)(); +#endif // GTEST_HAS_SEH +} + +// Runs the given method and catches and reports C++ and/or SEH-style +// exceptions, if they are supported; returns the 0-value for type +// Result in case of an SEH exception. +template +Result HandleExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { + // NOTE: The user code can affect the way in which Google Test handles + // exceptions by setting GTEST_FLAG(catch_exceptions), but only before + // RUN_ALL_TESTS() starts. It is technically possible to check the flag + // after the exception is caught and either report or re-throw the + // exception based on the flag's value: + // + // try { + // // Perform the test method. + // } catch (...) { + // if (GTEST_FLAG(catch_exceptions)) + // // Report the exception as failure. + // else + // throw; // Re-throws the original exception. + // } + // + // However, the purpose of this flag is to allow the program to drop into + // the debugger when the exception is thrown. On most platforms, once the + // control enters the catch block, the exception origin information is + // lost and the debugger will stop the program at the point of the + // re-throw in this function -- instead of at the point of the original + // throw statement in the code under test. For this reason, we perform + // the check early, sacrificing the ability to affect Google Test's + // exception handling in the method where the exception is thrown. + if (internal::GetUnitTestImpl()->catch_exceptions()) { +#if GTEST_HAS_EXCEPTIONS + try { + return HandleSehExceptionsInMethodIfSupported(object, method, location); + } catch (const internal::GoogleTestFailureException&) { // NOLINT + // This exception type can only be thrown by a failed Google + // Test assertion with the intention of letting another testing + // framework catch it. Therefore we just re-throw it. + throw; + } catch (const std::exception& e) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(e.what(), location)); + } catch (...) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(NULL, location)); + } + return static_cast(0); +#else + return HandleSehExceptionsInMethodIfSupported(object, method, location); +#endif // GTEST_HAS_EXCEPTIONS + } else { + return (object->*method)(); + } +} + +} // namespace internal + +// Runs the test and updates the test result. +void Test::Run() { + if (!HasSameFixtureClass()) return; + + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); + // We will run the test only if SetUp() was successful. + if (!HasFatalFailure()) { + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &Test::TestBody, "the test body"); + } + + // However, we want to clean up as much as possible. Hence we will + // always call TearDown(), even if SetUp() or the test body has + // failed. + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &Test::TearDown, "TearDown()"); +} + +// Returns true iff the current test has a fatal failure. +bool Test::HasFatalFailure() { + return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); +} + +// Returns true iff the current test has a non-fatal failure. +bool Test::HasNonfatalFailure() { + return internal::GetUnitTestImpl()->current_test_result()-> + HasNonfatalFailure(); +} + +// class TestInfo + +// Constructs a TestInfo object. It assumes ownership of the test factory +// object. +TestInfo::TestInfo(const std::string& a_test_case_name, + const std::string& a_name, + const char* a_type_param, + const char* a_value_param, + internal::TypeId fixture_class_id, + internal::TestFactoryBase* factory) + : test_case_name_(a_test_case_name), + name_(a_name), + type_param_(a_type_param ? new std::string(a_type_param) : NULL), + value_param_(a_value_param ? new std::string(a_value_param) : NULL), + fixture_class_id_(fixture_class_id), + should_run_(false), + is_disabled_(false), + matches_filter_(false), + factory_(factory), + result_() {} + +// Destructs a TestInfo object. +TestInfo::~TestInfo() { delete factory_; } + +namespace internal { + +// Creates a new TestInfo object and registers it with Google Test; +// returns the created object. +// +// Arguments: +// +// test_case_name: name of the test case +// name: name of the test +// type_param: the name of the test's type parameter, or NULL if +// this is not a typed or a type-parameterized test. +// value_param: text representation of the test's value parameter, +// or NULL if this is not a value-parameterized test. +// fixture_class_id: ID of the test fixture class +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +// factory: pointer to the factory that creates a test object. +// The newly created TestInfo instance will assume +// ownership of the factory object. +TestInfo* MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory) { + TestInfo* const test_info = + new TestInfo(test_case_name, name, type_param, value_param, + fixture_class_id, factory); + GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); + return test_info; +} + +#if GTEST_HAS_PARAM_TEST +void ReportInvalidTestCaseType(const char* test_case_name, + const char* file, int line) { + Message errors; + errors + << "Attempted redefinition of test case " << test_case_name << ".\n" + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " << test_case_name << ", you tried\n" + << "to define a test using a fixture class different from the one\n" + << "used earlier. This can happen if the two fixture classes are\n" + << "from different namespaces and have the same name. You should\n" + << "probably rename one of the classes to put the tests into different\n" + << "test cases."; + + fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), + errors.GetString().c_str()); +} +#endif // GTEST_HAS_PARAM_TEST + +} // namespace internal + +namespace { + +// A predicate that checks the test name of a TestInfo against a known +// value. +// +// This is used for implementation of the TestCase class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestNameIs is copyable. +class TestNameIs { + public: + // Constructor. + // + // TestNameIs has NO default constructor. + explicit TestNameIs(const char* name) + : name_(name) {} + + // Returns true iff the test name of test_info matches name_. + bool operator()(const TestInfo * test_info) const { + return test_info && test_info->name() == name_; + } + + private: + std::string name_; +}; + +} // namespace + +namespace internal { + +// This method expands all parameterized tests registered with macros TEST_P +// and INSTANTIATE_TEST_CASE_P into regular tests and registers those. +// This will be done just once during the program runtime. +void UnitTestImpl::RegisterParameterizedTests() { +#if GTEST_HAS_PARAM_TEST + if (!parameterized_tests_registered_) { + parameterized_test_registry_.RegisterTests(); + parameterized_tests_registered_ = true; + } +#endif +} + +} // namespace internal + +// Creates the test object, runs it, records its result, and then +// deletes it. +void TestInfo::Run() { + if (!should_run_) return; + + // Tells UnitTest where to store test result. + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_info(this); + + TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + + // Notifies the unit test event listeners that a test is about to start. + repeater->OnTestStart(*this); + + const TimeInMillis start = internal::GetTimeInMillis(); + + impl->os_stack_trace_getter()->UponLeavingGTest(); + + // Creates the test object. + Test* const test = internal::HandleExceptionsInMethodIfSupported( + factory_, &internal::TestFactoryBase::CreateTest, + "the test fixture's constructor"); + + // Runs the test only if the test object was created and its + // constructor didn't generate a fatal failure. + if ((test != NULL) && !Test::HasFatalFailure()) { + // This doesn't throw as all user code that can throw are wrapped into + // exception handling code. + test->Run(); + } + + // Deletes the test object. + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + test, &Test::DeleteSelf_, "the test fixture's destructor"); + + result_.set_elapsed_time(internal::GetTimeInMillis() - start); + + // Notifies the unit test event listener that a test has just finished. + repeater->OnTestEnd(*this); + + // Tells UnitTest to stop associating assertion results to this + // test. + impl->set_current_test_info(NULL); +} + +// class TestCase + +// Gets the number of successful tests in this test case. +int TestCase::successful_test_count() const { + return CountIf(test_info_list_, TestPassed); +} + +// Gets the number of failed tests in this test case. +int TestCase::failed_test_count() const { + return CountIf(test_info_list_, TestFailed); +} + +// Gets the number of disabled tests that will be reported in the XML report. +int TestCase::reportable_disabled_test_count() const { + return CountIf(test_info_list_, TestReportableDisabled); +} + +// Gets the number of disabled tests in this test case. +int TestCase::disabled_test_count() const { + return CountIf(test_info_list_, TestDisabled); +} + +// Gets the number of tests to be printed in the XML report. +int TestCase::reportable_test_count() const { + return CountIf(test_info_list_, TestReportable); +} + +// Get the number of tests in this test case that should run. +int TestCase::test_to_run_count() const { + return CountIf(test_info_list_, ShouldRunTest); +} + +// Gets the number of all tests. +int TestCase::total_test_count() const { + return static_cast(test_info_list_.size()); +} + +// Creates a TestCase with the given name. +// +// Arguments: +// +// name: name of the test case +// a_type_param: the name of the test case's type parameter, or NULL if +// this is not a typed or a type-parameterized test case. +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +TestCase::TestCase(const char* a_name, const char* a_type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc) + : name_(a_name), + type_param_(a_type_param ? new std::string(a_type_param) : NULL), + set_up_tc_(set_up_tc), + tear_down_tc_(tear_down_tc), + should_run_(false), + elapsed_time_(0) { +} + +// Destructor of TestCase. +TestCase::~TestCase() { + // Deletes every Test in the collection. + ForEach(test_info_list_, internal::Delete); +} + +// Returns the i-th test among all the tests. i can range from 0 to +// total_test_count() - 1. If i is not in that range, returns NULL. +const TestInfo* TestCase::GetTestInfo(int i) const { + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; +} + +// Returns the i-th test among all the tests. i can range from 0 to +// total_test_count() - 1. If i is not in that range, returns NULL. +TestInfo* TestCase::GetMutableTestInfo(int i) { + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; +} + +// Adds a test to this test case. Will delete the test upon +// destruction of the TestCase object. +void TestCase::AddTestInfo(TestInfo * test_info) { + test_info_list_.push_back(test_info); + test_indices_.push_back(static_cast(test_indices_.size())); +} + +// Runs every test in this TestCase. +void TestCase::Run() { + if (!should_run_) return; + + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_case(this); + + TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + + repeater->OnTestCaseStart(*this); + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); + + const internal::TimeInMillis start = internal::GetTimeInMillis(); + for (int i = 0; i < total_test_count(); i++) { + GetMutableTestInfo(i)->Run(); + } + elapsed_time_ = internal::GetTimeInMillis() - start; + + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); + + repeater->OnTestCaseEnd(*this); + impl->set_current_test_case(NULL); +} + +// Clears the results of all tests in this test case. +void TestCase::ClearResult() { + ad_hoc_test_result_.Clear(); + ForEach(test_info_list_, TestInfo::ClearTestResult); +} + +// Shuffles the tests in this test case. +void TestCase::ShuffleTests(internal::Random* random) { + Shuffle(random, &test_indices_); +} + +// Restores the test order to before the first shuffle. +void TestCase::UnshuffleTests() { + for (size_t i = 0; i < test_indices_.size(); i++) { + test_indices_[i] = static_cast(i); + } +} + +// Formats a countable noun. Depending on its quantity, either the +// singular form or the plural form is used. e.g. +// +// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". +// FormatCountableNoun(5, "book", "books") returns "5 books". +static std::string FormatCountableNoun(int count, + const char * singular_form, + const char * plural_form) { + return internal::StreamableToString(count) + " " + + (count == 1 ? singular_form : plural_form); +} + +// Formats the count of tests. +static std::string FormatTestCount(int test_count) { + return FormatCountableNoun(test_count, "test", "tests"); +} + +// Formats the count of test cases. +static std::string FormatTestCaseCount(int test_case_count) { + return FormatCountableNoun(test_case_count, "test case", "test cases"); +} + +// Converts a TestPartResult::Type enum to human-friendly string +// representation. Both kNonFatalFailure and kFatalFailure are translated +// to "Failure", as the user usually doesn't care about the difference +// between the two when viewing the test result. +static const char * TestPartResultTypeToString(TestPartResult::Type type) { + switch (type) { + case TestPartResult::kSuccess: + return "Success"; + + case TestPartResult::kNonFatalFailure: + case TestPartResult::kFatalFailure: +#ifdef _MSC_VER + return "error: "; +#else + return "Failure\n"; +#endif + default: + return "Unknown result type"; + } +} + +namespace internal { + +// Prints a TestPartResult to an std::string. +static std::string PrintTestPartResultToString( + const TestPartResult& test_part_result) { + return (Message() + << internal::FormatFileLocation(test_part_result.file_name(), + test_part_result.line_number()) + << " " << TestPartResultTypeToString(test_part_result.type()) + << test_part_result.message()).GetString(); +} + +// Prints a TestPartResult. +static void PrintTestPartResult(const TestPartResult& test_part_result) { + const std::string& result = + PrintTestPartResultToString(test_part_result); + printf("%s\n", result.c_str()); + fflush(stdout); + // If the test program runs in Visual Studio or a debugger, the + // following statements add the test part result message to the Output + // window such that the user can double-click on it to jump to the + // corresponding source code location; otherwise they do nothing. +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + // We don't call OutputDebugString*() on Windows Mobile, as printing + // to stdout is done by OutputDebugString() there already - we don't + // want the same message printed twice. + ::OutputDebugStringA(result.c_str()); + ::OutputDebugStringA("\n"); +#endif +} + +// class PrettyUnitTestResultPrinter + +enum GTestColor { + COLOR_DEFAULT, + COLOR_RED, + COLOR_GREEN, + COLOR_YELLOW +}; + +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + +// Returns the character attribute for the given color. +WORD GetColorAttribute(GTestColor color) { + switch (color) { + case COLOR_RED: return FOREGROUND_RED; + case COLOR_GREEN: return FOREGROUND_GREEN; + case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; + default: return 0; + } +} + +#else + +// Returns the ANSI color code for the given color. COLOR_DEFAULT is +// an invalid input. +const char* GetAnsiColorCode(GTestColor color) { + switch (color) { + case COLOR_RED: return "1"; + case COLOR_GREEN: return "2"; + case COLOR_YELLOW: return "3"; + default: return NULL; + }; +} + +#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + +// Returns true iff Google Test should use colors in the output. +bool ShouldUseColor(bool stdout_is_tty) { + const char* const gtest_color = GTEST_FLAG(color).c_str(); + + if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { +#if GTEST_OS_WINDOWS + // On Windows the TERM variable is usually not set, but the + // console there does support colors. + return stdout_is_tty; +#else + // On non-Windows platforms, we rely on the TERM variable. + const char* const term = posix::GetEnv("TERM"); + const bool term_supports_color = + String::CStringEquals(term, "xterm") || + String::CStringEquals(term, "xterm-color") || + String::CStringEquals(term, "xterm-256color") || + String::CStringEquals(term, "screen") || + String::CStringEquals(term, "screen-256color") || + String::CStringEquals(term, "linux") || + String::CStringEquals(term, "cygwin"); + return stdout_is_tty && term_supports_color; +#endif // GTEST_OS_WINDOWS + } + + return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || + String::CaseInsensitiveCStringEquals(gtest_color, "true") || + String::CaseInsensitiveCStringEquals(gtest_color, "t") || + String::CStringEquals(gtest_color, "1"); + // We take "yes", "true", "t", and "1" as meaning "yes". If the + // value is neither one of these nor "auto", we treat it as "no" to + // be conservative. +} + +// Helpers for printing colored strings to stdout. Note that on Windows, we +// cannot simply emit special characters and have the terminal change colors. +// This routine must actually emit the characters rather than return a string +// that would be colored when printed, as can be done on Linux. +void ColoredPrintf(GTestColor color, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS + const bool use_color = false; +#else + static const bool in_color_mode = + ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); + const bool use_color = in_color_mode && (color != COLOR_DEFAULT); +#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS + // The '!= 0' comparison is necessary to satisfy MSVC 7.1. + + if (!use_color) { + vprintf(fmt, args); + va_end(args); + return; + } + +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); + + // Gets the current text color. + CONSOLE_SCREEN_BUFFER_INFO buffer_info; + GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); + const WORD old_color_attrs = buffer_info.wAttributes; + + // We need to flush the stream buffers into the console before each + // SetConsoleTextAttribute call lest it affect the text that is already + // printed but has not yet reached the console. + fflush(stdout); + SetConsoleTextAttribute(stdout_handle, + GetColorAttribute(color) | FOREGROUND_INTENSITY); + vprintf(fmt, args); + + fflush(stdout); + // Restores the text color. + SetConsoleTextAttribute(stdout_handle, old_color_attrs); +#else + printf("\033[0;3%sm", GetAnsiColorCode(color)); + vprintf(fmt, args); + printf("\033[m"); // Resets the terminal to default. +#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + va_end(args); +} + +// Text printed in Google Test's text output and --gunit_list_tests +// output to label the type parameter and value parameter for a test. +static const char kTypeParamLabel[] = "TypeParam"; +static const char kValueParamLabel[] = "GetParam()"; + +void PrintFullTestCommentIfPresent(const TestInfo& test_info) { + const char* const type_param = test_info.type_param(); + const char* const value_param = test_info.value_param(); + + if (type_param != NULL || value_param != NULL) { + printf(", where "); + if (type_param != NULL) { + printf("%s = %s", kTypeParamLabel, type_param); + if (value_param != NULL) + printf(" and "); + } + if (value_param != NULL) { + printf("%s = %s", kValueParamLabel, value_param); + } + } +} + +// This class implements the TestEventListener interface. +// +// Class PrettyUnitTestResultPrinter is copyable. +class PrettyUnitTestResultPrinter : public TestEventListener { + public: + PrettyUnitTestResultPrinter() {} + static void PrintTestName(const char * test_case, const char * test) { + printf("%s.%s", test_case, test); + } + + // The following methods override what's in the TestEventListener class. + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} + + private: + static void PrintFailedTests(const UnitTest& unit_test); +}; + + // Fired before each iteration of tests starts. +void PrettyUnitTestResultPrinter::OnTestIterationStart( + const UnitTest& unit_test, int iteration) { + if (GTEST_FLAG(repeat) != 1) + printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); + + const char* const filter = GTEST_FLAG(filter).c_str(); + + // Prints the filter if it's not *. This reminds the user that some + // tests may be skipped. + if (!String::CStringEquals(filter, kUniversalFilter)) { + ColoredPrintf(COLOR_YELLOW, + "Note: %s filter = %s\n", GTEST_NAME_, filter); + } + + if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { + const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); + ColoredPrintf(COLOR_YELLOW, + "Note: This is test shard %d of %s.\n", + static_cast(shard_index) + 1, + internal::posix::GetEnv(kTestTotalShards)); + } + + if (GTEST_FLAG(shuffle)) { + ColoredPrintf(COLOR_YELLOW, + "Note: Randomizing tests' orders with a seed of %d .\n", + unit_test.random_seed()); + } + + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("Running %s from %s.\n", + FormatTestCount(unit_test.test_to_run_count()).c_str(), + FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( + const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("Global test environment set-up.\n"); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { + const std::string counts = + FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("%s from %s", counts.c_str(), test_case.name()); + if (test_case.type_param() == NULL) { + printf("\n"); + } else { + printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); + } + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { + ColoredPrintf(COLOR_GREEN, "[ RUN ] "); + PrintTestName(test_info.test_case_name(), test_info.name()); + printf("\n"); + fflush(stdout); +} + +// Called after an assertion failure. +void PrettyUnitTestResultPrinter::OnTestPartResult( + const TestPartResult& result) { + // If the test part succeeded, we don't need to do anything. + if (result.type() == TestPartResult::kSuccess) + return; + + // Print failure message from the assertion (e.g. expected this and got that). + PrintTestPartResult(result); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { + if (test_info.result()->Passed()) { + ColoredPrintf(COLOR_GREEN, "[ OK ] "); + } else { + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + } + PrintTestName(test_info.test_case_name(), test_info.name()); + if (test_info.result()->Failed()) + PrintFullTestCommentIfPresent(test_info); + + if (GTEST_FLAG(print_time)) { + printf(" (%s ms)\n", internal::StreamableToString( + test_info.result()->elapsed_time()).c_str()); + } else { + printf("\n"); + } + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { + if (!GTEST_FLAG(print_time)) return; + + const std::string counts = + FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("%s from %s (%s ms total)\n\n", + counts.c_str(), test_case.name(), + internal::StreamableToString(test_case.elapsed_time()).c_str()); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( + const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("Global test environment tear-down\n"); + fflush(stdout); +} + +// Internal helper for printing the list of failed tests. +void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { + const int failed_test_count = unit_test.failed_test_count(); + if (failed_test_count == 0) { + return; + } + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + const TestCase& test_case = *unit_test.GetTestCase(i); + if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { + continue; + } + for (int j = 0; j < test_case.total_test_count(); ++j) { + const TestInfo& test_info = *test_case.GetTestInfo(j); + if (!test_info.should_run() || test_info.result()->Passed()) { + continue; + } + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s.%s", test_case.name(), test_info.name()); + PrintFullTestCommentIfPresent(test_info); + printf("\n"); + } + } +} + +void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("%s from %s ran.", + FormatTestCount(unit_test.test_to_run_count()).c_str(), + FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + if (GTEST_FLAG(print_time)) { + printf(" (%s ms total)", + internal::StreamableToString(unit_test.elapsed_time()).c_str()); + } + printf("\n"); + ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); + printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); + + int num_failures = unit_test.failed_test_count(); + if (!unit_test.Passed()) { + const int failed_test_count = unit_test.failed_test_count(); + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); + PrintFailedTests(unit_test); + printf("\n%2d FAILED %s\n", num_failures, + num_failures == 1 ? "TEST" : "TESTS"); + } + + int num_disabled = unit_test.reportable_disabled_test_count(); + if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { + if (!num_failures) { + printf("\n"); // Add a spacer if no FAILURE banner is displayed. + } + ColoredPrintf(COLOR_YELLOW, + " YOU HAVE %d DISABLED %s\n\n", + num_disabled, + num_disabled == 1 ? "TEST" : "TESTS"); + } + // Ensure that Google Test output is printed before, e.g., heapchecker output. + fflush(stdout); +} + +// End PrettyUnitTestResultPrinter + +// class TestEventRepeater +// +// This class forwards events to other event listeners. +class TestEventRepeater : public TestEventListener { + public: + TestEventRepeater() : forwarding_enabled_(true) {} + virtual ~TestEventRepeater(); + void Append(TestEventListener *listener); + TestEventListener* Release(TestEventListener* listener); + + // Controls whether events will be forwarded to listeners_. Set to false + // in death test child processes. + bool forwarding_enabled() const { return forwarding_enabled_; } + void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } + + virtual void OnTestProgramStart(const UnitTest& unit_test); + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& unit_test); + + private: + // Controls whether events will be forwarded to listeners_. Set to false + // in death test child processes. + bool forwarding_enabled_; + // The list of listeners that receive events. + std::vector listeners_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); +}; + +TestEventRepeater::~TestEventRepeater() { + ForEach(listeners_, Delete); +} + +void TestEventRepeater::Append(TestEventListener *listener) { + listeners_.push_back(listener); +} + +// TODO(vladl@google.com): Factor the search functionality into Vector::Find. +TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { + for (size_t i = 0; i < listeners_.size(); ++i) { + if (listeners_[i] == listener) { + listeners_.erase(listeners_.begin() + i); + return listener; + } + } + + return NULL; +} + +// Since most methods are very similar, use macros to reduce boilerplate. +// This defines a member that forwards the call to all listeners. +#define GTEST_REPEATER_METHOD_(Name, Type) \ +void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (size_t i = 0; i < listeners_.size(); i++) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ +} +// This defines a member that forwards the call to all listeners in reverse +// order. +#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ +void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ +} + +GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) +GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) +GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) +GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) +GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) +GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) +GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) +GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) + +#undef GTEST_REPEATER_METHOD_ +#undef GTEST_REVERSE_REPEATER_METHOD_ + +void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, + int iteration) { + if (forwarding_enabled_) { + for (size_t i = 0; i < listeners_.size(); i++) { + listeners_[i]->OnTestIterationStart(unit_test, iteration); + } + } +} + +void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, + int iteration) { + if (forwarding_enabled_) { + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { + listeners_[i]->OnTestIterationEnd(unit_test, iteration); + } + } +} + +// End TestEventRepeater + +// This class generates an XML output file. +class XmlUnitTestResultPrinter : public EmptyTestEventListener { + public: + explicit XmlUnitTestResultPrinter(const char* output_file); + + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + + private: + // Is c a whitespace character that is normalized to a space character + // when it appears in an XML attribute value? + static bool IsNormalizableWhitespace(char c) { + return c == 0x9 || c == 0xA || c == 0xD; + } + + // May c appear in a well-formed XML document? + static bool IsValidXmlCharacter(char c) { + return IsNormalizableWhitespace(c) || c >= 0x20; + } + + // Returns an XML-escaped copy of the input string str. If + // is_attribute is true, the text is meant to appear as an attribute + // value, and normalizable whitespace is preserved by replacing it + // with character references. + static std::string EscapeXml(const std::string& str, bool is_attribute); + + // Returns the given string with all characters invalid in XML removed. + static std::string RemoveInvalidXmlCharacters(const std::string& str); + + // Convenience wrapper around EscapeXml when str is an attribute value. + static std::string EscapeXmlAttribute(const std::string& str) { + return EscapeXml(str, true); + } + + // Convenience wrapper around EscapeXml when str is not an attribute value. + static std::string EscapeXmlText(const char* str) { + return EscapeXml(str, false); + } + + // Verifies that the given attribute belongs to the given element and + // streams the attribute as XML. + static void OutputXmlAttribute(std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value); + + // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. + static void OutputXmlCDataSection(::std::ostream* stream, const char* data); + + // Streams an XML representation of a TestInfo object. + static void OutputXmlTestInfo(::std::ostream* stream, + const char* test_case_name, + const TestInfo& test_info); + + // Prints an XML representation of a TestCase object + static void PrintXmlTestCase(::std::ostream* stream, + const TestCase& test_case); + + // Prints an XML summary of unit_test to output stream out. + static void PrintXmlUnitTest(::std::ostream* stream, + const UnitTest& unit_test); + + // Produces a string representing the test properties in a result as space + // delimited XML attributes based on the property key="value" pairs. + // When the std::string is not empty, it includes a space at the beginning, + // to delimit this attribute from prior attributes. + static std::string TestPropertiesAsXmlAttributes(const TestResult& result); + + // The output file. + const std::string output_file_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); +}; + +// Creates a new XmlUnitTestResultPrinter. +XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) + : output_file_(output_file) { + if (output_file_.c_str() == NULL || output_file_.empty()) { + fprintf(stderr, "XML output file may not be null\n"); + fflush(stderr); + exit(EXIT_FAILURE); + } +} + +// Called after the unit test ends. +void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { + FILE* xmlout = NULL; + FilePath output_file(output_file_); + FilePath output_dir(output_file.RemoveFileName()); + + if (output_dir.CreateDirectoriesRecursively()) { + xmlout = posix::FOpen(output_file_.c_str(), "w"); + } + if (xmlout == NULL) { + // TODO(wan): report the reason of the failure. + // + // We don't do it for now as: + // + // 1. There is no urgent need for it. + // 2. It's a bit involved to make the errno variable thread-safe on + // all three operating systems (Linux, Windows, and Mac OS). + // 3. To interpret the meaning of errno in a thread-safe way, + // we need the strerror_r() function, which is not available on + // Windows. + fprintf(stderr, + "Unable to open file \"%s\"\n", + output_file_.c_str()); + fflush(stderr); + exit(EXIT_FAILURE); + } + std::stringstream stream; + PrintXmlUnitTest(&stream, unit_test); + fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); + fclose(xmlout); +} + +// Returns an XML-escaped copy of the input string str. If is_attribute +// is true, the text is meant to appear as an attribute value, and +// normalizable whitespace is preserved by replacing it with character +// references. +// +// Invalid XML characters in str, if any, are stripped from the output. +// It is expected that most, if not all, of the text processed by this +// module will consist of ordinary English text. +// If this module is ever modified to produce version 1.1 XML output, +// most invalid characters can be retained using character references. +// TODO(wan): It might be nice to have a minimally invasive, human-readable +// escaping scheme for invalid characters, rather than dropping them. +std::string XmlUnitTestResultPrinter::EscapeXml( + const std::string& str, bool is_attribute) { + Message m; + + for (size_t i = 0; i < str.size(); ++i) { + const char ch = str[i]; + switch (ch) { + case '<': + m << "<"; + break; + case '>': + m << ">"; + break; + case '&': + m << "&"; + break; + case '\'': + if (is_attribute) + m << "'"; + else + m << '\''; + break; + case '"': + if (is_attribute) + m << """; + else + m << '"'; + break; + default: + if (IsValidXmlCharacter(ch)) { + if (is_attribute && IsNormalizableWhitespace(ch)) + m << "&#x" << String::FormatByte(static_cast(ch)) + << ";"; + else + m << ch; + } + break; + } + } + + return m.GetString(); +} + +// Returns the given string with all characters invalid in XML removed. +// Currently invalid characters are dropped from the string. An +// alternative is to replace them with certain characters such as . or ?. +std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( + const std::string& str) { + std::string output; + output.reserve(str.size()); + for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) + if (IsValidXmlCharacter(*it)) + output.push_back(*it); + + return output; +} + +// The following routines generate an XML representation of a UnitTest +// object. +// +// This is how Google Test concepts map to the DTD: +// +// <-- corresponds to a UnitTest object +// <-- corresponds to a TestCase object +// <-- corresponds to a TestInfo object +// ... +// ... +// ... +// <-- individual assertion failures +// +// +// + +// Formats the given time in milliseconds as seconds. +std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { + ::std::stringstream ss; + ss << ms/1000.0; + return ss.str(); +} + +// Converts the given epoch time in milliseconds to a date string in the ISO +// 8601 format, without the timezone information. +std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { + // Using non-reentrant version as localtime_r is not portable. + time_t seconds = static_cast(ms / 1000); +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4996) // Temporarily disables warning 4996 + // (function or variable may be unsafe). + const struct tm* const time_struct = localtime(&seconds); // NOLINT +# pragma warning(pop) // Restores the warning state again. +#else + const struct tm* const time_struct = localtime(&seconds); // NOLINT +#endif + if (time_struct == NULL) + return ""; // Invalid ms value + + // YYYY-MM-DDThh:mm:ss + return StreamableToString(time_struct->tm_year + 1900) + "-" + + String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct->tm_mday) + "T" + + String::FormatIntWidth2(time_struct->tm_hour) + ":" + + String::FormatIntWidth2(time_struct->tm_min) + ":" + + String::FormatIntWidth2(time_struct->tm_sec); +} + +// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. +void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, + const char* data) { + const char* segment = data; + *stream << ""); + if (next_segment != NULL) { + stream->write( + segment, static_cast(next_segment - segment)); + *stream << "]]>]]>"); + } else { + *stream << segment; + break; + } + } + *stream << "]]>"; +} + +void XmlUnitTestResultPrinter::OutputXmlAttribute( + std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value) { + const std::vector& allowed_names = + GetReservedAttributesForElement(element_name); + + GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != + allowed_names.end()) + << "Attribute " << name << " is not allowed for element <" << element_name + << ">."; + + *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; +} + +// Prints an XML representation of a TestInfo object. +// TODO(wan): There is also value in printing properties with the plain printer. +void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, + const char* test_case_name, + const TestInfo& test_info) { + const TestResult& result = *test_info.result(); + const std::string kTestcase = "testcase"; + + *stream << " \n"; + } + const string location = internal::FormatCompilerIndependentFileLocation( + part.file_name(), part.line_number()); + const string summary = location + "\n" + part.summary(); + *stream << " "; + const string detail = location + "\n" + part.message(); + OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); + *stream << "\n"; + } + } + + if (failures == 0) + *stream << " />\n"; + else + *stream << " \n"; +} + +// Prints an XML representation of a TestCase object +void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, + const TestCase& test_case) { + const std::string kTestsuite = "testsuite"; + *stream << " <" << kTestsuite; + OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); + OutputXmlAttribute(stream, kTestsuite, "tests", + StreamableToString(test_case.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuite, "failures", + StreamableToString(test_case.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuite, "disabled", + StreamableToString(test_case.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuite, "errors", "0"); + OutputXmlAttribute(stream, kTestsuite, "time", + FormatTimeInMillisAsSeconds(test_case.elapsed_time())); + *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) + << ">\n"; + + for (int i = 0; i < test_case.total_test_count(); ++i) { + if (test_case.GetTestInfo(i)->is_reportable()) + OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); + } + *stream << " \n"; +} + +// Prints an XML summary of unit_test to output stream out. +void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, + const UnitTest& unit_test) { + const std::string kTestsuites = "testsuites"; + + *stream << "\n"; + *stream << "<" << kTestsuites; + + OutputXmlAttribute(stream, kTestsuites, "tests", + StreamableToString(unit_test.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuites, "failures", + StreamableToString(unit_test.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuites, "disabled", + StreamableToString(unit_test.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuites, "errors", "0"); + OutputXmlAttribute( + stream, kTestsuites, "timestamp", + FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); + OutputXmlAttribute(stream, kTestsuites, "time", + FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); + + if (GTEST_FLAG(shuffle)) { + OutputXmlAttribute(stream, kTestsuites, "random_seed", + StreamableToString(unit_test.random_seed())); + } + + *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); + + OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); + *stream << ">\n"; + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + if (unit_test.GetTestCase(i)->reportable_test_count() > 0) + PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); + } + *stream << "\n"; +} + +// Produces a string representing the test properties in a result as space +// delimited XML attributes based on the property key="value" pairs. +std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( + const TestResult& result) { + Message attributes; + for (int i = 0; i < result.test_property_count(); ++i) { + const TestProperty& property = result.GetTestProperty(i); + attributes << " " << property.key() << "=" + << "\"" << EscapeXmlAttribute(property.value()) << "\""; + } + return attributes.GetString(); +} + +// End XmlUnitTestResultPrinter + +#if GTEST_CAN_STREAM_RESULTS_ + +// Checks if str contains '=', '&', '%' or '\n' characters. If yes, +// replaces them by "%xx" where xx is their hexadecimal value. For +// example, replaces "=" with "%3D". This algorithm is O(strlen(str)) +// in both time and space -- important as the input str may contain an +// arbitrarily long test failure message and stack trace. +string StreamingListener::UrlEncode(const char* str) { + string result; + result.reserve(strlen(str) + 1); + for (char ch = *str; ch != '\0'; ch = *++str) { + switch (ch) { + case '%': + case '=': + case '&': + case '\n': + result.append("%" + String::FormatByte(static_cast(ch))); + break; + default: + result.push_back(ch); + break; + } + } + return result; +} + +void StreamingListener::SocketWriter::MakeConnection() { + GTEST_CHECK_(sockfd_ == -1) + << "MakeConnection() can't be called when there is already a connection."; + + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. + hints.ai_socktype = SOCK_STREAM; + addrinfo* servinfo = NULL; + + // Use the getaddrinfo() to get a linked list of IP addresses for + // the given host name. + const int error_num = getaddrinfo( + host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); + if (error_num != 0) { + GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " + << gai_strerror(error_num); + } + + // Loop through all the results and connect to the first we can. + for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; + cur_addr = cur_addr->ai_next) { + sockfd_ = socket( + cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); + if (sockfd_ != -1) { + // Connect the client socket to the server socket. + if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { + close(sockfd_); + sockfd_ = -1; + } + } + } + + freeaddrinfo(servinfo); // all done with this structure + + if (sockfd_ == -1) { + GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " + << host_name_ << ":" << port_num_; + } +} + +// End of class Streaming Listener +#endif // GTEST_CAN_STREAM_RESULTS__ + +// Class ScopedTrace + +// Pushes the given source file location and message onto a per-thread +// trace stack maintained by Google Test. +ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { + TraceInfo trace; + trace.file = file; + trace.line = line; + trace.message = message.GetString(); + + UnitTest::GetInstance()->PushGTestTrace(trace); +} + +// Pops the info pushed by the c'tor. +ScopedTrace::~ScopedTrace() + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { + UnitTest::GetInstance()->PopGTestTrace(); +} + + +// class OsStackTraceGetter + +// Returns the current OS stack trace as an std::string. Parameters: +// +// max_depth - the maximum number of stack frames to be included +// in the trace. +// skip_count - the number of top frames to be skipped; doesn't count +// against max_depth. +// +string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */, + int /* skip_count */) + GTEST_LOCK_EXCLUDED_(mutex_) { + return ""; +} + +void OsStackTraceGetter::UponLeavingGTest() + GTEST_LOCK_EXCLUDED_(mutex_) { +} + +const char* const +OsStackTraceGetter::kElidedFramesMarker = + "... " GTEST_NAME_ " internal frames ..."; + +// A helper class that creates the premature-exit file in its +// constructor and deletes the file in its destructor. +class ScopedPrematureExitFile { + public: + explicit ScopedPrematureExitFile(const char* premature_exit_filepath) + : premature_exit_filepath_(premature_exit_filepath) { + // If a path to the premature-exit file is specified... + if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { + // create the file with a single "0" character in it. I/O + // errors are ignored as there's nothing better we can do and we + // don't want to fail the test because of this. + FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); + fwrite("0", 1, 1, pfile); + fclose(pfile); + } + } + + ~ScopedPrematureExitFile() { + if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { + remove(premature_exit_filepath_); + } + } + + private: + const char* const premature_exit_filepath_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); +}; + +} // namespace internal + +// class TestEventListeners + +TestEventListeners::TestEventListeners() + : repeater_(new internal::TestEventRepeater()), + default_result_printer_(NULL), + default_xml_generator_(NULL) { +} + +TestEventListeners::~TestEventListeners() { delete repeater_; } + +// Returns the standard listener responsible for the default console +// output. Can be removed from the listeners list to shut down default +// console output. Note that removing this object from the listener list +// with Release transfers its ownership to the user. +void TestEventListeners::Append(TestEventListener* listener) { + repeater_->Append(listener); +} + +// Removes the given event listener from the list and returns it. It then +// becomes the caller's responsibility to delete the listener. Returns +// NULL if the listener is not found in the list. +TestEventListener* TestEventListeners::Release(TestEventListener* listener) { + if (listener == default_result_printer_) + default_result_printer_ = NULL; + else if (listener == default_xml_generator_) + default_xml_generator_ = NULL; + return repeater_->Release(listener); +} + +// Returns repeater that broadcasts the TestEventListener events to all +// subscribers. +TestEventListener* TestEventListeners::repeater() { return repeater_; } + +// Sets the default_result_printer attribute to the provided listener. +// The listener is also added to the listener list and previous +// default_result_printer is removed from it and deleted. The listener can +// also be NULL in which case it will not be added to the list. Does +// nothing if the previous and the current listener objects are the same. +void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { + if (default_result_printer_ != listener) { + // It is an error to pass this method a listener that is already in the + // list. + delete Release(default_result_printer_); + default_result_printer_ = listener; + if (listener != NULL) + Append(listener); + } +} + +// Sets the default_xml_generator attribute to the provided listener. The +// listener is also added to the listener list and previous +// default_xml_generator is removed from it and deleted. The listener can +// also be NULL in which case it will not be added to the list. Does +// nothing if the previous and the current listener objects are the same. +void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { + if (default_xml_generator_ != listener) { + // It is an error to pass this method a listener that is already in the + // list. + delete Release(default_xml_generator_); + default_xml_generator_ = listener; + if (listener != NULL) + Append(listener); + } +} + +// Controls whether events will be forwarded by the repeater to the +// listeners in the list. +bool TestEventListeners::EventForwardingEnabled() const { + return repeater_->forwarding_enabled(); +} + +void TestEventListeners::SuppressEventForwarding() { + repeater_->set_forwarding_enabled(false); +} + +// class UnitTest + +// Gets the singleton UnitTest object. The first time this method is +// called, a UnitTest object is constructed and returned. Consecutive +// calls will return the same object. +// +// We don't protect this under mutex_ as a user is not supposed to +// call this before main() starts, from which point on the return +// value will never change. +UnitTest* UnitTest::GetInstance() { + // When compiled with MSVC 7.1 in optimized mode, destroying the + // UnitTest object upon exiting the program messes up the exit code, + // causing successful tests to appear failed. We have to use a + // different implementation in this case to bypass the compiler bug. + // This implementation makes the compiler happy, at the cost of + // leaking the UnitTest object. + + // CodeGear C++Builder insists on a public destructor for the + // default implementation. Use this implementation to keep good OO + // design with private destructor. + +#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) + static UnitTest* const instance = new UnitTest; + return instance; +#else + static UnitTest instance; + return &instance; +#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) +} + +// Gets the number of successful test cases. +int UnitTest::successful_test_case_count() const { + return impl()->successful_test_case_count(); +} + +// Gets the number of failed test cases. +int UnitTest::failed_test_case_count() const { + return impl()->failed_test_case_count(); +} + +// Gets the number of all test cases. +int UnitTest::total_test_case_count() const { + return impl()->total_test_case_count(); +} + +// Gets the number of all test cases that contain at least one test +// that should run. +int UnitTest::test_case_to_run_count() const { + return impl()->test_case_to_run_count(); +} + +// Gets the number of successful tests. +int UnitTest::successful_test_count() const { + return impl()->successful_test_count(); +} + +// Gets the number of failed tests. +int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } + +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTest::reportable_disabled_test_count() const { + return impl()->reportable_disabled_test_count(); +} + +// Gets the number of disabled tests. +int UnitTest::disabled_test_count() const { + return impl()->disabled_test_count(); +} + +// Gets the number of tests to be printed in the XML report. +int UnitTest::reportable_test_count() const { + return impl()->reportable_test_count(); +} + +// Gets the number of all tests. +int UnitTest::total_test_count() const { return impl()->total_test_count(); } + +// Gets the number of tests that should run. +int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } + +// Gets the time of the test program start, in ms from the start of the +// UNIX epoch. +internal::TimeInMillis UnitTest::start_timestamp() const { + return impl()->start_timestamp(); +} + +// Gets the elapsed time, in milliseconds. +internal::TimeInMillis UnitTest::elapsed_time() const { + return impl()->elapsed_time(); +} + +// Returns true iff the unit test passed (i.e. all test cases passed). +bool UnitTest::Passed() const { return impl()->Passed(); } + +// Returns true iff the unit test failed (i.e. some test case failed +// or something outside of all tests failed). +bool UnitTest::Failed() const { return impl()->Failed(); } + +// Gets the i-th test case among all the test cases. i can range from 0 to +// total_test_case_count() - 1. If i is not in that range, returns NULL. +const TestCase* UnitTest::GetTestCase(int i) const { + return impl()->GetTestCase(i); +} + +// Returns the TestResult containing information on test failures and +// properties logged outside of individual test cases. +const TestResult& UnitTest::ad_hoc_test_result() const { + return *impl()->ad_hoc_test_result(); +} + +// Gets the i-th test case among all the test cases. i can range from 0 to +// total_test_case_count() - 1. If i is not in that range, returns NULL. +TestCase* UnitTest::GetMutableTestCase(int i) { + return impl()->GetMutableTestCase(i); +} + +// Returns the list of event listeners that can be used to track events +// inside Google Test. +TestEventListeners& UnitTest::listeners() { + return *impl()->listeners(); +} + +// Registers and returns a global test environment. When a test +// program is run, all global test environments will be set-up in the +// order they were registered. After all tests in the program have +// finished, all global test environments will be torn-down in the +// *reverse* order they were registered. +// +// The UnitTest object takes ownership of the given environment. +// +// We don't protect this under mutex_, as we only support calling it +// from the main thread. +Environment* UnitTest::AddEnvironment(Environment* env) { + if (env == NULL) { + return NULL; + } + + impl_->environments().push_back(env); + return env; +} + +// Adds a TestPartResult to the current TestResult object. All Google Test +// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call +// this to report their results. The user code should use the +// assertion macros instead of calling this directly. +void UnitTest::AddTestPartResult( + TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { + Message msg; + msg << message; + + internal::MutexLock lock(&mutex_); + if (impl_->gtest_trace_stack().size() > 0) { + msg << "\n" << GTEST_NAME_ << " trace:"; + + for (int i = static_cast(impl_->gtest_trace_stack().size()); + i > 0; --i) { + const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; + msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) + << " " << trace.message; + } + } + + if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { + msg << internal::kStackTraceMarker << os_stack_trace; + } + + const TestPartResult result = + TestPartResult(result_type, file_name, line_number, + msg.GetString().c_str()); + impl_->GetTestPartResultReporterForCurrentThread()-> + ReportTestPartResult(result); + + if (result_type != TestPartResult::kSuccess) { + // gtest_break_on_failure takes precedence over + // gtest_throw_on_failure. This allows a user to set the latter + // in the code (perhaps in order to use Google Test assertions + // with another testing framework) and specify the former on the + // command line for debugging. + if (GTEST_FLAG(break_on_failure)) { +#if GTEST_OS_WINDOWS + // Using DebugBreak on Windows allows gtest to still break into a debugger + // when a failure happens and both the --gtest_break_on_failure and + // the --gtest_catch_exceptions flags are specified. + DebugBreak(); +#else + // Dereference NULL through a volatile pointer to prevent the compiler + // from removing. We use this rather than abort() or __builtin_trap() for + // portability: Symbian doesn't implement abort() well, and some debuggers + // don't correctly trap abort(). + *static_cast(NULL) = 1; +#endif // GTEST_OS_WINDOWS + } else if (GTEST_FLAG(throw_on_failure)) { +#if GTEST_HAS_EXCEPTIONS + throw internal::GoogleTestFailureException(result); +#else + // We cannot call abort() as it generates a pop-up in debug mode + // that cannot be suppressed in VC 7.1 or below. + exit(1); +#endif + } + } +} + +// Adds a TestProperty to the current TestResult object when invoked from +// inside a test, to current TestCase's ad_hoc_test_result_ when invoked +// from SetUpTestCase or TearDownTestCase, or to the global property set +// when invoked elsewhere. If the result already contains a property with +// the same key, the value will be updated. +void UnitTest::RecordProperty(const std::string& key, + const std::string& value) { + impl_->RecordProperty(TestProperty(key, value)); +} + +// Runs all tests in this UnitTest object and prints the result. +// Returns 0 if successful, or 1 otherwise. +// +// We don't protect this under mutex_, as we only support calling it +// from the main thread. +int UnitTest::Run() { + const bool in_death_test_child_process = + internal::GTEST_FLAG(internal_run_death_test).length() > 0; + + // Google Test implements this protocol for catching that a test + // program exits before returning control to Google Test: + // + // 1. Upon start, Google Test creates a file whose absolute path + // is specified by the environment variable + // TEST_PREMATURE_EXIT_FILE. + // 2. When Google Test has finished its work, it deletes the file. + // + // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before + // running a Google-Test-based test program and check the existence + // of the file at the end of the test execution to see if it has + // exited prematurely. + + // If we are in the child process of a death test, don't + // create/delete the premature exit file, as doing so is unnecessary + // and will confuse the parent process. Otherwise, create/delete + // the file upon entering/leaving this function. If the program + // somehow exits before this function has a chance to return, the + // premature-exit file will be left undeleted, causing a test runner + // that understands the premature-exit-file protocol to report the + // test as having failed. + const internal::ScopedPrematureExitFile premature_exit_file( + in_death_test_child_process ? + NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); + + // Captures the value of GTEST_FLAG(catch_exceptions). This value will be + // used for the duration of the program. + impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); + +#if GTEST_HAS_SEH + // Either the user wants Google Test to catch exceptions thrown by the + // tests or this is executing in the context of death test child + // process. In either case the user does not want to see pop-up dialogs + // about crashes - they are expected. + if (impl()->catch_exceptions() || in_death_test_child_process) { +# if !GTEST_OS_WINDOWS_MOBILE + // SetErrorMode doesn't exist on CE. + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | + SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); +# endif // !GTEST_OS_WINDOWS_MOBILE + +# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE + // Death test children can be terminated with _abort(). On Windows, + // _abort() can show a dialog with a warning message. This forces the + // abort message to go to stderr instead. + _set_error_mode(_OUT_TO_STDERR); +# endif + +# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE + // In the debug version, Visual Studio pops up a separate dialog + // offering a choice to debug the aborted program. We need to suppress + // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement + // executed. Google Test will notify the user of any unexpected + // failure via stderr. + // + // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. + // Users of prior VC versions shall suffer the agony and pain of + // clicking through the countless debug dialogs. + // TODO(vladl@google.com): find a way to suppress the abort dialog() in the + // debug mode when compiled with VC 7.1 or lower. + if (!GTEST_FLAG(break_on_failure)) + _set_abort_behavior( + 0x0, // Clear the following flags: + _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. +# endif + } +#endif // GTEST_HAS_SEH + + return internal::HandleExceptionsInMethodIfSupported( + impl(), + &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") ? 0 : 1; +} + +// Returns the working directory when the first TEST() or TEST_F() was +// executed. +const char* UnitTest::original_working_dir() const { + return impl_->original_working_dir_.c_str(); +} + +// Returns the TestCase object for the test that's currently running, +// or NULL if no test is running. +const TestCase* UnitTest::current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_case(); +} + +// Returns the TestInfo object for the test that's currently running, +// or NULL if no test is running. +const TestInfo* UnitTest::current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_info(); +} + +// Returns the random seed used at the start of the current test run. +int UnitTest::random_seed() const { return impl_->random_seed(); } + +#if GTEST_HAS_PARAM_TEST +// Returns ParameterizedTestCaseRegistry object used to keep track of +// value-parameterized tests and instantiate and register them. +internal::ParameterizedTestCaseRegistry& + UnitTest::parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_) { + return impl_->parameterized_test_registry(); +} +#endif // GTEST_HAS_PARAM_TEST + +// Creates an empty UnitTest. +UnitTest::UnitTest() { + impl_ = new internal::UnitTestImpl(this); +} + +// Destructor of UnitTest. +UnitTest::~UnitTest() { + delete impl_; +} + +// Pushes a trace defined by SCOPED_TRACE() on to the per-thread +// Google Test trace stack. +void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + impl_->gtest_trace_stack().push_back(trace); +} + +// Pops a trace from the per-thread Google Test trace stack. +void UnitTest::PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + impl_->gtest_trace_stack().pop_back(); +} + +namespace internal { + +UnitTestImpl::UnitTestImpl(UnitTest* parent) + : parent_(parent), +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4355) // Temporarily disables warning 4355 + // (using this in initializer). + default_global_test_part_result_reporter_(this), + default_per_thread_test_part_result_reporter_(this), +# pragma warning(pop) // Restores the warning state again. +#else + default_global_test_part_result_reporter_(this), + default_per_thread_test_part_result_reporter_(this), +#endif // _MSC_VER + global_test_part_result_repoter_( + &default_global_test_part_result_reporter_), + per_thread_test_part_result_reporter_( + &default_per_thread_test_part_result_reporter_), +#if GTEST_HAS_PARAM_TEST + parameterized_test_registry_(), + parameterized_tests_registered_(false), +#endif // GTEST_HAS_PARAM_TEST + last_death_test_case_(-1), + current_test_case_(NULL), + current_test_info_(NULL), + ad_hoc_test_result_(), + os_stack_trace_getter_(NULL), + post_flag_parse_init_performed_(false), + random_seed_(0), // Will be overridden by the flag before first use. + random_(0), // Will be reseeded before first use. + start_timestamp_(0), + elapsed_time_(0), +#if GTEST_HAS_DEATH_TEST + death_test_factory_(new DefaultDeathTestFactory), +#endif + // Will be overridden by the flag before first use. + catch_exceptions_(false) { + listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); +} + +UnitTestImpl::~UnitTestImpl() { + // Deletes every TestCase. + ForEach(test_cases_, internal::Delete); + + // Deletes every Environment. + ForEach(environments_, internal::Delete); + + delete os_stack_trace_getter_; +} + +// Adds a TestProperty to the current TestResult object when invoked in a +// context of a test, to current test case's ad_hoc_test_result when invoke +// from SetUpTestCase/TearDownTestCase, or to the global property set +// otherwise. If the result already contains a property with the same key, +// the value will be updated. +void UnitTestImpl::RecordProperty(const TestProperty& test_property) { + std::string xml_element; + TestResult* test_result; // TestResult appropriate for property recording. + + if (current_test_info_ != NULL) { + xml_element = "testcase"; + test_result = &(current_test_info_->result_); + } else if (current_test_case_ != NULL) { + xml_element = "testsuite"; + test_result = &(current_test_case_->ad_hoc_test_result_); + } else { + xml_element = "testsuites"; + test_result = &ad_hoc_test_result_; + } + test_result->RecordProperty(xml_element, test_property); +} + +#if GTEST_HAS_DEATH_TEST +// Disables event forwarding if the control is currently in a death test +// subprocess. Must not be called before InitGoogleTest. +void UnitTestImpl::SuppressTestEventsIfInSubprocess() { + if (internal_run_death_test_flag_.get() != NULL) + listeners()->SuppressEventForwarding(); +} +#endif // GTEST_HAS_DEATH_TEST + +// Initializes event listeners performing XML output as specified by +// UnitTestOptions. Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureXmlOutput() { + const std::string& output_format = UnitTestOptions::GetOutputFormat(); + if (output_format == "xml") { + listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( + UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); + } else if (output_format != "") { + printf("WARNING: unrecognized output format \"%s\" ignored.\n", + output_format.c_str()); + fflush(stdout); + } +} + +#if GTEST_CAN_STREAM_RESULTS_ +// Initializes event listeners for streaming test results in string form. +// Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureStreamingOutput() { + const std::string& target = GTEST_FLAG(stream_result_to); + if (!target.empty()) { + const size_t pos = target.find(':'); + if (pos != std::string::npos) { + listeners()->Append(new StreamingListener(target.substr(0, pos), + target.substr(pos+1))); + } else { + printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", + target.c_str()); + fflush(stdout); + } + } +} +#endif // GTEST_CAN_STREAM_RESULTS_ + +// Performs initialization dependent upon flag values obtained in +// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to +// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest +// this function is also called from RunAllTests. Since this function can be +// called more than once, it has to be idempotent. +void UnitTestImpl::PostFlagParsingInit() { + // Ensures that this function does not execute more than once. + if (!post_flag_parse_init_performed_) { + post_flag_parse_init_performed_ = true; + +#if GTEST_HAS_DEATH_TEST + InitDeathTestSubprocessControlInfo(); + SuppressTestEventsIfInSubprocess(); +#endif // GTEST_HAS_DEATH_TEST + + // Registers parameterized tests. This makes parameterized tests + // available to the UnitTest reflection API without running + // RUN_ALL_TESTS. + RegisterParameterizedTests(); + + // Configures listeners for XML output. This makes it possible for users + // to shut down the default XML output before invoking RUN_ALL_TESTS. + ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Configures listeners for streaming test results to the specified server. + ConfigureStreamingOutput(); +#endif // GTEST_CAN_STREAM_RESULTS_ + } +} + +// A predicate that checks the name of a TestCase against a known +// value. +// +// This is used for implementation of the UnitTest class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestCaseNameIs is copyable. +class TestCaseNameIs { + public: + // Constructor. + explicit TestCaseNameIs(const std::string& name) + : name_(name) {} + + // Returns true iff the name of test_case matches name_. + bool operator()(const TestCase* test_case) const { + return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; + } + + private: + std::string name_; +}; + +// Finds and returns a TestCase with the given name. If one doesn't +// exist, creates one and returns it. It's the CALLER'S +// RESPONSIBILITY to ensure that this function is only called WHEN THE +// TESTS ARE NOT SHUFFLED. +// +// Arguments: +// +// test_case_name: name of the test case +// type_param: the name of the test case's type parameter, or NULL if +// this is not a typed or a type-parameterized test case. +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, + const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc) { + // Can we find a TestCase with the given name? + const std::vector::const_iterator test_case = + std::find_if(test_cases_.begin(), test_cases_.end(), + TestCaseNameIs(test_case_name)); + + if (test_case != test_cases_.end()) + return *test_case; + + // No. Let's create one. + TestCase* const new_test_case = + new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); + + // Is this a death test case? + if (internal::UnitTestOptions::MatchesFilter(test_case_name, + kDeathTestCaseFilter)) { + // Yes. Inserts the test case after the last death test case + // defined so far. This only works when the test cases haven't + // been shuffled. Otherwise we may end up running a death test + // after a non-death test. + ++last_death_test_case_; + test_cases_.insert(test_cases_.begin() + last_death_test_case_, + new_test_case); + } else { + // No. Appends to the end of the list. + test_cases_.push_back(new_test_case); + } + + test_case_indices_.push_back(static_cast(test_case_indices_.size())); + return new_test_case; +} + +// Helpers for setting up / tearing down the given environment. They +// are for use in the ForEach() function. +static void SetUpEnvironment(Environment* env) { env->SetUp(); } +static void TearDownEnvironment(Environment* env) { env->TearDown(); } + +// Runs all tests in this UnitTest object, prints the result, and +// returns true if all tests are successful. If any exception is +// thrown during a test, the test is considered to be failed, but the +// rest of the tests will still be run. +// +// When parameterized tests are enabled, it expands and registers +// parameterized tests first in RegisterParameterizedTests(). +// All other functions called from RunAllTests() may safely assume that +// parameterized tests are ready to be counted and run. +bool UnitTestImpl::RunAllTests() { + // Makes sure InitGoogleTest() was called. + if (!GTestIsInitialized()) { + printf("%s", + "\nThis test program did NOT call ::testing::InitGoogleTest " + "before calling RUN_ALL_TESTS(). Please fix it.\n"); + return false; + } + + // Do not run any test if the --help flag was specified. + if (g_help_flag) + return true; + + // Repeats the call to the post-flag parsing initialization in case the + // user didn't call InitGoogleTest. + PostFlagParsingInit(); + + // Even if sharding is not on, test runners may want to use the + // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding + // protocol. + internal::WriteToShardStatusFileIfNeeded(); + + // True iff we are in a subprocess for running a thread-safe-style + // death test. + bool in_subprocess_for_death_test = false; + +#if GTEST_HAS_DEATH_TEST + in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); +#endif // GTEST_HAS_DEATH_TEST + + const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, + in_subprocess_for_death_test); + + // Compares the full test names with the filter to decide which + // tests to run. + const bool has_tests_to_run = FilterTests(should_shard + ? HONOR_SHARDING_PROTOCOL + : IGNORE_SHARDING_PROTOCOL) > 0; + + // Lists the tests and exits if the --gtest_list_tests flag was specified. + if (GTEST_FLAG(list_tests)) { + // This must be called *after* FilterTests() has been called. + ListTestsMatchingFilter(); + return true; + } + + random_seed_ = GTEST_FLAG(shuffle) ? + GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; + + // True iff at least one test has failed. + bool failed = false; + + TestEventListener* repeater = listeners()->repeater(); + + start_timestamp_ = GetTimeInMillis(); + repeater->OnTestProgramStart(*parent_); + + // How many times to repeat the tests? We don't want to repeat them + // when we are inside the subprocess of a death test. + const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); + // Repeats forever if the repeat count is negative. + const bool forever = repeat < 0; + for (int i = 0; forever || i != repeat; i++) { + // We want to preserve failures generated by ad-hoc test + // assertions executed before RUN_ALL_TESTS(). + ClearNonAdHocTestResult(); + + const TimeInMillis start = GetTimeInMillis(); + + // Shuffles test cases and tests if requested. + if (has_tests_to_run && GTEST_FLAG(shuffle)) { + random()->Reseed(random_seed_); + // This should be done before calling OnTestIterationStart(), + // such that a test event listener can see the actual test order + // in the event. + ShuffleTests(); + } + + // Tells the unit test event listeners that the tests are about to start. + repeater->OnTestIterationStart(*parent_, i); + + // Runs each test case if there is at least one test to run. + if (has_tests_to_run) { + // Sets up all environments beforehand. + repeater->OnEnvironmentsSetUpStart(*parent_); + ForEach(environments_, SetUpEnvironment); + repeater->OnEnvironmentsSetUpEnd(*parent_); + + // Runs the tests only if there was no fatal failure during global + // set-up. + if (!Test::HasFatalFailure()) { + for (int test_index = 0; test_index < total_test_case_count(); + test_index++) { + GetMutableTestCase(test_index)->Run(); + } + } + + // Tears down all environments in reverse order afterwards. + repeater->OnEnvironmentsTearDownStart(*parent_); + std::for_each(environments_.rbegin(), environments_.rend(), + TearDownEnvironment); + repeater->OnEnvironmentsTearDownEnd(*parent_); + } + + elapsed_time_ = GetTimeInMillis() - start; + + // Tells the unit test event listener that the tests have just finished. + repeater->OnTestIterationEnd(*parent_, i); + + // Gets the result and clears it. + if (!Passed()) { + failed = true; + } + + // Restores the original test order after the iteration. This + // allows the user to quickly repro a failure that happens in the + // N-th iteration without repeating the first (N - 1) iterations. + // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in + // case the user somehow changes the value of the flag somewhere + // (it's always safe to unshuffle the tests). + UnshuffleTests(); + + if (GTEST_FLAG(shuffle)) { + // Picks a new random seed for each iteration. + random_seed_ = GetNextRandomSeed(random_seed_); + } + } + + repeater->OnTestProgramEnd(*parent_); + + return !failed; +} + +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file +// if the variable is present. If a file already exists at this location, this +// function will write over it. If the variable is present, but the file cannot +// be created, prints an error and exits. +void WriteToShardStatusFileIfNeeded() { + const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); + if (test_shard_file != NULL) { + FILE* const file = posix::FOpen(test_shard_file, "w"); + if (file == NULL) { + ColoredPrintf(COLOR_RED, + "Could not write to the test shard status file \"%s\" " + "specified by the %s environment variable.\n", + test_shard_file, kTestShardStatusFile); + fflush(stdout); + exit(EXIT_FAILURE); + } + fclose(file); + } +} + +// Checks whether sharding is enabled by examining the relevant +// environment variable values. If the variables are present, +// but inconsistent (i.e., shard_index >= total_shards), prints +// an error and exits. If in_subprocess_for_death_test, sharding is +// disabled because it must only be applied to the original test +// process. Otherwise, we could filter out death tests we intended to execute. +bool ShouldShard(const char* total_shards_env, + const char* shard_index_env, + bool in_subprocess_for_death_test) { + if (in_subprocess_for_death_test) { + return false; + } + + const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); + const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); + + if (total_shards == -1 && shard_index == -1) { + return false; + } else if (total_shards == -1 && shard_index != -1) { + const Message msg = Message() + << "Invalid environment variables: you have " + << kTestShardIndex << " = " << shard_index + << ", but have left " << kTestTotalShards << " unset.\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } else if (total_shards != -1 && shard_index == -1) { + const Message msg = Message() + << "Invalid environment variables: you have " + << kTestTotalShards << " = " << total_shards + << ", but have left " << kTestShardIndex << " unset.\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } else if (shard_index < 0 || shard_index >= total_shards) { + const Message msg = Message() + << "Invalid environment variables: we require 0 <= " + << kTestShardIndex << " < " << kTestTotalShards + << ", but you have " << kTestShardIndex << "=" << shard_index + << ", " << kTestTotalShards << "=" << total_shards << ".\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } + + return total_shards > 1; +} + +// Parses the environment variable var as an Int32. If it is unset, +// returns default_val. If it is not an Int32, prints an error +// and aborts. +Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { + const char* str_val = posix::GetEnv(var); + if (str_val == NULL) { + return default_val; + } + + Int32 result; + if (!ParseInt32(Message() << "The value of environment variable " << var, + str_val, &result)) { + exit(EXIT_FAILURE); + } + return result; +} + +// Given the total number of shards, the shard index, and the test id, +// returns true iff the test should be run on this shard. The test id is +// some arbitrary but unique non-negative integer assigned to each test +// method. Assumes that 0 <= shard_index < total_shards. +bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { + return (test_id % total_shards) == shard_index; +} + +// Compares the name of each test with the user-specified filter to +// decide whether the test should be run, then records the result in +// each TestCase and TestInfo object. +// If shard_tests == true, further filters tests based on sharding +// variables in the environment - see +// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. +// Returns the number of tests that should run. +int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { + const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? + Int32FromEnvOrDie(kTestTotalShards, -1) : -1; + const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? + Int32FromEnvOrDie(kTestShardIndex, -1) : -1; + + // num_runnable_tests are the number of tests that will + // run across all shards (i.e., match filter and are not disabled). + // num_selected_tests are the number of tests to be run on + // this shard. + int num_runnable_tests = 0; + int num_selected_tests = 0; + for (size_t i = 0; i < test_cases_.size(); i++) { + TestCase* const test_case = test_cases_[i]; + const std::string &test_case_name = test_case->name(); + test_case->set_should_run(false); + + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + TestInfo* const test_info = test_case->test_info_list()[j]; + const std::string test_name(test_info->name()); + // A test is disabled if test case name or test name matches + // kDisableTestFilter. + const bool is_disabled = + internal::UnitTestOptions::MatchesFilter(test_case_name, + kDisableTestFilter) || + internal::UnitTestOptions::MatchesFilter(test_name, + kDisableTestFilter); + test_info->is_disabled_ = is_disabled; + + const bool matches_filter = + internal::UnitTestOptions::FilterMatchesTest(test_case_name, + test_name); + test_info->matches_filter_ = matches_filter; + + const bool is_runnable = + (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && + matches_filter; + + const bool is_selected = is_runnable && + (shard_tests == IGNORE_SHARDING_PROTOCOL || + ShouldRunTestOnShard(total_shards, shard_index, + num_runnable_tests)); + + num_runnable_tests += is_runnable; + num_selected_tests += is_selected; + + test_info->should_run_ = is_selected; + test_case->set_should_run(test_case->should_run() || is_selected); + } + } + return num_selected_tests; +} + +// Prints the given C-string on a single line by replacing all '\n' +// characters with string "\\n". If the output takes more than +// max_length characters, only prints the first max_length characters +// and "...". +static void PrintOnOneLine(const char* str, int max_length) { + if (str != NULL) { + for (int i = 0; *str != '\0'; ++str) { + if (i >= max_length) { + printf("..."); + break; + } + if (*str == '\n') { + printf("\\n"); + i += 2; + } else { + printf("%c", *str); + ++i; + } + } + } +} + +// Prints the names of the tests matching the user-specified filter flag. +void UnitTestImpl::ListTestsMatchingFilter() { + // Print at most this many characters for each type/value parameter. + const int kMaxParamLength = 250; + + for (size_t i = 0; i < test_cases_.size(); i++) { + const TestCase* const test_case = test_cases_[i]; + bool printed_test_case_name = false; + + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + const TestInfo* const test_info = + test_case->test_info_list()[j]; + if (test_info->matches_filter_) { + if (!printed_test_case_name) { + printed_test_case_name = true; + printf("%s.", test_case->name()); + if (test_case->type_param() != NULL) { + printf(" # %s = ", kTypeParamLabel); + // We print the type parameter on a single line to make + // the output easy to parse by a program. + PrintOnOneLine(test_case->type_param(), kMaxParamLength); + } + printf("\n"); + } + printf(" %s", test_info->name()); + if (test_info->value_param() != NULL) { + printf(" # %s = ", kValueParamLabel); + // We print the value parameter on a single line to make the + // output easy to parse by a program. + PrintOnOneLine(test_info->value_param(), kMaxParamLength); + } + printf("\n"); + } + } + } + fflush(stdout); +} + +// Sets the OS stack trace getter. +// +// Does nothing if the input and the current OS stack trace getter are +// the same; otherwise, deletes the old getter and makes the input the +// current getter. +void UnitTestImpl::set_os_stack_trace_getter( + OsStackTraceGetterInterface* getter) { + if (os_stack_trace_getter_ != getter) { + delete os_stack_trace_getter_; + os_stack_trace_getter_ = getter; + } +} + +// Returns the current OS stack trace getter if it is not NULL; +// otherwise, creates an OsStackTraceGetter, makes it the current +// getter, and returns it. +OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { + if (os_stack_trace_getter_ == NULL) { + os_stack_trace_getter_ = new OsStackTraceGetter; + } + + return os_stack_trace_getter_; +} + +// Returns the TestResult for the test that's currently running, or +// the TestResult for the ad hoc test if no test is running. +TestResult* UnitTestImpl::current_test_result() { + return current_test_info_ ? + &(current_test_info_->result_) : &ad_hoc_test_result_; +} + +// Shuffles all test cases, and the tests within each test case, +// making sure that death tests are still run first. +void UnitTestImpl::ShuffleTests() { + // Shuffles the death test cases. + ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); + + // Shuffles the non-death test cases. + ShuffleRange(random(), last_death_test_case_ + 1, + static_cast(test_cases_.size()), &test_case_indices_); + + // Shuffles the tests inside each test case. + for (size_t i = 0; i < test_cases_.size(); i++) { + test_cases_[i]->ShuffleTests(random()); + } +} + +// Restores the test cases and tests to their order before the first shuffle. +void UnitTestImpl::UnshuffleTests() { + for (size_t i = 0; i < test_cases_.size(); i++) { + // Unshuffles the tests in each test case. + test_cases_[i]->UnshuffleTests(); + // Resets the index of each test case. + test_case_indices_[i] = static_cast(i); + } +} + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. +std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, + int skip_count) { + // We pass skip_count + 1 to skip this wrapper function in addition + // to what the user really wants to skip. + return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); +} + +// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to +// suppress unreachable code warnings. +namespace { +class ClassUniqueToAlwaysTrue {}; +} + +bool IsTrue(bool condition) { return condition; } + +bool AlwaysTrue() { +#if GTEST_HAS_EXCEPTIONS + // This condition is always false so AlwaysTrue() never actually throws, + // but it makes the compiler think that it may throw. + if (IsTrue(false)) + throw ClassUniqueToAlwaysTrue(); +#endif // GTEST_HAS_EXCEPTIONS + return true; +} + +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +bool SkipPrefix(const char* prefix, const char** pstr) { + const size_t prefix_len = strlen(prefix); + if (strncmp(*pstr, prefix, prefix_len) == 0) { + *pstr += prefix_len; + return true; + } + return false; +} + +// Parses a string as a command line flag. The string should have +// the format "--flag=value". When def_optional is true, the "=value" +// part can be omitted. +// +// Returns the value of the flag, or NULL if the parsing failed. +const char* ParseFlagValue(const char* str, + const char* flag, + bool def_optional) { + // str and flag must not be NULL. + if (str == NULL || flag == NULL) return NULL; + + // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. + const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; + const size_t flag_len = flag_str.length(); + if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; + + // Skips the flag name. + const char* flag_end = str + flag_len; + + // When def_optional is true, it's OK to not have a "=value" part. + if (def_optional && (flag_end[0] == '\0')) { + return flag_end; + } + + // If def_optional is true and there are more characters after the + // flag name, or if def_optional is false, there must be a '=' after + // the flag name. + if (flag_end[0] != '=') return NULL; + + // Returns the string after "=". + return flag_end + 1; +} + +// Parses a string for a bool flag, in the form of either +// "--flag=value" or "--flag". +// +// In the former case, the value is taken as true as long as it does +// not start with '0', 'f', or 'F'. +// +// In the latter case, the value is taken as true. +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseBoolFlag(const char* str, const char* flag, bool* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, true); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Converts the string value to a bool. + *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); + return true; +} + +// Parses a string for an Int32 flag, in the form of +// "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + return ParseInt32(Message() << "The value of flag --" << flag, + value_str, value); +} + +// Parses a string for a string flag, in the form of +// "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseStringFlag(const char* str, const char* flag, std::string* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + *value = value_str; + return true; +} + +// Determines whether a string has a prefix that Google Test uses for its +// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. +// If Google Test detects that a command line flag has its prefix but is not +// recognized, it will print its help message. Flags starting with +// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test +// internal flags and do not trigger the help message. +static bool HasGoogleTestFlagPrefix(const char* str) { + return (SkipPrefix("--", &str) || + SkipPrefix("-", &str) || + SkipPrefix("/", &str)) && + !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && + (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || + SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); +} + +// Prints a string containing code-encoded text. The following escape +// sequences can be used in the string to control the text color: +// +// @@ prints a single '@' character. +// @R changes the color to red. +// @G changes the color to green. +// @Y changes the color to yellow. +// @D changes to the default terminal text color. +// +// TODO(wan@google.com): Write tests for this once we add stdout +// capturing to Google Test. +static void PrintColorEncoded(const char* str) { + GTestColor color = COLOR_DEFAULT; // The current color. + + // Conceptually, we split the string into segments divided by escape + // sequences. Then we print one segment at a time. At the end of + // each iteration, the str pointer advances to the beginning of the + // next segment. + for (;;) { + const char* p = strchr(str, '@'); + if (p == NULL) { + ColoredPrintf(color, "%s", str); + return; + } + + ColoredPrintf(color, "%s", std::string(str, p).c_str()); + + const char ch = p[1]; + str = p + 2; + if (ch == '@') { + ColoredPrintf(color, "@"); + } else if (ch == 'D') { + color = COLOR_DEFAULT; + } else if (ch == 'R') { + color = COLOR_RED; + } else if (ch == 'G') { + color = COLOR_GREEN; + } else if (ch == 'Y') { + color = COLOR_YELLOW; + } else { + --str; + } + } +} + +static const char kColorEncodedHelpMessage[] = +"This program contains tests written using " GTEST_NAME_ ". You can use the\n" +"following command line flags to control its behavior:\n" +"\n" +"Test Selection:\n" +" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" +" List the names of all tests instead of running them. The name of\n" +" TEST(Foo, Bar) is \"Foo.Bar\".\n" +" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" + "[@G-@YNEGATIVE_PATTERNS]@D\n" +" Run only the tests whose name matches one of the positive patterns but\n" +" none of the negative patterns. '?' matches any single character; '*'\n" +" matches any substring; ':' separates two patterns.\n" +" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" +" Run all disabled tests too.\n" +"\n" +"Test Execution:\n" +" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" +" Run the tests repeatedly; use a negative count to repeat forever.\n" +" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" +" Randomize tests' orders on every iteration.\n" +" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" +" Random number seed to use for shuffling test orders (between 1 and\n" +" 99999, or 0 to use a seed based on the current time).\n" +"\n" +"Test Output:\n" +" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" +" Enable/disable colored output. The default is @Gauto@D.\n" +" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" +" Don't print the elapsed time of each test.\n" +" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" + GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" +" Generate an XML report in the given directory or with the given file\n" +" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" +#if GTEST_CAN_STREAM_RESULTS_ +" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" +" Stream test results to the given server.\n" +#endif // GTEST_CAN_STREAM_RESULTS_ +"\n" +"Assertion Behavior:\n" +#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" +" Set the default death test style.\n" +#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" +" Turn assertion failures into debugger break-points.\n" +" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" +" Turn assertion failures into C++ exceptions.\n" +" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" +" Do not report exceptions as test failures. Instead, allow them\n" +" to crash the program or throw a pop-up (on Windows).\n" +"\n" +"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " + "the corresponding\n" +"environment variable of a flag (all letters in upper-case). For example, to\n" +"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ + "color=no@D or set\n" +"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" +"\n" +"For more information, please read the " GTEST_NAME_ " documentation at\n" +"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" +"(not one in your own code or tests), please report it to\n" +"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. The type parameter CharType can be +// instantiated to either char or wchar_t. +template +void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { + for (int i = 1; i < *argc; i++) { + const std::string arg_string = StreamableToString(argv[i]); + const char* const arg = arg_string.c_str(); + + using internal::ParseBoolFlag; + using internal::ParseInt32Flag; + using internal::ParseStringFlag; + + // Do we see a Google Test flag? + if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, + >EST_FLAG(also_run_disabled_tests)) || + ParseBoolFlag(arg, kBreakOnFailureFlag, + >EST_FLAG(break_on_failure)) || + ParseBoolFlag(arg, kCatchExceptionsFlag, + >EST_FLAG(catch_exceptions)) || + ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || + ParseStringFlag(arg, kDeathTestStyleFlag, + >EST_FLAG(death_test_style)) || + ParseBoolFlag(arg, kDeathTestUseFork, + >EST_FLAG(death_test_use_fork)) || + ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || + ParseStringFlag(arg, kInternalRunDeathTestFlag, + >EST_FLAG(internal_run_death_test)) || + ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || + ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || + ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || + ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || + ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || + ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || + ParseInt32Flag(arg, kStackTraceDepthFlag, + >EST_FLAG(stack_trace_depth)) || + ParseStringFlag(arg, kStreamResultToFlag, + >EST_FLAG(stream_result_to)) || + ParseBoolFlag(arg, kThrowOnFailureFlag, + >EST_FLAG(throw_on_failure)) + ) { + // Yes. Shift the remainder of the argv list left by one. Note + // that argv has (*argc + 1) elements, the last one always being + // NULL. The following loop moves the trailing NULL element as + // well. + for (int j = i; j != *argc; j++) { + argv[j] = argv[j + 1]; + } + + // Decrements the argument count. + (*argc)--; + + // We also need to decrement the iterator as we just removed + // an element. + i--; + } else if (arg_string == "--help" || arg_string == "-h" || + arg_string == "-?" || arg_string == "/?" || + HasGoogleTestFlagPrefix(arg)) { + // Both help flag and unrecognized Google Test flags (excluding + // internal ones) trigger help display. + g_help_flag = true; + } + } + + if (g_help_flag) { + // We print the help here instead of in RUN_ALL_TESTS(), as the + // latter may not be called at all if the user is using Google + // Test with another testing framework. + PrintColorEncoded(kColorEncodedHelpMessage); + } +} + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. +void ParseGoogleTestFlagsOnly(int* argc, char** argv) { + ParseGoogleTestFlagsOnlyImpl(argc, argv); +} +void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { + ParseGoogleTestFlagsOnlyImpl(argc, argv); +} + +// The internal implementation of InitGoogleTest(). +// +// The type parameter CharType can be instantiated to either char or +// wchar_t. +template +void InitGoogleTestImpl(int* argc, CharType** argv) { + g_init_gtest_count++; + + // We don't want to run the initialization code twice. + if (g_init_gtest_count != 1) return; + + if (*argc <= 0) return; + + internal::g_executable_path = internal::StreamableToString(argv[0]); + +#if GTEST_HAS_DEATH_TEST + + g_argvs.clear(); + for (int i = 0; i != *argc; i++) { + g_argvs.push_back(StreamableToString(argv[i])); + } + +#endif // GTEST_HAS_DEATH_TEST + + ParseGoogleTestFlagsOnly(argc, argv); + GetUnitTestImpl()->PostFlagParsingInit(); +} + +} // namespace internal + +// Initializes Google Test. This must be called before calling +// RUN_ALL_TESTS(). In particular, it parses a command line for the +// flags that Google Test recognizes. Whenever a Google Test flag is +// seen, it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Test flag variables are +// updated. +// +// Calling the function for the second time has no user-visible effect. +void InitGoogleTest(int* argc, char** argv) { + internal::InitGoogleTestImpl(argc, argv); +} + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +void InitGoogleTest(int* argc, wchar_t** argv) { + internal::InitGoogleTestImpl(argc, argv); +} + +} // namespace testing +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) +// +// This file implements death tests. + + +#if GTEST_HAS_DEATH_TEST + +# if GTEST_OS_MAC +# include +# endif // GTEST_OS_MAC + +# include +# include +# include + +# if GTEST_OS_LINUX +# include +# endif // GTEST_OS_LINUX + +# include + +# if GTEST_OS_WINDOWS +# include +# else +# include +# include +# endif // GTEST_OS_WINDOWS + +# if GTEST_OS_QNX +# include +# endif // GTEST_OS_QNX + +#endif // GTEST_HAS_DEATH_TEST + + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#undef GTEST_IMPLEMENTATION_ + +namespace testing { + +// Constants. + +// The default death test style. +static const char kDefaultDeathTestStyle[] = "fast"; + +GTEST_DEFINE_string_( + death_test_style, + internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), + "Indicates how to run a death test in a forked child process: " + "\"threadsafe\" (child process re-executes the test binary " + "from the beginning, running only the specific death test) or " + "\"fast\" (child process runs the death test immediately " + "after forking)."); + +GTEST_DEFINE_bool_( + death_test_use_fork, + internal::BoolFromGTestEnv("death_test_use_fork", false), + "Instructs to use fork()/_exit() instead of clone() in death tests. " + "Ignored and always uses fork() on POSIX systems where clone() is not " + "implemented. Useful when running under valgrind or similar tools if " + "those do not support clone(). Valgrind 3.3.1 will just fail if " + "it sees an unsupported combination of clone() flags. " + "It is not recommended to use this flag w/o valgrind though it will " + "work in 99% of the cases. Once valgrind is fixed, this flag will " + "most likely be removed."); + +namespace internal { +GTEST_DEFINE_string_( + internal_run_death_test, "", + "Indicates the file, line number, temporal index of " + "the single death test to run, and a file descriptor to " + "which a success code may be sent, all separated by " + "the '|' characters. This flag is specified if and only if the current " + "process is a sub-process launched for running a thread-safe " + "death test. FOR INTERNAL USE ONLY."); +} // namespace internal + +#if GTEST_HAS_DEATH_TEST + +namespace internal { + +// Valid only for fast death tests. Indicates the code is running in the +// child process of a fast style death test. +static bool g_in_fast_death_test_child = false; + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +bool InDeathTestChild() { +# if GTEST_OS_WINDOWS + + // On Windows, death tests are thread-safe regardless of the value of the + // death_test_style flag. + return !GTEST_FLAG(internal_run_death_test).empty(); + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") + return !GTEST_FLAG(internal_run_death_test).empty(); + else + return g_in_fast_death_test_child; +#endif +} + +} // namespace internal + +// ExitedWithCode constructor. +ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { +} + +// ExitedWithCode function-call operator. +bool ExitedWithCode::operator()(int exit_status) const { +# if GTEST_OS_WINDOWS + + return exit_status == exit_code_; + +# else + + return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; + +# endif // GTEST_OS_WINDOWS +} + +# if !GTEST_OS_WINDOWS +// KilledBySignal constructor. +KilledBySignal::KilledBySignal(int signum) : signum_(signum) { +} + +// KilledBySignal function-call operator. +bool KilledBySignal::operator()(int exit_status) const { + return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; +} +# endif // !GTEST_OS_WINDOWS + +namespace internal { + +// Utilities needed for death tests. + +// Generates a textual description of a given exit code, in the format +// specified by wait(2). +static std::string ExitSummary(int exit_code) { + Message m; + +# if GTEST_OS_WINDOWS + + m << "Exited with exit status " << exit_code; + +# else + + if (WIFEXITED(exit_code)) { + m << "Exited with exit status " << WEXITSTATUS(exit_code); + } else if (WIFSIGNALED(exit_code)) { + m << "Terminated by signal " << WTERMSIG(exit_code); + } +# ifdef WCOREDUMP + if (WCOREDUMP(exit_code)) { + m << " (core dumped)"; + } +# endif +# endif // GTEST_OS_WINDOWS + + return m.GetString(); +} + +// Returns true if exit_status describes a process that was terminated +// by a signal, or exited normally with a nonzero exit code. +bool ExitedUnsuccessfully(int exit_status) { + return !ExitedWithCode(0)(exit_status); +} + +# if !GTEST_OS_WINDOWS +// Generates a textual failure message when a death test finds more than +// one thread running, or cannot determine the number of threads, prior +// to executing the given statement. It is the responsibility of the +// caller not to pass a thread_count of 1. +static std::string DeathTestThreadWarning(size_t thread_count) { + Message msg; + msg << "Death tests use fork(), which is unsafe particularly" + << " in a threaded context. For this test, " << GTEST_NAME_ << " "; + if (thread_count == 0) + msg << "couldn't detect the number of threads."; + else + msg << "detected " << thread_count << " threads."; + return msg.GetString(); +} +# endif // !GTEST_OS_WINDOWS + +// Flag characters for reporting a death test that did not die. +static const char kDeathTestLived = 'L'; +static const char kDeathTestReturned = 'R'; +static const char kDeathTestThrew = 'T'; +static const char kDeathTestInternalError = 'I'; + +// An enumeration describing all of the possible ways that a death test can +// conclude. DIED means that the process died while executing the test +// code; LIVED means that process lived beyond the end of the test code; +// RETURNED means that the test statement attempted to execute a return +// statement, which is not allowed; THREW means that the test statement +// returned control by throwing an exception. IN_PROGRESS means the test +// has not yet concluded. +// TODO(vladl@google.com): Unify names and possibly values for +// AbortReason, DeathTestOutcome, and flag characters above. +enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; + +// Routine for aborting the program which is safe to call from an +// exec-style death test child process, in which case the error +// message is propagated back to the parent process. Otherwise, the +// message is simply printed to stderr. In either case, the program +// then exits with status 1. +void DeathTestAbort(const std::string& message) { + // On a POSIX system, this function may be called from a threadsafe-style + // death test child process, which operates on a very small stack. Use + // the heap for any additional non-minuscule memory requirements. + const InternalRunDeathTestFlag* const flag = + GetUnitTestImpl()->internal_run_death_test_flag(); + if (flag != NULL) { + FILE* parent = posix::FDOpen(flag->write_fd(), "w"); + fputc(kDeathTestInternalError, parent); + fprintf(parent, "%s", message.c_str()); + fflush(parent); + _exit(1); + } else { + fprintf(stderr, "%s", message.c_str()); + fflush(stderr); + posix::Abort(); + } +} + +// A replacement for CHECK that calls DeathTestAbort if the assertion +// fails. +# define GTEST_DEATH_TEST_CHECK_(expression) \ + do { \ + if (!::testing::internal::IsTrue(expression)) { \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression); \ + } \ + } while (::testing::internal::AlwaysFalse()) + +// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for +// evaluating any system call that fulfills two conditions: it must return +// -1 on failure, and set errno to EINTR when it is interrupted and +// should be tried again. The macro expands to a loop that repeatedly +// evaluates the expression as long as it evaluates to -1 and sets +// errno to EINTR. If the expression evaluates to -1 but errno is +// something other than EINTR, DeathTestAbort is called. +# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ + do { \ + int gtest_retval; \ + do { \ + gtest_retval = (expression); \ + } while (gtest_retval == -1 && errno == EINTR); \ + if (gtest_retval == -1) { \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression + " != -1"); \ + } \ + } while (::testing::internal::AlwaysFalse()) + +// Returns the message describing the last system error in errno. +std::string GetLastErrnoDescription() { + return errno == 0 ? "" : posix::StrError(errno); +} + +// This is called from a death test parent process to read a failure +// message from the death test child process and log it with the FATAL +// severity. On Windows, the message is read from a pipe handle. On other +// platforms, it is read from a file descriptor. +static void FailFromInternalError(int fd) { + Message error; + char buffer[256]; + int num_read; + + do { + while ((num_read = posix::Read(fd, buffer, 255)) > 0) { + buffer[num_read] = '\0'; + error << buffer; + } + } while (num_read == -1 && errno == EINTR); + + if (num_read == 0) { + GTEST_LOG_(FATAL) << error.GetString(); + } else { + const int last_error = errno; + GTEST_LOG_(FATAL) << "Error while reading death test internal: " + << GetLastErrnoDescription() << " [" << last_error << "]"; + } +} + +// Death test constructor. Increments the running death test count +// for the current test. +DeathTest::DeathTest() { + TestInfo* const info = GetUnitTestImpl()->current_test_info(); + if (info == NULL) { + DeathTestAbort("Cannot run a death test outside of a TEST or " + "TEST_F construct"); + } +} + +// Creates and returns a death test by dispatching to the current +// death test factory. +bool DeathTest::Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test) { + return GetUnitTestImpl()->death_test_factory()->Create( + statement, regex, file, line, test); +} + +const char* DeathTest::LastMessage() { + return last_death_test_message_.c_str(); +} + +void DeathTest::set_last_death_test_message(const std::string& message) { + last_death_test_message_ = message; +} + +std::string DeathTest::last_death_test_message_; + +// Provides cross platform implementation for some death functionality. +class DeathTestImpl : public DeathTest { + protected: + DeathTestImpl(const char* a_statement, const RE* a_regex) + : statement_(a_statement), + regex_(a_regex), + spawned_(false), + status_(-1), + outcome_(IN_PROGRESS), + read_fd_(-1), + write_fd_(-1) {} + + // read_fd_ is expected to be closed and cleared by a derived class. + ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } + + void Abort(AbortReason reason); + virtual bool Passed(bool status_ok); + + const char* statement() const { return statement_; } + const RE* regex() const { return regex_; } + bool spawned() const { return spawned_; } + void set_spawned(bool is_spawned) { spawned_ = is_spawned; } + int status() const { return status_; } + void set_status(int a_status) { status_ = a_status; } + DeathTestOutcome outcome() const { return outcome_; } + void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } + int read_fd() const { return read_fd_; } + void set_read_fd(int fd) { read_fd_ = fd; } + int write_fd() const { return write_fd_; } + void set_write_fd(int fd) { write_fd_ = fd; } + + // Called in the parent process only. Reads the result code of the death + // test child process via a pipe, interprets it to set the outcome_ + // member, and closes read_fd_. Outputs diagnostics and terminates in + // case of unexpected codes. + void ReadAndInterpretStatusByte(); + + private: + // The textual content of the code this object is testing. This class + // doesn't own this string and should not attempt to delete it. + const char* const statement_; + // The regular expression which test output must match. DeathTestImpl + // doesn't own this object and should not attempt to delete it. + const RE* const regex_; + // True if the death test child process has been successfully spawned. + bool spawned_; + // The exit status of the child process. + int status_; + // How the death test concluded. + DeathTestOutcome outcome_; + // Descriptor to the read end of the pipe to the child process. It is + // always -1 in the child process. The child keeps its write end of the + // pipe in write_fd_. + int read_fd_; + // Descriptor to the child's write end of the pipe to the parent process. + // It is always -1 in the parent process. The parent keeps its end of the + // pipe in read_fd_. + int write_fd_; +}; + +// Called in the parent process only. Reads the result code of the death +// test child process via a pipe, interprets it to set the outcome_ +// member, and closes read_fd_. Outputs diagnostics and terminates in +// case of unexpected codes. +void DeathTestImpl::ReadAndInterpretStatusByte() { + char flag; + int bytes_read; + + // The read() here blocks until data is available (signifying the + // failure of the death test) or until the pipe is closed (signifying + // its success), so it's okay to call this in the parent before + // the child process has exited. + do { + bytes_read = posix::Read(read_fd(), &flag, 1); + } while (bytes_read == -1 && errno == EINTR); + + if (bytes_read == 0) { + set_outcome(DIED); + } else if (bytes_read == 1) { + switch (flag) { + case kDeathTestReturned: + set_outcome(RETURNED); + break; + case kDeathTestThrew: + set_outcome(THREW); + break; + case kDeathTestLived: + set_outcome(LIVED); + break; + case kDeathTestInternalError: + FailFromInternalError(read_fd()); // Does not return. + break; + default: + GTEST_LOG_(FATAL) << "Death test child process reported " + << "unexpected status byte (" + << static_cast(flag) << ")"; + } + } else { + GTEST_LOG_(FATAL) << "Read from death test child process failed: " + << GetLastErrnoDescription(); + } + GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); + set_read_fd(-1); +} + +// Signals that the death test code which should have exited, didn't. +// Should be called only in a death test child process. +// Writes a status byte to the child's status file descriptor, then +// calls _exit(1). +void DeathTestImpl::Abort(AbortReason reason) { + // The parent process considers the death test to be a failure if + // it finds any data in our pipe. So, here we write a single flag byte + // to the pipe, then exit. + const char status_ch = + reason == TEST_DID_NOT_DIE ? kDeathTestLived : + reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; + + GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); + // We are leaking the descriptor here because on some platforms (i.e., + // when built as Windows DLL), destructors of global objects will still + // run after calling _exit(). On such systems, write_fd_ will be + // indirectly closed from the destructor of UnitTestImpl, causing double + // close if it is also closed here. On debug configurations, double close + // may assert. As there are no in-process buffers to flush here, we are + // relying on the OS to close the descriptor after the process terminates + // when the destructors are not run. + _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) +} + +// Returns an indented copy of stderr output for a death test. +// This makes distinguishing death test output lines from regular log lines +// much easier. +static ::std::string FormatDeathTestOutput(const ::std::string& output) { + ::std::string ret; + for (size_t at = 0; ; ) { + const size_t line_end = output.find('\n', at); + ret += "[ DEATH ] "; + if (line_end == ::std::string::npos) { + ret += output.substr(at); + break; + } + ret += output.substr(at, line_end + 1 - at); + at = line_end + 1; + } + return ret; +} + +// Assesses the success or failure of a death test, using both private +// members which have previously been set, and one argument: +// +// Private data members: +// outcome: An enumeration describing how the death test +// concluded: DIED, LIVED, THREW, or RETURNED. The death test +// fails in the latter three cases. +// status: The exit status of the child process. On *nix, it is in the +// in the format specified by wait(2). On Windows, this is the +// value supplied to the ExitProcess() API or a numeric code +// of the exception that terminated the program. +// regex: A regular expression object to be applied to +// the test's captured standard error output; the death test +// fails if it does not match. +// +// Argument: +// status_ok: true if exit_status is acceptable in the context of +// this particular death test, which fails if it is false +// +// Returns true iff all of the above conditions are met. Otherwise, the +// first failing condition, in the order given above, is the one that is +// reported. Also sets the last death test message string. +bool DeathTestImpl::Passed(bool status_ok) { + if (!spawned()) + return false; + + const std::string error_message = GetCapturedStderr(); + + bool success = false; + Message buffer; + + buffer << "Death test: " << statement() << "\n"; + switch (outcome()) { + case LIVED: + buffer << " Result: failed to die.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case THREW: + buffer << " Result: threw an exception.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case RETURNED: + buffer << " Result: illegal return in test statement.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case DIED: + if (status_ok) { + const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); + if (matched) { + success = true; + } else { + buffer << " Result: died but not with expected error.\n" + << " Expected: " << regex()->pattern() << "\n" + << "Actual msg:\n" << FormatDeathTestOutput(error_message); + } + } else { + buffer << " Result: died but not with expected exit code:\n" + << " " << ExitSummary(status()) << "\n" + << "Actual msg:\n" << FormatDeathTestOutput(error_message); + } + break; + case IN_PROGRESS: + default: + GTEST_LOG_(FATAL) + << "DeathTest::Passed somehow called before conclusion of test"; + } + + DeathTest::set_last_death_test_message(buffer.GetString()); + return success; +} + +# if GTEST_OS_WINDOWS +// WindowsDeathTest implements death tests on Windows. Due to the +// specifics of starting new processes on Windows, death tests there are +// always threadsafe, and Google Test considers the +// --gtest_death_test_style=fast setting to be equivalent to +// --gtest_death_test_style=threadsafe there. +// +// A few implementation notes: Like the Linux version, the Windows +// implementation uses pipes for child-to-parent communication. But due to +// the specifics of pipes on Windows, some extra steps are required: +// +// 1. The parent creates a communication pipe and stores handles to both +// ends of it. +// 2. The parent starts the child and provides it with the information +// necessary to acquire the handle to the write end of the pipe. +// 3. The child acquires the write end of the pipe and signals the parent +// using a Windows event. +// 4. Now the parent can release the write end of the pipe on its side. If +// this is done before step 3, the object's reference count goes down to +// 0 and it is destroyed, preventing the child from acquiring it. The +// parent now has to release it, or read operations on the read end of +// the pipe will not return when the child terminates. +// 5. The parent reads child's output through the pipe (outcome code and +// any possible error messages) from the pipe, and its stderr and then +// determines whether to fail the test. +// +// Note: to distinguish Win32 API calls from the local method and function +// calls, the former are explicitly resolved in the global namespace. +// +class WindowsDeathTest : public DeathTestImpl { + public: + WindowsDeathTest(const char* a_statement, + const RE* a_regex, + const char* file, + int line) + : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} + + // All of these virtual functions are inherited from DeathTest. + virtual int Wait(); + virtual TestRole AssumeRole(); + + private: + // The name of the file in which the death test is located. + const char* const file_; + // The line number on which the death test is located. + const int line_; + // Handle to the write end of the pipe to the child process. + AutoHandle write_handle_; + // Child process handle. + AutoHandle child_handle_; + // Event the child process uses to signal the parent that it has + // acquired the handle to the write end of the pipe. After seeing this + // event the parent can release its own handles to make sure its + // ReadFile() calls return when the child terminates. + AutoHandle event_handle_; +}; + +// Waits for the child in a death test to exit, returning its exit +// status, or 0 if no child process exists. As a side effect, sets the +// outcome data member. +int WindowsDeathTest::Wait() { + if (!spawned()) + return 0; + + // Wait until the child either signals that it has acquired the write end + // of the pipe or it dies. + const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; + switch (::WaitForMultipleObjects(2, + wait_handles, + FALSE, // Waits for any of the handles. + INFINITE)) { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + break; + default: + GTEST_DEATH_TEST_CHECK_(false); // Should not get here. + } + + // The child has acquired the write end of the pipe or exited. + // We release the handle on our side and continue. + write_handle_.Reset(); + event_handle_.Reset(); + + ReadAndInterpretStatusByte(); + + // Waits for the child process to exit if it haven't already. This + // returns immediately if the child has already exited, regardless of + // whether previous calls to WaitForMultipleObjects synchronized on this + // handle or not. + GTEST_DEATH_TEST_CHECK_( + WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), + INFINITE)); + DWORD status_code; + GTEST_DEATH_TEST_CHECK_( + ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); + child_handle_.Reset(); + set_status(static_cast(status_code)); + return status(); +} + +// The AssumeRole process for a Windows death test. It creates a child +// process with the same executable as the current process to run the +// death test. The child process is given the --gtest_filter and +// --gtest_internal_run_death_test flags such that it knows to run the +// current death test only. +DeathTest::TestRole WindowsDeathTest::AssumeRole() { + const UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const TestInfo* const info = impl->current_test_info(); + const int death_test_index = info->result()->death_test_count(); + + if (flag != NULL) { + // ParseInternalRunDeathTestFlag() has performed all the necessary + // processing. + set_write_fd(flag->write_fd()); + return EXECUTE_TEST; + } + + // WindowsDeathTest uses an anonymous pipe to communicate results of + // a death test. + SECURITY_ATTRIBUTES handles_are_inheritable = { + sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + HANDLE read_handle, write_handle; + GTEST_DEATH_TEST_CHECK_( + ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, + 0) // Default buffer size. + != FALSE); + set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), + O_RDONLY)); + write_handle_.Reset(write_handle); + event_handle_.Reset(::CreateEvent( + &handles_are_inheritable, + TRUE, // The event will automatically reset to non-signaled state. + FALSE, // The initial state is non-signalled. + NULL)); // The even is unnamed. + GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + + "=" + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(static_cast(::GetCurrentProcessId())) + + // size_t has the same width as pointers on both 32-bit and 64-bit + // Windows platforms. + // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. + "|" + StreamableToString(reinterpret_cast(write_handle)) + + "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); + + char executable_path[_MAX_PATH + 1]; // NOLINT + GTEST_DEATH_TEST_CHECK_( + _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, + executable_path, + _MAX_PATH)); + + std::string command_line = + std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + + internal_flag + "\""; + + DeathTest::set_last_death_test_message(""); + + CaptureStderr(); + // Flush the log buffers since the log streams are shared with the child. + FlushInfoLog(); + + // The child process will share the standard handles with the parent. + STARTUPINFOA startup_info; + memset(&startup_info, 0, sizeof(STARTUPINFO)); + startup_info.dwFlags = STARTF_USESTDHANDLES; + startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); + startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); + startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); + + PROCESS_INFORMATION process_info; + GTEST_DEATH_TEST_CHECK_(::CreateProcessA( + executable_path, + const_cast(command_line.c_str()), + NULL, // Retuned process handle is not inheritable. + NULL, // Retuned thread handle is not inheritable. + TRUE, // Child inherits all inheritable handles (for write_handle_). + 0x0, // Default creation flags. + NULL, // Inherit the parent's environment. + UnitTest::GetInstance()->original_working_dir(), + &startup_info, + &process_info) != FALSE); + child_handle_.Reset(process_info.hProcess); + ::CloseHandle(process_info.hThread); + set_spawned(true); + return OVERSEE_TEST; +} +# else // We are not on Windows. + +// ForkingDeathTest provides implementations for most of the abstract +// methods of the DeathTest interface. Only the AssumeRole method is +// left undefined. +class ForkingDeathTest : public DeathTestImpl { + public: + ForkingDeathTest(const char* statement, const RE* regex); + + // All of these virtual functions are inherited from DeathTest. + virtual int Wait(); + + protected: + void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } + + private: + // PID of child process during death test; 0 in the child process itself. + pid_t child_pid_; +}; + +// Constructs a ForkingDeathTest. +ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) + : DeathTestImpl(a_statement, a_regex), + child_pid_(-1) {} + +// Waits for the child in a death test to exit, returning its exit +// status, or 0 if no child process exists. As a side effect, sets the +// outcome data member. +int ForkingDeathTest::Wait() { + if (!spawned()) + return 0; + + ReadAndInterpretStatusByte(); + + int status_value; + GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); + set_status(status_value); + return status_value; +} + +// A concrete death test class that forks, then immediately runs the test +// in the child process. +class NoExecDeathTest : public ForkingDeathTest { + public: + NoExecDeathTest(const char* a_statement, const RE* a_regex) : + ForkingDeathTest(a_statement, a_regex) { } + virtual TestRole AssumeRole(); +}; + +// The AssumeRole process for a fork-and-run death test. It implements a +// straightforward fork, with a simple pipe to transmit the status byte. +DeathTest::TestRole NoExecDeathTest::AssumeRole() { + const size_t thread_count = GetThreadCount(); + if (thread_count != 1) { + GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); + } + + int pipe_fd[2]; + GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); + + DeathTest::set_last_death_test_message(""); + CaptureStderr(); + // When we fork the process below, the log file buffers are copied, but the + // file descriptors are shared. We flush all log files here so that closing + // the file descriptors in the child process doesn't throw off the + // synchronization between descriptors and buffers in the parent process. + // This is as close to the fork as possible to avoid a race condition in case + // there are multiple threads running before the death test, and another + // thread writes to the log file. + FlushInfoLog(); + + const pid_t child_pid = fork(); + GTEST_DEATH_TEST_CHECK_(child_pid != -1); + set_child_pid(child_pid); + if (child_pid == 0) { + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); + set_write_fd(pipe_fd[1]); + // Redirects all logging to stderr in the child process to prevent + // concurrent writes to the log files. We capture stderr in the parent + // process and append the child process' output to a log. + LogToStderr(); + // Event forwarding to the listeners of event listener API mush be shut + // down in death test subprocesses. + GetUnitTestImpl()->listeners()->SuppressEventForwarding(); + g_in_fast_death_test_child = true; + return EXECUTE_TEST; + } else { + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); + set_read_fd(pipe_fd[0]); + set_spawned(true); + return OVERSEE_TEST; + } +} + +// A concrete death test class that forks and re-executes the main +// program from the beginning, with command-line flags set that cause +// only this specific death test to be run. +class ExecDeathTest : public ForkingDeathTest { + public: + ExecDeathTest(const char* a_statement, const RE* a_regex, + const char* file, int line) : + ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } + virtual TestRole AssumeRole(); + private: + static ::std::vector + GetArgvsForDeathTestChildProcess() { + ::std::vector args = GetInjectableArgvs(); + return args; + } + // The name of the file in which the death test is located. + const char* const file_; + // The line number on which the death test is located. + const int line_; +}; + +// Utility class for accumulating command-line arguments. +class Arguments { + public: + Arguments() { + args_.push_back(NULL); + } + + ~Arguments() { + for (std::vector::iterator i = args_.begin(); i != args_.end(); + ++i) { + free(*i); + } + } + void AddArgument(const char* argument) { + args_.insert(args_.end() - 1, posix::StrDup(argument)); + } + + template + void AddArguments(const ::std::vector& arguments) { + for (typename ::std::vector::const_iterator i = arguments.begin(); + i != arguments.end(); + ++i) { + args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); + } + } + char* const* Argv() { + return &args_[0]; + } + + private: + std::vector args_; +}; + +// A struct that encompasses the arguments to the child process of a +// threadsafe-style death test process. +struct ExecDeathTestArgs { + char* const* argv; // Command-line arguments for the child's call to exec + int close_fd; // File descriptor to close; the read end of a pipe +}; + +# if GTEST_OS_MAC +inline char** GetEnviron() { + // When Google Test is built as a framework on MacOS X, the environ variable + // is unavailable. Apple's documentation (man environ) recommends using + // _NSGetEnviron() instead. + return *_NSGetEnviron(); +} +# else +// Some POSIX platforms expect you to declare environ. extern "C" makes +// it reside in the global namespace. +extern "C" char** environ; +inline char** GetEnviron() { return environ; } +# endif // GTEST_OS_MAC + +# if !GTEST_OS_QNX +// The main function for a threadsafe-style death test child process. +// This function is called in a clone()-ed process and thus must avoid +// any potentially unsafe operations like malloc or libc functions. +static int ExecDeathTestChildMain(void* child_arg) { + ExecDeathTestArgs* const args = static_cast(child_arg); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); + + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + // We can safely call execve() as it's a direct system call. We + // cannot use execvp() as it's a libc function and thus potentially + // unsafe. Since execve() doesn't search the PATH, the user must + // invoke the test program via a valid path that contains at least + // one path separator. + execve(args->argv[0], args->argv, GetEnviron()); + DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + + original_dir + " failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; +} +# endif // !GTEST_OS_QNX + +// Two utility routines that together determine the direction the stack +// grows. +// This could be accomplished more elegantly by a single recursive +// function, but we want to guard against the unlikely possibility of +// a smart compiler optimizing the recursion away. +// +// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining +// StackLowerThanAddress into StackGrowsDown, which then doesn't give +// correct answer. +void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; +void StackLowerThanAddress(const void* ptr, bool* result) { + int dummy; + *result = (&dummy < ptr); +} + +bool StackGrowsDown() { + int dummy; + bool result; + StackLowerThanAddress(&dummy, &result); + return result; +} + +// Spawns a child process with the same executable as the current process in +// a thread-safe manner and instructs it to run the death test. The +// implementation uses fork(2) + exec. On systems where clone(2) is +// available, it is used instead, being slightly more thread-safe. On QNX, +// fork supports only single-threaded environments, so this function uses +// spawn(2) there instead. The function dies with an error message if +// anything goes wrong. +static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { + ExecDeathTestArgs args = { argv, close_fd }; + pid_t child_pid = -1; + +# if GTEST_OS_QNX + // Obtains the current directory and sets it to be closed in the child + // process. + const int cwd_fd = open(".", O_RDONLY); + GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + int fd_flags; + // Set close_fd to be closed after spawn. + GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, + fd_flags | FD_CLOEXEC)); + struct inheritance inherit = {0}; + // spawn is a system call. + child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); + // Restores the current working directory. + GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); + +# else // GTEST_OS_QNX +# if GTEST_OS_LINUX + // When a SIGPROF signal is received while fork() or clone() are executing, + // the process may hang. To avoid this, we ignore SIGPROF here and re-enable + // it after the call to fork()/clone() is complete. + struct sigaction saved_sigprof_action; + struct sigaction ignore_sigprof_action; + memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); + sigemptyset(&ignore_sigprof_action.sa_mask); + ignore_sigprof_action.sa_handler = SIG_IGN; + GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( + SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); +# endif // GTEST_OS_LINUX + +# if GTEST_HAS_CLONE + const bool use_fork = GTEST_FLAG(death_test_use_fork); + + if (!use_fork) { + static const bool stack_grows_down = StackGrowsDown(); + const size_t stack_size = getpagesize(); + // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. + void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); + + // Maximum stack alignment in bytes: For a downward-growing stack, this + // amount is subtracted from size of the stack space to get an address + // that is within the stack space and is aligned on all systems we care + // about. As far as I know there is no ABI with stack alignment greater + // than 64. We assume stack and stack_size already have alignment of + // kMaxStackAlignment. + const size_t kMaxStackAlignment = 64; + void* const stack_top = + static_cast(stack) + + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && + reinterpret_cast(stack_top) % kMaxStackAlignment == 0); + + child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); + + GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); + } +# else + const bool use_fork = true; +# endif // GTEST_HAS_CLONE + + if (use_fork && (child_pid = fork()) == 0) { + ExecDeathTestChildMain(&args); + _exit(0); + } +# endif // GTEST_OS_QNX +# if GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_( + sigaction(SIGPROF, &saved_sigprof_action, NULL)); +# endif // GTEST_OS_LINUX + + GTEST_DEATH_TEST_CHECK_(child_pid != -1); + return child_pid; +} + +// The AssumeRole process for a fork-and-exec death test. It re-executes the +// main program from the beginning, setting the --gtest_filter +// and --gtest_internal_run_death_test flags to cause only the current +// death test to be re-run. +DeathTest::TestRole ExecDeathTest::AssumeRole() { + const UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const TestInfo* const info = impl->current_test_info(); + const int death_test_index = info->result()->death_test_count(); + + if (flag != NULL) { + set_write_fd(flag->write_fd()); + return EXECUTE_TEST; + } + + int pipe_fd[2]; + GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); + // Clear the close-on-exec flag on the write end of the pipe, lest + // it be closed when the child process does an exec: + GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); + + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(pipe_fd[1]); + Arguments args; + args.AddArguments(GetArgvsForDeathTestChildProcess()); + args.AddArgument(filter_flag.c_str()); + args.AddArgument(internal_flag.c_str()); + + DeathTest::set_last_death_test_message(""); + + CaptureStderr(); + // See the comment in NoExecDeathTest::AssumeRole for why the next line + // is necessary. + FlushInfoLog(); + + const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); + set_child_pid(child_pid); + set_read_fd(pipe_fd[0]); + set_spawned(true); + return OVERSEE_TEST; +} + +# endif // !GTEST_OS_WINDOWS + +// Creates a concrete DeathTest-derived class that depends on the +// --gtest_death_test_style flag, and sets the pointer pointed to +// by the "test" argument to its address. If the test should be +// skipped, sets that pointer to NULL. Returns true, unless the +// flag is set to an invalid value. +bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, + const char* file, int line, + DeathTest** test) { + UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const int death_test_index = impl->current_test_info() + ->increment_death_test_count(); + + if (flag != NULL) { + if (death_test_index > flag->index()) { + DeathTest::set_last_death_test_message( + "Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); + return false; + } + + if (!(flag->file() == file && flag->line() == line && + flag->index() == death_test_index)) { + *test = NULL; + return true; + } + } + +# if GTEST_OS_WINDOWS + + if (GTEST_FLAG(death_test_style) == "threadsafe" || + GTEST_FLAG(death_test_style) == "fast") { + *test = new WindowsDeathTest(statement, regex, file, line); + } + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") { + *test = new ExecDeathTest(statement, regex, file, line); + } else if (GTEST_FLAG(death_test_style) == "fast") { + *test = new NoExecDeathTest(statement, regex); + } + +# endif // GTEST_OS_WINDOWS + + else { // NOLINT - this is more readable than unbalanced brackets inside #if. + DeathTest::set_last_death_test_message( + "Unknown death test style \"" + GTEST_FLAG(death_test_style) + + "\" encountered"); + return false; + } + + return true; +} + +// Splits a given string on a given delimiter, populating a given +// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have +// ::std::string, so we can use it here. +static void SplitString(const ::std::string& str, char delimiter, + ::std::vector< ::std::string>* dest) { + ::std::vector< ::std::string> parsed; + ::std::string::size_type pos = 0; + while (::testing::internal::AlwaysTrue()) { + const ::std::string::size_type colon = str.find(delimiter, pos); + if (colon == ::std::string::npos) { + parsed.push_back(str.substr(pos)); + break; + } else { + parsed.push_back(str.substr(pos, colon - pos)); + pos = colon + 1; + } + } + dest->swap(parsed); +} + +# if GTEST_OS_WINDOWS +// Recreates the pipe and event handles from the provided parameters, +// signals the event, and returns a file descriptor wrapped around the pipe +// handle. This function is called in the child process only. +int GetStatusFileDescriptor(unsigned int parent_process_id, + size_t write_handle_as_size_t, + size_t event_handle_as_size_t) { + AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, + FALSE, // Non-inheritable. + parent_process_id)); + if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { + DeathTestAbort("Unable to open parent process " + + StreamableToString(parent_process_id)); + } + + // TODO(vladl@google.com): Replace the following check with a + // compile-time assertion when available. + GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); + + const HANDLE write_handle = + reinterpret_cast(write_handle_as_size_t); + HANDLE dup_write_handle; + + // The newly initialized handle is accessible only in in the parent + // process. To obtain one accessible within the child, we need to use + // DuplicateHandle. + if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, + ::GetCurrentProcess(), &dup_write_handle, + 0x0, // Requested privileges ignored since + // DUPLICATE_SAME_ACCESS is used. + FALSE, // Request non-inheritable handler. + DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the pipe handle " + + StreamableToString(write_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); + } + + const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); + HANDLE dup_event_handle; + + if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, + ::GetCurrentProcess(), &dup_event_handle, + 0x0, + FALSE, + DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the event handle " + + StreamableToString(event_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); + } + + const int write_fd = + ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); + if (write_fd == -1) { + DeathTestAbort("Unable to convert pipe handle " + + StreamableToString(write_handle_as_size_t) + + " to a file descriptor"); + } + + // Signals the parent that the write end of the pipe has been acquired + // so the parent can release its own write end. + ::SetEvent(dup_event_handle); + + return write_fd; +} +# endif // GTEST_OS_WINDOWS + +// Returns a newly created InternalRunDeathTestFlag object with fields +// initialized from the GTEST_FLAG(internal_run_death_test) flag if +// the flag is specified; otherwise returns NULL. +InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { + if (GTEST_FLAG(internal_run_death_test) == "") return NULL; + + // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we + // can use it here. + int line = -1; + int index = -1; + ::std::vector< ::std::string> fields; + SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); + int write_fd = -1; + +# if GTEST_OS_WINDOWS + + unsigned int parent_process_id = 0; + size_t write_handle_as_size_t = 0; + size_t event_handle_as_size_t = 0; + + if (fields.size() != 6 + || !ParseNaturalNumber(fields[1], &line) + || !ParseNaturalNumber(fields[2], &index) + || !ParseNaturalNumber(fields[3], &parent_process_id) + || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) + || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); + } + write_fd = GetStatusFileDescriptor(parent_process_id, + write_handle_as_size_t, + event_handle_as_size_t); +# else + + if (fields.size() != 4 + || !ParseNaturalNumber(fields[1], &line) + || !ParseNaturalNumber(fields[2], &index) + || !ParseNaturalNumber(fields[3], &write_fd)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); + } + +# endif // GTEST_OS_WINDOWS + + return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); +} + +} // namespace internal + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace testing +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: keith.ray@gmail.com (Keith Ray) + + +#include + +#if GTEST_OS_WINDOWS_MOBILE +# include +#elif GTEST_OS_WINDOWS +# include +# include +#elif GTEST_OS_SYMBIAN +// Symbian OpenC has PATH_MAX in sys/syslimits.h +# include +#else +# include +# include // Some Linux distributions define PATH_MAX here. +#endif // GTEST_OS_WINDOWS_MOBILE + +#if GTEST_OS_WINDOWS +# define GTEST_PATH_MAX_ _MAX_PATH +#elif defined(PATH_MAX) +# define GTEST_PATH_MAX_ PATH_MAX +#elif defined(_XOPEN_PATH_MAX) +# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX +#else +# define GTEST_PATH_MAX_ _POSIX_PATH_MAX +#endif // GTEST_OS_WINDOWS + + +namespace testing { +namespace internal { + +#if GTEST_OS_WINDOWS +// On Windows, '\\' is the standard path separator, but many tools and the +// Windows API also accept '/' as an alternate path separator. Unless otherwise +// noted, a file path can contain either kind of path separators, or a mixture +// of them. +const char kPathSeparator = '\\'; +const char kAlternatePathSeparator = '/'; +const char kPathSeparatorString[] = "\\"; +const char kAlternatePathSeparatorString[] = "/"; +# if GTEST_OS_WINDOWS_MOBILE +// Windows CE doesn't have a current directory. You should not use +// the current directory in tests on Windows CE, but this at least +// provides a reasonable fallback. +const char kCurrentDirectoryString[] = "\\"; +// Windows CE doesn't define INVALID_FILE_ATTRIBUTES +const DWORD kInvalidFileAttributes = 0xffffffff; +# else +const char kCurrentDirectoryString[] = ".\\"; +# endif // GTEST_OS_WINDOWS_MOBILE +#else +const char kPathSeparator = '/'; +//const char kPathSeparatorString[] = "/"; +const char kCurrentDirectoryString[] = "./"; +#endif // GTEST_OS_WINDOWS + +// Returns whether the given character is a valid path separator. +static bool IsPathSeparator(char c) { +#if GTEST_HAS_ALT_PATH_SEP_ + return (c == kPathSeparator) || (c == kAlternatePathSeparator); +#else + return c == kPathSeparator; +#endif +} + +// Returns the current working directory, or "" if unsuccessful. +FilePath FilePath::GetCurrentDir() { +#if GTEST_OS_WINDOWS_MOBILE + // Windows CE doesn't have a current directory, so we just return + // something reasonable. + return FilePath(kCurrentDirectoryString); +#elif GTEST_OS_WINDOWS + char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); +#else + char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); +#endif // GTEST_OS_WINDOWS_MOBILE +} + +// Returns a copy of the FilePath with the case-insensitive extension removed. +// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns +// FilePath("dir/file"). If a case-insensitive extension is not +// found, returns a copy of the original FilePath. +FilePath FilePath::RemoveExtension(const char* extension) const { + const std::string dot_extension = std::string(".") + extension; + if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { + return FilePath(pathname_.substr( + 0, pathname_.length() - dot_extension.length())); + } + return *this; +} + +// Returns a pointer to the last occurence of a valid path separator in +// the FilePath. On Windows, for example, both '/' and '\' are valid path +// separators. Returns NULL if no path separator was found. +const char* FilePath::FindLastPathSeparator() const { + const char* const last_sep = strrchr(c_str(), kPathSeparator); +#if GTEST_HAS_ALT_PATH_SEP_ + const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); + // Comparing two pointers of which only one is NULL is undefined. + if (last_alt_sep != NULL && + (last_sep == NULL || last_alt_sep > last_sep)) { + return last_alt_sep; + } +#endif + return last_sep; +} + +// Returns a copy of the FilePath with the directory part removed. +// Example: FilePath("path/to/file").RemoveDirectoryName() returns +// FilePath("file"). If there is no directory part ("just_a_file"), it returns +// the FilePath unmodified. If there is no file part ("just_a_dir/") it +// returns an empty FilePath (""). +// On Windows platform, '\' is the path separator, otherwise it is '/'. +FilePath FilePath::RemoveDirectoryName() const { + const char* const last_sep = FindLastPathSeparator(); + return last_sep ? FilePath(last_sep + 1) : *this; +} + +// RemoveFileName returns the directory path with the filename removed. +// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". +// If the FilePath is "a_file" or "/a_file", RemoveFileName returns +// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does +// not have a file, like "just/a/dir/", it returns the FilePath unmodified. +// On Windows platform, '\' is the path separator, otherwise it is '/'. +FilePath FilePath::RemoveFileName() const { + const char* const last_sep = FindLastPathSeparator(); + std::string dir; + if (last_sep) { + dir = std::string(c_str(), last_sep + 1 - c_str()); + } else { + dir = kCurrentDirectoryString; + } + return FilePath(dir); +} + +// Helper functions for naming files in a directory for xml output. + +// Given directory = "dir", base_name = "test", number = 0, +// extension = "xml", returns "dir/test.xml". If number is greater +// than zero (e.g., 12), returns "dir/test_12.xml". +// On Windows platform, uses \ as the separator rather than /. +FilePath FilePath::MakeFileName(const FilePath& directory, + const FilePath& base_name, + int number, + const char* extension) { + std::string file; + if (number == 0) { + file = base_name.string() + "." + extension; + } else { + file = base_name.string() + "_" + StreamableToString(number) + + "." + extension; + } + return ConcatPaths(directory, FilePath(file)); +} + +// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". +// On Windows, uses \ as the separator rather than /. +FilePath FilePath::ConcatPaths(const FilePath& directory, + const FilePath& relative_path) { + if (directory.IsEmpty()) + return relative_path; + const FilePath dir(directory.RemoveTrailingPathSeparator()); + return FilePath(dir.string() + kPathSeparator + relative_path.string()); +} + +// Returns true if pathname describes something findable in the file-system, +// either a file, directory, or whatever. +bool FilePath::FileOrDirectoryExists() const { +#if GTEST_OS_WINDOWS_MOBILE + LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); + const DWORD attributes = GetFileAttributes(unicode); + delete [] unicode; + return attributes != kInvalidFileAttributes; +#else + posix::StatStruct file_stat; + return posix::Stat(pathname_.c_str(), &file_stat) == 0; +#endif // GTEST_OS_WINDOWS_MOBILE +} + +// Returns true if pathname describes a directory in the file-system +// that exists. +bool FilePath::DirectoryExists() const { + bool result = false; +#if GTEST_OS_WINDOWS + // Don't strip off trailing separator if path is a root directory on + // Windows (like "C:\\"). + const FilePath& path(IsRootDirectory() ? *this : + RemoveTrailingPathSeparator()); +#else + const FilePath& path(*this); +#endif + +#if GTEST_OS_WINDOWS_MOBILE + LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); + const DWORD attributes = GetFileAttributes(unicode); + delete [] unicode; + if ((attributes != kInvalidFileAttributes) && + (attributes & FILE_ATTRIBUTE_DIRECTORY)) { + result = true; + } +#else + posix::StatStruct file_stat; + result = posix::Stat(path.c_str(), &file_stat) == 0 && + posix::IsDir(file_stat); +#endif // GTEST_OS_WINDOWS_MOBILE + + return result; +} + +// Returns true if pathname describes a root directory. (Windows has one +// root directory per disk drive.) +bool FilePath::IsRootDirectory() const { +#if GTEST_OS_WINDOWS + // TODO(wan@google.com): on Windows a network share like + // \\server\share can be a root directory, although it cannot be the + // current directory. Handle this properly. + return pathname_.length() == 3 && IsAbsolutePath(); +#else + return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); +#endif +} + +// Returns true if pathname describes an absolute path. +bool FilePath::IsAbsolutePath() const { + const char* const name = pathname_.c_str(); +#if GTEST_OS_WINDOWS + return pathname_.length() >= 3 && + ((name[0] >= 'a' && name[0] <= 'z') || + (name[0] >= 'A' && name[0] <= 'Z')) && + name[1] == ':' && + IsPathSeparator(name[2]); +#else + return IsPathSeparator(name[0]); +#endif +} + +// Returns a pathname for a file that does not currently exist. The pathname +// will be directory/base_name.extension or +// directory/base_name_.extension if directory/base_name.extension +// already exists. The number will be incremented until a pathname is found +// that does not already exist. +// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. +// There could be a race condition if two or more processes are calling this +// function at the same time -- they could both pick the same filename. +FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, + const FilePath& base_name, + const char* extension) { + FilePath full_pathname; + int number = 0; + do { + full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); + } while (full_pathname.FileOrDirectoryExists()); + return full_pathname; +} + +// Returns true if FilePath ends with a path separator, which indicates that +// it is intended to represent a directory. Returns false otherwise. +// This does NOT check that a directory (or file) actually exists. +bool FilePath::IsDirectory() const { + return !pathname_.empty() && + IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); +} + +// Create directories so that path exists. Returns true if successful or if +// the directories already exist; returns false if unable to create directories +// for any reason. +bool FilePath::CreateDirectoriesRecursively() const { + if (!this->IsDirectory()) { + return false; + } + + if (pathname_.length() == 0 || this->DirectoryExists()) { + return true; + } + + const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); + return parent.CreateDirectoriesRecursively() && this->CreateFolder(); +} + +// Create the directory so that path exists. Returns true if successful or +// if the directory already exists; returns false if unable to create the +// directory for any reason, including if the parent directory does not +// exist. Not named "CreateDirectory" because that's a macro on Windows. +bool FilePath::CreateFolder() const { +#if GTEST_OS_WINDOWS_MOBILE + FilePath removed_sep(this->RemoveTrailingPathSeparator()); + LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); + int result = CreateDirectory(unicode, NULL) ? 0 : -1; + delete [] unicode; +#elif GTEST_OS_WINDOWS + int result = _mkdir(pathname_.c_str()); +#else + int result = mkdir(pathname_.c_str(), 0777); +#endif // GTEST_OS_WINDOWS_MOBILE + + if (result == -1) { + return this->DirectoryExists(); // An error is OK if the directory exists. + } + return true; // No error. +} + +// If input name has a trailing separator character, remove it and return the +// name, otherwise return the name string unmodified. +// On Windows platform, uses \ as the separator, other platforms use /. +FilePath FilePath::RemoveTrailingPathSeparator() const { + return IsDirectory() + ? FilePath(pathname_.substr(0, pathname_.length() - 1)) + : *this; +} + +// Removes any redundant separators that might be in the pathname. +// For example, "bar///foo" becomes "bar/foo". Does not eliminate other +// redundancies that might be in a pathname involving "." or "..". +// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). +void FilePath::Normalize() { + if (pathname_.c_str() == NULL) { + pathname_ = ""; + return; + } + const char* src = pathname_.c_str(); + char* const dest = new char[pathname_.length() + 1]; + char* dest_ptr = dest; + memset(dest_ptr, 0, pathname_.length() + 1); + + while (*src != '\0') { + *dest_ptr = *src; + if (!IsPathSeparator(*src)) { + src++; + } else { +#if GTEST_HAS_ALT_PATH_SEP_ + if (*dest_ptr == kAlternatePathSeparator) { + *dest_ptr = kPathSeparator; + } +#endif + while (IsPathSeparator(*src)) + src++; + } + dest_ptr++; + } + *dest_ptr = '\0'; + pathname_ = dest; + delete[] dest; +} + +} // namespace internal +} // namespace testing +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + + +#include +#include +#include +#include + +#if GTEST_OS_WINDOWS_MOBILE +# include // For TerminateProcess() +#elif GTEST_OS_WINDOWS +# include +# include +#else +# include +#endif // GTEST_OS_WINDOWS_MOBILE + +#if GTEST_OS_MAC +# include +# include +# include +#endif // GTEST_OS_MAC + +#if GTEST_OS_QNX +# include +# include +#endif // GTEST_OS_QNX + + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#undef GTEST_IMPLEMENTATION_ + +namespace testing { +namespace internal { + +#if defined(_MSC_VER) || defined(__BORLANDC__) +// MSVC and C++Builder do not provide a definition of STDERR_FILENO. +const int kStdOutFileno = 1; +const int kStdErrFileno = 2; +#else +const int kStdOutFileno = STDOUT_FILENO; +const int kStdErrFileno = STDERR_FILENO; +#endif // _MSC_VER + +#if GTEST_OS_MAC + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +size_t GetThreadCount() { + const task_t task = mach_task_self(); + mach_msg_type_number_t thread_count; + thread_act_array_t thread_list; + const kern_return_t status = task_threads(task, &thread_list, &thread_count); + if (status == KERN_SUCCESS) { + // task_threads allocates resources in thread_list and we need to free them + // to avoid leaks. + vm_deallocate(task, + reinterpret_cast(thread_list), + sizeof(thread_t) * thread_count); + return static_cast(thread_count); + } else { + return 0; + } +} + +#elif GTEST_OS_QNX + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +size_t GetThreadCount() { + const int fd = open("/proc/self/as", O_RDONLY); + if (fd < 0) { + return 0; + } + procfs_info process_info; + const int status = + devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); + close(fd); + if (status == EOK) { + return static_cast(process_info.num_threads); + } else { + return 0; + } +} + +#else + +size_t GetThreadCount() { + // There's no portable way to detect the number of threads, so we just + // return 0 to indicate that we cannot detect it. + return 0; +} + +#endif // GTEST_OS_MAC + +#if GTEST_USES_POSIX_RE + +// Implements RE. Currently only needed for death tests. + +RE::~RE() { + if (is_valid_) { + // regfree'ing an invalid regex might crash because the content + // of the regex is undefined. Since the regex's are essentially + // the same, one cannot be valid (or invalid) without the other + // being so too. + regfree(&partial_regex_); + regfree(&full_regex_); + } + free(const_cast(pattern_)); +} + +// Returns true iff regular expression re matches the entire str. +bool RE::FullMatch(const char* str, const RE& re) { + if (!re.is_valid_) return false; + + regmatch_t match; + return regexec(&re.full_regex_, str, 1, &match, 0) == 0; +} + +// Returns true iff regular expression re matches a substring of str +// (including str itself). +bool RE::PartialMatch(const char* str, const RE& re) { + if (!re.is_valid_) return false; + + regmatch_t match; + return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; +} + +// Initializes an RE from its string representation. +void RE::Init(const char* regex) { + pattern_ = posix::StrDup(regex); + + // Reserves enough bytes to hold the regular expression used for a + // full match. + const size_t full_regex_len = strlen(regex) + 10; + char* const full_pattern = new char[full_regex_len]; + + snprintf(full_pattern, full_regex_len, "^(%s)$", regex); + is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; + // We want to call regcomp(&partial_regex_, ...) even if the + // previous expression returns false. Otherwise partial_regex_ may + // not be properly initialized can may cause trouble when it's + // freed. + // + // Some implementation of POSIX regex (e.g. on at least some + // versions of Cygwin) doesn't accept the empty string as a valid + // regex. We change it to an equivalent form "()" to be safe. + if (is_valid_) { + const char* const partial_regex = (*regex == '\0') ? "()" : regex; + is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; + } + EXPECT_TRUE(is_valid_) + << "Regular expression \"" << regex + << "\" is not a valid POSIX Extended regular expression."; + + delete[] full_pattern; +} + +#elif GTEST_USES_SIMPLE_RE + +// Returns true iff ch appears anywhere in str (excluding the +// terminating '\0' character). +bool IsInSet(char ch, const char* str) { + return ch != '\0' && strchr(str, ch) != NULL; +} + +// Returns true iff ch belongs to the given classification. Unlike +// similar functions in , these aren't affected by the +// current locale. +bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } +bool IsAsciiPunct(char ch) { + return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); +} +bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } +bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } +bool IsAsciiWordChar(char ch) { + return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || + ('0' <= ch && ch <= '9') || ch == '_'; +} + +// Returns true iff "\\c" is a supported escape sequence. +bool IsValidEscape(char c) { + return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); +} + +// Returns true iff the given atom (specified by escaped and pattern) +// matches ch. The result is undefined if the atom is invalid. +bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { + if (escaped) { // "\\p" where p is pattern_char. + switch (pattern_char) { + case 'd': return IsAsciiDigit(ch); + case 'D': return !IsAsciiDigit(ch); + case 'f': return ch == '\f'; + case 'n': return ch == '\n'; + case 'r': return ch == '\r'; + case 's': return IsAsciiWhiteSpace(ch); + case 'S': return !IsAsciiWhiteSpace(ch); + case 't': return ch == '\t'; + case 'v': return ch == '\v'; + case 'w': return IsAsciiWordChar(ch); + case 'W': return !IsAsciiWordChar(ch); + } + return IsAsciiPunct(pattern_char) && pattern_char == ch; + } + + return (pattern_char == '.' && ch != '\n') || pattern_char == ch; +} + +// Helper function used by ValidateRegex() to format error messages. +std::string FormatRegexSyntaxError(const char* regex, int index) { + return (Message() << "Syntax error at index " << index + << " in simple regular expression \"" << regex << "\": ").GetString(); +} + +// Generates non-fatal failures and returns false if regex is invalid; +// otherwise returns true. +bool ValidateRegex(const char* regex) { + if (regex == NULL) { + // TODO(wan@google.com): fix the source file location in the + // assertion failures to match where the regex is used in user + // code. + ADD_FAILURE() << "NULL is not a valid simple regular expression."; + return false; + } + + bool is_valid = true; + + // True iff ?, *, or + can follow the previous atom. + bool prev_repeatable = false; + for (int i = 0; regex[i]; i++) { + if (regex[i] == '\\') { // An escape sequence + i++; + if (regex[i] == '\0') { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) + << "'\\' cannot appear at the end."; + return false; + } + + if (!IsValidEscape(regex[i])) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) + << "invalid escape sequence \"\\" << regex[i] << "\"."; + is_valid = false; + } + prev_repeatable = true; + } else { // Not an escape sequence. + const char ch = regex[i]; + + if (ch == '^' && i > 0) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'^' can only appear at the beginning."; + is_valid = false; + } else if (ch == '$' && regex[i + 1] != '\0') { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'$' can only appear at the end."; + is_valid = false; + } else if (IsInSet(ch, "()[]{}|")) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'" << ch << "' is unsupported."; + is_valid = false; + } else if (IsRepeat(ch) && !prev_repeatable) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'" << ch << "' can only follow a repeatable token."; + is_valid = false; + } + + prev_repeatable = !IsInSet(ch, "^$?*+"); + } + } + + return is_valid; +} + +// Matches a repeated regex atom followed by a valid simple regular +// expression. The regex atom is defined as c if escaped is false, +// or \c otherwise. repeat is the repetition meta character (?, *, +// or +). The behavior is undefined if str contains too many +// characters to be indexable by size_t, in which case the test will +// probably time out anyway. We are fine with this limitation as +// std::string has it too. +bool MatchRepetitionAndRegexAtHead( + bool escaped, char c, char repeat, const char* regex, + const char* str) { + const size_t min_count = (repeat == '+') ? 1 : 0; + const size_t max_count = (repeat == '?') ? 1 : + static_cast(-1) - 1; + // We cannot call numeric_limits::max() as it conflicts with the + // max() macro on Windows. + + for (size_t i = 0; i <= max_count; ++i) { + // We know that the atom matches each of the first i characters in str. + if (i >= min_count && MatchRegexAtHead(regex, str + i)) { + // We have enough matches at the head, and the tail matches too. + // Since we only care about *whether* the pattern matches str + // (as opposed to *how* it matches), there is no need to find a + // greedy match. + return true; + } + if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) + return false; + } + return false; +} + +// Returns true iff regex matches a prefix of str. regex must be a +// valid simple regular expression and not start with "^", or the +// result is undefined. +bool MatchRegexAtHead(const char* regex, const char* str) { + if (*regex == '\0') // An empty regex matches a prefix of anything. + return true; + + // "$" only matches the end of a string. Note that regex being + // valid guarantees that there's nothing after "$" in it. + if (*regex == '$') + return *str == '\0'; + + // Is the first thing in regex an escape sequence? + const bool escaped = *regex == '\\'; + if (escaped) + ++regex; + if (IsRepeat(regex[1])) { + // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so + // here's an indirect recursion. It terminates as the regex gets + // shorter in each recursion. + return MatchRepetitionAndRegexAtHead( + escaped, regex[0], regex[1], regex + 2, str); + } else { + // regex isn't empty, isn't "$", and doesn't start with a + // repetition. We match the first atom of regex with the first + // character of str and recurse. + return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && + MatchRegexAtHead(regex + 1, str + 1); + } +} + +// Returns true iff regex matches any substring of str. regex must be +// a valid simple regular expression, or the result is undefined. +// +// The algorithm is recursive, but the recursion depth doesn't exceed +// the regex length, so we won't need to worry about running out of +// stack space normally. In rare cases the time complexity can be +// exponential with respect to the regex length + the string length, +// but usually it's must faster (often close to linear). +bool MatchRegexAnywhere(const char* regex, const char* str) { + if (regex == NULL || str == NULL) + return false; + + if (*regex == '^') + return MatchRegexAtHead(regex + 1, str); + + // A successful match can be anywhere in str. + do { + if (MatchRegexAtHead(regex, str)) + return true; + } while (*str++ != '\0'); + return false; +} + +// Implements the RE class. + +RE::~RE() { + free(const_cast(pattern_)); + free(const_cast(full_pattern_)); +} + +// Returns true iff regular expression re matches the entire str. +bool RE::FullMatch(const char* str, const RE& re) { + return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); +} + +// Returns true iff regular expression re matches a substring of str +// (including str itself). +bool RE::PartialMatch(const char* str, const RE& re) { + return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); +} + +// Initializes an RE from its string representation. +void RE::Init(const char* regex) { + pattern_ = full_pattern_ = NULL; + if (regex != NULL) { + pattern_ = posix::StrDup(regex); + } + + is_valid_ = ValidateRegex(regex); + if (!is_valid_) { + // No need to calculate the full pattern when the regex is invalid. + return; + } + + const size_t len = strlen(regex); + // Reserves enough bytes to hold the regular expression used for a + // full match: we need space to prepend a '^', append a '$', and + // terminate the string with '\0'. + char* buffer = static_cast(malloc(len + 3)); + full_pattern_ = buffer; + + if (*regex != '^') + *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. + + // We don't use snprintf or strncpy, as they trigger a warning when + // compiled with VC++ 8.0. + memcpy(buffer, regex, len); + buffer += len; + + if (len == 0 || regex[len - 1] != '$') + *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. + + *buffer = '\0'; +} + +#endif // GTEST_USES_POSIX_RE + +const char kUnknownFile[] = "unknown file"; + +// Formats a source file path and a line number as they would appear +// in an error message from the compiler used to compile this code. +GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { + const std::string file_name(file == NULL ? kUnknownFile : file); + + if (line < 0) { + return file_name + ":"; + } +#ifdef _MSC_VER + return file_name + "(" + StreamableToString(line) + "):"; +#else + return file_name + ":" + StreamableToString(line) + ":"; +#endif // _MSC_VER +} + +// Formats a file location for compiler-independent XML output. +// Although this function is not platform dependent, we put it next to +// FormatFileLocation in order to contrast the two functions. +// Note that FormatCompilerIndependentFileLocation() does NOT append colon +// to the file location it produces, unlike FormatFileLocation(). +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( + const char* file, int line) { + const std::string file_name(file == NULL ? kUnknownFile : file); + + if (line < 0) + return file_name; + else + return file_name + ":" + StreamableToString(line); +} + + +GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) + : severity_(severity) { + const char* const marker = + severity == GTEST_INFO ? "[ INFO ]" : + severity == GTEST_WARNING ? "[WARNING]" : + severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; + GetStream() << ::std::endl << marker << " " + << FormatFileLocation(file, line).c_str() << ": "; +} + +// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. +GTestLog::~GTestLog() { + GetStream() << ::std::endl; + if (severity_ == GTEST_FATAL) { + fflush(stderr); + posix::Abort(); + } +} +// Disable Microsoft deprecation warnings for POSIX functions called from +// this class (creat, dup, dup2, and close) +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) +#endif // _MSC_VER + +#if GTEST_HAS_STREAM_REDIRECTION + +// Object that captures an output stream (stdout/stderr). +class CapturedStream { + public: + // The ctor redirects the stream to a temporary file. + explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { +# if GTEST_OS_WINDOWS + char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT + char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT + + ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); + const UINT success = ::GetTempFileNameA(temp_dir_path, + "gtest_redir", + 0, // Generate unique file name. + temp_file_path); + GTEST_CHECK_(success != 0) + << "Unable to create a temporary file in " << temp_dir_path; + const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); + GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " + << temp_file_path; + filename_ = temp_file_path; +# else + // There's no guarantee that a test has write access to the current + // directory, so we create the temporary file in the /tmp directory + // instead. We use /tmp on most systems, and /sdcard on Android. + // That's because Android doesn't have /tmp. +# if GTEST_OS_LINUX_ANDROID + // Note: Android applications are expected to call the framework's + // Context.getExternalStorageDirectory() method through JNI to get + // the location of the world-writable SD Card directory. However, + // this requires a Context handle, which cannot be retrieved + // globally from native code. Doing so also precludes running the + // code as part of a regular standalone executable, which doesn't + // run in a Dalvik process (e.g. when running it through 'adb shell'). + // + // The location /sdcard is directly accessible from native code + // and is the only location (unofficially) supported by the Android + // team. It's generally a symlink to the real SD Card mount point + // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or + // other OEM-customized locations. Never rely on these, and always + // use /sdcard. + char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; +# else + char name_template[] = "/tmp/captured_stream.XXXXXX"; +# endif // GTEST_OS_LINUX_ANDROID + const int captured_fd = mkstemp(name_template); + filename_ = name_template; +# endif // GTEST_OS_WINDOWS + fflush(NULL); + dup2(captured_fd, fd_); + close(captured_fd); + } + + ~CapturedStream() { + remove(filename_.c_str()); + } + + std::string GetCapturedString() { + if (uncaptured_fd_ != -1) { + // Restores the original stream. + fflush(NULL); + dup2(uncaptured_fd_, fd_); + close(uncaptured_fd_); + uncaptured_fd_ = -1; + } + + FILE* const file = posix::FOpen(filename_.c_str(), "r"); + const std::string content = ReadEntireFile(file); + posix::FClose(file); + return content; + } + + private: + // Reads the entire content of a file as an std::string. + static std::string ReadEntireFile(FILE* file); + + // Returns the size (in bytes) of a file. + static size_t GetFileSize(FILE* file); + + const int fd_; // A stream to capture. + int uncaptured_fd_; + // Name of the temporary file holding the stderr output. + ::std::string filename_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); +}; + +// Returns the size (in bytes) of a file. +size_t CapturedStream::GetFileSize(FILE* file) { + fseek(file, 0, SEEK_END); + return static_cast(ftell(file)); +} + +// Reads the entire content of a file as a string. +std::string CapturedStream::ReadEntireFile(FILE* file) { + const size_t file_size = GetFileSize(file); + char* const buffer = new char[file_size]; + + size_t bytes_last_read = 0; // # of bytes read in the last fread() + size_t bytes_read = 0; // # of bytes read so far + + fseek(file, 0, SEEK_SET); + + // Keeps reading the file until we cannot read further or the + // pre-determined file size is reached. + do { + bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_read += bytes_last_read; + } while (bytes_last_read > 0 && bytes_read < file_size); + + const std::string content(buffer, bytes_read); + delete[] buffer; + + return content; +} + +# ifdef _MSC_VER +# pragma warning(pop) +# endif // _MSC_VER + +static CapturedStream* g_captured_stderr = NULL; +static CapturedStream* g_captured_stdout = NULL; + +// Starts capturing an output stream (stdout/stderr). +void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { + if (*stream != NULL) { + GTEST_LOG_(FATAL) << "Only one " << stream_name + << " capturer can exist at a time."; + } + *stream = new CapturedStream(fd); +} + +// Stops capturing the output stream and returns the captured string. +std::string GetCapturedStream(CapturedStream** captured_stream) { + const std::string content = (*captured_stream)->GetCapturedString(); + + delete *captured_stream; + *captured_stream = NULL; + + return content; +} + +// Starts capturing stdout. +void CaptureStdout() { + CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); +} + +// Starts capturing stderr. +void CaptureStderr() { + CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); +} + +// Stops capturing stdout and returns the captured string. +std::string GetCapturedStdout() { + return GetCapturedStream(&g_captured_stdout); +} + +// Stops capturing stderr and returns the captured string. +std::string GetCapturedStderr() { + return GetCapturedStream(&g_captured_stderr); +} + +#endif // GTEST_HAS_STREAM_REDIRECTION + +#if GTEST_HAS_DEATH_TEST + +// A copy of all command line arguments. Set by InitGoogleTest(). +::std::vector g_argvs; + +static const ::std::vector* g_injected_test_argvs = + NULL; // Owned. + +void SetInjectableArgvs(const ::std::vector* argvs) { + if (g_injected_test_argvs != argvs) + delete g_injected_test_argvs; + g_injected_test_argvs = argvs; +} + +const ::std::vector& GetInjectableArgvs() { + if (g_injected_test_argvs != NULL) { + return *g_injected_test_argvs; + } + return g_argvs; +} +#endif // GTEST_HAS_DEATH_TEST + +#if GTEST_OS_WINDOWS_MOBILE +namespace posix { +void Abort() { + DebugBreak(); + TerminateProcess(GetCurrentProcess(), 1); +} +} // namespace posix +#endif // GTEST_OS_WINDOWS_MOBILE + +// Returns the name of the environment variable corresponding to the +// given flag. For example, FlagToEnvVar("foo") will return +// "GTEST_FOO" in the open-source version. +static std::string FlagToEnvVar(const char* flag) { + const std::string full_flag = + (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); + + Message env_var; + for (size_t i = 0; i != full_flag.length(); i++) { + env_var << ToUpper(full_flag.c_str()[i]); + } + + return env_var.GetString(); +} + +// Parses 'str' for a 32-bit signed integer. If successful, writes +// the result to *value and returns true; otherwise leaves *value +// unchanged and returns false. +bool ParseInt32(const Message& src_text, const char* str, Int32* value) { + // Parses the environment variable as a decimal integer. + char* end = NULL; + const long long_value = strtol(str, &end, 10); // NOLINT + + // Has strtol() consumed all characters in the string? + if (*end != '\0') { + // No - an invalid character was encountered. + Message msg; + msg << "WARNING: " << src_text + << " is expected to be a 32-bit integer, but actually" + << " has value \"" << str << "\".\n"; + printf("%s", msg.GetString().c_str()); + fflush(stdout); + return false; + } + + // Is the parsed value in the range of an Int32? + const Int32 result = static_cast(long_value); + if (long_value == LONG_MAX || long_value == LONG_MIN || + // The parsed value overflows as a long. (strtol() returns + // LONG_MAX or LONG_MIN when the input overflows.) + result != long_value + // The parsed value overflows as an Int32. + ) { + Message msg; + msg << "WARNING: " << src_text + << " is expected to be a 32-bit integer, but actually" + << " has value " << str << ", which overflows.\n"; + printf("%s", msg.GetString().c_str()); + fflush(stdout); + return false; + } + + *value = result; + return true; +} + +// Reads and returns the Boolean environment variable corresponding to +// the given flag; if it's not set, returns default_value. +// +// The value is considered true iff it's not "0". +bool BoolFromGTestEnv(const char* flag, bool default_value) { + const std::string env_var = FlagToEnvVar(flag); + const char* const string_value = posix::GetEnv(env_var.c_str()); + return string_value == NULL ? + default_value : strcmp(string_value, "0") != 0; +} + +// Reads and returns a 32-bit integer stored in the environment +// variable corresponding to the given flag; if it isn't set or +// doesn't represent a valid 32-bit integer, returns default_value. +Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { + const std::string env_var = FlagToEnvVar(flag); + const char* const string_value = posix::GetEnv(env_var.c_str()); + if (string_value == NULL) { + // The environment variable is not set. + return default_value; + } + + Int32 result = default_value; + if (!ParseInt32(Message() << "Environment variable " << env_var, + string_value, &result)) { + printf("The default value %s is used.\n", + (Message() << default_value).GetString().c_str()); + fflush(stdout); + return default_value; + } + + return result; +} + +// Reads and returns the string environment variable corresponding to +// the given flag; if it's not set, returns default_value. +const char* StringFromGTestEnv(const char* flag, const char* default_value) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value = posix::GetEnv(env_var.c_str()); + return value == NULL ? default_value : value; +} + +} // namespace internal +} // namespace testing +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing Framework +// +// This file implements a universal value printer that can print a +// value of any type T: +// +// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); +// +// It uses the << operator when possible, and prints the bytes in the +// object otherwise. A user can override its behavior for a class +// type Foo by defining either operator<<(::std::ostream&, const Foo&) +// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that +// defines Foo. + +#include +#include +#include // NOLINT +#include + +namespace testing { + +namespace { + +using ::std::ostream; + +// Prints a segment of bytes in the given object. +void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, + size_t count, ostream* os) { + char text[5] = ""; + for (size_t i = 0; i != count; i++) { + const size_t j = start + i; + if (i != 0) { + // Organizes the bytes into groups of 2 for easy parsing by + // human. + if ((j % 2) == 0) + *os << ' '; + else + *os << '-'; + } + GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); + *os << text; + } +} + +// Prints the bytes in the given value to the given ostream. +void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, + ostream* os) { + // Tells the user how big the object is. + *os << count << "-byte object <"; + + const size_t kThreshold = 132; + const size_t kChunkSize = 64; + // If the object size is bigger than kThreshold, we'll have to omit + // some details by printing only the first and the last kChunkSize + // bytes. + // TODO(wan): let the user control the threshold using a flag. + if (count < kThreshold) { + PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); + } else { + PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); + *os << " ... "; + // Rounds up to 2-byte boundary. + const size_t resume_pos = (count - kChunkSize + 1)/2*2; + PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); + } + *os << ">"; +} + +} // namespace + +namespace internal2 { + +// Delegates to PrintBytesInObjectToImpl() to print the bytes in the +// given object. The delegation simplifies the implementation, which +// uses the << operator and thus is easier done outside of the +// ::testing::internal namespace, which contains a << operator that +// sometimes conflicts with the one in STL. +void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, + ostream* os) { + PrintBytesInObjectToImpl(obj_bytes, count, os); +} + +} // namespace internal2 + +namespace internal { + +// Depending on the value of a char (or wchar_t), we print it in one +// of three formats: +// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), +// - as a hexidecimal escape sequence (e.g. '\x7F'), or +// - as a special escape sequence (e.g. '\r', '\n'). +enum CharFormat { + kAsIs, + kHexEscape, + kSpecialEscape +}; + +// Returns true if c is a printable ASCII character. We test the +// value of c directly instead of calling isprint(), which is buggy on +// Windows Mobile. +inline bool IsPrintableAscii(wchar_t c) { + return 0x20 <= c && c <= 0x7E; +} + +// Prints a wide or narrow char c as a character literal without the +// quotes, escaping it when necessary; returns how c was formatted. +// The template argument UnsignedChar is the unsigned version of Char, +// which is the type of c. +template +static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { + switch (static_cast(c)) { + case L'\0': + *os << "\\0"; + break; + case L'\'': + *os << "\\'"; + break; + case L'\\': + *os << "\\\\"; + break; + case L'\a': + *os << "\\a"; + break; + case L'\b': + *os << "\\b"; + break; + case L'\f': + *os << "\\f"; + break; + case L'\n': + *os << "\\n"; + break; + case L'\r': + *os << "\\r"; + break; + case L'\t': + *os << "\\t"; + break; + case L'\v': + *os << "\\v"; + break; + default: + if (IsPrintableAscii(c)) { + *os << static_cast(c); + return kAsIs; + } else { + *os << "\\x" + String::FormatHexInt(static_cast(c)); + return kHexEscape; + } + } + return kSpecialEscape; +} + +// Prints a wchar_t c as if it's part of a string literal, escaping it when +// necessary; returns how c was formatted. +static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { + switch (c) { + case L'\'': + *os << "'"; + return kAsIs; + case L'"': + *os << "\\\""; + return kSpecialEscape; + default: + return PrintAsCharLiteralTo(c, os); + } +} + +// Prints a char c as if it's part of a string literal, escaping it when +// necessary; returns how c was formatted. +static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { + return PrintAsStringLiteralTo( + static_cast(static_cast(c)), os); +} + +// Prints a wide or narrow character c and its code. '\0' is printed +// as "'\\0'", other unprintable characters are also properly escaped +// using the standard C++ escape sequence. The template argument +// UnsignedChar is the unsigned version of Char, which is the type of c. +template +void PrintCharAndCodeTo(Char c, ostream* os) { + // First, print c as a literal in the most readable form we can find. + *os << ((sizeof(c) > 1) ? "L'" : "'"); + const CharFormat format = PrintAsCharLiteralTo(c, os); + *os << "'"; + + // To aid user debugging, we also print c's code in decimal, unless + // it's 0 (in which case c was printed as '\\0', making the code + // obvious). + if (c == 0) + return; + *os << " (" << static_cast(c); + + // For more convenience, we print c's code again in hexidecimal, + // unless c was already printed in the form '\x##' or the code is in + // [1, 9]. + if (format == kHexEscape || (1 <= c && c <= 9)) { + // Do nothing. + } else { + *os << ", 0x" << String::FormatHexInt(static_cast(c)); + } + *os << ")"; +} + +void PrintTo(unsigned char c, ::std::ostream* os) { + PrintCharAndCodeTo(c, os); +} +void PrintTo(signed char c, ::std::ostream* os) { + PrintCharAndCodeTo(c, os); +} + +// Prints a wchar_t as a symbol if it is printable or as its internal +// code otherwise and also as its code. L'\0' is printed as "L'\\0'". +void PrintTo(wchar_t wc, ostream* os) { + PrintCharAndCodeTo(wc, os); +} + +// Prints the given array of characters to the ostream. CharType must be either +// char or wchar_t. +// The array starts at begin, the length is len, it may include '\0' characters +// and may not be NUL-terminated. +template +static void PrintCharsAsStringTo( + const CharType* begin, size_t len, ostream* os) { + const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; + *os << kQuoteBegin; + bool is_previous_hex = false; + for (size_t index = 0; index < len; ++index) { + const CharType cur = begin[index]; + if (is_previous_hex && IsXDigit(cur)) { + // Previous character is of '\x..' form and this character can be + // interpreted as another hexadecimal digit in its number. Break string to + // disambiguate. + *os << "\" " << kQuoteBegin; + } + is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; + } + *os << "\""; +} + +// Prints a (const) char/wchar_t array of 'len' elements, starting at address +// 'begin'. CharType must be either char or wchar_t. +template +static void UniversalPrintCharArray( + const CharType* begin, size_t len, ostream* os) { + // The code + // const char kFoo[] = "foo"; + // generates an array of 4, not 3, elements, with the last one being '\0'. + // + // Therefore when printing a char array, we don't print the last element if + // it's '\0', such that the output matches the string literal as it's + // written in the source code. + if (len > 0 && begin[len - 1] == '\0') { + PrintCharsAsStringTo(begin, len - 1, os); + return; + } + + // If, however, the last element in the array is not '\0', e.g. + // const char kFoo[] = { 'f', 'o', 'o' }; + // we must print the entire array. We also print a message to indicate + // that the array is not NUL-terminated. + PrintCharsAsStringTo(begin, len, os); + *os << " (no terminating NUL)"; +} + +// Prints a (const) char array of 'len' elements, starting at address 'begin'. +void UniversalPrintArray(const char* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); +} + +// Prints a (const) wchar_t array of 'len' elements, starting at address +// 'begin'. +void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); +} + +// Prints the given C string to the ostream. +void PrintTo(const char* s, ostream* os) { + if (s == NULL) { + *os << "NULL"; + } else { + *os << ImplicitCast_(s) << " pointing to "; + PrintCharsAsStringTo(s, strlen(s), os); + } +} + +// MSVC compiler can be configured to define whar_t as a typedef +// of unsigned short. Defining an overload for const wchar_t* in that case +// would cause pointers to unsigned shorts be printed as wide strings, +// possibly accessing more memory than intended and causing invalid +// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when +// wchar_t is implemented as a native type. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// Prints the given wide C string to the ostream. +void PrintTo(const wchar_t* s, ostream* os) { + if (s == NULL) { + *os << "NULL"; + } else { + *os << ImplicitCast_(s) << " pointing to "; + PrintCharsAsStringTo(s, wcslen(s), os); + } +} +#endif // wchar_t is native + +// Prints a ::string object. +#if GTEST_HAS_GLOBAL_STRING +void PrintStringTo(const ::string& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_GLOBAL_STRING + +void PrintStringTo(const ::std::string& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} + +// Prints a ::wstring object. +#if GTEST_HAS_GLOBAL_WSTRING +void PrintWideStringTo(const ::wstring& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +void PrintWideStringTo(const ::std::wstring& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_STD_WSTRING + +} // namespace internal + +} // namespace testing +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// +// The Google C++ Testing Framework (Google Test) + + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#undef GTEST_IMPLEMENTATION_ + +namespace testing { + +using internal::GetUnitTestImpl; + +// Gets the summary of the failure message by omitting the stack trace +// in it. +std::string TestPartResult::ExtractSummary(const char* message) { + const char* const stack_trace = strstr(message, internal::kStackTraceMarker); + return stack_trace == NULL ? message : + std::string(message, stack_trace); +} + +// Prints a TestPartResult object. +std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { + return os + << result.file_name() << ":" << result.line_number() << ": " + << (result.type() == TestPartResult::kSuccess ? "Success" : + result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : + "Non-fatal failure") << ":\n" + << result.message() << std::endl; +} + +// Appends a TestPartResult to the array. +void TestPartResultArray::Append(const TestPartResult& result) { + array_.push_back(result); +} + +// Returns the TestPartResult at the given index (0-based). +const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { + if (index < 0 || index >= size()) { + printf("\nInvalid index (%d) into TestPartResultArray.\n", index); + internal::posix::Abort(); + } + + return array_[index]; +} + +// Returns the number of TestPartResult objects in the array. +int TestPartResultArray::size() const { + return static_cast(array_.size()); +} + +namespace internal { + +HasNewFatalFailureHelper::HasNewFatalFailureHelper() + : has_new_fatal_failure_(false), + original_reporter_(GetUnitTestImpl()-> + GetTestPartResultReporterForCurrentThread()) { + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); +} + +HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( + original_reporter_); +} + +void HasNewFatalFailureHelper::ReportTestPartResult( + const TestPartResult& result) { + if (result.fatally_failed()) + has_new_fatal_failure_ = true; + original_reporter_->ReportTestPartResult(result); +} + +} // namespace internal + +} // namespace testing +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + + +namespace testing { +namespace internal { + +#if GTEST_HAS_TYPED_TEST_P + +// Skips to the first non-space char in str. Returns an empty string if str +// contains only whitespace characters. +static const char* SkipSpaces(const char* str) { + while (IsSpace(*str)) + str++; + return str; +} + +// Verifies that registered_tests match the test names in +// defined_test_names_; returns registered_tests if successful, or +// aborts the program otherwise. +const char* TypedTestCasePState::VerifyRegisteredTestNames( + const char* file, int line, const char* registered_tests) { + typedef ::std::set::const_iterator DefinedTestIter; + registered_ = true; + + // Skip initial whitespace in registered_tests since some + // preprocessors prefix stringizied literals with whitespace. + registered_tests = SkipSpaces(registered_tests); + + Message errors; + ::std::set tests; + for (const char* names = registered_tests; names != NULL; + names = SkipComma(names)) { + const std::string name = GetPrefixUntilComma(names); + if (tests.count(name) != 0) { + errors << "Test " << name << " is listed more than once.\n"; + continue; + } + + bool found = false; + for (DefinedTestIter it = defined_test_names_.begin(); + it != defined_test_names_.end(); + ++it) { + if (name == *it) { + found = true; + break; + } + } + + if (found) { + tests.insert(name); + } else { + errors << "No test named " << name + << " can be found in this test case.\n"; + } + } + + for (DefinedTestIter it = defined_test_names_.begin(); + it != defined_test_names_.end(); + ++it) { + if (tests.count(*it) == 0) { + errors << "You forgot to list test " << *it << ".\n"; + } + } + + const std::string& errors_str = errors.GetString(); + if (errors_str != "") { + fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), + errors_str.c_str()); + fflush(stderr); + posix::Abort(); + } + + return registered_tests; +} + +#endif // GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing diff --git a/src/ext/gtest/gtest.h b/src/ext/gtest/gtest.h new file mode 100644 index 00000000..9bea4c8a --- /dev/null +++ b/src/ext/gtest/gtest.h @@ -0,0 +1,20065 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the public API for Google Test. It should be +// included by any test program that uses Google Test. +// +// IMPORTANT NOTE: Due to limitation of the C++ language, we have to +// leave some internal implementation details in this header file. +// They are clearly marked by comments like this: +// +// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// +// Such code is NOT meant to be used by a user directly, and is subject +// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user +// program! +// +// Acknowledgment: Google Test borrowed the idea of automatic test +// registration from Barthelemy Dagenais' (barthelemy@prologique.com) +// easyUnit framework. + +#if _MSC_VER > 1910 +#define GTEST_HAS_TR1_TUPLE 0 +#endif + +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_H_ + +#include +#include +#include + +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file declares functions and macros used internally by +// Google Test. They are subject to change without notice. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ + +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan) +// +// Low-level types and utilities for porting Google Test to various +// platforms. They are subject to change without notice. DO NOT USE +// THEM IN USER CODE. +// +// This file is fundamental to Google Test. All other Google Test source +// files are expected to #include this. Therefore, it cannot #include +// any other Google Test header. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ + +// The user can define the following macros in the build script to +// control Google Test's behavior. If the user doesn't define a macro +// in this list, Google Test will define it. +// +// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) +// is/isn't available. +// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions +// are enabled. +// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string +// is/isn't available (some systems define +// ::string, which is different to std::string). +// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string +// is/isn't available (some systems define +// ::wstring, which is different to std::wstring). +// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular +// expressions are/aren't available. +// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that +// is/isn't available. +// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't +// enabled. +// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that +// std::wstring does/doesn't work (Google Test can +// be used where std::wstring is unavailable). +// GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple +// is/isn't available. +// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the +// compiler supports Microsoft's "Structured +// Exception Handling". +// GTEST_HAS_STREAM_REDIRECTION +// - Define it to 1/0 to indicate whether the +// platform supports I/O stream redirection using +// dup() and dup2(). +// GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google +// Test's own tr1 tuple implementation should be +// used. Unused when the user sets +// GTEST_HAS_TR1_TUPLE to 0. +// GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test +// is building in C++11/C++98 mode. +// GTEST_LINKED_AS_SHARED_LIBRARY +// - Define to 1 when compiling tests that use +// Google Test as a shared library (known as +// DLL on Windows). +// GTEST_CREATE_SHARED_LIBRARY +// - Define to 1 when compiling Google Test itself +// as a shared library. + +// This header defines the following utilities: +// +// Macros indicating the current platform (defined to 1 if compiled on +// the given platform; otherwise undefined): +// GTEST_OS_AIX - IBM AIX +// GTEST_OS_CYGWIN - Cygwin +// GTEST_OS_HPUX - HP-UX +// GTEST_OS_LINUX - Linux +// GTEST_OS_LINUX_ANDROID - Google Android +// GTEST_OS_MAC - Mac OS X +// GTEST_OS_IOS - iOS +// GTEST_OS_IOS_SIMULATOR - iOS simulator +// GTEST_OS_NACL - Google Native Client (NaCl) +// GTEST_OS_OPENBSD - OpenBSD +// GTEST_OS_QNX - QNX +// GTEST_OS_SOLARIS - Sun Solaris +// GTEST_OS_SYMBIAN - Symbian +// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) +// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop +// GTEST_OS_WINDOWS_MINGW - MinGW +// GTEST_OS_WINDOWS_MOBILE - Windows Mobile +// GTEST_OS_ZOS - z/OS +// +// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the +// most stable support. Since core members of the Google Test project +// don't have access to other platforms, support for them may be less +// stable. If you notice any problems on your platform, please notify +// googletestframework@googlegroups.com (patches for fixing them are +// even more welcome!). +// +// Note that it is possible that none of the GTEST_OS_* macros are defined. +// +// Macros indicating available Google Test features (defined to 1 if +// the corresponding feature is supported; otherwise undefined): +// GTEST_HAS_COMBINE - the Combine() function (for value-parameterized +// tests) +// GTEST_HAS_DEATH_TEST - death tests +// GTEST_HAS_PARAM_TEST - value-parameterized tests +// GTEST_HAS_TYPED_TEST - typed tests +// GTEST_HAS_TYPED_TEST_P - type-parameterized tests +// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with +// GTEST_HAS_POSIX_RE (see above) which users can +// define themselves. +// GTEST_USES_SIMPLE_RE - our own simple regex is used; +// the above two are mutually exclusive. +// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). +// +// Macros for basic C++ coding: +// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. +// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a +// variable don't have to be used. +// GTEST_DISALLOW_ASSIGN_ - disables operator=. +// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. +// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. +// +// Synchronization: +// Mutex, MutexLock, ThreadLocal, GetThreadCount() +// - synchronization primitives. +// GTEST_IS_THREADSAFE - defined to 1 to indicate that the above +// synchronization primitives have real implementations +// and Google Test is thread-safe; or 0 otherwise. +// +// Template meta programming: +// is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. +// IteratorTraits - partial implementation of std::iterator_traits, which +// is not available in libCstd when compiled with Sun C++. +// +// Smart pointers: +// scoped_ptr - as in TR2. +// +// Regular expressions: +// RE - a simple regular expression class using the POSIX +// Extended Regular Expression syntax on UNIX-like +// platforms, or a reduced regular exception syntax on +// other platforms, including Windows. +// +// Logging: +// GTEST_LOG_() - logs messages at the specified severity level. +// LogToStderr() - directs all log messages to stderr. +// FlushInfoLog() - flushes informational log messages. +// +// Stdout and stderr capturing: +// CaptureStdout() - starts capturing stdout. +// GetCapturedStdout() - stops capturing stdout and returns the captured +// string. +// CaptureStderr() - starts capturing stderr. +// GetCapturedStderr() - stops capturing stderr and returns the captured +// string. +// +// Integer types: +// TypeWithSize - maps an integer to a int type. +// Int32, UInt32, Int64, UInt64, TimeInMillis +// - integers of known sizes. +// BiggestInt - the biggest signed integer type. +// +// Command-line utilities: +// GTEST_FLAG() - references a flag. +// GTEST_DECLARE_*() - declares a flag. +// GTEST_DEFINE_*() - defines a flag. +// GetInjectableArgvs() - returns the command line as a vector of strings. +// +// Environment variable utilities: +// GetEnv() - gets the value of an environment variable. +// BoolFromGTestEnv() - parses a bool environment variable. +// Int32FromGTestEnv() - parses an Int32 environment variable. +// StringFromGTestEnv() - parses a string environment variable. + +#include // for isspace, etc +#include // for ptrdiff_t +#include +#include +#include +#ifndef _WIN32_WCE +# include +# include +#endif // !_WIN32_WCE + +#if defined __APPLE__ +# include +# include +#endif + +#include // NOLINT +#include // NOLINT +#include // NOLINT + +#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +#define GTEST_FLAG_PREFIX_ "gtest_" +#define GTEST_FLAG_PREFIX_DASH_ "gtest-" +#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +#define GTEST_NAME_ "Google Test" +#define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" + +// Determines the version of gcc that is used to compile this. +#ifdef __GNUC__ +// 40302 means version 4.3.2. +# define GTEST_GCC_VER_ \ + (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +#endif // __GNUC__ + +// Determines the platform on which Google Test is compiled. +#ifdef __CYGWIN__ +# define GTEST_OS_CYGWIN 1 +#elif defined __SYMBIAN32__ +# define GTEST_OS_SYMBIAN 1 +#elif defined _WIN32 +# define GTEST_OS_WINDOWS 1 +# ifdef _WIN32_WCE +# define GTEST_OS_WINDOWS_MOBILE 1 +# elif defined(__MINGW__) || defined(__MINGW32__) +# define GTEST_OS_WINDOWS_MINGW 1 +# else +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif // _WIN32_WCE +#elif defined __APPLE__ +# define GTEST_OS_MAC 1 +# if TARGET_OS_IPHONE +# define GTEST_OS_IOS 1 +# if TARGET_IPHONE_SIMULATOR +# define GTEST_OS_IOS_SIMULATOR 1 +# endif +# endif +#elif defined __linux__ +# define GTEST_OS_LINUX 1 +# if defined __ANDROID__ +# define GTEST_OS_LINUX_ANDROID 1 +# endif +#elif defined __MVS__ +# define GTEST_OS_ZOS 1 +#elif defined(__sun) && defined(__SVR4) +# define GTEST_OS_SOLARIS 1 +#elif defined(_AIX) +# define GTEST_OS_AIX 1 +#elif defined(__hpux) +# define GTEST_OS_HPUX 1 +#elif defined __native_client__ +# define GTEST_OS_NACL 1 +#elif defined __OpenBSD__ +# define GTEST_OS_OPENBSD 1 +#elif defined __QNX__ +# define GTEST_OS_QNX 1 +#endif // __CYGWIN__ + +#ifndef GTEST_LANG_CXX11 +// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when +// -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a +// value for __cplusplus, and recent versions of clang, gcc, and +// probably other compilers set that too in C++11 mode. +# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L +// Compiling in at least C++11 mode. +# define GTEST_LANG_CXX11 1 +# else +# define GTEST_LANG_CXX11 0 +# endif +#endif + +// Brings in definitions for functions used in the testing::internal::posix +// namespace (read, write, close, chdir, isatty, stat). We do not currently +// use them on Windows Mobile. +#if !GTEST_OS_WINDOWS +// This assumes that non-Windows OSes provide unistd.h. For OSes where this +// is not the case, we need to include headers that provide the functions +// mentioned above. +# include +# include +#elif !GTEST_OS_WINDOWS_MOBILE +# include +# include +#endif + +#if GTEST_OS_LINUX_ANDROID +// Used to define __ANDROID_API__ matching the target NDK API level. +# include // NOLINT +#endif + +// Defines this to true iff Google Test can use POSIX regular expressions. +#ifndef GTEST_HAS_POSIX_RE +# if GTEST_OS_LINUX_ANDROID +// On Android, is only available starting with Gingerbread. +# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +# else +# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +# endif +#endif + +#if GTEST_HAS_POSIX_RE + +// On some platforms, needs someone to define size_t, and +// won't compile otherwise. We can #include it here as we already +// included , which is guaranteed to define size_t through +// . +# include // NOLINT + +# define GTEST_USES_POSIX_RE 1 + +#elif GTEST_OS_WINDOWS + +// is not available on Windows. Use our own simple regex +// implementation instead. +# define GTEST_USES_SIMPLE_RE 1 + +#else + +// may not be available on this platform. Use our own +// simple regex implementation instead. +# define GTEST_USES_SIMPLE_RE 1 + +#endif // GTEST_HAS_POSIX_RE + +#ifndef GTEST_HAS_EXCEPTIONS +// The user didn't tell us whether exceptions are enabled, so we need +// to figure it out. +# if defined(_MSC_VER) || defined(__BORLANDC__) +// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS +// macro to enable exceptions, so we'll do the same. +// Assumes that exceptions are enabled by default. +# ifndef _HAS_EXCEPTIONS +# define _HAS_EXCEPTIONS 1 +# endif // _HAS_EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +# elif defined(__GNUC__) && __EXCEPTIONS +// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__SUNPRO_CC) +// Sun Pro CC supports exceptions. However, there is no compile-time way of +// detecting whether they are enabled or not. Therefore, we assume that +// they are enabled unless the user tells us otherwise. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__IBMCPP__) && __EXCEPTIONS +// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__HP_aCC) +// Exception handling is in effect by default in HP aCC compiler. It has to +// be turned of by +noeh compiler option if desired. +# define GTEST_HAS_EXCEPTIONS 1 +# else +// For other compilers, we assume exceptions are disabled to be +// conservative. +# define GTEST_HAS_EXCEPTIONS 0 +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +#endif // GTEST_HAS_EXCEPTIONS + +#if !defined(GTEST_HAS_STD_STRING) +// Even though we don't use this macro any longer, we keep it in case +// some clients still depend on it. +# define GTEST_HAS_STD_STRING 1 +#elif !GTEST_HAS_STD_STRING +// The user told us that ::std::string isn't available. +# error "Google Test cannot be used where ::std::string isn't available." +#endif // !defined(GTEST_HAS_STD_STRING) + +#ifndef GTEST_HAS_GLOBAL_STRING +// The user didn't tell us whether ::string is available, so we need +// to figure it out. + +# define GTEST_HAS_GLOBAL_STRING 0 + +#endif // GTEST_HAS_GLOBAL_STRING + +#ifndef GTEST_HAS_STD_WSTRING +// The user didn't tell us whether ::std::wstring is available, so we need +// to figure it out. +// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring +// is available. + +// Cygwin 1.7 and below doesn't support ::std::wstring. +// Solaris' libc++ doesn't support it either. Android has +// no support for it at least as recent as Froyo (2.2). +# define GTEST_HAS_STD_WSTRING \ + (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) + +#endif // GTEST_HAS_STD_WSTRING + +#ifndef GTEST_HAS_GLOBAL_WSTRING +// The user didn't tell us whether ::wstring is available, so we need +// to figure it out. +# define GTEST_HAS_GLOBAL_WSTRING \ + (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) +#endif // GTEST_HAS_GLOBAL_WSTRING + +// Determines whether RTTI is available. +#ifndef GTEST_HAS_RTTI +// The user didn't tell us whether RTTI is enabled, so we need to +// figure it out. + +# ifdef _MSC_VER + +# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif + +// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) + +# ifdef __GXX_RTTI +// When building against STLport with the Android NDK and with +// -frtti -fno-exceptions, the build fails at link time with undefined +// references to __cxa_bad_typeid. Note sure if STL or toolchain bug, +// so disable RTTI when detected. +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ + !defined(__EXCEPTIONS) +# define GTEST_HAS_RTTI 0 +# else +# define GTEST_HAS_RTTI 1 +# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS +# else +# define GTEST_HAS_RTTI 0 +# endif // __GXX_RTTI + +// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends +// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the +// first version with C++ support. +# elif defined(__clang__) + +# define GTEST_HAS_RTTI __has_feature(cxx_rtti) + +// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if +// both the typeid and dynamic_cast features are present. +# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) + +# ifdef __RTTI_ALL__ +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif + +# else + +// For all other compilers, we assume RTTI is enabled. +# define GTEST_HAS_RTTI 1 + +# endif // _MSC_VER + +#endif // GTEST_HAS_RTTI + +// It's this header's responsibility to #include when RTTI +// is enabled. +#if GTEST_HAS_RTTI +# include +#endif + +// Determines whether Google Test can use the pthreads library. +#ifndef GTEST_HAS_PTHREAD +// The user didn't tell us explicitly, so we assume pthreads support is +// available on Linux and Mac. +// +// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 +// to your compiler flags. +# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ + || GTEST_OS_QNX) +#endif // GTEST_HAS_PTHREAD + +#if GTEST_HAS_PTHREAD +// gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is +// true. +# include // NOLINT + +// For timespec and nanosleep, used below. +# include // NOLINT +#endif + +// Determines whether Google Test can use tr1/tuple. You can define +// this macro to 0 to prevent Google Test from using tuple (any +// feature depending on tuple with be disabled in this mode). +#ifndef GTEST_HAS_TR1_TUPLE +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) +// STLport, provided with the Android NDK, has neither or . +# define GTEST_HAS_TR1_TUPLE 0 +# else +// The user didn't tell us not to do it, so we assume it's OK. +# define GTEST_HAS_TR1_TUPLE 1 +# endif +#endif // GTEST_HAS_TR1_TUPLE + +// Determines whether Google Test's own tr1 tuple implementation +// should be used. +#ifndef GTEST_USE_OWN_TR1_TUPLE +// The user didn't tell us, so we need to figure it out. + +// We use our own TR1 tuple if we aren't sure the user has an +// implementation of it already. At this time, libstdc++ 4.0.0+ and +// MSVC 2010 are the only mainstream standard libraries that come +// with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler +// pretends to be GCC by defining __GNUC__ and friends, but cannot +// compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 +// tuple in a 323 MB Feature Pack download, which we cannot assume the +// user has. QNX's QCC compiler is a modified GCC but it doesn't +// support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, +// and it can be used with some compilers that define __GNUC__. +# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ + && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 +# define GTEST_ENV_HAS_TR1_TUPLE_ 1 +# endif + +// C++11 specifies that provides std::tuple. Use that if gtest is used +// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 +// can build with clang but need to use gcc4.2's libstdc++). +# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) +# define GTEST_ENV_HAS_STD_TUPLE_ 1 +# endif + +# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ +# define GTEST_USE_OWN_TR1_TUPLE 0 +# else +# define GTEST_USE_OWN_TR1_TUPLE 1 +# endif + +#endif // GTEST_USE_OWN_TR1_TUPLE + +// To avoid conditional compilation everywhere, we make it +// gtest-port.h's responsibility to #include the header implementing +// tr1/tuple. +#if GTEST_HAS_TR1_TUPLE + +# if GTEST_USE_OWN_TR1_TUPLE +// This file was GENERATED by command: +// pump.py gtest-tuple.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2009 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Implements a subset of TR1 tuple needed by Google Test and Google Mock. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ + +#include // For ::std::pair. + +// The compiler used in Symbian has a bug that prevents us from declaring the +// tuple template as a friend (it complains that tuple is redefined). This +// hack bypasses the bug by declaring the members that should otherwise be +// private as public. +// Sun Studio versions < 12 also have the above bug. +#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: +#else +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ + template friend class tuple; \ + private: +#endif + +// GTEST_n_TUPLE_(T) is the type of an n-tuple. +#define GTEST_0_TUPLE_(T) tuple<> +#define GTEST_1_TUPLE_(T) tuple +#define GTEST_2_TUPLE_(T) tuple +#define GTEST_3_TUPLE_(T) tuple +#define GTEST_4_TUPLE_(T) tuple +#define GTEST_5_TUPLE_(T) tuple +#define GTEST_6_TUPLE_(T) tuple +#define GTEST_7_TUPLE_(T) tuple +#define GTEST_8_TUPLE_(T) tuple +#define GTEST_9_TUPLE_(T) tuple +#define GTEST_10_TUPLE_(T) tuple + +// GTEST_n_TYPENAMES_(T) declares a list of n typenames. +#define GTEST_0_TYPENAMES_(T) +#define GTEST_1_TYPENAMES_(T) typename T##0 +#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 +#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 +#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3 +#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4 +#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5 +#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6 +#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 +#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8 +#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8, typename T##9 + +// In theory, defining stuff in the ::std namespace is undefined +// behavior. We can do this as we are playing the role of a standard +// library vendor. +namespace std { +namespace tr1 { + +template +class tuple; + +// Anything in namespace gtest_internal is Google Test's INTERNAL +// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. +namespace gtest_internal { + +// ByRef::type is T if T is a reference; otherwise it's const T&. +template +struct ByRef { typedef const T& type; }; // NOLINT +template +struct ByRef { typedef T& type; }; // NOLINT + +// A handy wrapper for ByRef. +#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type + +// AddRef::type is T if T is a reference; otherwise it's T&. This +// is the same as tr1::add_reference::type. +template +struct AddRef { typedef T& type; }; // NOLINT +template +struct AddRef { typedef T& type; }; // NOLINT + +// A handy wrapper for AddRef. +#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type + +// A helper for implementing get(). +template class Get; + +// A helper for implementing tuple_element. kIndexValid is true +// iff k < the number of fields in tuple type T. +template +struct TupleElement; + +template +struct TupleElement { + typedef T0 type; +}; + +template +struct TupleElement { + typedef T1 type; +}; + +template +struct TupleElement { + typedef T2 type; +}; + +template +struct TupleElement { + typedef T3 type; +}; + +template +struct TupleElement { + typedef T4 type; +}; + +template +struct TupleElement { + typedef T5 type; +}; + +template +struct TupleElement { + typedef T6 type; +}; + +template +struct TupleElement { + typedef T7 type; +}; + +template +struct TupleElement { + typedef T8 type; +}; + +template +struct TupleElement { + typedef T9 type; +}; + +} // namespace gtest_internal + +template <> +class tuple<> { + public: + tuple() {} + tuple(const tuple& /* t */) {} + tuple& operator=(const tuple& /* t */) { return *this; } +}; + +template +class GTEST_1_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} + + tuple(const tuple& t) : f0_(t.f0_) {} + + template + tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_1_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { + f0_ = t.f0_; + return *this; + } + + T0 f0_; +}; + +template +class GTEST_2_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), + f1_(f1) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} + + template + tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} + template + tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_2_TUPLE_(U)& t) { + return CopyFrom(t); + } + template + tuple& operator=(const ::std::pair& p) { + f0_ = p.first; + f1_ = p.second; + return *this; + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + return *this; + } + + T0 f0_; + T1 f1_; +}; + +template +class GTEST_3_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + + template + tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_3_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; +}; + +template +class GTEST_4_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} + + template + tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_4_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; +}; + +template +class GTEST_5_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_) {} + + template + tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_5_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; +}; + +template +class GTEST_6_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_) {} + + template + tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_6_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; +}; + +template +class GTEST_7_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + + template + tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_7_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; +}; + +template +class GTEST_8_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, + GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5), f6_(f6), f7_(f7) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + + template + tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_8_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; +}; + +template +class GTEST_9_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + + template + tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_9_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + f8_ = t.f8_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; + T8 f8_; +}; + +template +class tuple { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), + f9_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} + + template + tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), + f9_(t.f9_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_10_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + f8_ = t.f8_; + f9_ = t.f9_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; + T8 f8_; + T9 f9_; +}; + +// 6.1.3.2 Tuple creation functions. + +// Known limitations: we don't support passing an +// std::tr1::reference_wrapper to make_tuple(). And we don't +// implement tie(). + +inline tuple<> make_tuple() { return tuple<>(); } + +template +inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { + return GTEST_1_TUPLE_(T)(f0); +} + +template +inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { + return GTEST_2_TUPLE_(T)(f0, f1); +} + +template +inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { + return GTEST_3_TUPLE_(T)(f0, f1, f2); +} + +template +inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3) { + return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); +} + +template +inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4) { + return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); +} + +template +inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5) { + return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); +} + +template +inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6) { + return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); +} + +template +inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { + return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); +} + +template +inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, + const T8& f8) { + return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); +} + +template +inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, + const T8& f8, const T9& f9) { + return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); +} + +// 6.1.3.3 Tuple helper classes. + +template struct tuple_size; + +template +struct tuple_size { + static const int value = 0; +}; + +template +struct tuple_size { + static const int value = 1; +}; + +template +struct tuple_size { + static const int value = 2; +}; + +template +struct tuple_size { + static const int value = 3; +}; + +template +struct tuple_size { + static const int value = 4; +}; + +template +struct tuple_size { + static const int value = 5; +}; + +template +struct tuple_size { + static const int value = 6; +}; + +template +struct tuple_size { + static const int value = 7; +}; + +template +struct tuple_size { + static const int value = 8; +}; + +template +struct tuple_size { + static const int value = 9; +}; + +template +struct tuple_size { + static const int value = 10; +}; + +template +struct tuple_element { + typedef typename gtest_internal::TupleElement< + k < (tuple_size::value), k, Tuple>::type type; +}; + +#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type + +// 6.1.3.4 Element access. + +namespace gtest_internal { + +template <> +class Get<0> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) + Field(Tuple& t) { return t.f0_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) + ConstField(const Tuple& t) { return t.f0_; } +}; + +template <> +class Get<1> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) + Field(Tuple& t) { return t.f1_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) + ConstField(const Tuple& t) { return t.f1_; } +}; + +template <> +class Get<2> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) + Field(Tuple& t) { return t.f2_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) + ConstField(const Tuple& t) { return t.f2_; } +}; + +template <> +class Get<3> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) + Field(Tuple& t) { return t.f3_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) + ConstField(const Tuple& t) { return t.f3_; } +}; + +template <> +class Get<4> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) + Field(Tuple& t) { return t.f4_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) + ConstField(const Tuple& t) { return t.f4_; } +}; + +template <> +class Get<5> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) + Field(Tuple& t) { return t.f5_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) + ConstField(const Tuple& t) { return t.f5_; } +}; + +template <> +class Get<6> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) + Field(Tuple& t) { return t.f6_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) + ConstField(const Tuple& t) { return t.f6_; } +}; + +template <> +class Get<7> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) + Field(Tuple& t) { return t.f7_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) + ConstField(const Tuple& t) { return t.f7_; } +}; + +template <> +class Get<8> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) + Field(Tuple& t) { return t.f8_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) + ConstField(const Tuple& t) { return t.f8_; } +}; + +template <> +class Get<9> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) + Field(Tuple& t) { return t.f9_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) + ConstField(const Tuple& t) { return t.f9_; } +}; + +} // namespace gtest_internal + +template +GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(GTEST_10_TUPLE_(T)& t) { + return gtest_internal::Get::Field(t); +} + +template +GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(const GTEST_10_TUPLE_(T)& t) { + return gtest_internal::Get::ConstField(t); +} + +// 6.1.3.5 Relational operators + +// We only implement == and !=, as we don't have a need for the rest yet. + +namespace gtest_internal { + +// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the +// first k fields of t1 equals the first k fields of t2. +// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if +// k1 != k2. +template +struct SameSizeTuplePrefixComparator; + +template <> +struct SameSizeTuplePrefixComparator<0, 0> { + template + static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { + return true; + } +}; + +template +struct SameSizeTuplePrefixComparator { + template + static bool Eq(const Tuple1& t1, const Tuple2& t2) { + return SameSizeTuplePrefixComparator::Eq(t1, t2) && + ::std::tr1::get(t1) == ::std::tr1::get(t2); + } +}; + +} // namespace gtest_internal + +template +inline bool operator==(const GTEST_10_TUPLE_(T)& t, + const GTEST_10_TUPLE_(U)& u) { + return gtest_internal::SameSizeTuplePrefixComparator< + tuple_size::value, + tuple_size::value>::Eq(t, u); +} + +template +inline bool operator!=(const GTEST_10_TUPLE_(T)& t, + const GTEST_10_TUPLE_(U)& u) { return !(t == u); } + +// 6.1.4 Pairs. +// Unimplemented. + +} // namespace tr1 +} // namespace std + +#undef GTEST_0_TUPLE_ +#undef GTEST_1_TUPLE_ +#undef GTEST_2_TUPLE_ +#undef GTEST_3_TUPLE_ +#undef GTEST_4_TUPLE_ +#undef GTEST_5_TUPLE_ +#undef GTEST_6_TUPLE_ +#undef GTEST_7_TUPLE_ +#undef GTEST_8_TUPLE_ +#undef GTEST_9_TUPLE_ +#undef GTEST_10_TUPLE_ + +#undef GTEST_0_TYPENAMES_ +#undef GTEST_1_TYPENAMES_ +#undef GTEST_2_TYPENAMES_ +#undef GTEST_3_TYPENAMES_ +#undef GTEST_4_TYPENAMES_ +#undef GTEST_5_TYPENAMES_ +#undef GTEST_6_TYPENAMES_ +#undef GTEST_7_TYPENAMES_ +#undef GTEST_8_TYPENAMES_ +#undef GTEST_9_TYPENAMES_ +#undef GTEST_10_TYPENAMES_ + +#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ +#undef GTEST_BY_REF_ +#undef GTEST_ADD_REF_ +#undef GTEST_TUPLE_ELEMENT_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ +# elif GTEST_ENV_HAS_STD_TUPLE_ +# include +// C++11 puts its tuple into the ::std namespace rather than +// ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. +// This causes undefined behavior, but supported compilers react in +// the way we intend. +namespace std { +namespace tr1 { +using ::std::get; +using ::std::make_tuple; +using ::std::tuple; +using ::std::tuple_element; +using ::std::tuple_size; +} +} + +# elif GTEST_OS_SYMBIAN + +// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to +// use STLport's tuple implementation, which unfortunately doesn't +// work as the copy of STLport distributed with Symbian is incomplete. +// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to +// use its own tuple implementation. +# ifdef BOOST_HAS_TR1_TUPLE +# undef BOOST_HAS_TR1_TUPLE +# endif // BOOST_HAS_TR1_TUPLE + +// This prevents , which defines +// BOOST_HAS_TR1_TUPLE, from being #included by Boost's . +# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED +# include + +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) +// GCC 4.0+ implements tr1/tuple in the header. This does +// not conform to the TR1 spec, which requires the header to be . + +# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 +// Until version 4.3.2, gcc has a bug that causes , +// which is #included by , to not compile when RTTI is +// disabled. _TR1_FUNCTIONAL is the header guard for +// . Hence the following #define is a hack to prevent +// from being included. +# define _TR1_FUNCTIONAL 1 +# include +# undef _TR1_FUNCTIONAL // Allows the user to #include + // if he chooses to. +# else +# include // NOLINT +# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 + +# else +// If the compiler is not GCC 4.0+, we assume the user is using a +// spec-conforming TR1 implementation. +# include // NOLINT +# endif // GTEST_USE_OWN_TR1_TUPLE + +#endif // GTEST_HAS_TR1_TUPLE + +// Determines whether clone(2) is supported. +// Usually it will only be available on Linux, excluding +// Linux on the Itanium architecture. +// Also see http://linux.die.net/man/2/clone. +#ifndef GTEST_HAS_CLONE +// The user didn't tell us, so we need to figure it out. + +# if GTEST_OS_LINUX && !defined(__ia64__) +# if GTEST_OS_LINUX_ANDROID +// On Android, clone() is only available on ARM starting with Gingerbread. +# if defined(__arm__) && __ANDROID_API__ >= 9 +# define GTEST_HAS_CLONE 1 +# else +# define GTEST_HAS_CLONE 0 +# endif +# else +# define GTEST_HAS_CLONE 1 +# endif +# else +# define GTEST_HAS_CLONE 0 +# endif // GTEST_OS_LINUX && !defined(__ia64__) + +#endif // GTEST_HAS_CLONE + +// Determines whether to support stream redirection. This is used to test +// output correctness and to implement death tests. +#ifndef GTEST_HAS_STREAM_REDIRECTION +// By default, we assume that stream redirection is supported on all +// platforms except known mobile ones. +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN +# define GTEST_HAS_STREAM_REDIRECTION 0 +# else +# define GTEST_HAS_STREAM_REDIRECTION 1 +# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +#endif // GTEST_HAS_STREAM_REDIRECTION + +// Determines whether to support death tests. +// Google Test does not support death tests for VC 7.1 and earlier as +// abort() in a VC 7.1 application compiled as GUI in debug config +// pops up a dialog window that cannot be suppressed programmatically. +#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ + (GTEST_OS_MAC && !GTEST_OS_IOS) || GTEST_OS_IOS_SIMULATOR || \ + (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ + GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ + GTEST_OS_OPENBSD || GTEST_OS_QNX) +# define GTEST_HAS_DEATH_TEST 1 +# include // NOLINT +#endif + +// We don't support MSVC 7.1 with exceptions disabled now. Therefore +// all the compilers we care about are adequate for supporting +// value-parameterized tests. +#define GTEST_HAS_PARAM_TEST 1 + +// Determines whether to support type-driven tests. + +// Typed tests need and variadic macros, which GCC, VC++ 8.0, +// Sun Pro CC, IBM Visual Age, and HP aCC support. +#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ + defined(__IBMCPP__) || defined(__HP_aCC) +# define GTEST_HAS_TYPED_TEST 1 +# define GTEST_HAS_TYPED_TEST_P 1 +#endif + +// Determines whether to support Combine(). This only makes sense when +// value-parameterized tests are enabled. The implementation doesn't +// work on Sun Studio since it doesn't understand templated conversion +// operators. +#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) +# define GTEST_HAS_COMBINE 1 +#endif + +// Determines whether the system compiler uses UTF-16 for encoding wide strings. +#define GTEST_WIDE_STRING_USES_UTF16_ \ + (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) + +// Determines whether test results can be streamed to a socket. +#if GTEST_OS_LINUX +# define GTEST_CAN_STREAM_RESULTS_ 1 +#endif + +// Defines some utility macros. + +// The GNU compiler emits a warning if nested "if" statements are followed by +// an "else" statement and braces are not used to explicitly disambiguate the +// "else" binding. This leads to problems with code like: +// +// if (gate) +// ASSERT_*(condition) << "Some message"; +// +// The "switch (0) case 0:" idiom is used to suppress this. +#ifdef __INTEL_COMPILER +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ +#else +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT +#endif + +// Use this annotation at the end of a struct/class definition to +// prevent the compiler from optimizing away instances that are never +// used. This is useful when all interesting logic happens inside the +// c'tor and / or d'tor. Example: +// +// struct Foo { +// Foo() { ... } +// } GTEST_ATTRIBUTE_UNUSED_; +// +// Also use it after a variable or parameter declaration to tell the +// compiler the variable/parameter does not have to be used. +#if defined(__GNUC__) && !defined(COMPILER_ICC) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +#else +# define GTEST_ATTRIBUTE_UNUSED_ +#endif + +// A macro to disallow operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_ASSIGN_(type)\ + void operator=(type const &) + +// A macro to disallow copy constructor and operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ + type(type const &);\ + GTEST_DISALLOW_ASSIGN_(type) + +// Tell the compiler to warn about unused return values for functions declared +// with this macro. The macro should be used on function declarations +// following the argument list: +// +// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; +#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) +# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) +#else +# define GTEST_MUST_USE_RESULT_ +#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC + +// Determine whether the compiler supports Microsoft's Structured Exception +// Handling. This is supported by several Windows compilers but generally +// does not exist on any other system. +#ifndef GTEST_HAS_SEH +// The user didn't tell us, so we need to figure it out. + +# if defined(_MSC_VER) || defined(__BORLANDC__) +// These two compilers are known to support SEH. +# define GTEST_HAS_SEH 1 +# else +// Assume no SEH. +# define GTEST_HAS_SEH 0 +# endif + +#endif // GTEST_HAS_SEH + +#ifdef _MSC_VER + +# if GTEST_LINKED_AS_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllimport) +# elif GTEST_CREATE_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllexport) +# endif + +#endif // _MSC_VER + +#ifndef GTEST_API_ +# define GTEST_API_ +#endif + +#ifdef __GNUC__ +// Ask the compiler to never inline a given function. +# define GTEST_NO_INLINE_ __attribute__((noinline)) +#else +# define GTEST_NO_INLINE_ +#endif + +// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. +#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) +# define GTEST_HAS_CXXABI_H_ 1 +#else +# define GTEST_HAS_CXXABI_H_ 0 +#endif + +namespace testing { + +class Message; + +namespace internal { + +// A secret type that Google Test users don't know about. It has no +// definition on purpose. Therefore it's impossible to create a +// Secret object, which is what we want. +class Secret; + +// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time +// expression is true. For example, you could use it to verify the +// size of a static array: +// +// GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, +// content_type_names_incorrect_size); +// +// or to make sure a struct is smaller than a certain size: +// +// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); +// +// The second argument to the macro is the name of the variable. If +// the expression is false, most compilers will issue a warning/error +// containing the name of the variable. + +template +struct CompileAssert { +}; + +#define GTEST_COMPILE_ASSERT_(expr, msg) \ + typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ + msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ + +// Implementation details of GTEST_COMPILE_ASSERT_: +// +// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 +// elements (and thus is invalid) when the expression is false. +// +// - The simpler definition +// +// #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] +// +// does not work, as gcc supports variable-length arrays whose sizes +// are determined at run-time (this is gcc's extension and not part +// of the C++ standard). As a result, gcc fails to reject the +// following code with the simple definition: +// +// int foo; +// GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is +// // not a compile-time constant. +// +// - By using the type CompileAssert<(bool(expr))>, we ensures that +// expr is a compile-time constant. (Template arguments must be +// determined at compile-time.) +// +// - The outter parentheses in CompileAssert<(bool(expr))> are necessary +// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written +// +// CompileAssert +// +// instead, these compilers will refuse to compile +// +// GTEST_COMPILE_ASSERT_(5 > 0, some_message); +// +// (They seem to think the ">" in "5 > 0" marks the end of the +// template argument list.) +// +// - The array size is (bool(expr) ? 1 : -1), instead of simply +// +// ((expr) ? 1 : -1). +// +// This is to avoid running into a bug in MS VC 7.1, which +// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. + +// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. +// +// This template is declared, but intentionally undefined. +template +struct StaticAssertTypeEqHelper; + +template +struct StaticAssertTypeEqHelper {}; + +#if GTEST_HAS_GLOBAL_STRING +typedef ::string string; +#else +typedef ::std::string string; +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_GLOBAL_WSTRING +typedef ::wstring wstring; +#elif GTEST_HAS_STD_WSTRING +typedef ::std::wstring wstring; +#endif // GTEST_HAS_GLOBAL_WSTRING + +// A helper for suppressing warnings on constant condition. It just +// returns 'condition'. +GTEST_API_ bool IsTrue(bool condition); + +// Defines scoped_ptr. + +// This implementation of scoped_ptr is PARTIAL - it only contains +// enough stuff to satisfy Google Test's need. +template +class scoped_ptr { + public: + typedef T element_type; + + explicit scoped_ptr(T* p = NULL) : ptr_(p) {} + ~scoped_ptr() { reset(); } + + T& operator*() const { return *ptr_; } + T* operator->() const { return ptr_; } + T* get() const { return ptr_; } + + T* release() { + T* const ptr = ptr_; + ptr_ = NULL; + return ptr; + } + + void reset(T* p = NULL) { + if (p != ptr_) { + if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. + delete ptr_; + } + ptr_ = p; + } + } + + private: + T* ptr_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); +}; + +// Defines RE. + +// A simple C++ wrapper for . It uses the POSIX Extended +// Regular Expression syntax. +class GTEST_API_ RE { + public: + // A copy constructor is required by the Standard to initialize object + // references from r-values. + RE(const RE& other) { Init(other.pattern()); } + + // Constructs an RE from a string. + RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + + RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT + +#endif // GTEST_HAS_GLOBAL_STRING + + RE(const char* regex) { Init(regex); } // NOLINT + ~RE(); + + // Returns the string representation of the regex. + const char* pattern() const { return pattern_; } + + // FullMatch(str, re) returns true iff regular expression re matches + // the entire str. + // PartialMatch(str, re) returns true iff regular expression re + // matches a substring of str (including str itself). + // + // TODO(wan@google.com): make FullMatch() and PartialMatch() work + // when str contains NUL characters. + static bool FullMatch(const ::std::string& str, const RE& re) { + return FullMatch(str.c_str(), re); + } + static bool PartialMatch(const ::std::string& str, const RE& re) { + return PartialMatch(str.c_str(), re); + } + +#if GTEST_HAS_GLOBAL_STRING + + static bool FullMatch(const ::string& str, const RE& re) { + return FullMatch(str.c_str(), re); + } + static bool PartialMatch(const ::string& str, const RE& re) { + return PartialMatch(str.c_str(), re); + } + +#endif // GTEST_HAS_GLOBAL_STRING + + static bool FullMatch(const char* str, const RE& re); + static bool PartialMatch(const char* str, const RE& re); + + private: + void Init(const char* regex); + + // We use a const char* instead of an std::string, as Google Test used to be + // used where std::string is not available. TODO(wan@google.com): change to + // std::string. + const char* pattern_; + bool is_valid_; + +#if GTEST_USES_POSIX_RE + + regex_t full_regex_; // For FullMatch(). + regex_t partial_regex_; // For PartialMatch(). + +#else // GTEST_USES_SIMPLE_RE + + const char* full_pattern_; // For FullMatch(); + +#endif + + GTEST_DISALLOW_ASSIGN_(RE); +}; + +// Formats a source file path and a line number as they would appear +// in an error message from the compiler used to compile this code. +GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); + +// Formats a file location for compiler-independent XML output. +// Although this function is not platform dependent, we put it next to +// FormatFileLocation in order to contrast the two functions. +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, + int line); + +// Defines logging utilities: +// GTEST_LOG_(severity) - logs messages at the specified severity level. The +// message itself is streamed into the macro. +// LogToStderr() - directs all log messages to stderr. +// FlushInfoLog() - flushes informational log messages. + +enum GTestLogSeverity { + GTEST_INFO, + GTEST_WARNING, + GTEST_ERROR, + GTEST_FATAL +}; + +// Formats log entry severity, provides a stream object for streaming the +// log message, and terminates the message with a newline when going out of +// scope. +class GTEST_API_ GTestLog { + public: + GTestLog(GTestLogSeverity severity, const char* file, int line); + + // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. + ~GTestLog(); + + ::std::ostream& GetStream() { return ::std::cerr; } + + private: + const GTestLogSeverity severity_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); +}; + +#define GTEST_LOG_(severity) \ + ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ + __FILE__, __LINE__).GetStream() + +inline void LogToStderr() {} +inline void FlushInfoLog() { fflush(NULL); } + +// INTERNAL IMPLEMENTATION - DO NOT USE. +// +// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition +// is not satisfied. +// Synopsys: +// GTEST_CHECK_(boolean_condition); +// or +// GTEST_CHECK_(boolean_condition) << "Additional message"; +// +// This checks the condition and if the condition is not satisfied +// it prints message about the condition violation, including the +// condition itself, plus additional message streamed into it, if any, +// and then it aborts the program. It aborts the program irrespective of +// whether it is built in the debug mode or not. +#define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::IsTrue(condition)) \ + ; \ + else \ + GTEST_LOG_(FATAL) << "Condition " #condition " failed. " + +// An all-mode assert to verify that the given POSIX-style function +// call returns 0 (indicating success). Known limitation: this +// doesn't expand to a balanced 'if' statement, so enclose the macro +// in {} if you need to use it as the only statement in an 'if' +// branch. +#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ + if (const int gtest_error = (posix_call)) \ + GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ + << gtest_error + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Use ImplicitCast_ as a safe version of static_cast for upcasting in +// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a +// const Foo*). When you use ImplicitCast_, the compiler checks that +// the cast is safe. Such explicit ImplicitCast_s are necessary in +// surprisingly many situations where C++ demands an exact type match +// instead of an argument type convertable to a target type. +// +// The syntax for using ImplicitCast_ is the same as for static_cast: +// +// ImplicitCast_(expr) +// +// ImplicitCast_ would have been part of the C++ standard library, +// but the proposal was submitted too late. It will probably make +// its way into the language in the future. +// +// This relatively ugly name is intentional. It prevents clashes with +// similar functions users may have (e.g., implicit_cast). The internal +// namespace alone is not enough because the function can be found by ADL. +template +inline To ImplicitCast_(To x) { return x; } + +// When you upcast (that is, cast a pointer from type Foo to type +// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts +// always succeed. When you downcast (that is, cast a pointer from +// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because +// how do you know the pointer is really of type SubclassOfFoo? It +// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, +// when you downcast, you should use this macro. In debug mode, we +// use dynamic_cast<> to double-check the downcast is legal (we die +// if it's not). In normal mode, we do the efficient static_cast<> +// instead. Thus, it's important to test in debug mode to make sure +// the cast is legal! +// This is the only place in the code we should use dynamic_cast<>. +// In particular, you SHOULDN'T be using dynamic_cast<> in order to +// do RTTI (eg code like this: +// if (dynamic_cast(foo)) HandleASubclass1Object(foo); +// if (dynamic_cast(foo)) HandleASubclass2Object(foo); +// You should design the code some other way not to need this. +// +// This relatively ugly name is intentional. It prevents clashes with +// similar functions users may have (e.g., down_cast). The internal +// namespace alone is not enough because the function can be found by ADL. +template // use like this: DownCast_(foo); +inline To DownCast_(From* f) { // so we only accept pointers + // Ensures that To is a sub-type of From *. This test is here only + // for compile-time type checking, and has no overhead in an + // optimized build at run-time, as it will be optimized away + // completely. + if (false) { + const To to = NULL; + ::testing::internal::ImplicitCast_(to); + } + +#if GTEST_HAS_RTTI + // RTTI: debug mode only! + GTEST_CHECK_(f == NULL || dynamic_cast(f) != NULL); +#endif + return static_cast(f); +} + +// Downcasts the pointer of type Base to Derived. +// Derived must be a subclass of Base. The parameter MUST +// point to a class of type Derived, not any subclass of it. +// When RTTI is available, the function performs a runtime +// check to enforce this. +template +Derived* CheckedDowncastToActualType(Base* base) { +#if GTEST_HAS_RTTI + GTEST_CHECK_(typeid(*base) == typeid(Derived)); + return dynamic_cast(base); // NOLINT +#else + return static_cast(base); // Poor man's downcast. +#endif +} + +#if GTEST_HAS_STREAM_REDIRECTION + +// Defines the stderr capturer: +// CaptureStdout - starts capturing stdout. +// GetCapturedStdout - stops capturing stdout and returns the captured string. +// CaptureStderr - starts capturing stderr. +// GetCapturedStderr - stops capturing stderr and returns the captured string. +// +GTEST_API_ void CaptureStdout(); +GTEST_API_ std::string GetCapturedStdout(); +GTEST_API_ void CaptureStderr(); +GTEST_API_ std::string GetCapturedStderr(); + +#endif // GTEST_HAS_STREAM_REDIRECTION + + +#if GTEST_HAS_DEATH_TEST + +const ::std::vector& GetInjectableArgvs(); +void SetInjectableArgvs(const ::std::vector* + new_argvs); + +// A copy of all command line arguments. Set by InitGoogleTest(). +extern ::std::vector g_argvs; + +#endif // GTEST_HAS_DEATH_TEST + +// Defines synchronization primitives. + +#if GTEST_HAS_PTHREAD + +// Sleeps for (roughly) n milli-seconds. This function is only for +// testing Google Test's own constructs. Don't use it in user tests, +// either directly or indirectly. +inline void SleepMilliseconds(int n) { + const timespec time = { + 0, // 0 seconds. + n * 1000L * 1000L, // And n ms. + }; + nanosleep(&time, NULL); +} + +// Allows a controller thread to pause execution of newly created +// threads until notified. Instances of this class must be created +// and destroyed in the controller thread. +// +// This class is only for testing Google Test's own constructs. Do not +// use it in user tests, either directly or indirectly. +class Notification { + public: + Notification() : notified_(false) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + } + ~Notification() { + pthread_mutex_destroy(&mutex_); + } + + // Notifies all threads created with this notification to start. Must + // be called from the controller thread. + void Notify() { + pthread_mutex_lock(&mutex_); + notified_ = true; + pthread_mutex_unlock(&mutex_); + } + + // Blocks until the controller thread notifies. Must be called from a test + // thread. + void WaitForNotification() { + for (;;) { + pthread_mutex_lock(&mutex_); + const bool notified = notified_; + pthread_mutex_unlock(&mutex_); + if (notified) + break; + SleepMilliseconds(10); + } + } + + private: + pthread_mutex_t mutex_; + bool notified_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); +}; + +// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. +// Consequently, it cannot select a correct instantiation of ThreadWithParam +// in order to call its Run(). Introducing ThreadWithParamBase as a +// non-templated base class for ThreadWithParam allows us to bypass this +// problem. +class ThreadWithParamBase { + public: + virtual ~ThreadWithParamBase() {} + virtual void Run() = 0; +}; + +// pthread_create() accepts a pointer to a function type with the C linkage. +// According to the Standard (7.5/1), function types with different linkages +// are different even if they are otherwise identical. Some compilers (for +// example, SunStudio) treat them as different types. Since class methods +// cannot be defined with C-linkage we need to define a free C-function to +// pass into pthread_create(). +extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { + static_cast(thread)->Run(); + return NULL; +} + +// Helper class for testing Google Test's multi-threading constructs. +// To use it, write: +// +// void ThreadFunc(int param) { /* Do things with param */ } +// Notification thread_can_start; +// ... +// // The thread_can_start parameter is optional; you can supply NULL. +// ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); +// thread_can_start.Notify(); +// +// These classes are only for testing Google Test's own constructs. Do +// not use them in user tests, either directly or indirectly. +template +class ThreadWithParam : public ThreadWithParamBase { + public: + typedef void (*UserThreadFunc)(T); + + ThreadWithParam( + UserThreadFunc func, T param, Notification* thread_can_start) + : func_(func), + param_(param), + thread_can_start_(thread_can_start), + finished_(false) { + ThreadWithParamBase* const base = this; + // The thread can be created only after all fields except thread_ + // have been initialized. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); + } + ~ThreadWithParam() { Join(); } + + void Join() { + if (!finished_) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); + finished_ = true; + } + } + + virtual void Run() { + if (thread_can_start_ != NULL) + thread_can_start_->WaitForNotification(); + func_(param_); + } + + private: + const UserThreadFunc func_; // User-supplied thread function. + const T param_; // User-supplied parameter to the thread function. + // When non-NULL, used to block execution until the controller thread + // notifies. + Notification* const thread_can_start_; + bool finished_; // true iff we know that the thread function has finished. + pthread_t thread_; // The native thread object. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); +}; + +// MutexBase and Mutex implement mutex on pthreads-based platforms. They +// are used in conjunction with class MutexLock: +// +// Mutex mutex; +// ... +// MutexLock lock(&mutex); // Acquires the mutex and releases it at the end +// // of the current scope. +// +// MutexBase implements behavior for both statically and dynamically +// allocated mutexes. Do not use MutexBase directly. Instead, write +// the following to define a static mutex: +// +// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); +// +// You can forward declare a static mutex like this: +// +// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); +// +// To create a dynamic mutex, just define an object of type Mutex. +class MutexBase { + public: + // Acquires this mutex. + void Lock() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); + owner_ = pthread_self(); + has_owner_ = true; + } + + // Releases this mutex. + void Unlock() { + // Since the lock is being released the owner_ field should no longer be + // considered valid. We don't protect writing to has_owner_ here, as it's + // the caller's responsibility to ensure that the current thread holds the + // mutex when this is called. + has_owner_ = false; + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); + } + + // Does nothing if the current thread holds the mutex. Otherwise, crashes + // with high probability. + void AssertHeld() const { + GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) + << "The current thread is not holding the mutex @" << this; + } + + // A static mutex may be used before main() is entered. It may even + // be used before the dynamic initialization stage. Therefore we + // must be able to initialize a static mutex object at link time. + // This means MutexBase has to be a POD and its member variables + // have to be public. + public: + pthread_mutex_t mutex_; // The underlying pthread mutex. + // has_owner_ indicates whether the owner_ field below contains a valid thread + // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All + // accesses to the owner_ field should be protected by a check of this field. + // An alternative might be to memset() owner_ to all zeros, but there's no + // guarantee that a zero'd pthread_t is necessarily invalid or even different + // from pthread_self(). + bool has_owner_; + pthread_t owner_; // The thread holding the mutex. +}; + +// Forward-declares a static mutex. +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::MutexBase mutex + +// Defines and statically (i.e. at link time) initializes a static mutex. +// The initialization list here does not explicitly initialize each field, +// instead relying on default initialization for the unspecified fields. In +// particular, the owner_ field (a pthread_t) is not explicitly initialized. +// This allows initialization to work whether pthread_t is a scalar or struct. +// The flag -Wmissing-field-initializers must not be specified for this to work. +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false } + +// The Mutex class can only be used for mutexes created at runtime. It +// shares its API with MutexBase otherwise. +class Mutex : public MutexBase { + public: + Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + has_owner_ = false; + } + ~Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); +}; + +// We cannot name this class MutexLock as the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(MutexBase* mutex) + : mutex_(mutex) { mutex_->Lock(); } + + ~GTestMutexLock() { mutex_->Unlock(); } + + private: + MutexBase* const mutex_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); +}; + +typedef GTestMutexLock MutexLock; + +// Helpers for ThreadLocal. + +// pthread_key_create() requires DeleteThreadLocalValue() to have +// C-linkage. Therefore it cannot be templatized to access +// ThreadLocal. Hence the need for class +// ThreadLocalValueHolderBase. +class ThreadLocalValueHolderBase { + public: + virtual ~ThreadLocalValueHolderBase() {} +}; + +// Called by pthread to delete thread-local data stored by +// pthread_setspecific(). +extern "C" inline void DeleteThreadLocalValue(void* value_holder) { + delete static_cast(value_holder); +} + +// Implements thread-local storage on pthreads-based systems. +// +// // Thread 1 +// ThreadLocal tl(100); // 100 is the default value for each thread. +// +// // Thread 2 +// tl.set(150); // Changes the value for thread 2 only. +// EXPECT_EQ(150, tl.get()); +// +// // Thread 1 +// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. +// tl.set(200); +// EXPECT_EQ(200, tl.get()); +// +// The template type argument T must have a public copy constructor. +// In addition, the default ThreadLocal constructor requires T to have +// a public default constructor. +// +// An object managed for a thread by a ThreadLocal instance is deleted +// when the thread exits. Or, if the ThreadLocal instance dies in +// that thread, when the ThreadLocal dies. It's the user's +// responsibility to ensure that all other threads using a ThreadLocal +// have exited when it dies, or the per-thread objects for those +// threads will not be deleted. +// +// Google Test only uses global ThreadLocal objects. That means they +// will die after main() has returned. Therefore, no per-thread +// object managed by Google Test will be leaked as long as all threads +// using Google Test have exited when main() returns. +template +class ThreadLocal { + public: + ThreadLocal() : key_(CreateKey()), + default_() {} + explicit ThreadLocal(const T& value) : key_(CreateKey()), + default_(value) {} + + ~ThreadLocal() { + // Destroys the managed object for the current thread, if any. + DeleteThreadLocalValue(pthread_getspecific(key_)); + + // Releases resources associated with the key. This will *not* + // delete managed objects for other threads. + GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); + } + + T* pointer() { return GetOrCreateValue(); } + const T* pointer() const { return GetOrCreateValue(); } + const T& get() const { return *pointer(); } + void set(const T& value) { *pointer() = value; } + + private: + // Holds a value of type T. + class ValueHolder : public ThreadLocalValueHolderBase { + public: + explicit ValueHolder(const T& value) : value_(value) {} + + T* pointer() { return &value_; } + + private: + T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); + }; + + static pthread_key_t CreateKey() { + pthread_key_t key; + // When a thread exits, DeleteThreadLocalValue() will be called on + // the object managed for that thread. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_key_create(&key, &DeleteThreadLocalValue)); + return key; + } + + T* GetOrCreateValue() const { + ThreadLocalValueHolderBase* const holder = + static_cast(pthread_getspecific(key_)); + if (holder != NULL) { + return CheckedDowncastToActualType(holder)->pointer(); + } + + ValueHolder* const new_holder = new ValueHolder(default_); + ThreadLocalValueHolderBase* const holder_base = new_holder; + GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); + return new_holder->pointer(); + } + + // A key pthreads uses for looking up per-thread values. + const pthread_key_t key_; + const T default_; // The default value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); +}; + +# define GTEST_IS_THREADSAFE 1 + +#else // GTEST_HAS_PTHREAD + +// A dummy implementation of synchronization primitives (mutex, lock, +// and thread-local variable). Necessary for compiling Google Test where +// mutex is not supported - using Google Test in multiple threads is not +// supported on such platforms. + +class Mutex { + public: + Mutex() {} + void Lock() {} + void Unlock() {} + void AssertHeld() const {} +}; + +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex + +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex + +class GTestMutexLock { + public: + explicit GTestMutexLock(Mutex*) {} // NOLINT +}; + +typedef GTestMutexLock MutexLock; + +template +class ThreadLocal { + public: + ThreadLocal() : value_() {} + explicit ThreadLocal(const T& value) : value_(value) {} + T* pointer() { return &value_; } + const T* pointer() const { return &value_; } + const T& get() const { return value_; } + void set(const T& value) { value_ = value; } + private: + T value_; +}; + +// The above synchronization primitives have dummy implementations. +// Therefore Google Test is not thread-safe. +# define GTEST_IS_THREADSAFE 0 + +#endif // GTEST_HAS_PTHREAD + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +GTEST_API_ size_t GetThreadCount(); + +// Passing non-POD classes through ellipsis (...) crashes the ARM +// compiler and generates a warning in Sun Studio. The Nokia Symbian +// and the IBM XL C/C++ compiler try to instantiate a copy constructor +// for objects passed through ellipsis (...), failing for uncopyable +// objects. We define this to ensure that only POD is passed through +// ellipsis on these systems. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +# define GTEST_ELLIPSIS_NEEDS_POD_ 1 +#else +# define GTEST_CAN_COMPARE_NULL 1 +#endif + +// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between +// const T& and const T* in a function template. These compilers +// _can_ decide between class template specializations for T and T*, +// so a tr1::type_traits-like is_pointer works. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) +# define GTEST_NEEDS_IS_POINTER_ 1 +#endif + +template +struct bool_constant { + typedef bool_constant type; + static const bool value = bool_value; +}; +template const bool bool_constant::value; + +typedef bool_constant false_type; +typedef bool_constant true_type; + +template +struct is_pointer : public false_type {}; + +template +struct is_pointer : public true_type {}; + +template +struct IteratorTraits { + typedef typename Iterator::value_type value_type; +}; + +template +struct IteratorTraits { + typedef T value_type; +}; + +template +struct IteratorTraits { + typedef T value_type; +}; + +#if GTEST_OS_WINDOWS +# define GTEST_PATH_SEP_ "\\" +# define GTEST_HAS_ALT_PATH_SEP_ 1 +// The biggest signed integer type the compiler supports. +typedef __int64 BiggestInt; +#else +# define GTEST_PATH_SEP_ "/" +# define GTEST_HAS_ALT_PATH_SEP_ 0 +typedef long long BiggestInt; // NOLINT +#endif // GTEST_OS_WINDOWS + +// Utilities for char. + +// isspace(int ch) and friends accept an unsigned char or EOF. char +// may be signed, depending on the compiler (or compiler flags). +// Therefore we need to cast a char to unsigned char before calling +// isspace(), etc. + +inline bool IsAlpha(char ch) { + return isalpha(static_cast(ch)) != 0; +} +inline bool IsAlNum(char ch) { + return isalnum(static_cast(ch)) != 0; +} +inline bool IsDigit(char ch) { + return isdigit(static_cast(ch)) != 0; +} +inline bool IsLower(char ch) { + return islower(static_cast(ch)) != 0; +} +inline bool IsSpace(char ch) { + return isspace(static_cast(ch)) != 0; +} +inline bool IsUpper(char ch) { + return isupper(static_cast(ch)) != 0; +} +inline bool IsXDigit(char ch) { + return isxdigit(static_cast(ch)) != 0; +} +inline bool IsXDigit(wchar_t ch) { + const unsigned char low_byte = static_cast(ch); + return ch == low_byte && isxdigit(low_byte) != 0; +} + +inline char ToLower(char ch) { + return static_cast(tolower(static_cast(ch))); +} +inline char ToUpper(char ch) { + return static_cast(toupper(static_cast(ch))); +} + +// The testing::internal::posix namespace holds wrappers for common +// POSIX functions. These wrappers hide the differences between +// Windows/MSVC and POSIX systems. Since some compilers define these +// standard functions as macros, the wrapper cannot have the same name +// as the wrapped function. + +namespace posix { + +// Functions with a different name on Windows. + +#if GTEST_OS_WINDOWS + +typedef struct _stat StatStruct; + +# ifdef __BORLANDC__ +inline int IsATTY(int fd) { return isatty(fd); } +inline int StrCaseCmp(const char* s1, const char* s2) { + return stricmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +# else // !__BORLANDC__ +# if GTEST_OS_WINDOWS_MOBILE +inline int IsATTY(int /* fd */) { return 0; } +# else +inline int IsATTY(int fd) { return _isatty(fd); } +# endif // GTEST_OS_WINDOWS_MOBILE +inline int StrCaseCmp(const char* s1, const char* s2) { + return _stricmp(s1, s2); +} +inline char* StrDup(const char* src) { return _strdup(src); } +# endif // __BORLANDC__ + +# if GTEST_OS_WINDOWS_MOBILE +inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } +// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this +// time and thus not defined there. +# else +inline int FileNo(FILE* file) { return _fileno(file); } +inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } +inline int RmDir(const char* dir) { return _rmdir(dir); } +inline bool IsDir(const StatStruct& st) { + return (_S_IFDIR & st.st_mode) != 0; +} +# endif // GTEST_OS_WINDOWS_MOBILE + +#else + +typedef struct stat StatStruct; + +inline int FileNo(FILE* file) { return fileno(file); } +inline int IsATTY(int fd) { return isatty(fd); } +inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } +inline int StrCaseCmp(const char* s1, const char* s2) { + return strcasecmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +inline int RmDir(const char* dir) { return rmdir(dir); } +inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } + +#endif // GTEST_OS_WINDOWS + +// Functions deprecated by MSVC 8.0. + +#ifdef _MSC_VER +// Temporarily disable warning 4996 (deprecated function). +# pragma warning(push) +# pragma warning(disable:4996) +#endif + +inline const char* StrNCpy(char* dest, const char* src, size_t n) { + return strncpy(dest, src, n); +} + +// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and +// StrError() aren't needed on Windows CE at this time and thus not +// defined there. + +#if !GTEST_OS_WINDOWS_MOBILE +inline int ChDir(const char* dir) { return chdir(dir); } +#endif +inline FILE* FOpen(const char* path, const char* mode) { + return fopen(path, mode); +} +#if !GTEST_OS_WINDOWS_MOBILE +inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { + return freopen(path, mode, stream); +} +inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } +#endif +inline int FClose(FILE* fp) { return fclose(fp); } +#if !GTEST_OS_WINDOWS_MOBILE +inline int Read(int fd, void* buf, unsigned int count) { + return static_cast(read(fd, buf, count)); +} +inline int Write(int fd, const void* buf, unsigned int count) { + return static_cast(write(fd, buf, count)); +} +inline int Close(int fd) { return close(fd); } +inline const char* StrError(int errnum) { return strerror(errnum); } +#endif +inline const char* GetEnv(const char* name) { +#if GTEST_OS_WINDOWS_MOBILE + // We are on Windows CE, which has no environment variables. + return NULL; +#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) + // Environment variables which we programmatically clear will be set to the + // empty string rather than unset (NULL). Handle that case. + const char* const env = getenv(name); + return (env != NULL && env[0] != '\0') ? env : NULL; +#else + return getenv(name); +#endif +} + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif + +#if GTEST_OS_WINDOWS_MOBILE +// Windows CE has no C library. The abort() function is used in +// several places in Google Test. This implementation provides a reasonable +// imitation of standard behaviour. +void Abort(); +#else +inline void Abort() { abort(); } +#endif // GTEST_OS_WINDOWS_MOBILE + +} // namespace posix + +// MSVC "deprecates" snprintf and issues warnings wherever it is used. In +// order to avoid these warnings, we need to use _snprintf or _snprintf_s on +// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate +// function in order to achieve that. We use macro definition here because +// snprintf is a variadic function. +#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE +// MSVC 2005 and above support variadic macros. +# define GTEST_SNPRINTF_(buffer, size, format, ...) \ + _snprintf_s(buffer, size, size, format, __VA_ARGS__) +#elif defined(_MSC_VER) +// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't +// complain about _snprintf. +# define GTEST_SNPRINTF_ _snprintf +#else +# define GTEST_SNPRINTF_ snprintf +#endif + +// The maximum number a BiggestInt can represent. This definition +// works no matter BiggestInt is represented in one's complement or +// two's complement. +// +// We cannot rely on numeric_limits in STL, as __int64 and long long +// are not part of standard C++ and numeric_limits doesn't need to be +// defined for them. +const BiggestInt kMaxBiggestInt = + ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); + +// This template class serves as a compile-time function from size to +// type. It maps a size in bytes to a primitive type with that +// size. e.g. +// +// TypeWithSize<4>::UInt +// +// is typedef-ed to be unsigned int (unsigned integer made up of 4 +// bytes). +// +// Such functionality should belong to STL, but I cannot find it +// there. +// +// Google Test uses this class in the implementation of floating-point +// comparison. +// +// For now it only handles UInt (unsigned int) as that's all Google Test +// needs. Other types can be easily added in the future if need +// arises. +template +class TypeWithSize { + public: + // This prevents the user from using TypeWithSize with incorrect + // values of N. + typedef void UInt; +}; + +// The specialization for size 4. +template <> +class TypeWithSize<4> { + public: + // unsigned int has size 4 in both gcc and MSVC. + // + // As base/basictypes.h doesn't compile on Windows, we cannot use + // uint32, uint64, and etc here. + typedef int Int; + typedef unsigned int UInt; +}; + +// The specialization for size 8. +template <> +class TypeWithSize<8> { + public: +#if GTEST_OS_WINDOWS + typedef __int64 Int; + typedef unsigned __int64 UInt; +#else + typedef long long Int; // NOLINT + typedef unsigned long long UInt; // NOLINT +#endif // GTEST_OS_WINDOWS +}; + +// Integer types of known sizes. +typedef TypeWithSize<4>::Int Int32; +typedef TypeWithSize<4>::UInt UInt32; +typedef TypeWithSize<8>::Int Int64; +typedef TypeWithSize<8>::UInt UInt64; +typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. + +// Utilities for command line flags and environment variables. + +// Macro for referencing flags. +#define GTEST_FLAG(name) FLAGS_gtest_##name + +// Macros for declaring flags. +#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) +#define GTEST_DECLARE_int32_(name) \ + GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) +#define GTEST_DECLARE_string_(name) \ + GTEST_API_ extern ::std::string GTEST_FLAG(name) + +// Macros for defining flags. +#define GTEST_DEFINE_bool_(name, default_val, doc) \ + GTEST_API_ bool GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_int32_(name, default_val, doc) \ + GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_string_(name, default_val, doc) \ + GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) + +// Thread annotations +#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +#define GTEST_LOCK_EXCLUDED_(locks) + +// Parses 'str' for a 32-bit signed integer. If successful, writes the result +// to *value and returns true; otherwise leaves *value unchanged and returns +// false. +// TODO(chandlerc): Find a better way to refactor flag and environment parsing +// out of both gtest-port.cc and gtest.cc to avoid exporting this utility +// function. +bool ParseInt32(const Message& src_text, const char* str, Int32* value); + +// Parses a bool/Int32/string from the environment variable +// corresponding to the given Google Test flag. +bool BoolFromGTestEnv(const char* flag, bool default_val); +GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); +const char* StringFromGTestEnv(const char* flag, const char* default_val); + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ + +#if GTEST_OS_LINUX +# include +# include +# include +# include +#endif // GTEST_OS_LINUX + +#if GTEST_HAS_EXCEPTIONS +# include +#endif + +#include +#include +#include +#include +#include +#include + +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the Message class. +// +// IMPORTANT NOTE: Due to limitation of the C++ language, we have to +// leave some internal implementation details in this header file. +// They are clearly marked by comments like this: +// +// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// +// Such code is NOT meant to be used by a user directly, and is subject +// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user +// program! + +#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ +#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ + +#include + + +// Ensures that there is at least one operator<< in the global namespace. +// See Message& operator<<(...) below for why. +void operator<<(const testing::internal::Secret&, int); + +namespace testing { + +// The Message class works like an ostream repeater. +// +// Typical usage: +// +// 1. You stream a bunch of values to a Message object. +// It will remember the text in a stringstream. +// 2. Then you stream the Message object to an ostream. +// This causes the text in the Message to be streamed +// to the ostream. +// +// For example; +// +// testing::Message foo; +// foo << 1 << " != " << 2; +// std::cout << foo; +// +// will print "1 != 2". +// +// Message is not intended to be inherited from. In particular, its +// destructor is not virtual. +// +// Note that stringstream behaves differently in gcc and in MSVC. You +// can stream a NULL char pointer to it in the former, but not in the +// latter (it causes an access violation if you do). The Message +// class hides this difference by treating a NULL char pointer as +// "(null)". +class GTEST_API_ Message { + private: + // The type of basic IO manipulators (endl, ends, and flush) for + // narrow streams. + typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); + + public: + // Constructs an empty Message. + Message(); + + // Copy constructor. + Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT + *ss_ << msg.GetString(); + } + + // Constructs a Message from a C-string. + explicit Message(const char* str) : ss_(new ::std::stringstream) { + *ss_ << str; + } + +#if GTEST_OS_SYMBIAN + // Streams a value (either a pointer or not) to this object. + template + inline Message& operator <<(const T& value) { + StreamHelper(typename internal::is_pointer::type(), value); + return *this; + } +#else + // Streams a non-pointer value to this object. + template + inline Message& operator <<(const T& val) { + // Some libraries overload << for STL containers. These + // overloads are defined in the global namespace instead of ::std. + // + // C++'s symbol lookup rule (i.e. Koenig lookup) says that these + // overloads are visible in either the std namespace or the global + // namespace, but not other namespaces, including the testing + // namespace which Google Test's Message class is in. + // + // To allow STL containers (and other types that has a << operator + // defined in the global namespace) to be used in Google Test + // assertions, testing::Message must access the custom << operator + // from the global namespace. With this using declaration, + // overloads of << defined in the global namespace and those + // visible via Koenig lookup are both exposed in this function. + using ::operator <<; + *ss_ << val; + return *this; + } + + // Streams a pointer value to this object. + // + // This function is an overload of the previous one. When you + // stream a pointer to a Message, this definition will be used as it + // is more specialized. (The C++ Standard, section + // [temp.func.order].) If you stream a non-pointer, then the + // previous definition will be used. + // + // The reason for this overload is that streaming a NULL pointer to + // ostream is undefined behavior. Depending on the compiler, you + // may get "0", "(nil)", "(null)", or an access violation. To + // ensure consistent result across compilers, we always treat NULL + // as "(null)". + template + inline Message& operator <<(T* const& pointer) { // NOLINT + if (pointer == NULL) { + *ss_ << "(null)"; + } else { + *ss_ << pointer; + } + return *this; + } +#endif // GTEST_OS_SYMBIAN + + // Since the basic IO manipulators are overloaded for both narrow + // and wide streams, we have to provide this specialized definition + // of operator <<, even though its body is the same as the + // templatized version above. Without this definition, streaming + // endl or other basic IO manipulators to Message will confuse the + // compiler. + Message& operator <<(BasicNarrowIoManip val) { + *ss_ << val; + return *this; + } + + // Instead of 1/0, we want to see true/false for bool values. + Message& operator <<(bool b) { + return *this << (b ? "true" : "false"); + } + + // These two overloads allow streaming a wide C string to a Message + // using the UTF-8 encoding. + Message& operator <<(const wchar_t* wide_c_str); + Message& operator <<(wchar_t* wide_c_str); + +#if GTEST_HAS_STD_WSTRING + // Converts the given wide string to a narrow string using the UTF-8 + // encoding, and streams the result to this Message object. + Message& operator <<(const ::std::wstring& wstr); +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_GLOBAL_WSTRING + // Converts the given wide string to a narrow string using the UTF-8 + // encoding, and streams the result to this Message object. + Message& operator <<(const ::wstring& wstr); +#endif // GTEST_HAS_GLOBAL_WSTRING + + // Gets the text streamed to this object so far as an std::string. + // Each '\0' character in the buffer is replaced with "\\0". + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + std::string GetString() const; + + private: + +#if GTEST_OS_SYMBIAN + // These are needed as the Nokia Symbian Compiler cannot decide between + // const T& and const T* in a function template. The Nokia compiler _can_ + // decide between class template specializations for T and T*, so a + // tr1::type_traits-like is_pointer works, and we can overload on that. + template + inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { + if (pointer == NULL) { + *ss_ << "(null)"; + } else { + *ss_ << pointer; + } + } + template + inline void StreamHelper(internal::false_type /*is_pointer*/, + const T& value) { + // See the comments in Message& operator <<(const T&) above for why + // we need this using statement. + using ::operator <<; + *ss_ << value; + } +#endif // GTEST_OS_SYMBIAN + + // We'll hold the text streamed to this object here. + const internal::scoped_ptr< ::std::stringstream> ss_; + + // We declare (but don't implement) this to prevent the compiler + // from implementing the assignment operator. + void operator=(const Message&); +}; + +// Streams a Message to an ostream. +inline std::ostream& operator <<(std::ostream& os, const Message& sb) { + return os << sb.GetString(); +} + +namespace internal { + +// Converts a streamable value to an std::string. A NULL pointer is +// converted to "(null)". When the input value is a ::string, +// ::std::string, ::wstring, or ::std::wstring object, each NUL +// character in it is replaced with "\\0". +template +std::string StreamableToString(const T& streamable) { + return (Message() << streamable).GetString(); +} + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file declares the String class and functions used internally by +// Google Test. They are subject to change without notice. They should not used +// by code external to Google Test. +// +// This header file is #included by . +// It should not be #included by other files. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ + +#ifdef __BORLANDC__ +// string.h is not guaranteed to provide strcpy on C++ Builder. +# include +#endif + +#include +#include + + +namespace testing { +namespace internal { + +// String - an abstract class holding static string utilities. +class GTEST_API_ String { + public: + // Static utility methods + + // Clones a 0-terminated C string, allocating memory using new. The + // caller is responsible for deleting the return value using + // delete[]. Returns the cloned string, or NULL if the input is + // NULL. + // + // This is different from strdup() in string.h, which allocates + // memory using malloc(). + static const char* CloneCString(const char* c_str); + +#if GTEST_OS_WINDOWS_MOBILE + // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be + // able to pass strings to Win32 APIs on CE we need to convert them + // to 'Unicode', UTF-16. + + // Creates a UTF-16 wide string from the given ANSI string, allocating + // memory using new. The caller is responsible for deleting the return + // value using delete[]. Returns the wide string, or NULL if the + // input is NULL. + // + // The wide string is created using the ANSI codepage (CP_ACP) to + // match the behaviour of the ANSI versions of Win32 calls and the + // C runtime. + static LPCWSTR AnsiToUtf16(const char* c_str); + + // Creates an ANSI string from the given wide string, allocating + // memory using new. The caller is responsible for deleting the return + // value using delete[]. Returns the ANSI string, or NULL if the + // input is NULL. + // + // The returned string is created using the ANSI codepage (CP_ACP) to + // match the behaviour of the ANSI versions of Win32 calls and the + // C runtime. + static const char* Utf16ToAnsi(LPCWSTR utf16_str); +#endif + + // Compares two C strings. Returns true iff they have the same content. + // + // Unlike strcmp(), this function can handle NULL argument(s). A + // NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool CStringEquals(const char* lhs, const char* rhs); + + // Converts a wide C string to a String using the UTF-8 encoding. + // NULL will be converted to "(null)". If an error occurred during + // the conversion, "(failed to convert from wide string)" is + // returned. + static std::string ShowWideCString(const wchar_t* wide_c_str); + + // Compares two wide C strings. Returns true iff they have the same + // content. + // + // Unlike wcscmp(), this function can handle NULL argument(s). A + // NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); + + // Compares two C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike strcasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool CaseInsensitiveCStringEquals(const char* lhs, + const char* rhs); + + // Compares two wide C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike wcscasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL wide C string, + // including the empty string. + // NB: The implementations on different platforms slightly differ. + // On windows, this method uses _wcsicmp which compares according to LC_CTYPE + // environment variable. On GNU platform this method uses wcscasecmp + // which compares according to LC_CTYPE category of the current locale. + // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the + // current locale. + static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, + const wchar_t* rhs); + + // Returns true iff the given string ends with the given suffix, ignoring + // case. Any string is considered to end with an empty suffix. + static bool EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix); + + // Formats an int value as "%02d". + static std::string FormatIntWidth2(int value); // "%02d" for width == 2 + + // Formats an int value as "%X". + static std::string FormatHexInt(int value); + + // Formats a byte as "%02X". + static std::string FormatByte(unsigned char value); + + private: + String(); // Not meant to be instantiated. +}; // class String + +// Gets the content of the stringstream's buffer as an std::string. Each '\0' +// character in the buffer is replaced with "\\0". +GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: keith.ray@gmail.com (Keith Ray) +// +// Google Test filepath utilities +// +// This header file declares classes and functions used internally by +// Google Test. They are subject to change without notice. +// +// This file is #included in . +// Do not include this header file separately! + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ + + +namespace testing { +namespace internal { + +// FilePath - a class for file and directory pathname manipulation which +// handles platform-specific conventions (like the pathname separator). +// Used for helper functions for naming files in a directory for xml output. +// Except for Set methods, all methods are const or static, which provides an +// "immutable value object" -- useful for peace of mind. +// A FilePath with a value ending in a path separator ("like/this/") represents +// a directory, otherwise it is assumed to represent a file. In either case, +// it may or may not represent an actual file or directory in the file system. +// Names are NOT checked for syntax correctness -- no checking for illegal +// characters, malformed paths, etc. + +class GTEST_API_ FilePath { + public: + FilePath() : pathname_("") { } + FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } + + explicit FilePath(const std::string& pathname) : pathname_(pathname) { + Normalize(); + } + + FilePath& operator=(const FilePath& rhs) { + Set(rhs); + return *this; + } + + void Set(const FilePath& rhs) { + pathname_ = rhs.pathname_; + } + + const std::string& string() const { return pathname_; } + const char* c_str() const { return pathname_.c_str(); } + + // Returns the current working directory, or "" if unsuccessful. + static FilePath GetCurrentDir(); + + // Given directory = "dir", base_name = "test", number = 0, + // extension = "xml", returns "dir/test.xml". If number is greater + // than zero (e.g., 12), returns "dir/test_12.xml". + // On Windows platform, uses \ as the separator rather than /. + static FilePath MakeFileName(const FilePath& directory, + const FilePath& base_name, + int number, + const char* extension); + + // Given directory = "dir", relative_path = "test.xml", + // returns "dir/test.xml". + // On Windows, uses \ as the separator rather than /. + static FilePath ConcatPaths(const FilePath& directory, + const FilePath& relative_path); + + // Returns a pathname for a file that does not currently exist. The pathname + // will be directory/base_name.extension or + // directory/base_name_.extension if directory/base_name.extension + // already exists. The number will be incremented until a pathname is found + // that does not already exist. + // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. + // There could be a race condition if two or more processes are calling this + // function at the same time -- they could both pick the same filename. + static FilePath GenerateUniqueFileName(const FilePath& directory, + const FilePath& base_name, + const char* extension); + + // Returns true iff the path is "". + bool IsEmpty() const { return pathname_.empty(); } + + // If input name has a trailing separator character, removes it and returns + // the name, otherwise return the name string unmodified. + // On Windows platform, uses \ as the separator, other platforms use /. + FilePath RemoveTrailingPathSeparator() const; + + // Returns a copy of the FilePath with the directory part removed. + // Example: FilePath("path/to/file").RemoveDirectoryName() returns + // FilePath("file"). If there is no directory part ("just_a_file"), it returns + // the FilePath unmodified. If there is no file part ("just_a_dir/") it + // returns an empty FilePath (""). + // On Windows platform, '\' is the path separator, otherwise it is '/'. + FilePath RemoveDirectoryName() const; + + // RemoveFileName returns the directory path with the filename removed. + // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". + // If the FilePath is "a_file" or "/a_file", RemoveFileName returns + // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does + // not have a file, like "just/a/dir/", it returns the FilePath unmodified. + // On Windows platform, '\' is the path separator, otherwise it is '/'. + FilePath RemoveFileName() const; + + // Returns a copy of the FilePath with the case-insensitive extension removed. + // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns + // FilePath("dir/file"). If a case-insensitive extension is not + // found, returns a copy of the original FilePath. + FilePath RemoveExtension(const char* extension) const; + + // Creates directories so that path exists. Returns true if successful or if + // the directories already exist; returns false if unable to create + // directories for any reason. Will also return false if the FilePath does + // not represent a directory (that is, it doesn't end with a path separator). + bool CreateDirectoriesRecursively() const; + + // Create the directory so that path exists. Returns true if successful or + // if the directory already exists; returns false if unable to create the + // directory for any reason, including if the parent directory does not + // exist. Not named "CreateDirectory" because that's a macro on Windows. + bool CreateFolder() const; + + // Returns true if FilePath describes something in the file-system, + // either a file, directory, or whatever, and that something exists. + bool FileOrDirectoryExists() const; + + // Returns true if pathname describes a directory in the file-system + // that exists. + bool DirectoryExists() const; + + // Returns true if FilePath ends with a path separator, which indicates that + // it is intended to represent a directory. Returns false otherwise. + // This does NOT check that a directory (or file) actually exists. + bool IsDirectory() const; + + // Returns true if pathname describes a root directory. (Windows has one + // root directory per disk drive.) + bool IsRootDirectory() const; + + // Returns true if pathname describes an absolute path. + bool IsAbsolutePath() const; + + private: + // Replaces multiple consecutive separators with a single separator. + // For example, "bar///foo" becomes "bar/foo". Does not eliminate other + // redundancies that might be in a pathname involving "." or "..". + // + // A pathname with multiple consecutive separators may occur either through + // user error or as a result of some scripts or APIs that generate a pathname + // with a trailing separator. On other platforms the same API or script + // may NOT generate a pathname with a trailing "/". Then elsewhere that + // pathname may have another "/" and pathname components added to it, + // without checking for the separator already being there. + // The script language and operating system may allow paths like "foo//bar" + // but some of the functions in FilePath will not handle that correctly. In + // particular, RemoveTrailingPathSeparator() only removes one separator, and + // it is called in CreateDirectoriesRecursively() assuming that it will change + // a pathname from directory syntax (trailing separator) to filename syntax. + // + // On Windows this method also replaces the alternate path separator '/' with + // the primary path separator '\\', so that for example "bar\\/\\foo" becomes + // "bar\\foo". + + void Normalize(); + + // Returns a pointer to the last occurence of a valid path separator in + // the FilePath. On Windows, for example, both '/' and '\' are valid path + // separators. Returns NULL if no path separator was found. + const char* FindLastPathSeparator() const; + + std::string pathname_; +}; // class FilePath + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ +// This file was GENERATED by command: +// pump.py gtest-type-util.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Type utilities needed for implementing typed and type-parameterized +// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently we support at most 50 types in a list, and at most 50 +// type-parameterized tests in one type-parameterized test case. +// Please contact googletestframework@googlegroups.com if you need +// more. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ + + +// #ifdef __GNUC__ is too general here. It is possible to use gcc without using +// libstdc++ (which is where cxxabi.h comes from). +# if GTEST_HAS_CXXABI_H_ +# include +# elif defined(__HP_aCC) +# include +# endif // GTEST_HASH_CXXABI_H_ + +namespace testing { +namespace internal { + +// GetTypeName() returns a human-readable name of type T. +// NB: This function is also used in Google Mock, so don't move it inside of +// the typed-test-only section below. +template +std::string GetTypeName() { +# if GTEST_HAS_RTTI + + const char* const name = typeid(T).name(); +# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) + int status = 0; + // gcc's implementation of typeid(T).name() mangles the type name, + // so we have to demangle it. +# if GTEST_HAS_CXXABI_H_ + using abi::__cxa_demangle; +# endif // GTEST_HAS_CXXABI_H_ + char* const readable_name = __cxa_demangle(name, 0, 0, &status); + const std::string name_str(status == 0 ? readable_name : name); + free(readable_name); + return name_str; +# else + return name; +# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC + +# else + + return ""; + +# endif // GTEST_HAS_RTTI +} + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// AssertyTypeEq::type is defined iff T1 and T2 are the same +// type. This can be used as a compile-time assertion to ensure that +// two types are equal. + +template +struct AssertTypeEq; + +template +struct AssertTypeEq { + typedef bool type; +}; + +// A unique type used as the default value for the arguments of class +// template Types. This allows us to simulate variadic templates +// (e.g. Types, Type, and etc), which C++ doesn't +// support directly. +struct None {}; + +// The following family of struct and struct templates are used to +// represent type lists. In particular, TypesN +// represents a type list with N types (T1, T2, ..., and TN) in it. +// Except for Types0, every struct in the family has two member types: +// Head for the first type in the list, and Tail for the rest of the +// list. + +// The empty type list. +struct Types0 {}; + +// Type lists of length 1, 2, 3, and so on. + +template +struct Types1 { + typedef T1 Head; + typedef Types0 Tail; +}; +template +struct Types2 { + typedef T1 Head; + typedef Types1 Tail; +}; + +template +struct Types3 { + typedef T1 Head; + typedef Types2 Tail; +}; + +template +struct Types4 { + typedef T1 Head; + typedef Types3 Tail; +}; + +template +struct Types5 { + typedef T1 Head; + typedef Types4 Tail; +}; + +template +struct Types6 { + typedef T1 Head; + typedef Types5 Tail; +}; + +template +struct Types7 { + typedef T1 Head; + typedef Types6 Tail; +}; + +template +struct Types8 { + typedef T1 Head; + typedef Types7 Tail; +}; + +template +struct Types9 { + typedef T1 Head; + typedef Types8 Tail; +}; + +template +struct Types10 { + typedef T1 Head; + typedef Types9 Tail; +}; + +template +struct Types11 { + typedef T1 Head; + typedef Types10 Tail; +}; + +template +struct Types12 { + typedef T1 Head; + typedef Types11 Tail; +}; + +template +struct Types13 { + typedef T1 Head; + typedef Types12 Tail; +}; + +template +struct Types14 { + typedef T1 Head; + typedef Types13 Tail; +}; + +template +struct Types15 { + typedef T1 Head; + typedef Types14 Tail; +}; + +template +struct Types16 { + typedef T1 Head; + typedef Types15 Tail; +}; + +template +struct Types17 { + typedef T1 Head; + typedef Types16 Tail; +}; + +template +struct Types18 { + typedef T1 Head; + typedef Types17 Tail; +}; + +template +struct Types19 { + typedef T1 Head; + typedef Types18 Tail; +}; + +template +struct Types20 { + typedef T1 Head; + typedef Types19 Tail; +}; + +template +struct Types21 { + typedef T1 Head; + typedef Types20 Tail; +}; + +template +struct Types22 { + typedef T1 Head; + typedef Types21 Tail; +}; + +template +struct Types23 { + typedef T1 Head; + typedef Types22 Tail; +}; + +template +struct Types24 { + typedef T1 Head; + typedef Types23 Tail; +}; + +template +struct Types25 { + typedef T1 Head; + typedef Types24 Tail; +}; + +template +struct Types26 { + typedef T1 Head; + typedef Types25 Tail; +}; + +template +struct Types27 { + typedef T1 Head; + typedef Types26 Tail; +}; + +template +struct Types28 { + typedef T1 Head; + typedef Types27 Tail; +}; + +template +struct Types29 { + typedef T1 Head; + typedef Types28 Tail; +}; + +template +struct Types30 { + typedef T1 Head; + typedef Types29 Tail; +}; + +template +struct Types31 { + typedef T1 Head; + typedef Types30 Tail; +}; + +template +struct Types32 { + typedef T1 Head; + typedef Types31 Tail; +}; + +template +struct Types33 { + typedef T1 Head; + typedef Types32 Tail; +}; + +template +struct Types34 { + typedef T1 Head; + typedef Types33 Tail; +}; + +template +struct Types35 { + typedef T1 Head; + typedef Types34 Tail; +}; + +template +struct Types36 { + typedef T1 Head; + typedef Types35 Tail; +}; + +template +struct Types37 { + typedef T1 Head; + typedef Types36 Tail; +}; + +template +struct Types38 { + typedef T1 Head; + typedef Types37 Tail; +}; + +template +struct Types39 { + typedef T1 Head; + typedef Types38 Tail; +}; + +template +struct Types40 { + typedef T1 Head; + typedef Types39 Tail; +}; + +template +struct Types41 { + typedef T1 Head; + typedef Types40 Tail; +}; + +template +struct Types42 { + typedef T1 Head; + typedef Types41 Tail; +}; + +template +struct Types43 { + typedef T1 Head; + typedef Types42 Tail; +}; + +template +struct Types44 { + typedef T1 Head; + typedef Types43 Tail; +}; + +template +struct Types45 { + typedef T1 Head; + typedef Types44 Tail; +}; + +template +struct Types46 { + typedef T1 Head; + typedef Types45 Tail; +}; + +template +struct Types47 { + typedef T1 Head; + typedef Types46 Tail; +}; + +template +struct Types48 { + typedef T1 Head; + typedef Types47 Tail; +}; + +template +struct Types49 { + typedef T1 Head; + typedef Types48 Tail; +}; + +template +struct Types50 { + typedef T1 Head; + typedef Types49 Tail; +}; + + +} // namespace internal + +// We don't want to require the users to write TypesN<...> directly, +// as that would require them to count the length. Types<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Types +// will appear as Types in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Types, and Google Test will translate +// that to TypesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Types template. +template +struct Types { + typedef internal::Types50 type; +}; + +template <> +struct Types { + typedef internal::Types0 type; +}; +template +struct Types { + typedef internal::Types1 type; +}; +template +struct Types { + typedef internal::Types2 type; +}; +template +struct Types { + typedef internal::Types3 type; +}; +template +struct Types { + typedef internal::Types4 type; +}; +template +struct Types { + typedef internal::Types5 type; +}; +template +struct Types { + typedef internal::Types6 type; +}; +template +struct Types { + typedef internal::Types7 type; +}; +template +struct Types { + typedef internal::Types8 type; +}; +template +struct Types { + typedef internal::Types9 type; +}; +template +struct Types { + typedef internal::Types10 type; +}; +template +struct Types { + typedef internal::Types11 type; +}; +template +struct Types { + typedef internal::Types12 type; +}; +template +struct Types { + typedef internal::Types13 type; +}; +template +struct Types { + typedef internal::Types14 type; +}; +template +struct Types { + typedef internal::Types15 type; +}; +template +struct Types { + typedef internal::Types16 type; +}; +template +struct Types { + typedef internal::Types17 type; +}; +template +struct Types { + typedef internal::Types18 type; +}; +template +struct Types { + typedef internal::Types19 type; +}; +template +struct Types { + typedef internal::Types20 type; +}; +template +struct Types { + typedef internal::Types21 type; +}; +template +struct Types { + typedef internal::Types22 type; +}; +template +struct Types { + typedef internal::Types23 type; +}; +template +struct Types { + typedef internal::Types24 type; +}; +template +struct Types { + typedef internal::Types25 type; +}; +template +struct Types { + typedef internal::Types26 type; +}; +template +struct Types { + typedef internal::Types27 type; +}; +template +struct Types { + typedef internal::Types28 type; +}; +template +struct Types { + typedef internal::Types29 type; +}; +template +struct Types { + typedef internal::Types30 type; +}; +template +struct Types { + typedef internal::Types31 type; +}; +template +struct Types { + typedef internal::Types32 type; +}; +template +struct Types { + typedef internal::Types33 type; +}; +template +struct Types { + typedef internal::Types34 type; +}; +template +struct Types { + typedef internal::Types35 type; +}; +template +struct Types { + typedef internal::Types36 type; +}; +template +struct Types { + typedef internal::Types37 type; +}; +template +struct Types { + typedef internal::Types38 type; +}; +template +struct Types { + typedef internal::Types39 type; +}; +template +struct Types { + typedef internal::Types40 type; +}; +template +struct Types { + typedef internal::Types41 type; +}; +template +struct Types { + typedef internal::Types42 type; +}; +template +struct Types { + typedef internal::Types43 type; +}; +template +struct Types { + typedef internal::Types44 type; +}; +template +struct Types { + typedef internal::Types45 type; +}; +template +struct Types { + typedef internal::Types46 type; +}; +template +struct Types { + typedef internal::Types47 type; +}; +template +struct Types { + typedef internal::Types48 type; +}; +template +struct Types { + typedef internal::Types49 type; +}; + +namespace internal { + +# define GTEST_TEMPLATE_ template class + +// The template "selector" struct TemplateSel is used to +// represent Tmpl, which must be a class template with one type +// parameter, as a type. TemplateSel::Bind::type is defined +// as the type Tmpl. This allows us to actually instantiate the +// template "selected" by TemplateSel. +// +// This trick is necessary for simulating typedef for class templates, +// which C++ doesn't support directly. +template +struct TemplateSel { + template + struct Bind { + typedef Tmpl type; + }; +}; + +# define GTEST_BIND_(TmplSel, T) \ + TmplSel::template Bind::type + +// A unique struct template used as the default value for the +// arguments of class template Templates. This allows us to simulate +// variadic templates (e.g. Templates, Templates, +// and etc), which C++ doesn't support directly. +template +struct NoneT {}; + +// The following family of struct and struct templates are used to +// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except +// for Templates0, every struct in the family has two member types: +// Head for the selector of the first template in the list, and Tail +// for the rest of the list. + +// The empty template list. +struct Templates0 {}; + +// Template lists of length 1, 2, 3, and so on. + +template +struct Templates1 { + typedef TemplateSel Head; + typedef Templates0 Tail; +}; +template +struct Templates2 { + typedef TemplateSel Head; + typedef Templates1 Tail; +}; + +template +struct Templates3 { + typedef TemplateSel Head; + typedef Templates2 Tail; +}; + +template +struct Templates4 { + typedef TemplateSel Head; + typedef Templates3 Tail; +}; + +template +struct Templates5 { + typedef TemplateSel Head; + typedef Templates4 Tail; +}; + +template +struct Templates6 { + typedef TemplateSel Head; + typedef Templates5 Tail; +}; + +template +struct Templates7 { + typedef TemplateSel Head; + typedef Templates6 Tail; +}; + +template +struct Templates8 { + typedef TemplateSel Head; + typedef Templates7 Tail; +}; + +template +struct Templates9 { + typedef TemplateSel Head; + typedef Templates8 Tail; +}; + +template +struct Templates10 { + typedef TemplateSel Head; + typedef Templates9 Tail; +}; + +template +struct Templates11 { + typedef TemplateSel Head; + typedef Templates10 Tail; +}; + +template +struct Templates12 { + typedef TemplateSel Head; + typedef Templates11 Tail; +}; + +template +struct Templates13 { + typedef TemplateSel Head; + typedef Templates12 Tail; +}; + +template +struct Templates14 { + typedef TemplateSel Head; + typedef Templates13 Tail; +}; + +template +struct Templates15 { + typedef TemplateSel Head; + typedef Templates14 Tail; +}; + +template +struct Templates16 { + typedef TemplateSel Head; + typedef Templates15 Tail; +}; + +template +struct Templates17 { + typedef TemplateSel Head; + typedef Templates16 Tail; +}; + +template +struct Templates18 { + typedef TemplateSel Head; + typedef Templates17 Tail; +}; + +template +struct Templates19 { + typedef TemplateSel Head; + typedef Templates18 Tail; +}; + +template +struct Templates20 { + typedef TemplateSel Head; + typedef Templates19 Tail; +}; + +template +struct Templates21 { + typedef TemplateSel Head; + typedef Templates20 Tail; +}; + +template +struct Templates22 { + typedef TemplateSel Head; + typedef Templates21 Tail; +}; + +template +struct Templates23 { + typedef TemplateSel Head; + typedef Templates22 Tail; +}; + +template +struct Templates24 { + typedef TemplateSel Head; + typedef Templates23 Tail; +}; + +template +struct Templates25 { + typedef TemplateSel Head; + typedef Templates24 Tail; +}; + +template +struct Templates26 { + typedef TemplateSel Head; + typedef Templates25 Tail; +}; + +template +struct Templates27 { + typedef TemplateSel Head; + typedef Templates26 Tail; +}; + +template +struct Templates28 { + typedef TemplateSel Head; + typedef Templates27 Tail; +}; + +template +struct Templates29 { + typedef TemplateSel Head; + typedef Templates28 Tail; +}; + +template +struct Templates30 { + typedef TemplateSel Head; + typedef Templates29 Tail; +}; + +template +struct Templates31 { + typedef TemplateSel Head; + typedef Templates30 Tail; +}; + +template +struct Templates32 { + typedef TemplateSel Head; + typedef Templates31 Tail; +}; + +template +struct Templates33 { + typedef TemplateSel Head; + typedef Templates32 Tail; +}; + +template +struct Templates34 { + typedef TemplateSel Head; + typedef Templates33 Tail; +}; + +template +struct Templates35 { + typedef TemplateSel Head; + typedef Templates34 Tail; +}; + +template +struct Templates36 { + typedef TemplateSel Head; + typedef Templates35 Tail; +}; + +template +struct Templates37 { + typedef TemplateSel Head; + typedef Templates36 Tail; +}; + +template +struct Templates38 { + typedef TemplateSel Head; + typedef Templates37 Tail; +}; + +template +struct Templates39 { + typedef TemplateSel Head; + typedef Templates38 Tail; +}; + +template +struct Templates40 { + typedef TemplateSel Head; + typedef Templates39 Tail; +}; + +template +struct Templates41 { + typedef TemplateSel Head; + typedef Templates40 Tail; +}; + +template +struct Templates42 { + typedef TemplateSel Head; + typedef Templates41 Tail; +}; + +template +struct Templates43 { + typedef TemplateSel Head; + typedef Templates42 Tail; +}; + +template +struct Templates44 { + typedef TemplateSel Head; + typedef Templates43 Tail; +}; + +template +struct Templates45 { + typedef TemplateSel Head; + typedef Templates44 Tail; +}; + +template +struct Templates46 { + typedef TemplateSel Head; + typedef Templates45 Tail; +}; + +template +struct Templates47 { + typedef TemplateSel Head; + typedef Templates46 Tail; +}; + +template +struct Templates48 { + typedef TemplateSel Head; + typedef Templates47 Tail; +}; + +template +struct Templates49 { + typedef TemplateSel Head; + typedef Templates48 Tail; +}; + +template +struct Templates50 { + typedef TemplateSel Head; + typedef Templates49 Tail; +}; + + +// We don't want to require the users to write TemplatesN<...> directly, +// as that would require them to count the length. Templates<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Templates +// will appear as Templates in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Templates, and Google Test will translate +// that to TemplatesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Templates template. +template +struct Templates { + typedef Templates50 type; +}; + +template <> +struct Templates { + typedef Templates0 type; +}; +template +struct Templates { + typedef Templates1 type; +}; +template +struct Templates { + typedef Templates2 type; +}; +template +struct Templates { + typedef Templates3 type; +}; +template +struct Templates { + typedef Templates4 type; +}; +template +struct Templates { + typedef Templates5 type; +}; +template +struct Templates { + typedef Templates6 type; +}; +template +struct Templates { + typedef Templates7 type; +}; +template +struct Templates { + typedef Templates8 type; +}; +template +struct Templates { + typedef Templates9 type; +}; +template +struct Templates { + typedef Templates10 type; +}; +template +struct Templates { + typedef Templates11 type; +}; +template +struct Templates { + typedef Templates12 type; +}; +template +struct Templates { + typedef Templates13 type; +}; +template +struct Templates { + typedef Templates14 type; +}; +template +struct Templates { + typedef Templates15 type; +}; +template +struct Templates { + typedef Templates16 type; +}; +template +struct Templates { + typedef Templates17 type; +}; +template +struct Templates { + typedef Templates18 type; +}; +template +struct Templates { + typedef Templates19 type; +}; +template +struct Templates { + typedef Templates20 type; +}; +template +struct Templates { + typedef Templates21 type; +}; +template +struct Templates { + typedef Templates22 type; +}; +template +struct Templates { + typedef Templates23 type; +}; +template +struct Templates { + typedef Templates24 type; +}; +template +struct Templates { + typedef Templates25 type; +}; +template +struct Templates { + typedef Templates26 type; +}; +template +struct Templates { + typedef Templates27 type; +}; +template +struct Templates { + typedef Templates28 type; +}; +template +struct Templates { + typedef Templates29 type; +}; +template +struct Templates { + typedef Templates30 type; +}; +template +struct Templates { + typedef Templates31 type; +}; +template +struct Templates { + typedef Templates32 type; +}; +template +struct Templates { + typedef Templates33 type; +}; +template +struct Templates { + typedef Templates34 type; +}; +template +struct Templates { + typedef Templates35 type; +}; +template +struct Templates { + typedef Templates36 type; +}; +template +struct Templates { + typedef Templates37 type; +}; +template +struct Templates { + typedef Templates38 type; +}; +template +struct Templates { + typedef Templates39 type; +}; +template +struct Templates { + typedef Templates40 type; +}; +template +struct Templates { + typedef Templates41 type; +}; +template +struct Templates { + typedef Templates42 type; +}; +template +struct Templates { + typedef Templates43 type; +}; +template +struct Templates { + typedef Templates44 type; +}; +template +struct Templates { + typedef Templates45 type; +}; +template +struct Templates { + typedef Templates46 type; +}; +template +struct Templates { + typedef Templates47 type; +}; +template +struct Templates { + typedef Templates48 type; +}; +template +struct Templates { + typedef Templates49 type; +}; + +// The TypeList template makes it possible to use either a single type +// or a Types<...> list in TYPED_TEST_CASE() and +// INSTANTIATE_TYPED_TEST_CASE_P(). + +template +struct TypeList { + typedef Types1 type; +}; + +template +struct TypeList > { + typedef typename Types::type type; +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ + +// Due to C++ preprocessor weirdness, we need double indirection to +// concatenate two tokens when one of them is __LINE__. Writing +// +// foo ## __LINE__ +// +// will result in the token foo__LINE__, instead of foo followed by +// the current line number. For more details, see +// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 +#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) +#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar + +class ProtocolMessage; +namespace proto2 { class Message; } + +namespace testing { + +// Forward declarations. + +class AssertionResult; // Result of an assertion. +class Message; // Represents a failure message. +class Test; // Represents a test. +class TestInfo; // Information about a test. +class TestPartResult; // Result of a test part. +class UnitTest; // A collection of test cases. + +template +::std::string PrintToString(const T& value); + +namespace internal { + +struct TraceInfo; // Information about a trace point. +class ScopedTrace; // Implements scoped trace. +class TestInfoImpl; // Opaque implementation of TestInfo +class UnitTestImpl; // Opaque implementation of UnitTest + +// How many times InitGoogleTest() has been called. +GTEST_API_ extern int g_init_gtest_count; + +// The text used in failure messages to indicate the start of the +// stack trace. +GTEST_API_ extern const char kStackTraceMarker[]; + +// Two overloaded helpers for checking at compile time whether an +// expression is a null pointer literal (i.e. NULL or any 0-valued +// compile-time integral constant). Their return values have +// different sizes, so we can use sizeof() to test which version is +// picked by the compiler. These helpers have no implementations, as +// we only need their signatures. +// +// Given IsNullLiteralHelper(x), the compiler will pick the first +// version if x can be implicitly converted to Secret*, and pick the +// second version otherwise. Since Secret is a secret and incomplete +// type, the only expression a user can write that has type Secret* is +// a null pointer literal. Therefore, we know that x is a null +// pointer literal if and only if the first version is picked by the +// compiler. +char IsNullLiteralHelper(Secret* p); +char (&IsNullLiteralHelper(...))[2]; // NOLINT + +// A compile-time bool constant that is true if and only if x is a +// null pointer literal (i.e. NULL or any 0-valued compile-time +// integral constant). +#ifdef GTEST_ELLIPSIS_NEEDS_POD_ +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +# define GTEST_IS_NULL_LITERAL_(x) false +#else +# define GTEST_IS_NULL_LITERAL_(x) \ + (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) +#endif // GTEST_ELLIPSIS_NEEDS_POD_ + +// Appends the user-supplied message to the Google-Test-generated message. +GTEST_API_ std::string AppendUserMessage( + const std::string& gtest_msg, const Message& user_msg); + +#if GTEST_HAS_EXCEPTIONS + +// This exception is thrown by (and only by) a failed Google Test +// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions +// are enabled). We derive it from std::runtime_error, which is for +// errors presumably detectable only at run time. Since +// std::runtime_error inherits from std::exception, many testing +// frameworks know how to extract and print the message inside it. +class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { + public: + explicit GoogleTestFailureException(const TestPartResult& failure); +}; + +#endif // GTEST_HAS_EXCEPTIONS + +// A helper class for creating scoped traces in user programs. +class GTEST_API_ ScopedTrace { + public: + // The c'tor pushes the given source file location and message onto + // a trace stack maintained by Google Test. + ScopedTrace(const char* file, int line, const Message& message); + + // The d'tor pops the info pushed by the c'tor. + // + // Note that the d'tor is not virtual in order to be efficient. + // Don't inherit from ScopedTrace! + ~ScopedTrace(); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); +} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its + // c'tor and d'tor. Therefore it doesn't + // need to be used otherwise. + +// Constructs and returns the message for an equality assertion +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. +// +// The first four parameters are the expressions used in the assertion +// and their values, as strings. For example, for ASSERT_EQ(foo, bar) +// where foo is 5 and bar is 6, we have: +// +// expected_expression: "foo" +// actual_expression: "bar" +// expected_value: "5" +// actual_value: "6" +// +// The ignoring_case parameter is true iff the assertion is a +// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will +// be inserted into the message. +GTEST_API_ AssertionResult EqFailure(const char* expected_expression, + const char* actual_expression, + const std::string& expected_value, + const std::string& actual_value, + bool ignoring_case); + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +GTEST_API_ std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value); + +// This template class represents an IEEE floating-point number +// (either single-precision or double-precision, depending on the +// template parameters). +// +// The purpose of this class is to do more sophisticated number +// comparison. (Due to round-off error, etc, it's very unlikely that +// two floating-points will be equal exactly. Hence a naive +// comparison by the == operation often doesn't work.) +// +// Format of IEEE floating-point: +// +// The most-significant bit being the leftmost, an IEEE +// floating-point looks like +// +// sign_bit exponent_bits fraction_bits +// +// Here, sign_bit is a single bit that designates the sign of the +// number. +// +// For float, there are 8 exponent bits and 23 fraction bits. +// +// For double, there are 11 exponent bits and 52 fraction bits. +// +// More details can be found at +// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. +// +// Template parameter: +// +// RawType: the raw floating-point type (either float or double) +template +class FloatingPoint { + public: + // Defines the unsigned integer type that has the same size as the + // floating point number. + typedef typename TypeWithSize::UInt Bits; + + // Constants. + + // # of bits in a number. + static const size_t kBitCount = 8*sizeof(RawType); + + // # of fraction bits in a number. + static const size_t kFractionBitCount = + std::numeric_limits::digits - 1; + + // # of exponent bits in a number. + static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; + + // The mask for the sign bit. + static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); + + // The mask for the fraction bits. + static const Bits kFractionBitMask = + ~static_cast(0) >> (kExponentBitCount + 1); + + // The mask for the exponent bits. + static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); + + // How many ULP's (Units in the Last Place) we want to tolerate when + // comparing two numbers. The larger the value, the more error we + // allow. A 0 value means that two numbers must be exactly the same + // to be considered equal. + // + // The maximum error of a single floating-point operation is 0.5 + // units in the last place. On Intel CPU's, all floating-point + // calculations are done with 80-bit precision, while double has 64 + // bits. Therefore, 4 should be enough for ordinary use. + // + // See the following article for more details on ULP: + // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + static const size_t kMaxUlps = 4; + + // Constructs a FloatingPoint from a raw floating-point number. + // + // On an Intel CPU, passing a non-normalized NAN (Not a Number) + // around may change its bits, although the new value is guaranteed + // to be also a NAN. Therefore, don't expect this constructor to + // preserve the bits in x when x is a NAN. + explicit FloatingPoint(const RawType& x) { u_.value_ = x; } + + // Static methods + + // Reinterprets a bit pattern as a floating-point number. + // + // This function is needed to test the AlmostEquals() method. + static RawType ReinterpretBits(const Bits bits) { + FloatingPoint fp(0); + fp.u_.bits_ = bits; + return fp.u_.value_; + } + + // Returns the floating-point number that represent positive infinity. + static RawType Infinity() { + return ReinterpretBits(kExponentBitMask); + } + + // Returns the maximum representable finite floating-point number. + static RawType Max(); + + // Non-static methods + + // Returns the bits that represents this number. + const Bits &bits() const { return u_.bits_; } + + // Returns the exponent bits of this number. + Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } + + // Returns the fraction bits of this number. + Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } + + // Returns the sign bit of this number. + Bits sign_bit() const { return kSignBitMask & u_.bits_; } + + // Returns true iff this is NAN (not a number). + bool is_nan() const { + // It's a NAN if the exponent bits are all ones and the fraction + // bits are not entirely zeros. + return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); + } + + // Returns true iff this number is at most kMaxUlps ULP's away from + // rhs. In particular, this function: + // + // - returns false if either number is (or both are) NAN. + // - treats really large numbers as almost equal to infinity. + // - thinks +0.0 and -0.0 are 0 DLP's apart. + bool AlmostEquals(const FloatingPoint& rhs) const { + // The IEEE standard says that any comparison operation involving + // a NAN must return false. + if (is_nan() || rhs.is_nan()) return false; + + return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) + <= kMaxUlps; + } + + private: + // The data type used to store the actual floating-point number. + union FloatingPointUnion { + RawType value_; // The raw floating-point number. + Bits bits_; // The bits that represent the number. + }; + + // Converts an integer from the sign-and-magnitude representation to + // the biased representation. More precisely, let N be 2 to the + // power of (kBitCount - 1), an integer x is represented by the + // unsigned number x + N. + // + // For instance, + // + // -N + 1 (the most negative number representable using + // sign-and-magnitude) is represented by 1; + // 0 is represented by N; and + // N - 1 (the biggest number representable using + // sign-and-magnitude) is represented by 2N - 1. + // + // Read http://en.wikipedia.org/wiki/Signed_number_representations + // for more details on signed number representations. + static Bits SignAndMagnitudeToBiased(const Bits &sam) { + if (kSignBitMask & sam) { + // sam represents a negative number. + return ~sam + 1; + } else { + // sam represents a positive number. + return kSignBitMask | sam; + } + } + + // Given two numbers in the sign-and-magnitude representation, + // returns the distance between them as an unsigned number. + static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, + const Bits &sam2) { + const Bits biased1 = SignAndMagnitudeToBiased(sam1); + const Bits biased2 = SignAndMagnitudeToBiased(sam2); + return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); + } + + FloatingPointUnion u_; +}; + +// We cannot use std::numeric_limits::max() as it clashes with the max() +// macro defined by . +template <> +inline float FloatingPoint::Max() { return FLT_MAX; } +template <> +inline double FloatingPoint::Max() { return DBL_MAX; } + +// Typedefs the instances of the FloatingPoint template class that we +// care to use. +typedef FloatingPoint Float; +typedef FloatingPoint Double; + +// In order to catch the mistake of putting tests that use different +// test fixture classes in the same test case, we need to assign +// unique IDs to fixture classes and compare them. The TypeId type is +// used to hold such IDs. The user should treat TypeId as an opaque +// type: the only operation allowed on TypeId values is to compare +// them for equality using the == operator. +typedef const void* TypeId; + +template +class TypeIdHelper { + public: + // dummy_ must not have a const type. Otherwise an overly eager + // compiler (e.g. MSVC 7.1 & 8.0) may try to merge + // TypeIdHelper::dummy_ for different Ts as an "optimization". + static bool dummy_; +}; + +template +bool TypeIdHelper::dummy_ = false; + +// GetTypeId() returns the ID of type T. Different values will be +// returned for different types. Calling the function twice with the +// same type argument is guaranteed to return the same ID. +template +TypeId GetTypeId() { + // The compiler is required to allocate a different + // TypeIdHelper::dummy_ variable for each T used to instantiate + // the template. Therefore, the address of dummy_ is guaranteed to + // be unique. + return &(TypeIdHelper::dummy_); +} + +// Returns the type ID of ::testing::Test. Always call this instead +// of GetTypeId< ::testing::Test>() to get the type ID of +// ::testing::Test, as the latter may give the wrong result due to a +// suspected linker bug when compiling Google Test as a Mac OS X +// framework. +GTEST_API_ TypeId GetTestTypeId(); + +// Defines the abstract factory interface that creates instances +// of a Test object. +class TestFactoryBase { + public: + virtual ~TestFactoryBase() {} + + // Creates a test instance to run. The instance is both created and destroyed + // within TestInfoImpl::Run() + virtual Test* CreateTest() = 0; + + protected: + TestFactoryBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); +}; + +// This class provides implementation of TeastFactoryBase interface. +// It is used in TEST and TEST_F macros. +template +class TestFactoryImpl : public TestFactoryBase { + public: + virtual Test* CreateTest() { return new TestClass; } +}; + +#if GTEST_OS_WINDOWS + +// Predicate-formatters for implementing the HRESULT checking macros +// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} +// We pass a long instead of HRESULT to avoid causing an +// include dependency for the HRESULT type. +GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, + long hr); // NOLINT +GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, + long hr); // NOLINT + +#endif // GTEST_OS_WINDOWS + +// Types of SetUpTestCase() and TearDownTestCase() functions. +typedef void (*SetUpTestCaseFunc)(); +typedef void (*TearDownTestCaseFunc)(); + +// Creates a new TestInfo object and registers it with Google Test; +// returns the created object. +// +// Arguments: +// +// test_case_name: name of the test case +// name: name of the test +// type_param the name of the test's type parameter, or NULL if +// this is not a typed or a type-parameterized test. +// value_param text representation of the test's value parameter, +// or NULL if this is not a type-parameterized test. +// fixture_class_id: ID of the test fixture class +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +// factory: pointer to the factory that creates a test object. +// The newly created TestInfo instance will assume +// ownership of the factory object. +GTEST_API_ TestInfo* MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory); + +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// State of the definition of a type-parameterized test case. +class GTEST_API_ TypedTestCasePState { + public: + TypedTestCasePState() : registered_(false) {} + + // Adds the given test name to defined_test_names_ and return true + // if the test case hasn't been registered; otherwise aborts the + // program. + bool AddTestName(const char* file, int line, const char* case_name, + const char* test_name) { + if (registered_) { + fprintf(stderr, "%s Test %s must be defined before " + "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", + FormatFileLocation(file, line).c_str(), test_name, case_name); + fflush(stderr); + posix::Abort(); + } + defined_test_names_.insert(test_name); + return true; + } + + // Verifies that registered_tests match the test names in + // defined_test_names_; returns registered_tests if successful, or + // aborts the program otherwise. + const char* VerifyRegisteredTestNames( + const char* file, int line, const char* registered_tests); + + private: + bool registered_; + ::std::set defined_test_names_; +}; + +// Skips to the first non-space char after the first comma in 'str'; +// returns NULL if no comma is found in 'str'. +inline const char* SkipComma(const char* str) { + const char* comma = strchr(str, ','); + if (comma == NULL) { + return NULL; + } + while (IsSpace(*(++comma))) {} + return comma; +} + +// Returns the prefix of 'str' before the first comma in it; returns +// the entire string if it contains no comma. +inline std::string GetPrefixUntilComma(const char* str) { + const char* comma = strchr(str, ','); + return comma == NULL ? str : std::string(str, comma); +} + +// TypeParameterizedTest::Register() +// registers a list of type-parameterized tests with Google Test. The +// return value is insignificant - we just need to return something +// such that we can call this function in a namespace scope. +// +// Implementation note: The GTEST_TEMPLATE_ macro declares a template +// template parameter. It's defined in gtest-type-util.h. +template +class TypeParameterizedTest { + public: + // 'index' is the index of the test in the type list 'Types' + // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, + // Types). Valid values for 'index' are [0, N - 1] where N is the + // length of Types. + static bool Register(const char* prefix, const char* case_name, + const char* test_names, int index) { + typedef typename Types::Head Type; + typedef Fixture FixtureClass; + typedef typename GTEST_BIND_(TestSel, Type) TestClass; + + // First, registers the first type-parameterized test in the type + // list. + MakeAndRegisterTestInfo( + (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" + + StreamableToString(index)).c_str(), + GetPrefixUntilComma(test_names).c_str(), + GetTypeName().c_str(), + NULL, // No value parameter. + GetTypeId(), + TestClass::SetUpTestCase, + TestClass::TearDownTestCase, + new TestFactoryImpl); + + // Next, recurses (at compile time) with the tail of the type list. + return TypeParameterizedTest + ::Register(prefix, case_name, test_names, index + 1); + } +}; + +// The base case for the compile time recursion. +template +class TypeParameterizedTest { + public: + static bool Register(const char* /*prefix*/, const char* /*case_name*/, + const char* /*test_names*/, int /*index*/) { + return true; + } +}; + +// TypeParameterizedTestCase::Register() +// registers *all combinations* of 'Tests' and 'Types' with Google +// Test. The return value is insignificant - we just need to return +// something such that we can call this function in a namespace scope. +template +class TypeParameterizedTestCase { + public: + static bool Register(const char* prefix, const char* case_name, + const char* test_names) { + typedef typename Tests::Head Head; + + // First, register the first test in 'Test' for each type in 'Types'. + TypeParameterizedTest::Register( + prefix, case_name, test_names, 0); + + // Next, recurses (at compile time) with the tail of the test list. + return TypeParameterizedTestCase + ::Register(prefix, case_name, SkipComma(test_names)); + } +}; + +// The base case for the compile time recursion. +template +class TypeParameterizedTestCase { + public: + static bool Register(const char* /*prefix*/, const char* /*case_name*/, + const char* /*test_names*/) { + return true; + } +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( + UnitTest* unit_test, int skip_count); + +// Helpers for suppressing warnings on unreachable code or constant +// condition. + +// Always returns true. +GTEST_API_ bool AlwaysTrue(); + +// Always returns false. +inline bool AlwaysFalse() { return !AlwaysTrue(); } + +// Helper for suppressing false warning from Clang on a const char* +// variable declared in a conditional expression always being NULL in +// the else branch. +struct GTEST_API_ ConstCharPtr { + ConstCharPtr(const char* str) : value(str) {} + operator bool() const { return true; } + const char* value; +}; + +// A simple Linear Congruential Generator for generating random +// numbers with a uniform distribution. Unlike rand() and srand(), it +// doesn't use global state (and therefore can't interfere with user +// code). Unlike rand_r(), it's portable. An LCG isn't very random, +// but it's good enough for our purposes. +class GTEST_API_ Random { + public: + static const UInt32 kMaxRange = 1u << 31; + + explicit Random(UInt32 seed) : state_(seed) {} + + void Reseed(UInt32 seed) { state_ = seed; } + + // Generates a random number from [0, range). Crashes if 'range' is + // 0 or greater than kMaxRange. + UInt32 Generate(UInt32 range); + + private: + UInt32 state_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); +}; + +// Defining a variable of type CompileAssertTypesEqual will cause a +// compiler error iff T1 and T2 are different types. +template +struct CompileAssertTypesEqual; + +template +struct CompileAssertTypesEqual { +}; + +// Removes the reference from a type if it is a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::remove_reference, which is not widely available yet. +template +struct RemoveReference { typedef T type; }; // NOLINT +template +struct RemoveReference { typedef T type; }; // NOLINT + +// A handy wrapper around RemoveReference that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_REFERENCE_(T) \ + typename ::testing::internal::RemoveReference::type + +// Removes const from a type if it is a const type, otherwise leaves +// it unchanged. This is the same as tr1::remove_const, which is not +// widely available yet. +template +struct RemoveConst { typedef T type; }; // NOLINT +template +struct RemoveConst { typedef T type; }; // NOLINT + +// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above +// definition to fail to remove the const in 'const int[3]' and 'const +// char[3][4]'. The following specialization works around the bug. +template +struct RemoveConst { + typedef typename RemoveConst::type type[N]; +}; + +#if defined(_MSC_VER) && _MSC_VER < 1400 +// This is the only specialization that allows VC++ 7.1 to remove const in +// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC +// and thus needs to be conditionally compiled. +template +struct RemoveConst { + typedef typename RemoveConst::type type[N]; +}; +#endif + +// A handy wrapper around RemoveConst that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_CONST_(T) \ + typename ::testing::internal::RemoveConst::type + +// Turns const U&, U&, const U, and U all into U. +#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ + GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) + +// Adds reference to a type if it is not a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::add_reference, which is not widely available yet. +template +struct AddReference { typedef T& type; }; // NOLINT +template +struct AddReference { typedef T& type; }; // NOLINT + +// A handy wrapper around AddReference that works when the argument T +// depends on template parameters. +#define GTEST_ADD_REFERENCE_(T) \ + typename ::testing::internal::AddReference::type + +// Adds a reference to const on top of T as necessary. For example, +// it transforms +// +// char ==> const char& +// const char ==> const char& +// char& ==> const char& +// const char& ==> const char& +// +// The argument T must depend on some template parameters. +#define GTEST_REFERENCE_TO_CONST_(T) \ + GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) + +// ImplicitlyConvertible::value is a compile-time bool +// constant that's true iff type From can be implicitly converted to +// type To. +template +class ImplicitlyConvertible { + private: + // We need the following helper functions only for their types. + // They have no implementations. + + // MakeFrom() is an expression whose type is From. We cannot simply + // use From(), as the type From may not have a public default + // constructor. + static From MakeFrom(); + + // These two functions are overloaded. Given an expression + // Helper(x), the compiler will pick the first version if x can be + // implicitly converted to type To; otherwise it will pick the + // second version. + // + // The first version returns a value of size 1, and the second + // version returns a value of size 2. Therefore, by checking the + // size of Helper(x), which can be done at compile time, we can tell + // which version of Helper() is used, and hence whether x can be + // implicitly converted to type To. + static char Helper(To); + static char (&Helper(...))[2]; // NOLINT + + // We have to put the 'public' section after the 'private' section, + // or MSVC refuses to compile the code. + public: + // MSVC warns about implicitly converting from double to int for + // possible loss of data, so we need to temporarily disable the + // warning. +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4244) // Temporarily disables warning 4244. + + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; +# pragma warning(pop) // Restores the warning state. +#elif defined(__BORLANDC__) + // C++Builder cannot use member overload resolution during template + // instantiation. The simplest workaround is to use its C++0x type traits + // functions (C++Builder 2009 and above only). + static const bool value = __is_convertible(From, To); +#else + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; +#endif // _MSV_VER +}; +template +const bool ImplicitlyConvertible::value; + +// IsAProtocolMessage::value is a compile-time bool constant that's +// true iff T is type ProtocolMessage, proto2::Message, or a subclass +// of those. +template +struct IsAProtocolMessage + : public bool_constant< + ImplicitlyConvertible::value || + ImplicitlyConvertible::value> { +}; + +// When the compiler sees expression IsContainerTest(0), if C is an +// STL-style container class, the first overload of IsContainerTest +// will be viable (since both C::iterator* and C::const_iterator* are +// valid types and NULL can be implicitly converted to them). It will +// be picked over the second overload as 'int' is a perfect match for +// the type of argument 0. If C::iterator or C::const_iterator is not +// a valid type, the first overload is not viable, and the second +// overload will be picked. Therefore, we can determine whether C is +// a container class by checking the type of IsContainerTest(0). +// The value of the expression is insignificant. +// +// Note that we look for both C::iterator and C::const_iterator. The +// reason is that C++ injects the name of a class as a member of the +// class itself (e.g. you can refer to class iterator as either +// 'iterator' or 'iterator::iterator'). If we look for C::iterator +// only, for example, we would mistakenly think that a class named +// iterator is an STL container. +// +// Also note that the simpler approach of overloading +// IsContainerTest(typename C::const_iterator*) and +// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. +typedef int IsContainer; +template +IsContainer IsContainerTest(int /* dummy */, + typename C::iterator* /* it */ = NULL, + typename C::const_iterator* /* const_it */ = NULL) { + return 0; +} + +typedef char IsNotContainer; +template +IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } + +// EnableIf::type is void when 'Cond' is true, and +// undefined when 'Cond' is false. To use SFINAE to make a function +// overload only apply when a particular expression is true, add +// "typename EnableIf::type* = 0" as the last parameter. +template struct EnableIf; +template<> struct EnableIf { typedef void type; }; // NOLINT + +// Utilities for native arrays. + +// ArrayEq() compares two k-dimensional native arrays using the +// elements' operator==, where k can be any integer >= 0. When k is +// 0, ArrayEq() degenerates into comparing a single pair of values. + +template +bool ArrayEq(const T* lhs, size_t size, const U* rhs); + +// This generic version is used when k is 0. +template +inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } + +// This overload is used when k >= 1. +template +inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { + return internal::ArrayEq(lhs, N, rhs); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous ArrayEq() function, arrays with different sizes would +// lead to different copies of the template code. +template +bool ArrayEq(const T* lhs, size_t size, const U* rhs) { + for (size_t i = 0; i != size; i++) { + if (!internal::ArrayEq(lhs[i], rhs[i])) + return false; + } + return true; +} + +// Finds the first element in the iterator range [begin, end) that +// equals elem. Element may be a native array type itself. +template +Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { + for (Iter it = begin; it != end; ++it) { + if (internal::ArrayEq(*it, elem)) + return it; + } + return end; +} + +// CopyArray() copies a k-dimensional native array using the elements' +// operator=, where k can be any integer >= 0. When k is 0, +// CopyArray() degenerates into copying a single value. + +template +void CopyArray(const T* from, size_t size, U* to); + +// This generic version is used when k is 0. +template +inline void CopyArray(const T& from, U* to) { *to = from; } + +// This overload is used when k >= 1. +template +inline void CopyArray(const T(&from)[N], U(*to)[N]) { + internal::CopyArray(from, N, *to); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous CopyArray() function, arrays with different sizes +// would lead to different copies of the template code. +template +void CopyArray(const T* from, size_t size, U* to) { + for (size_t i = 0; i != size; i++) { + internal::CopyArray(from[i], to + i); + } +} + +// The relation between an NativeArray object (see below) and the +// native array it represents. +enum RelationToSource { + kReference, // The NativeArray references the native array. + kCopy // The NativeArray makes a copy of the native array and + // owns the copy. +}; + +// Adapts a native array to a read-only STL-style container. Instead +// of the complete STL container concept, this adaptor only implements +// members useful for Google Mock's container matchers. New members +// should be added as needed. To simplify the implementation, we only +// support Element being a raw type (i.e. having no top-level const or +// reference modifier). It's the client's responsibility to satisfy +// this requirement. Element can be an array type itself (hence +// multi-dimensional arrays are supported). +template +class NativeArray { + public: + // STL-style container typedefs. + typedef Element value_type; + typedef Element* iterator; + typedef const Element* const_iterator; + + // Constructs from a native array. + NativeArray(const Element* array, size_t count, RelationToSource relation) { + Init(array, count, relation); + } + + // Copy constructor. + NativeArray(const NativeArray& rhs) { + Init(rhs.array_, rhs.size_, rhs.relation_to_source_); + } + + ~NativeArray() { + // Ensures that the user doesn't instantiate NativeArray with a + // const or reference type. + static_cast(StaticAssertTypeEqHelper()); + if (relation_to_source_ == kCopy) + delete[] array_; + } + + // STL-style container methods. + size_t size() const { return size_; } + const_iterator begin() const { return array_; } + const_iterator end() const { return array_ + size_; } + bool operator==(const NativeArray& rhs) const { + return size() == rhs.size() && + ArrayEq(begin(), size(), rhs.begin()); + } + + private: + // Initializes this object; makes a copy of the input array if + // 'relation' is kCopy. + void Init(const Element* array, size_t a_size, RelationToSource relation) { + if (relation == kReference) { + array_ = array; + } else { + Element* const copy = new Element[a_size]; + CopyArray(array, a_size, copy); + array_ = copy; + } + size_ = a_size; + relation_to_source_ = relation; + } + + const Element* array_; + size_t size_; + RelationToSource relation_to_source_; + + GTEST_DISALLOW_ASSIGN_(NativeArray); +}; + +} // namespace internal +} // namespace testing + +#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ + ::testing::internal::AssertHelper(result_type, file, line, message) \ + = ::testing::Message() + +#define GTEST_MESSAGE_(message, result_type) \ + GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) + +#define GTEST_FATAL_FAILURE_(message) \ + return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) + +#define GTEST_NONFATAL_FAILURE_(message) \ + GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) + +#define GTEST_SUCCESS_(message) \ + GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) + +// Suppresses MSVC warnings 4072 (unreachable code) for the code following +// statement if it returns or throws (or doesn't return or throw in some +// situations). +#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ + if (::testing::internal::AlwaysTrue()) { statement; } + +#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::ConstCharPtr gtest_msg = "") { \ + bool gtest_caught_expected = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (expected_exception const&) { \ + gtest_caught_expected = true; \ + } \ + catch (...) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws a different type."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + if (!gtest_caught_expected) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws nothing."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ + fail(gtest_msg.value) + +#define GTEST_TEST_NO_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (...) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ + fail("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: it throws.") + +#define GTEST_TEST_ANY_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + bool gtest_caught_any = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (...) { \ + gtest_caught_any = true; \ + } \ + if (!gtest_caught_any) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ + fail("Expected: " #statement " throws an exception.\n" \ + " Actual: it doesn't.") + + +// Implements Boolean test assertions such as EXPECT_TRUE. expression can be +// either a boolean expression or an AssertionResult. text is a textual +// represenation of expression as it was passed into the EXPECT_TRUE. +#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar_ = \ + ::testing::AssertionResult(expression)) \ + ; \ + else \ + fail(::testing::internal::GetBoolAssertionFailureMessage(\ + gtest_ar_, text, #actual, #expected).c_str()) + +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ + fail("Expected: " #statement " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") + +// Expands to the name of the class that implements the given test. +#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + test_case_name##_##test_name##_Test + +// Helper macro for defining tests. +#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ +class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ + public:\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ + private:\ + virtual void TestBody();\ + static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ +};\ +\ +::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ + ::test_info_ =\ + ::testing::internal::MakeAndRegisterTestInfo(\ + #test_case_name, #test_name, NULL, NULL, \ + (parent_id), \ + parent_class::SetUpTestCase, \ + parent_class::TearDownTestCase, \ + new ::testing::internal::TestFactoryImpl<\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ +void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the public API for death tests. It is +// #included by gtest.h so a user doesn't need to include this +// directly. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ + +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines internal utilities needed for implementing +// death tests. They are subject to change without notice. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ + + +#include + +namespace testing { +namespace internal { + +GTEST_DECLARE_string_(internal_run_death_test); + +// Names of the flags (needed for parsing Google Test flags). +const char kDeathTestStyleFlag[] = "death_test_style"; +const char kDeathTestUseFork[] = "death_test_use_fork"; +const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; + +#if GTEST_HAS_DEATH_TEST + +// DeathTest is a class that hides much of the complexity of the +// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method +// returns a concrete class that depends on the prevailing death test +// style, as defined by the --gtest_death_test_style and/or +// --gtest_internal_run_death_test flags. + +// In describing the results of death tests, these terms are used with +// the corresponding definitions: +// +// exit status: The integer exit information in the format specified +// by wait(2) +// exit code: The integer code passed to exit(3), _exit(2), or +// returned from main() +class GTEST_API_ DeathTest { + public: + // Create returns false if there was an error determining the + // appropriate action to take for the current death test; for example, + // if the gtest_death_test_style flag is set to an invalid value. + // The LastMessage method will return a more detailed message in that + // case. Otherwise, the DeathTest pointer pointed to by the "test" + // argument is set. If the death test should be skipped, the pointer + // is set to NULL; otherwise, it is set to the address of a new concrete + // DeathTest object that controls the execution of the current test. + static bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); + DeathTest(); + virtual ~DeathTest() { } + + // A helper class that aborts a death test when it's deleted. + class ReturnSentinel { + public: + explicit ReturnSentinel(DeathTest* test) : test_(test) { } + ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } + private: + DeathTest* const test_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); + } GTEST_ATTRIBUTE_UNUSED_; + + // An enumeration of possible roles that may be taken when a death + // test is encountered. EXECUTE means that the death test logic should + // be executed immediately. OVERSEE means that the program should prepare + // the appropriate environment for a child process to execute the death + // test, then wait for it to complete. + enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; + + // An enumeration of the three reasons that a test might be aborted. + enum AbortReason { + TEST_ENCOUNTERED_RETURN_STATEMENT, + TEST_THREW_EXCEPTION, + TEST_DID_NOT_DIE + }; + + // Assumes one of the above roles. + virtual TestRole AssumeRole() = 0; + + // Waits for the death test to finish and returns its status. + virtual int Wait() = 0; + + // Returns true if the death test passed; that is, the test process + // exited during the test, its exit status matches a user-supplied + // predicate, and its stderr output matches a user-supplied regular + // expression. + // The user-supplied predicate may be a macro expression rather + // than a function pointer or functor, or else Wait and Passed could + // be combined. + virtual bool Passed(bool exit_status_ok) = 0; + + // Signals that the death test did not die as expected. + virtual void Abort(AbortReason reason) = 0; + + // Returns a human-readable outcome message regarding the outcome of + // the last death test. + static const char* LastMessage(); + + static void set_last_death_test_message(const std::string& message); + + private: + // A string containing a description of the outcome of the last death test. + static std::string last_death_test_message_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); +}; + +// Factory interface for death tests. May be mocked out for testing. +class DeathTestFactory { + public: + virtual ~DeathTestFactory() { } + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test) = 0; +}; + +// A concrete DeathTestFactory implementation for normal use. +class DefaultDeathTestFactory : public DeathTestFactory { + public: + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); +}; + +// Returns true if exit_status describes a process that was terminated +// by a signal, or exited normally with a nonzero exit code. +GTEST_API_ bool ExitedUnsuccessfully(int exit_status); + +// Traps C++ exceptions escaping statement and reports them as test +// failures. Note that trapping SEH exceptions is not implemented here. +# if GTEST_HAS_EXCEPTIONS +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (const ::std::exception& gtest_exception) { \ + fprintf(\ + stderr, \ + "\n%s: Caught std::exception-derived exception escaping the " \ + "death test statement. Exception message: %s\n", \ + ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ + gtest_exception.what()); \ + fflush(stderr); \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } catch (...) { \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } + +# else +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) + +# endif + +// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, +// ASSERT_EXIT*, and EXPECT_EXIT*. +# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + const ::testing::internal::RE& gtest_regex = (regex); \ + ::testing::internal::DeathTest* gtest_dt; \ + if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ + __FILE__, __LINE__, >est_dt)) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + if (gtest_dt != NULL) { \ + ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ + gtest_dt_ptr(gtest_dt); \ + switch (gtest_dt->AssumeRole()) { \ + case ::testing::internal::DeathTest::OVERSEE_TEST: \ + if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + break; \ + case ::testing::internal::DeathTest::EXECUTE_TEST: { \ + ::testing::internal::DeathTest::ReturnSentinel \ + gtest_sentinel(gtest_dt); \ + GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ + gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ + break; \ + } \ + default: \ + break; \ + } \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ + fail(::testing::internal::DeathTest::LastMessage()) +// The symbol "fail" here expands to something into which a message +// can be streamed. + +// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in +// NDEBUG mode. In this case we need the statements to be executed, the regex is +// ignored, and the macro must accept a streamed message even though the message +// is never printed. +# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } else \ + ::testing::Message() + +// A class representing the parsed contents of the +// --gtest_internal_run_death_test flag, as it existed when +// RUN_ALL_TESTS was called. +class InternalRunDeathTestFlag { + public: + InternalRunDeathTestFlag(const std::string& a_file, + int a_line, + int an_index, + int a_write_fd) + : file_(a_file), line_(a_line), index_(an_index), + write_fd_(a_write_fd) {} + + ~InternalRunDeathTestFlag() { + if (write_fd_ >= 0) + posix::Close(write_fd_); + } + + const std::string& file() const { return file_; } + int line() const { return line_; } + int index() const { return index_; } + int write_fd() const { return write_fd_; } + + private: + std::string file_; + int line_; + int index_; + int write_fd_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); +}; + +// Returns a newly created InternalRunDeathTestFlag object with fields +// initialized from the GTEST_FLAG(internal_run_death_test) flag if +// the flag is specified; otherwise returns NULL. +InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); + +#else // GTEST_HAS_DEATH_TEST + +// This macro is used for implementing macros such as +// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where +// death tests are not supported. Those macros must compile on such systems +// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on +// systems that support death tests. This allows one to write such a macro +// on a system that does not support death tests and be sure that it will +// compile on a death-test supporting system. +// +// Parameters: +// statement - A statement that a macro such as EXPECT_DEATH would test +// for program termination. This macro has to make sure this +// statement is compiled but not executed, to ensure that +// EXPECT_DEATH_IF_SUPPORTED compiles with a certain +// parameter iff EXPECT_DEATH compiles with it. +// regex - A regex that a macro such as EXPECT_DEATH would use to test +// the output of statement. This parameter has to be +// compiled but not evaluated by this macro, to ensure that +// this macro only accepts expressions that a macro such as +// EXPECT_DEATH would accept. +// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED +// and a return statement for ASSERT_DEATH_IF_SUPPORTED. +// This ensures that ASSERT_DEATH_IF_SUPPORTED will not +// compile inside functions where ASSERT_DEATH doesn't +// compile. +// +// The branch that has an always false condition is used to ensure that +// statement and regex are compiled (and thus syntactically correct) but +// never executed. The unreachable code macro protects the terminator +// statement from generating an 'unreachable code' warning in case +// statement unconditionally returns or throws. The Message constructor at +// the end allows the syntax of streaming additional messages into the +// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. +# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_LOG_(WARNING) \ + << "Death tests are not supported on this platform.\n" \ + << "Statement '" #statement "' cannot be verified."; \ + } else if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::RE::PartialMatch(".*", (regex)); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + terminator; \ + } else \ + ::testing::Message() + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ + +namespace testing { + +// This flag controls the style of death tests. Valid values are "threadsafe", +// meaning that the death test child process will re-execute the test binary +// from the start, running only a single death test, or "fast", +// meaning that the child process will execute the test logic immediately +// after forking. +GTEST_DECLARE_string_(death_test_style); + +#if GTEST_HAS_DEATH_TEST + +namespace internal { + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +GTEST_API_ bool InDeathTestChild(); + +} // namespace internal + +// The following macros are useful for writing death tests. + +// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is +// executed: +// +// 1. It generates a warning if there is more than one active +// thread. This is because it's safe to fork() or clone() only +// when there is a single thread. +// +// 2. The parent process clone()s a sub-process and runs the death +// test in it; the sub-process exits with code 0 at the end of the +// death test, if it hasn't exited already. +// +// 3. The parent process waits for the sub-process to terminate. +// +// 4. The parent process checks the exit code and error message of +// the sub-process. +// +// Examples: +// +// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); +// for (int i = 0; i < 5; i++) { +// EXPECT_DEATH(server.ProcessRequest(i), +// "Invalid request .* in ProcessRequest()") +// << "Failed to die on request " << i; +// } +// +// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); +// +// bool KilledBySIGHUP(int exit_code) { +// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; +// } +// +// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); +// +// On the regular expressions used in death tests: +// +// On POSIX-compliant systems (*nix), we use the library, +// which uses the POSIX extended regex syntax. +// +// On other platforms (e.g. Windows), we only support a simple regex +// syntax implemented as part of Google Test. This limited +// implementation should be enough most of the time when writing +// death tests; though it lacks many features you can find in PCRE +// or POSIX extended regex syntax. For example, we don't support +// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and +// repetition count ("x{5,7}"), among others. +// +// Below is the syntax that we do support. We chose it to be a +// subset of both PCRE and POSIX extended regex, so it's easy to +// learn wherever you come from. In the following: 'A' denotes a +// literal character, period (.), or a single \\ escape sequence; +// 'x' and 'y' denote regular expressions; 'm' and 'n' are for +// natural numbers. +// +// c matches any literal character c +// \\d matches any decimal digit +// \\D matches any character that's not a decimal digit +// \\f matches \f +// \\n matches \n +// \\r matches \r +// \\s matches any ASCII whitespace, including \n +// \\S matches any character that's not a whitespace +// \\t matches \t +// \\v matches \v +// \\w matches any letter, _, or decimal digit +// \\W matches any character that \\w doesn't match +// \\c matches any literal character c, which must be a punctuation +// . matches any single character except \n +// A? matches 0 or 1 occurrences of A +// A* matches 0 or many occurrences of A +// A+ matches 1 or many occurrences of A +// ^ matches the beginning of a string (not that of each line) +// $ matches the end of a string (not that of each line) +// xy matches x followed by y +// +// If you accidentally use PCRE or POSIX extended regex features +// not implemented by us, you will get a run-time failure. In that +// case, please try to rewrite your regular expression within the +// above syntax. +// +// This implementation is *not* meant to be as highly tuned or robust +// as a compiled regex library, but should perform well enough for a +// death test, which already incurs significant overhead by launching +// a child process. +// +// Known caveats: +// +// A "threadsafe" style death test obtains the path to the test +// program from argv[0] and re-executes it in the sub-process. For +// simplicity, the current implementation doesn't search the PATH +// when launching the sub-process. This means that the user must +// invoke the test program via a path that contains at least one +// path separator (e.g. path/to/foo_test and +// /absolute/path/to/bar_test are fine, but foo_test is not). This +// is rarely a problem as people usually don't put the test binary +// directory in PATH. +// +// TODO(wan@google.com): make thread-safe death tests search the PATH. + +// Asserts that a given statement causes the program to exit, with an +// integer exit status that satisfies predicate, and emitting error output +// that matches regex. +# define ASSERT_EXIT(statement, predicate, regex) \ + GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) + +// Like ASSERT_EXIT, but continues on to successive tests in the +// test case, if any: +# define EXPECT_EXIT(statement, predicate, regex) \ + GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) + +// Asserts that a given statement causes the program to exit, either by +// explicitly exiting with a nonzero exit code or being killed by a +// signal, and emitting error output that matches regex. +# define ASSERT_DEATH(statement, regex) \ + ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) + +// Like ASSERT_DEATH, but continues on to successive tests in the +// test case, if any: +# define EXPECT_DEATH(statement, regex) \ + EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) + +// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: + +// Tests that an exit code describes a normal exit with a given exit code. +class GTEST_API_ ExitedWithCode { + public: + explicit ExitedWithCode(int exit_code); + bool operator()(int exit_status) const; + private: + // No implementation - assignment is unsupported. + void operator=(const ExitedWithCode& other); + + const int exit_code_; +}; + +# if !GTEST_OS_WINDOWS +// Tests that an exit code describes an exit due to termination by a +// given signal. +class GTEST_API_ KilledBySignal { + public: + explicit KilledBySignal(int signum); + bool operator()(int exit_status) const; + private: + const int signum_; +}; +# endif // !GTEST_OS_WINDOWS + +// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. +// The death testing framework causes this to have interesting semantics, +// since the sideeffects of the call are only visible in opt mode, and not +// in debug mode. +// +// In practice, this can be used to test functions that utilize the +// LOG(DFATAL) macro using the following style: +// +// int DieInDebugOr12(int* sideeffect) { +// if (sideeffect) { +// *sideeffect = 12; +// } +// LOG(DFATAL) << "death"; +// return 12; +// } +// +// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { +// int sideeffect = 0; +// // Only asserts in dbg. +// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); +// +// #ifdef NDEBUG +// // opt-mode has sideeffect visible. +// EXPECT_EQ(12, sideeffect); +// #else +// // dbg-mode no visible sideeffect. +// EXPECT_EQ(0, sideeffect); +// #endif +// } +// +// This will assert that DieInDebugReturn12InOpt() crashes in debug +// mode, usually due to a DCHECK or LOG(DFATAL), but returns the +// appropriate fallback value (12 in this case) in opt mode. If you +// need to test that a function has appropriate side-effects in opt +// mode, include assertions against the side-effects. A general +// pattern for this is: +// +// EXPECT_DEBUG_DEATH({ +// // Side-effects here will have an effect after this statement in +// // opt mode, but none in debug mode. +// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); +// }, "death"); +// +# ifdef NDEBUG + +# define EXPECT_DEBUG_DEATH(statement, regex) \ + GTEST_EXECUTE_STATEMENT_(statement, regex) + +# define ASSERT_DEBUG_DEATH(statement, regex) \ + GTEST_EXECUTE_STATEMENT_(statement, regex) + +# else + +# define EXPECT_DEBUG_DEATH(statement, regex) \ + EXPECT_DEATH(statement, regex) + +# define ASSERT_DEBUG_DEATH(statement, regex) \ + ASSERT_DEATH(statement, regex) + +# endif // NDEBUG for EXPECT_DEBUG_DEATH +#endif // GTEST_HAS_DEATH_TEST + +// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and +// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if +// death tests are supported; otherwise they just issue a warning. This is +// useful when you are combining death test assertions with normal test +// assertions in one test. +#if GTEST_HAS_DEATH_TEST +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + EXPECT_DEATH(statement, regex) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + ASSERT_DEATH(statement, regex) +#else +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) +#endif + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ +// This file was GENERATED by command: +// pump.py gtest-param-test.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev) +// +// Macros and functions for implementing parameterized tests +// in Google C++ Testing Framework (Google Test) +// +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ + + +// Value-parameterized tests allow you to test your code with different +// parameters without writing multiple copies of the same test. +// +// Here is how you use value-parameterized tests: + +#if 0 + +// To write value-parameterized tests, first you should define a fixture +// class. It is usually derived from testing::TestWithParam (see below for +// another inheritance scheme that's sometimes useful in more complicated +// class hierarchies), where the type of your parameter values. +// TestWithParam is itself derived from testing::Test. T can be any +// copyable type. If it's a raw pointer, you are responsible for managing the +// lifespan of the pointed values. + +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual class fixture members here. +}; + +// Then, use the TEST_P macro to define as many parameterized tests +// for this fixture as you want. The _P suffix is for "parameterized" +// or "pattern", whichever you prefer to think. + +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} + +// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// case with any set of parameters you want. Google Test defines a number +// of functions for generating test parameters. They return what we call +// (surprise!) parameter generators. Here is a summary of them, which +// are all in the testing namespace: +// +// +// Range(begin, end [, step]) - Yields values {begin, begin+step, +// begin+step+step, ...}. The values do not +// include end. step defaults to 1. +// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. +// ValuesIn(container) - Yields values from a C-style array, an STL +// ValuesIn(begin,end) container, or an iterator range [begin, end). +// Bool() - Yields sequence {false, true}. +// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product +// for the math savvy) of the values generated +// by the N generators. +// +// For more details, see comments at the definitions of these functions below +// in this file. +// +// The following statement will instantiate tests from the FooTest test case +// each with parameter values "meeny", "miny", and "moe". + +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); + +// To distinguish different instances of the pattern, (yes, you +// can instantiate it more then once) the first argument to the +// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the +// actual test case name. Remember to pick unique prefixes for different +// instantiations. The tests from the instantiation above will have +// these names: +// +// * InstantiationName/FooTest.DoesBlah/0 for "meeny" +// * InstantiationName/FooTest.DoesBlah/1 for "miny" +// * InstantiationName/FooTest.DoesBlah/2 for "moe" +// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" +// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" +// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" +// +// You can use these names in --gtest_filter. +// +// This statement will instantiate all tests from FooTest again, each +// with parameter values "cat" and "dog": + +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); + +// The tests from the instantiation above will have these names: +// +// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" +// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" +// +// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests +// in the given test case, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_CASE_P statement. +// +// Please also note that generator expressions (including parameters to the +// generators) are evaluated in InitGoogleTest(), after main() has started. +// This allows the user on one hand, to adjust generator parameters in order +// to dynamically determine a set of tests to run and on the other hand, +// give the user a chance to inspect the generated tests with Google Test +// reflection API before RUN_ALL_TESTS() is executed. +// +// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc +// for more examples. +// +// In the future, we plan to publish the API for defining new parameter +// generators. But for now this interface remains part of the internal +// implementation and is subject to change. +// +// +// A parameterized test fixture must be derived from testing::Test and from +// testing::WithParamInterface, where T is the type of the parameter +// values. Inheriting from TestWithParam satisfies that requirement because +// TestWithParam inherits from both Test and WithParamInterface. In more +// complicated hierarchies, however, it is occasionally useful to inherit +// separately from Test and WithParamInterface. For example: + +class BaseTest : public ::testing::Test { + // You can inherit all the usual members for a non-parameterized test + // fixture here. +}; + +class DerivedTest : public BaseTest, public ::testing::WithParamInterface { + // The usual test fixture members go here too. +}; + +TEST_F(BaseTest, HasFoo) { + // This is an ordinary non-parameterized test. +} + +TEST_P(DerivedTest, DoesBlah) { + // GetParam works just the same here as if you inherit from TestWithParam. + EXPECT_TRUE(foo.Blah(GetParam())); +} + +#endif // 0 + + +#if !GTEST_OS_SYMBIAN +# include +#endif + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ + +#include +#include +#include + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +// Copyright 2003 Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: Dan Egnor (egnor@google.com) +// +// A "smart" pointer type with reference tracking. Every pointer to a +// particular object is kept on a circular linked list. When the last pointer +// to an object is destroyed or reassigned, the object is deleted. +// +// Used properly, this deletes the object when the last reference goes away. +// There are several caveats: +// - Like all reference counting schemes, cycles lead to leaks. +// - Each smart pointer is actually two pointers (8 bytes instead of 4). +// - Every time a pointer is assigned, the entire list of pointers to that +// object is traversed. This class is therefore NOT SUITABLE when there +// will often be more than two or three pointers to a particular object. +// - References are only tracked as long as linked_ptr<> objects are copied. +// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS +// will happen (double deletion). +// +// A good use of this class is storing object references in STL containers. +// You can safely put linked_ptr<> in a vector<>. +// Other uses may not be as good. +// +// Note: If you use an incomplete type with linked_ptr<>, the class +// *containing* linked_ptr<> must have a constructor and destructor (even +// if they do nothing!). +// +// Bill Gibbons suggested we use something like this. +// +// Thread Safety: +// Unlike other linked_ptr implementations, in this implementation +// a linked_ptr object is thread-safe in the sense that: +// - it's safe to copy linked_ptr objects concurrently, +// - it's safe to copy *from* a linked_ptr and read its underlying +// raw pointer (e.g. via get()) concurrently, and +// - it's safe to write to two linked_ptrs that point to the same +// shared object concurrently. +// TODO(wan@google.com): rename this to safe_linked_ptr to avoid +// confusion with normal linked_ptr. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ + +#include +#include + + +namespace testing { +namespace internal { + +// Protects copying of all linked_ptr objects. +GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); + +// This is used internally by all instances of linked_ptr<>. It needs to be +// a non-template class because different types of linked_ptr<> can refer to +// the same object (linked_ptr(obj) vs linked_ptr(obj)). +// So, it needs to be possible for different types of linked_ptr to participate +// in the same circular linked list, so we need a single class type here. +// +// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. +class linked_ptr_internal { + public: + // Create a new circle that includes only this instance. + void join_new() { + next_ = this; + } + + // Many linked_ptr operations may change p.link_ for some linked_ptr + // variable p in the same circle as this object. Therefore we need + // to prevent two such operations from occurring concurrently. + // + // Note that different types of linked_ptr objects can coexist in a + // circle (e.g. linked_ptr, linked_ptr, and + // linked_ptr). Therefore we must use a single mutex to + // protect all linked_ptr objects. This can create serious + // contention in production code, but is acceptable in a testing + // framework. + + // Join an existing circle. + void join(linked_ptr_internal const* ptr) + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + MutexLock lock(&g_linked_ptr_mutex); + + linked_ptr_internal const* p = ptr; + while (p->next_ != ptr) p = p->next_; + p->next_ = this; + next_ = ptr; + } + + // Leave whatever circle we're part of. Returns true if we were the + // last member of the circle. Once this is done, you can join() another. + bool depart() + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + MutexLock lock(&g_linked_ptr_mutex); + + if (next_ == this) return true; + linked_ptr_internal const* p = next_; + while (p->next_ != this) p = p->next_; + p->next_ = next_; + return false; + } + + private: + mutable linked_ptr_internal const* next_; +}; + +template +class linked_ptr { + public: + typedef T element_type; + + // Take over ownership of a raw pointer. This should happen as soon as + // possible after the object is created. + explicit linked_ptr(T* ptr = NULL) { capture(ptr); } + ~linked_ptr() { depart(); } + + // Copy an existing linked_ptr<>, adding ourselves to the list of references. + template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } + linked_ptr(linked_ptr const& ptr) { // NOLINT + assert(&ptr != this); + copy(&ptr); + } + + // Assignment releases the old value and acquires the new. + template linked_ptr& operator=(linked_ptr const& ptr) { + depart(); + copy(&ptr); + return *this; + } + + linked_ptr& operator=(linked_ptr const& ptr) { + if (&ptr != this) { + depart(); + copy(&ptr); + } + return *this; + } + + // Smart pointer members. + void reset(T* ptr = NULL) { + depart(); + capture(ptr); + } + T* get() const { return value_; } + T* operator->() const { return value_; } + T& operator*() const { return *value_; } + + bool operator==(T* p) const { return value_ == p; } + bool operator!=(T* p) const { return value_ != p; } + template + bool operator==(linked_ptr const& ptr) const { + return value_ == ptr.get(); + } + template + bool operator!=(linked_ptr const& ptr) const { + return value_ != ptr.get(); + } + + private: + template + friend class linked_ptr; + + T* value_; + linked_ptr_internal link_; + + void depart() { + if (link_.depart()) delete value_; + } + + void capture(T* ptr) { + value_ = ptr; + link_.join_new(); + } + + template void copy(linked_ptr const* ptr) { + value_ = ptr->get(); + if (value_) + link_.join(&ptr->link_); + else + link_.join_new(); + } +}; + +template inline +bool operator==(T* ptr, const linked_ptr& x) { + return ptr == x.get(); +} + +template inline +bool operator!=(T* ptr, const linked_ptr& x) { + return ptr != x.get(); +} + +// A function to convert T* into linked_ptr +// Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation +// for linked_ptr >(new FooBarBaz(arg)) +template +linked_ptr make_linked_ptr(T* ptr) { + return linked_ptr(ptr); +} + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing Framework +// +// This file implements a universal value printer that can print a +// value of any type T: +// +// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); +// +// A user can teach this function how to print a class type T by +// defining either operator<<() or PrintTo() in the namespace that +// defines T. More specifically, the FIRST defined function in the +// following list will be used (assuming T is defined in namespace +// foo): +// +// 1. foo::PrintTo(const T&, ostream*) +// 2. operator<<(ostream&, const T&) defined in either foo or the +// global namespace. +// +// If none of the above is defined, it will print the debug string of +// the value if it is a protocol buffer, or print the raw bytes in the +// value otherwise. +// +// To aid debugging: when T is a reference type, the address of the +// value is also printed; when T is a (const) char pointer, both the +// pointer value and the NUL-terminated string it points to are +// printed. +// +// We also provide some convenient wrappers: +// +// // Prints a value to a string. For a (const or not) char +// // pointer, the NUL-terminated string (but not the pointer) is +// // printed. +// std::string ::testing::PrintToString(const T& value); +// +// // Prints a value tersely: for a reference type, the referenced +// // value (but not the address) is printed; for a (const or not) char +// // pointer, the NUL-terminated string (but not the pointer) is +// // printed. +// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); +// +// // Prints value using the type inferred by the compiler. The difference +// // from UniversalTersePrint() is that this function prints both the +// // pointer and the NUL-terminated string for a (const or not) char pointer. +// void ::testing::internal::UniversalPrint(const T& value, ostream*); +// +// // Prints the fields of a tuple tersely to a string vector, one +// // element for each field. Tuple support must be enabled in +// // gtest-port.h. +// std::vector UniversalTersePrintTupleFieldsToStrings( +// const Tuple& value); +// +// Known limitation: +// +// The print primitives print the elements of an STL-style container +// using the compiler-inferred type of *iter where iter is a +// const_iterator of the container. When const_iterator is an input +// iterator but not a forward iterator, this inferred type may not +// match value_type, and the print output may be incorrect. In +// practice, this is rarely a problem as for most containers +// const_iterator is a forward iterator. We'll fix this if there's an +// actual need for it. Note that this fix cannot rely on value_type +// being defined as many user-defined container types don't have +// value_type. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ + +#include // NOLINT +#include +#include +#include +#include + +namespace testing { + +// Definitions in the 'internal' and 'internal2' name spaces are +// subject to change without notice. DO NOT USE THEM IN USER CODE! +namespace internal2 { + +// Prints the given number of bytes in the given object to the given +// ostream. +GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, + size_t count, + ::std::ostream* os); + +// For selecting which printer to use when a given type has neither << +// nor PrintTo(). +enum TypeKind { + kProtobuf, // a protobuf type + kConvertibleToInteger, // a type implicitly convertible to BiggestInt + // (e.g. a named or unnamed enum type) + kOtherType // anything else +}; + +// TypeWithoutFormatter::PrintValue(value, os) is called +// by the universal printer to print a value of type T when neither +// operator<< nor PrintTo() is defined for T, where kTypeKind is the +// "kind" of T as defined by enum TypeKind. +template +class TypeWithoutFormatter { + public: + // This default version is called when kTypeKind is kOtherType. + static void PrintValue(const T& value, ::std::ostream* os) { + PrintBytesInObjectTo(reinterpret_cast(&value), + sizeof(value), os); + } +}; + +// We print a protobuf using its ShortDebugString() when the string +// doesn't exceed this many characters; otherwise we print it using +// DebugString() for better readability. +const size_t kProtobufOneLinerMaxLength = 50; + +template +class TypeWithoutFormatter { + public: + static void PrintValue(const T& value, ::std::ostream* os) { + const ::testing::internal::string short_str = value.ShortDebugString(); + const ::testing::internal::string pretty_str = + short_str.length() <= kProtobufOneLinerMaxLength ? + short_str : ("\n" + value.DebugString()); + *os << ("<" + pretty_str + ">"); + } +}; + +template +class TypeWithoutFormatter { + public: + // Since T has no << operator or PrintTo() but can be implicitly + // converted to BiggestInt, we print it as a BiggestInt. + // + // Most likely T is an enum type (either named or unnamed), in which + // case printing it as an integer is the desired behavior. In case + // T is not an enum, printing it as an integer is the best we can do + // given that it has no user-defined printer. + static void PrintValue(const T& value, ::std::ostream* os) { + const internal::BiggestInt kBigInt = value; + *os << kBigInt; + } +}; + +// Prints the given value to the given ostream. If the value is a +// protocol message, its debug string is printed; if it's an enum or +// of a type implicitly convertible to BiggestInt, it's printed as an +// integer; otherwise the bytes in the value are printed. This is +// what UniversalPrinter::Print() does when it knows nothing about +// type T and T has neither << operator nor PrintTo(). +// +// A user can override this behavior for a class type Foo by defining +// a << operator in the namespace where Foo is defined. +// +// We put this operator in namespace 'internal2' instead of 'internal' +// to simplify the implementation, as much code in 'internal' needs to +// use << in STL, which would conflict with our own << were it defined +// in 'internal'. +// +// Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If +// we define it to take an std::ostream instead, we'll get an +// "ambiguous overloads" compiler error when trying to print a type +// Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether +// operator<<(std::ostream&, const T&) or +// operator<<(std::basic_stream, const Foo&) is more +// specific. +template +::std::basic_ostream& operator<<( + ::std::basic_ostream& os, const T& x) { + TypeWithoutFormatter::value ? kProtobuf : + internal::ImplicitlyConvertible::value ? + kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); + return os; +} + +} // namespace internal2 +} // namespace testing + +// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up +// magic needed for implementing UniversalPrinter won't work. +namespace testing_internal { + +// Used to print a value that is not an STL-style container when the +// user doesn't define PrintTo() for it. +template +void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { + // With the following statement, during unqualified name lookup, + // testing::internal2::operator<< appears as if it was declared in + // the nearest enclosing namespace that contains both + // ::testing_internal and ::testing::internal2, i.e. the global + // namespace. For more details, refer to the C++ Standard section + // 7.3.4-1 [namespace.udir]. This allows us to fall back onto + // testing::internal2::operator<< in case T doesn't come with a << + // operator. + // + // We cannot write 'using ::testing::internal2::operator<<;', which + // gcc 3.3 fails to compile due to a compiler bug. + using namespace ::testing::internal2; // NOLINT + + // Assuming T is defined in namespace foo, in the next statement, + // the compiler will consider all of: + // + // 1. foo::operator<< (thanks to Koenig look-up), + // 2. ::operator<< (as the current namespace is enclosed in ::), + // 3. testing::internal2::operator<< (thanks to the using statement above). + // + // The operator<< whose type matches T best will be picked. + // + // We deliberately allow #2 to be a candidate, as sometimes it's + // impossible to define #1 (e.g. when foo is ::std, defining + // anything in it is undefined behavior unless you are a compiler + // vendor.). + *os << value; +} + +} // namespace testing_internal + +namespace testing { +namespace internal { + +// UniversalPrinter::Print(value, ostream_ptr) prints the given +// value to the given ostream. The caller must ensure that +// 'ostream_ptr' is not NULL, or the behavior is undefined. +// +// We define UniversalPrinter as a class template (as opposed to a +// function template), as we need to partially specialize it for +// reference types, which cannot be done with function templates. +template +class UniversalPrinter; + +template +void UniversalPrint(const T& value, ::std::ostream* os); + +// Used to print an STL-style container when the user doesn't define +// a PrintTo() for it. +template +void DefaultPrintTo(IsContainer /* dummy */, + false_type /* is not a pointer */, + const C& container, ::std::ostream* os) { + const size_t kMaxCount = 32; // The maximum number of elements to print. + *os << '{'; + size_t count = 0; + for (typename C::const_iterator it = container.begin(); + it != container.end(); ++it, ++count) { + if (count > 0) { + *os << ','; + if (count == kMaxCount) { // Enough has been printed. + *os << " ..."; + break; + } + } + *os << ' '; + // We cannot call PrintTo(*it, os) here as PrintTo() doesn't + // handle *it being a native array. + internal::UniversalPrint(*it, os); + } + + if (count > 0) { + *os << ' '; + } + *os << '}'; +} + +// Used to print a pointer that is neither a char pointer nor a member +// pointer, when the user doesn't define PrintTo() for it. (A member +// variable pointer or member function pointer doesn't really point to +// a location in the address space. Their representation is +// implementation-defined. Therefore they will be printed as raw +// bytes.) +template +void DefaultPrintTo(IsNotContainer /* dummy */, + true_type /* is a pointer */, + T* p, ::std::ostream* os) { + if (p == NULL) { + *os << "NULL"; + } else { + // C++ doesn't allow casting from a function pointer to any object + // pointer. + // + // IsTrue() silences warnings: "Condition is always true", + // "unreachable code". + if (IsTrue(ImplicitlyConvertible::value)) { + // T is not a function type. We just call << to print p, + // relying on ADL to pick up user-defined << for their pointer + // types, if any. + *os << p; + } else { + // T is a function type, so '*os << p' doesn't do what we want + // (it just prints p as bool). We want to print p as a const + // void*. However, we cannot cast it to const void* directly, + // even using reinterpret_cast, as earlier versions of gcc + // (e.g. 3.4.5) cannot compile the cast when p is a function + // pointer. Casting to UInt64 first solves the problem. + *os << reinterpret_cast( + reinterpret_cast(p)); + } + } +} + +// Used to print a non-container, non-pointer value when the user +// doesn't define PrintTo() for it. +template +void DefaultPrintTo(IsNotContainer /* dummy */, + false_type /* is not a pointer */, + const T& value, ::std::ostream* os) { + ::testing_internal::DefaultPrintNonContainerTo(value, os); +} + +// Prints the given value using the << operator if it has one; +// otherwise prints the bytes in it. This is what +// UniversalPrinter::Print() does when PrintTo() is not specialized +// or overloaded for type T. +// +// A user can override this behavior for a class type Foo by defining +// an overload of PrintTo() in the namespace where Foo is defined. We +// give the user this option as sometimes defining a << operator for +// Foo is not desirable (e.g. the coding style may prevent doing it, +// or there is already a << operator but it doesn't do what the user +// wants). +template +void PrintTo(const T& value, ::std::ostream* os) { + // DefaultPrintTo() is overloaded. The type of its first two + // arguments determine which version will be picked. If T is an + // STL-style container, the version for container will be called; if + // T is a pointer, the pointer version will be called; otherwise the + // generic version will be called. + // + // Note that we check for container types here, prior to we check + // for protocol message types in our operator<<. The rationale is: + // + // For protocol messages, we want to give people a chance to + // override Google Mock's format by defining a PrintTo() or + // operator<<. For STL containers, other formats can be + // incompatible with Google Mock's format for the container + // elements; therefore we check for container types here to ensure + // that our format is used. + // + // The second argument of DefaultPrintTo() is needed to bypass a bug + // in Symbian's C++ compiler that prevents it from picking the right + // overload between: + // + // PrintTo(const T& x, ...); + // PrintTo(T* x, ...); + DefaultPrintTo(IsContainerTest(0), is_pointer(), value, os); +} + +// The following list of PrintTo() overloads tells +// UniversalPrinter::Print() how to print standard types (built-in +// types, strings, plain arrays, and pointers). + +// Overloads for various char types. +GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); +GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); +inline void PrintTo(char c, ::std::ostream* os) { + // When printing a plain char, we always treat it as unsigned. This + // way, the output won't be affected by whether the compiler thinks + // char is signed or not. + PrintTo(static_cast(c), os); +} + +// Overloads for other simple built-in types. +inline void PrintTo(bool x, ::std::ostream* os) { + *os << (x ? "true" : "false"); +} + +// Overload for wchar_t type. +// Prints a wchar_t as a symbol if it is printable or as its internal +// code otherwise and also as its decimal code (except for L'\0'). +// The L'\0' char is printed as "L'\\0'". The decimal code is printed +// as signed integer when wchar_t is implemented by the compiler +// as a signed type and is printed as an unsigned integer when wchar_t +// is implemented as an unsigned type. +GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); + +// Overloads for C strings. +GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); +inline void PrintTo(char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} + +// signed/unsigned char is often used for representing binary data, so +// we print pointers to it as void* to be safe. +inline void PrintTo(const signed char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(signed char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(const unsigned char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(unsigned char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} + +// MSVC can be configured to define wchar_t as a typedef of unsigned +// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native +// type. When wchar_t is a typedef, defining an overload for const +// wchar_t* would cause unsigned short* be printed as a wide string, +// possibly causing invalid memory accesses. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// Overloads for wide C strings +GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); +inline void PrintTo(wchar_t* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +#endif + +// Overload for C arrays. Multi-dimensional arrays are printed +// properly. + +// Prints the given number of elements in an array, without printing +// the curly braces. +template +void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { + UniversalPrint(a[0], os); + for (size_t i = 1; i != count; i++) { + *os << ", "; + UniversalPrint(a[i], os); + } +} + +// Overloads for ::string and ::std::string. +#if GTEST_HAS_GLOBAL_STRING +GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); +inline void PrintTo(const ::string& s, ::std::ostream* os) { + PrintStringTo(s, os); +} +#endif // GTEST_HAS_GLOBAL_STRING + +GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); +inline void PrintTo(const ::std::string& s, ::std::ostream* os) { + PrintStringTo(s, os); +} + +// Overloads for ::wstring and ::std::wstring. +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); +inline void PrintTo(const ::wstring& s, ::std::ostream* os) { + PrintWideStringTo(s, os); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); +inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { + PrintWideStringTo(s, os); +} +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_TR1_TUPLE +// Overload for ::std::tr1::tuple. Needed for printing function arguments, +// which are packed as tuples. + +// Helper function for printing a tuple. T must be instantiated with +// a tuple type. +template +void PrintTupleTo(const T& t, ::std::ostream* os); + +// Overloaded PrintTo() for tuples of various arities. We support +// tuples of up-to 10 fields. The following implementation works +// regardless of whether tr1::tuple is implemented using the +// non-standard variadic template feature or not. + +inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo( + const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} +#endif // GTEST_HAS_TR1_TUPLE + +// Overload for std::pair. +template +void PrintTo(const ::std::pair& value, ::std::ostream* os) { + *os << '('; + // We cannot use UniversalPrint(value.first, os) here, as T1 may be + // a reference type. The same for printing value.second. + UniversalPrinter::Print(value.first, os); + *os << ", "; + UniversalPrinter::Print(value.second, os); + *os << ')'; +} + +// Implements printing a non-reference type T by letting the compiler +// pick the right overload of PrintTo() for T. +template +class UniversalPrinter { + public: + // MSVC warns about adding const to a function type, so we want to + // disable the warning. +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4180) // Temporarily disables warning 4180. +#endif // _MSC_VER + + // Note: we deliberately don't call this PrintTo(), as that name + // conflicts with ::testing::internal::PrintTo in the body of the + // function. + static void Print(const T& value, ::std::ostream* os) { + // By default, ::testing::internal::PrintTo() is used for printing + // the value. + // + // Thanks to Koenig look-up, if T is a class and has its own + // PrintTo() function defined in its namespace, that function will + // be visible here. Since it is more specific than the generic ones + // in ::testing::internal, it will be picked by the compiler in the + // following statement - exactly what we want. + PrintTo(value, os); + } + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif // _MSC_VER +}; + +// UniversalPrintArray(begin, len, os) prints an array of 'len' +// elements, starting at address 'begin'. +template +void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { + if (len == 0) { + *os << "{}"; + } else { + *os << "{ "; + const size_t kThreshold = 18; + const size_t kChunkSize = 8; + // If the array has more than kThreshold elements, we'll have to + // omit some details by printing only the first and the last + // kChunkSize elements. + // TODO(wan@google.com): let the user control the threshold using a flag. + if (len <= kThreshold) { + PrintRawArrayTo(begin, len, os); + } else { + PrintRawArrayTo(begin, kChunkSize, os); + *os << ", ..., "; + PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); + } + *os << " }"; + } +} +// This overload prints a (const) char array compactly. +GTEST_API_ void UniversalPrintArray( + const char* begin, size_t len, ::std::ostream* os); + +// This overload prints a (const) wchar_t array compactly. +GTEST_API_ void UniversalPrintArray( + const wchar_t* begin, size_t len, ::std::ostream* os); + +// Implements printing an array type T[N]. +template +class UniversalPrinter { + public: + // Prints the given array, omitting some elements when there are too + // many. + static void Print(const T (&a)[N], ::std::ostream* os) { + UniversalPrintArray(a, N, os); + } +}; + +// Implements printing a reference type T&. +template +class UniversalPrinter { + public: + // MSVC warns about adding const to a function type, so we want to + // disable the warning. +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4180) // Temporarily disables warning 4180. +#endif // _MSC_VER + + static void Print(const T& value, ::std::ostream* os) { + // Prints the address of the value. We use reinterpret_cast here + // as static_cast doesn't compile when T is a function type. + *os << "@" << reinterpret_cast(&value) << " "; + + // Then prints the value itself. + UniversalPrint(value, os); + } + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif // _MSC_VER +}; + +// Prints a value tersely: for a reference type, the referenced value +// (but not the address) is printed; for a (const) char pointer, the +// NUL-terminated string (but not the pointer) is printed. + +template +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template +class UniversalTersePrinter { + public: + static void Print(const T (&value)[N], ::std::ostream* os) { + UniversalPrinter::Print(value, os); + } +}; +template <> +class UniversalTersePrinter { + public: + static void Print(const char* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(string(str), os); + } + } +}; +template <> +class UniversalTersePrinter { + public: + static void Print(char* str, ::std::ostream* os) { + UniversalTersePrinter::Print(str, os); + } +}; + +#if GTEST_HAS_STD_WSTRING +template <> +class UniversalTersePrinter { + public: + static void Print(const wchar_t* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(::std::wstring(str), os); + } + } +}; +#endif + +template <> +class UniversalTersePrinter { + public: + static void Print(wchar_t* str, ::std::ostream* os) { + UniversalTersePrinter::Print(str, os); + } +}; + +template +void UniversalTersePrint(const T& value, ::std::ostream* os) { + UniversalTersePrinter::Print(value, os); +} + +// Prints a value using the type inferred by the compiler. The +// difference between this and UniversalTersePrint() is that for a +// (const) char pointer, this prints both the pointer and the +// NUL-terminated string. +template +void UniversalPrint(const T& value, ::std::ostream* os) { + // A workarond for the bug in VC++ 7.1 that prevents us from instantiating + // UniversalPrinter with T directly. + typedef T T1; + UniversalPrinter::Print(value, os); +} + +#if GTEST_HAS_TR1_TUPLE +typedef ::std::vector Strings; + +// This helper template allows PrintTo() for tuples and +// UniversalTersePrintTupleFieldsToStrings() to be defined by +// induction on the number of tuple fields. The idea is that +// TuplePrefixPrinter::PrintPrefixTo(t, os) prints the first N +// fields in tuple t, and can be defined in terms of +// TuplePrefixPrinter. + +// The inductive case. +template +struct TuplePrefixPrinter { + // Prints the first N fields of a tuple. + template + static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { + TuplePrefixPrinter::PrintPrefixTo(t, os); + *os << ", "; + UniversalPrinter::type> + ::Print(::std::tr1::get(t), os); + } + + // Tersely prints the first N fields of a tuple to a string vector, + // one element for each field. + template + static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { + TuplePrefixPrinter::TersePrintPrefixToStrings(t, strings); + ::std::stringstream ss; + UniversalTersePrint(::std::tr1::get(t), &ss); + strings->push_back(ss.str()); + } +}; + +// Base cases. +template <> +struct TuplePrefixPrinter<0> { + template + static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} + + template + static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} +}; +// We have to specialize the entire TuplePrefixPrinter<> class +// template here, even though the definition of +// TersePrintPrefixToStrings() is the same as the generic version, as +// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't +// support specializing a method template of a class template. +template <> +struct TuplePrefixPrinter<1> { + template + static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { + UniversalPrinter::type>:: + Print(::std::tr1::get<0>(t), os); + } + + template + static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { + ::std::stringstream ss; + UniversalTersePrint(::std::tr1::get<0>(t), &ss); + strings->push_back(ss.str()); + } +}; + +// Helper function for printing a tuple. T must be instantiated with +// a tuple type. +template +void PrintTupleTo(const T& t, ::std::ostream* os) { + *os << "("; + TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: + PrintPrefixTo(t, os); + *os << ")"; +} + +// Prints the fields of a tuple tersely to a string vector, one +// element for each field. See the comment before +// UniversalTersePrint() for how we define "tersely". +template +Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { + Strings result; + TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: + TersePrintPrefixToStrings(value, &result); + return result; +} +#endif // GTEST_HAS_TR1_TUPLE + +} // namespace internal + +template +::std::string PrintToString(const T& value) { + ::std::stringstream ss; + internal::UniversalTersePrinter::Print(value, &ss); + return ss.str(); +} + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ + +#if GTEST_HAS_PARAM_TEST + +namespace testing { +namespace internal { + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Outputs a message explaining invalid registration of different +// fixture class for the same test case. This may happen when +// TEST_P macro is used to define two tests with the same name +// but in different namespaces. +GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, + const char* file, int line); + +template class ParamGeneratorInterface; +template class ParamGenerator; + +// Interface for iterating over elements provided by an implementation +// of ParamGeneratorInterface. +template +class ParamIteratorInterface { + public: + virtual ~ParamIteratorInterface() {} + // A pointer to the base generator instance. + // Used only for the purposes of iterator comparison + // to make sure that two iterators belong to the same generator. + virtual const ParamGeneratorInterface* BaseGenerator() const = 0; + // Advances iterator to point to the next element + // provided by the generator. The caller is responsible + // for not calling Advance() on an iterator equal to + // BaseGenerator()->End(). + virtual void Advance() = 0; + // Clones the iterator object. Used for implementing copy semantics + // of ParamIterator. + virtual ParamIteratorInterface* Clone() const = 0; + // Dereferences the current iterator and provides (read-only) access + // to the pointed value. It is the caller's responsibility not to call + // Current() on an iterator equal to BaseGenerator()->End(). + // Used for implementing ParamGenerator::operator*(). + virtual const T* Current() const = 0; + // Determines whether the given iterator and other point to the same + // element in the sequence generated by the generator. + // Used for implementing ParamGenerator::operator==(). + virtual bool Equals(const ParamIteratorInterface& other) const = 0; +}; + +// Class iterating over elements provided by an implementation of +// ParamGeneratorInterface. It wraps ParamIteratorInterface +// and implements the const forward iterator concept. +template +class ParamIterator { + public: + typedef T value_type; + typedef const T& reference; + typedef ptrdiff_t difference_type; + + // ParamIterator assumes ownership of the impl_ pointer. + ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} + ParamIterator& operator=(const ParamIterator& other) { + if (this != &other) + impl_.reset(other.impl_->Clone()); + return *this; + } + + const T& operator*() const { return *impl_->Current(); } + const T* operator->() const { return impl_->Current(); } + // Prefix version of operator++. + ParamIterator& operator++() { + impl_->Advance(); + return *this; + } + // Postfix version of operator++. + ParamIterator operator++(int /*unused*/) { + ParamIteratorInterface* clone = impl_->Clone(); + impl_->Advance(); + return ParamIterator(clone); + } + bool operator==(const ParamIterator& other) const { + return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); + } + bool operator!=(const ParamIterator& other) const { + return !(*this == other); + } + + private: + friend class ParamGenerator; + explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} + scoped_ptr > impl_; +}; + +// ParamGeneratorInterface is the binary interface to access generators +// defined in other translation units. +template +class ParamGeneratorInterface { + public: + typedef T ParamType; + + virtual ~ParamGeneratorInterface() {} + + // Generator interface definition + virtual ParamIteratorInterface* Begin() const = 0; + virtual ParamIteratorInterface* End() const = 0; +}; + +// Wraps ParamGeneratorInterface and provides general generator syntax +// compatible with the STL Container concept. +// This class implements copy initialization semantics and the contained +// ParamGeneratorInterface instance is shared among all copies +// of the original object. This is possible because that instance is immutable. +template +class ParamGenerator { + public: + typedef ParamIterator iterator; + + explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} + ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} + + ParamGenerator& operator=(const ParamGenerator& other) { + impl_ = other.impl_; + return *this; + } + + iterator begin() const { return iterator(impl_->Begin()); } + iterator end() const { return iterator(impl_->End()); } + + private: + linked_ptr > impl_; +}; + +// Generates values from a range of two comparable values. Can be used to +// generate sequences of user-defined types that implement operator+() and +// operator<(). +// This class is used in the Range() function. +template +class RangeGenerator : public ParamGeneratorInterface { + public: + RangeGenerator(T begin, T end, IncrementT step) + : begin_(begin), end_(end), + step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} + virtual ~RangeGenerator() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, begin_, 0, step_); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, end_, end_index_, step_); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, T value, int index, + IncrementT step) + : base_(base), value_(value), index_(index), step_(step) {} + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + virtual void Advance() { + value_ = value_ + step_; + index_++; + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const T* Current() const { return &value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const int other_index = + CheckedDowncastToActualType(&other)->index_; + return index_ == other_index; + } + + private: + Iterator(const Iterator& other) + : ParamIteratorInterface(), + base_(other.base_), value_(other.value_), index_(other.index_), + step_(other.step_) {} + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + T value_; + int index_; + const IncrementT step_; + }; // class RangeGenerator::Iterator + + static int CalculateEndIndex(const T& begin, + const T& end, + const IncrementT& step) { + int end_index = 0; + for (T i = begin; i < end; i = i + step) + end_index++; + return end_index; + } + + // No implementation - assignment is unsupported. + void operator=(const RangeGenerator& other); + + const T begin_; + const T end_; + const IncrementT step_; + // The index for the end() iterator. All the elements in the generated + // sequence are indexed (0-based) to aid iterator comparison. + const int end_index_; +}; // class RangeGenerator + + +// Generates values from a pair of STL-style iterators. Used in the +// ValuesIn() function. The elements are copied from the source range +// since the source can be located on the stack, and the generator +// is likely to persist beyond that stack frame. +template +class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { + public: + template + ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) + : container_(begin, end) {} + virtual ~ValuesInIteratorRangeGenerator() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, container_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, container_.end()); + } + + private: + typedef typename ::std::vector ContainerType; + + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + typename ContainerType::const_iterator iterator) + : base_(base), iterator_(iterator) {} + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + virtual void Advance() { + ++iterator_; + value_.reset(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + // We need to use cached value referenced by iterator_ because *iterator_ + // can return a temporary object (and of type other then T), so just + // having "return &*iterator_;" doesn't work. + // value_ is updated here and not in Advance() because Advance() + // can advance iterator_ beyond the end of the range, and we cannot + // detect that fact. The client code, on the other hand, is + // responsible for not calling Current() on an out-of-range iterator. + virtual const T* Current() const { + if (value_.get() == NULL) + value_.reset(new T(*iterator_)); + return value_.get(); + } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + return iterator_ == + CheckedDowncastToActualType(&other)->iterator_; + } + + private: + Iterator(const Iterator& other) + // The explicit constructor call suppresses a false warning + // emitted by gcc when supplied with the -Wextra option. + : ParamIteratorInterface(), + base_(other.base_), + iterator_(other.iterator_) {} + + const ParamGeneratorInterface* const base_; + typename ContainerType::const_iterator iterator_; + // A cached value of *iterator_. We keep it here to allow access by + // pointer in the wrapping iterator's operator->(). + // value_ needs to be mutable to be accessed in Current(). + // Use of scoped_ptr helps manage cached value's lifetime, + // which is bound by the lifespan of the iterator itself. + mutable scoped_ptr value_; + }; // class ValuesInIteratorRangeGenerator::Iterator + + // No implementation - assignment is unsupported. + void operator=(const ValuesInIteratorRangeGenerator& other); + + const ContainerType container_; +}; // class ValuesInIteratorRangeGenerator + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Stores a parameter value and later creates tests parameterized with that +// value. +template +class ParameterizedTestFactory : public TestFactoryBase { + public: + typedef typename TestClass::ParamType ParamType; + explicit ParameterizedTestFactory(ParamType parameter) : + parameter_(parameter) {} + virtual Test* CreateTest() { + TestClass::SetParam(¶meter_); + return new TestClass(); + } + + private: + const ParamType parameter_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// TestMetaFactoryBase is a base class for meta-factories that create +// test factories for passing into MakeAndRegisterTestInfo function. +template +class TestMetaFactoryBase { + public: + virtual ~TestMetaFactoryBase() {} + + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// TestMetaFactory creates test factories for passing into +// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives +// ownership of test factory pointer, same factory object cannot be passed +// into that method twice. But ParameterizedTestCaseInfo is going to call +// it for each Test/Parameter value combination. Thus it needs meta factory +// creator class. +template +class TestMetaFactory + : public TestMetaFactoryBase { + public: + typedef typename TestCase::ParamType ParamType; + + TestMetaFactory() {} + + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { + return new ParameterizedTestFactory(parameter); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseInfoBase is a generic interface +// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase +// accumulates test information provided by TEST_P macro invocations +// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations +// and uses that information to register all resulting test instances +// in RegisterTests method. The ParameterizeTestCaseRegistry class holds +// a collection of pointers to the ParameterizedTestCaseInfo objects +// and calls RegisterTests() on each of them when asked. +class ParameterizedTestCaseInfoBase { + public: + virtual ~ParameterizedTestCaseInfoBase() {} + + // Base part of test case name for display purposes. + virtual const string& GetTestCaseName() const = 0; + // Test case id to verify identity. + virtual TypeId GetTestCaseTypeId() const = 0; + // UnitTest class invokes this method to register tests in this + // test case right before running them in RUN_ALL_TESTS macro. + // This method should not be called more then once on any single + // instance of a ParameterizedTestCaseInfoBase derived class. + virtual void RegisterTests() = 0; + + protected: + ParameterizedTestCaseInfoBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P +// macro invocations for a particular test case and generators +// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that +// test case. It registers tests with all values generated by all +// generators when asked. +template +class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { + public: + // ParamType and GeneratorCreationFunc are private types but are required + // for declarations of public methods AddTestPattern() and + // AddTestCaseInstantiation(). + typedef typename TestCase::ParamType ParamType; + // A function that returns an instance of appropriate generator type. + typedef ParamGenerator(GeneratorCreationFunc)(); + + explicit ParameterizedTestCaseInfo(const char* name) + : test_case_name_(name) {} + + // Test case base name for display purposes. + virtual const string& GetTestCaseName() const { return test_case_name_; } + // Test case id to verify identity. + virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } + // TEST_P macro uses AddTestPattern() to record information + // about a single test in a LocalTestInfo structure. + // test_case_name is the base name of the test case (without invocation + // prefix). test_base_name is the name of an individual test without + // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is + // test case base name and DoBar is test base name. + void AddTestPattern(const char* test_case_name, + const char* test_base_name, + TestMetaFactoryBase* meta_factory) { + tests_.push_back(linked_ptr(new TestInfo(test_case_name, + test_base_name, + meta_factory))); + } + // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information + // about a generator. + int AddTestCaseInstantiation(const string& instantiation_name, + GeneratorCreationFunc* func, + const char* /* file */, + int /* line */) { + instantiations_.push_back(::std::make_pair(instantiation_name, func)); + return 0; // Return value used only to run this method in namespace scope. + } + // UnitTest class invokes this method to register tests in this test case + // test cases right before running tests in RUN_ALL_TESTS macro. + // This method should not be called more then once on any single + // instance of a ParameterizedTestCaseInfoBase derived class. + // UnitTest has a guard to prevent from calling this method more then once. + virtual void RegisterTests() { + for (typename TestInfoContainer::iterator test_it = tests_.begin(); + test_it != tests_.end(); ++test_it) { + linked_ptr test_info = *test_it; + for (typename InstantiationContainer::iterator gen_it = + instantiations_.begin(); gen_it != instantiations_.end(); + ++gen_it) { + const string& instantiation_name = gen_it->first; + ParamGenerator generator((*gen_it->second)()); + + string test_case_name; + if ( !instantiation_name.empty() ) + test_case_name = instantiation_name + "/"; + test_case_name += test_info->test_case_base_name; + + int i = 0; + for (typename ParamGenerator::iterator param_it = + generator.begin(); + param_it != generator.end(); ++param_it, ++i) { + Message test_name_stream; + test_name_stream << test_info->test_base_name << "/" << i; + MakeAndRegisterTestInfo( + test_case_name.c_str(), + test_name_stream.GetString().c_str(), + NULL, // No type parameter. + PrintToString(*param_it).c_str(), + GetTestCaseTypeId(), + TestCase::SetUpTestCase, + TestCase::TearDownTestCase, + test_info->test_meta_factory->CreateTestFactory(*param_it)); + } // for param_it + } // for gen_it + } // for test_it + } // RegisterTests + + private: + // LocalTestInfo structure keeps information about a single test registered + // with TEST_P macro. + struct TestInfo { + TestInfo(const char* a_test_case_base_name, + const char* a_test_base_name, + TestMetaFactoryBase* a_test_meta_factory) : + test_case_base_name(a_test_case_base_name), + test_base_name(a_test_base_name), + test_meta_factory(a_test_meta_factory) {} + + const string test_case_base_name; + const string test_base_name; + const scoped_ptr > test_meta_factory; + }; + typedef ::std::vector > TestInfoContainer; + // Keeps pairs of + // received from INSTANTIATE_TEST_CASE_P macros. + typedef ::std::vector > + InstantiationContainer; + + const string test_case_name_; + TestInfoContainer tests_; + InstantiationContainer instantiations_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); +}; // class ParameterizedTestCaseInfo + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase +// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P +// macros use it to locate their corresponding ParameterizedTestCaseInfo +// descriptors. +class ParameterizedTestCaseRegistry { + public: + ParameterizedTestCaseRegistry() {} + ~ParameterizedTestCaseRegistry() { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + delete *it; + } + } + + // Looks up or creates and returns a structure containing information about + // tests and instantiations of a particular test case. + template + ParameterizedTestCaseInfo* GetTestCasePatternHolder( + const char* test_case_name, + const char* file, + int line) { + ParameterizedTestCaseInfo* typed_test_info = NULL; + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + if ((*it)->GetTestCaseName() == test_case_name) { + if ((*it)->GetTestCaseTypeId() != GetTypeId()) { + // Complain about incorrect usage of Google Test facilities + // and terminate the program since we cannot guaranty correct + // test case setup and tear-down in this case. + ReportInvalidTestCaseType(test_case_name, file, line); + posix::Abort(); + } else { + // At this point we are sure that the object we found is of the same + // type we are looking for, so we downcast it to that type + // without further checks. + typed_test_info = CheckedDowncastToActualType< + ParameterizedTestCaseInfo >(*it); + } + break; + } + } + if (typed_test_info == NULL) { + typed_test_info = new ParameterizedTestCaseInfo(test_case_name); + test_case_infos_.push_back(typed_test_info); + } + return typed_test_info; + } + void RegisterTests() { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + (*it)->RegisterTests(); + } + } + + private: + typedef ::std::vector TestCaseInfoContainer; + + TestCaseInfoContainer test_case_infos_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); +}; + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ +// This file was GENERATED by command: +// pump.py gtest-param-util-generated.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently Google Test supports at most 50 arguments in Values, +// and at most 10 arguments in Combine. Please contact +// googletestframework@googlegroups.com if you need more. +// Please note that the number of arguments to Combine is limited +// by the maximum arity of the implementation of tr1::tuple which is +// currently set at 10. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Forward declarations of ValuesIn(), which is implemented in +// include/gtest/gtest-param-test.h. +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end); + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]); + +template +internal::ParamGenerator ValuesIn( + const Container& container); + +namespace internal { + +// Used in the Values() function to provide polymorphic capabilities. +template +class ValueArray1 { + public: + explicit ValueArray1(T1 v1) : v1_(v1) {} + + template + operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray1& other); + + const T1 v1_; +}; + +template +class ValueArray2 { + public: + ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray2& other); + + const T1 v1_; + const T2 v2_; +}; + +template +class ValueArray3 { + public: + ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray3& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; +}; + +template +class ValueArray4 { + public: + ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray4& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; +}; + +template +class ValueArray5 { + public: + ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray5& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; +}; + +template +class ValueArray6 { + public: + ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray6& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; +}; + +template +class ValueArray7 { + public: + ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray7& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; +}; + +template +class ValueArray8 { + public: + ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray8& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; +}; + +template +class ValueArray9 { + public: + ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray9& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; +}; + +template +class ValueArray10 { + public: + ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray10& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; +}; + +template +class ValueArray11 { + public: + ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray11& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; +}; + +template +class ValueArray12 { + public: + ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray12& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; +}; + +template +class ValueArray13 { + public: + ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray13& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; +}; + +template +class ValueArray14 { + public: + ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray14& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; +}; + +template +class ValueArray15 { + public: + ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray15& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; +}; + +template +class ValueArray16 { + public: + ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray16& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; +}; + +template +class ValueArray17 { + public: + ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray17& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; +}; + +template +class ValueArray18 { + public: + ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray18& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; +}; + +template +class ValueArray19 { + public: + ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray19& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; +}; + +template +class ValueArray20 { + public: + ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray20& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; +}; + +template +class ValueArray21 { + public: + ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray21& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; +}; + +template +class ValueArray22 { + public: + ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray22& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; +}; + +template +class ValueArray23 { + public: + ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray23& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; +}; + +template +class ValueArray24 { + public: + ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray24& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; +}; + +template +class ValueArray25 { + public: + ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray25& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; +}; + +template +class ValueArray26 { + public: + ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray26& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; +}; + +template +class ValueArray27 { + public: + ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray27& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; +}; + +template +class ValueArray28 { + public: + ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray28& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; +}; + +template +class ValueArray29 { + public: + ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray29& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; +}; + +template +class ValueArray30 { + public: + ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray30& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; +}; + +template +class ValueArray31 { + public: + ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray31& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; +}; + +template +class ValueArray32 { + public: + ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray32& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; +}; + +template +class ValueArray33 { + public: + ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, + T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray33& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; +}; + +template +class ValueArray34 { + public: + ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray34& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; +}; + +template +class ValueArray35 { + public: + ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), + v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray35& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; +}; + +template +class ValueArray36 { + public: + ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), + v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray36& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; +}; + +template +class ValueArray37 { + public: + ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), + v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), + v36_(v36), v37_(v37) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray37& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; +}; + +template +class ValueArray38 { + public: + ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray38& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; +}; + +template +class ValueArray39 { + public: + ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray39& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; +}; + +template +class ValueArray40 { + public: + ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), + v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), + v40_(v40) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray40& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; +}; + +template +class ValueArray41 { + public: + ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, + T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray41& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; +}; + +template +class ValueArray42 { + public: + ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray42& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; +}; + +template +class ValueArray43 { + public: + ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), + v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), + v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray43& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; +}; + +template +class ValueArray44 { + public: + ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), + v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), + v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), + v43_(v43), v44_(v44) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray44& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; +}; + +template +class ValueArray45 { + public: + ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), + v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), + v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), + v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray45& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; +}; + +template +class ValueArray46 { + public: + ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), + v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray46& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; +}; + +template +class ValueArray47 { + public: + ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), + v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), + v47_(v47) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray47& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; +}; + +template +class ValueArray48 { + public: + ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), + v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), + v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), + v46_(v46), v47_(v47), v48_(v48) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray48& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; +}; + +template +class ValueArray49 { + public: + ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, + T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), + v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_), static_cast(v49_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray49& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; + const T49 v49_; +}; + +template +class ValueArray50 { + public: + ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, + T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), + v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_), static_cast(v49_), static_cast(v50_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray50& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; + const T49 v49_; + const T50 v50_; +}; + +# if GTEST_HAS_COMBINE +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Generates values from the Cartesian product of values produced +// by the argument generators. +// +template +class CartesianProductGenerator2 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator2(const ParamGenerator& g1, + const ParamGenerator& g2) + : g1_(g1), g2_(g2) {} + virtual ~CartesianProductGenerator2() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current2_; + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + ParamType current_value_; + }; // class CartesianProductGenerator2::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator2& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; +}; // class CartesianProductGenerator2 + + +template +class CartesianProductGenerator3 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator3(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3) + : g1_(g1), g2_(g2), g3_(g3) {} + virtual ~CartesianProductGenerator3() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current3_; + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + ParamType current_value_; + }; // class CartesianProductGenerator3::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator3& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; +}; // class CartesianProductGenerator3 + + +template +class CartesianProductGenerator4 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator4(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} + virtual ~CartesianProductGenerator4() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current4_; + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + ParamType current_value_; + }; // class CartesianProductGenerator4::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator4& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; +}; // class CartesianProductGenerator4 + + +template +class CartesianProductGenerator5 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator5(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} + virtual ~CartesianProductGenerator5() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current5_; + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + ParamType current_value_; + }; // class CartesianProductGenerator5::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator5& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; +}; // class CartesianProductGenerator5 + + +template +class CartesianProductGenerator6 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator6(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} + virtual ~CartesianProductGenerator6() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current6_; + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + ParamType current_value_; + }; // class CartesianProductGenerator6::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator6& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; +}; // class CartesianProductGenerator6 + + +template +class CartesianProductGenerator7 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator7(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} + virtual ~CartesianProductGenerator7() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current7_; + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + ParamType current_value_; + }; // class CartesianProductGenerator7::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator7& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; +}; // class CartesianProductGenerator7 + + +template +class CartesianProductGenerator8 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator8(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), + g8_(g8) {} + virtual ~CartesianProductGenerator8() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current8_; + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + ParamType current_value_; + }; // class CartesianProductGenerator8::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator8& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; +}; // class CartesianProductGenerator8 + + +template +class CartesianProductGenerator9 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator9(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8, const ParamGenerator& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9) {} + virtual ~CartesianProductGenerator9() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end(), g9_, g9_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, + const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8), + begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current9_; + if (current9_ == end9_) { + current9_ = begin9_; + ++current8_; + } + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_ && + current9_ == typed_other->current9_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_, + *current9_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_ || + current9_ == end9_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + const typename ParamGenerator::iterator begin9_; + const typename ParamGenerator::iterator end9_; + typename ParamGenerator::iterator current9_; + ParamType current_value_; + }; // class CartesianProductGenerator9::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator9& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; + const ParamGenerator g9_; +}; // class CartesianProductGenerator9 + + +template +class CartesianProductGenerator10 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator10(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8, const ParamGenerator& g9, + const ParamGenerator& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9), g10_(g10) {} + virtual ~CartesianProductGenerator10() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end(), g9_, g9_.end(), g10_, g10_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, + const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9, + const ParamGenerator& g10, + const typename ParamGenerator::iterator& current10) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8), + begin9_(g9.begin()), end9_(g9.end()), current9_(current9), + begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current10_; + if (current10_ == end10_) { + current10_ = begin10_; + ++current9_; + } + if (current9_ == end9_) { + current9_ = begin9_; + ++current8_; + } + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_ && + current9_ == typed_other->current9_ && + current10_ == typed_other->current10_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_), + begin10_(other.begin10_), + end10_(other.end10_), + current10_(other.current10_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_, + *current9_, *current10_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_ || + current9_ == end9_ || + current10_ == end10_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + const typename ParamGenerator::iterator begin9_; + const typename ParamGenerator::iterator end9_; + typename ParamGenerator::iterator current9_; + const typename ParamGenerator::iterator begin10_; + const typename ParamGenerator::iterator end10_; + typename ParamGenerator::iterator current10_; + ParamType current_value_; + }; // class CartesianProductGenerator10::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator10& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; + const ParamGenerator g9_; + const ParamGenerator g10_; +}; // class CartesianProductGenerator10 + + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Helper classes providing Combine() with polymorphic features. They allow +// casting CartesianProductGeneratorN to ParamGenerator if T is +// convertible to U. +// +template +class CartesianProductHolder2 { + public: +CartesianProductHolder2(const Generator1& g1, const Generator2& g2) + : g1_(g1), g2_(g2) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator2( + static_cast >(g1_), + static_cast >(g2_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder2& other); + + const Generator1 g1_; + const Generator2 g2_; +}; // class CartesianProductHolder2 + +template +class CartesianProductHolder3 { + public: +CartesianProductHolder3(const Generator1& g1, const Generator2& g2, + const Generator3& g3) + : g1_(g1), g2_(g2), g3_(g3) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator3( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder3& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; +}; // class CartesianProductHolder3 + +template +class CartesianProductHolder4 { + public: +CartesianProductHolder4(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator4( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder4& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; +}; // class CartesianProductHolder4 + +template +class CartesianProductHolder5 { + public: +CartesianProductHolder5(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator5( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder5& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; +}; // class CartesianProductHolder5 + +template +class CartesianProductHolder6 { + public: +CartesianProductHolder6(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator6( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder6& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; +}; // class CartesianProductHolder6 + +template +class CartesianProductHolder7 { + public: +CartesianProductHolder7(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator7( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder7& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; +}; // class CartesianProductHolder7 + +template +class CartesianProductHolder8 { + public: +CartesianProductHolder8(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), + g8_(g8) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator8( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder8& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; +}; // class CartesianProductHolder8 + +template +class CartesianProductHolder9 { + public: +CartesianProductHolder9(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator9( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_), + static_cast >(g9_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder9& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; + const Generator9 g9_; +}; // class CartesianProductHolder9 + +template +class CartesianProductHolder10 { + public: +CartesianProductHolder10(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9, const Generator10& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9), g10_(g10) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator10( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_), + static_cast >(g9_), + static_cast >(g10_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder10& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; + const Generator9 g9_; + const Generator10 g10_; +}; // class CartesianProductHolder10 + +# endif // GTEST_HAS_COMBINE + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Functions producing parameter generators. +// +// Google Test uses these generators to produce parameters for value- +// parameterized tests. When a parameterized test case is instantiated +// with a particular generator, Google Test creates and runs tests +// for each element in the sequence produced by the generator. +// +// In the following sample, tests from test case FooTest are instantiated +// each three times with parameter values 3, 5, and 8: +// +// class FooTest : public TestWithParam { ... }; +// +// TEST_P(FooTest, TestThis) { +// } +// TEST_P(FooTest, TestThat) { +// } +// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// + +// Range() returns generators providing sequences of values in a range. +// +// Synopsis: +// Range(start, end) +// - returns a generator producing a sequence of values {start, start+1, +// start+2, ..., }. +// Range(start, end, step) +// - returns a generator producing a sequence of values {start, start+step, +// start+step+step, ..., }. +// Notes: +// * The generated sequences never include end. For example, Range(1, 5) +// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) +// returns a generator producing {1, 3, 5, 7}. +// * start and end must have the same type. That type may be any integral or +// floating-point type or a user defined type satisfying these conditions: +// * It must be assignable (have operator=() defined). +// * It must have operator+() (operator+(int-compatible type) for +// two-operand version). +// * It must have operator<() defined. +// Elements in the resulting sequences will also have that type. +// * Condition start < end must be satisfied in order for resulting sequences +// to contain any elements. +// +template +internal::ParamGenerator Range(T start, T end, IncrementT step) { + return internal::ParamGenerator( + new internal::RangeGenerator(start, end, step)); +} + +template +internal::ParamGenerator Range(T start, T end) { + return Range(start, end, 1); +} + +// ValuesIn() function allows generation of tests with parameters coming from +// a container. +// +// Synopsis: +// ValuesIn(const T (&array)[N]) +// - returns a generator producing sequences with elements from +// a C-style array. +// ValuesIn(const Container& container) +// - returns a generator producing sequences with elements from +// an STL-style container. +// ValuesIn(Iterator begin, Iterator end) +// - returns a generator producing sequences with elements from +// a range [begin, end) defined by a pair of STL-style iterators. These +// iterators can also be plain C pointers. +// +// Please note that ValuesIn copies the values from the containers +// passed in and keeps them to generate tests in RUN_ALL_TESTS(). +// +// Examples: +// +// This instantiates tests from test case StringTest +// each with C-string values of "foo", "bar", and "baz": +// +// const char* strings[] = {"foo", "bar", "baz"}; +// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); +// +// This instantiates tests from test case StlStringTest +// each with STL strings with values "a" and "b": +// +// ::std::vector< ::std::string> GetParameterStrings() { +// ::std::vector< ::std::string> v; +// v.push_back("a"); +// v.push_back("b"); +// return v; +// } +// +// INSTANTIATE_TEST_CASE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); +// +// +// This will also instantiate tests from CharTest +// each with parameter values 'a' and 'b': +// +// ::std::list GetParameterChars() { +// ::std::list list; +// list.push_back('a'); +// list.push_back('b'); +// return list; +// } +// ::std::list l = GetParameterChars(); +// INSTANTIATE_TEST_CASE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); +// +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end) { + typedef typename ::testing::internal::IteratorTraits + ::value_type ParamType; + return internal::ParamGenerator( + new internal::ValuesInIteratorRangeGenerator(begin, end)); +} + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]) { + return ValuesIn(array, array + N); +} + +template +internal::ParamGenerator ValuesIn( + const Container& container) { + return ValuesIn(container.begin(), container.end()); +} + +// Values() allows generating tests from explicitly specified list of +// parameters. +// +// Synopsis: +// Values(T v1, T v2, ..., T vN) +// - returns a generator producing sequences with elements v1, v2, ..., vN. +// +// For example, this instantiates tests from test case BarTest each +// with values "one", "two", and "three": +// +// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// +// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// The exact type of values will depend on the type of parameter in BazTest. +// +// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// +// Currently, Values() supports from 1 to 50 parameters. +// +template +internal::ValueArray1 Values(T1 v1) { + return internal::ValueArray1(v1); +} + +template +internal::ValueArray2 Values(T1 v1, T2 v2) { + return internal::ValueArray2(v1, v2); +} + +template +internal::ValueArray3 Values(T1 v1, T2 v2, T3 v3) { + return internal::ValueArray3(v1, v2, v3); +} + +template +internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { + return internal::ValueArray4(v1, v2, v3, v4); +} + +template +internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5) { + return internal::ValueArray5(v1, v2, v3, v4, v5); +} + +template +internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6) { + return internal::ValueArray6(v1, v2, v3, v4, v5, v6); +} + +template +internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7) { + return internal::ValueArray7(v1, v2, v3, v4, v5, + v6, v7); +} + +template +internal::ValueArray8 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { + return internal::ValueArray8(v1, v2, v3, v4, + v5, v6, v7, v8); +} + +template +internal::ValueArray9 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { + return internal::ValueArray9(v1, v2, v3, + v4, v5, v6, v7, v8, v9); +} + +template +internal::ValueArray10 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { + return internal::ValueArray10(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10); +} + +template +internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11) { + return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); +} + +template +internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12) { + return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); +} + +template +internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13) { + return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); +} + +template +internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { + return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14); +} + +template +internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { + return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15); +} + +template +internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16) { + return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16); +} + +template +internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17) { + return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17); +} + +template +internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18) { + return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18); +} + +template +internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { + return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); +} + +template +internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { + return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); +} + +template +internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { + return internal::ValueArray21(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); +} + +template +internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22) { + return internal::ValueArray22(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22); +} + +template +internal::ValueArray23 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23) { + return internal::ValueArray23(v1, v2, v3, + v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23); +} + +template +internal::ValueArray24 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24) { + return internal::ValueArray24(v1, v2, + v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24); +} + +template +internal::ValueArray25 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, + T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { + return internal::ValueArray25(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25); +} + +template +internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26) { + return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); +} + +template +internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27) { + return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); +} + +template +internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28) { + return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, + v28); +} + +template +internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29) { + return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, + v27, v28, v29); +} + +template +internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { + return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, + v26, v27, v28, v29, v30); +} + +template +internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { + return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31); +} + +template +internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32) { + return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32); +} + +template +internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33) { + return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); +} + +template +internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, + T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, + T31 v31, T32 v32, T33 v33, T34 v34) { + return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); +} + +template +internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { + return internal::ValueArray35(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, + v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); +} + +template +internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { + return internal::ValueArray36(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36); +} + +template +internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37) { + return internal::ValueArray37(v1, v2, v3, + v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36, v37); +} + +template +internal::ValueArray38 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37, T38 v38) { + return internal::ValueArray38(v1, v2, + v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, + v33, v34, v35, v36, v37, v38); +} + +template +internal::ValueArray39 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37, T38 v38, T39 v39) { + return internal::ValueArray39(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, + v32, v33, v34, v35, v36, v37, v38, v39); +} + +template +internal::ValueArray40 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, + T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, + T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { + return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, + v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); +} + +template +internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { + return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, + v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); +} + +template +internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42) { + return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, + v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, + v42); +} + +template +internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43) { + return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, + v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, + v41, v42, v43); +} + +template +internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44) { + return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, + v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, + v40, v41, v42, v43, v44); +} + +template +internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, + T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, + T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { + return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, + v39, v40, v41, v42, v43, v44, v45); +} + +template +internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { + return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, + v38, v39, v40, v41, v42, v43, v44, v45, v46); +} + +template +internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { + return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, + v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); +} + +template +internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, + T48 v48) { + return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, + v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); +} + +template +internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, + T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, + T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47, T48 v48, T49 v49) { + return internal::ValueArray49(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, + v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, + v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); +} + +template +internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, + T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, + T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { + return internal::ValueArray50(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, + v48, v49, v50); +} + +// Bool() allows generating tests with parameters in a set of (false, true). +// +// Synopsis: +// Bool() +// - returns a generator producing sequences with elements {false, true}. +// +// It is useful when testing code that depends on Boolean flags. Combinations +// of multiple flags can be tested when several Bool()'s are combined using +// Combine() function. +// +// In the following example all tests in the test case FlagDependentTest +// will be instantiated twice with parameters false and true. +// +// class FlagDependentTest : public testing::TestWithParam { +// virtual void SetUp() { +// external_flag = GetParam(); +// } +// } +// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// +inline internal::ParamGenerator Bool() { + return Values(false, true); +} + +# if GTEST_HAS_COMBINE +// Combine() allows the user to combine two or more sequences to produce +// values of a Cartesian product of those sequences' elements. +// +// Synopsis: +// Combine(gen1, gen2, ..., genN) +// - returns a generator producing sequences with elements coming from +// the Cartesian product of elements from the sequences generated by +// gen1, gen2, ..., genN. The sequence elements will have a type of +// tuple where T1, T2, ..., TN are the types +// of elements from sequences produces by gen1, gen2, ..., genN. +// +// Combine can have up to 10 arguments. This number is currently limited +// by the maximum number of elements in the tuple implementation used by Google +// Test. +// +// Example: +// +// This will instantiate tests in test case AnimalTest each one with +// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), +// tuple("dog", BLACK), and tuple("dog", WHITE): +// +// enum Color { BLACK, GRAY, WHITE }; +// class AnimalTest +// : public testing::TestWithParam > {...}; +// +// TEST_P(AnimalTest, AnimalLooksNice) {...} +// +// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); +// +// This will instantiate tests in FlagDependentTest with all variations of two +// Boolean flags: +// +// class FlagDependentTest +// : public testing::TestWithParam > { +// virtual void SetUp() { +// // Assigns external_flag_1 and external_flag_2 values from the tuple. +// tie(external_flag_1, external_flag_2) = GetParam(); +// } +// }; +// +// TEST_P(FlagDependentTest, TestFeature1) { +// // Test your code using external_flag_1 and external_flag_2 here. +// } +// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); +// +template +internal::CartesianProductHolder2 Combine( + const Generator1& g1, const Generator2& g2) { + return internal::CartesianProductHolder2( + g1, g2); +} + +template +internal::CartesianProductHolder3 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3) { + return internal::CartesianProductHolder3( + g1, g2, g3); +} + +template +internal::CartesianProductHolder4 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4) { + return internal::CartesianProductHolder4( + g1, g2, g3, g4); +} + +template +internal::CartesianProductHolder5 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5) { + return internal::CartesianProductHolder5( + g1, g2, g3, g4, g5); +} + +template +internal::CartesianProductHolder6 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6) { + return internal::CartesianProductHolder6( + g1, g2, g3, g4, g5, g6); +} + +template +internal::CartesianProductHolder7 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7) { + return internal::CartesianProductHolder7( + g1, g2, g3, g4, g5, g6, g7); +} + +template +internal::CartesianProductHolder8 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8) { + return internal::CartesianProductHolder8( + g1, g2, g3, g4, g5, g6, g7, g8); +} + +template +internal::CartesianProductHolder9 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8, const Generator9& g9) { + return internal::CartesianProductHolder9( + g1, g2, g3, g4, g5, g6, g7, g8, g9); +} + +template +internal::CartesianProductHolder10 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8, const Generator9& g9, + const Generator10& g10) { + return internal::CartesianProductHolder10( + g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); +} +# endif // GTEST_HAS_COMBINE + + + +# define TEST_P(test_case_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + : public test_case_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + virtual void TestBody(); \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ + #test_case_name, \ + #test_name, \ + new ::testing::internal::TestMetaFactory< \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ + return 0; \ + } \ + static int gtest_registering_dummy_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_case_name, \ + test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ + ::testing::internal::ParamGenerator \ + gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ + int gtest_##prefix##test_case_name##_dummy_ = \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ + #prefix, \ + >est_##prefix##test_case_name##_EvalGenerator_, \ + __FILE__, __LINE__) + +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Google C++ Testing Framework definitions useful in production code. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ + +// When you need to test the private or protected members of a class, +// use the FRIEND_TEST macro to declare your tests as friends of the +// class. For example: +// +// class MyClass { +// private: +// void MyMethod(); +// FRIEND_TEST(MyClassTest, MyMethod); +// }; +// +// class MyClassTest : public testing::Test { +// // ... +// }; +// +// TEST_F(MyClassTest, MyMethod) { +// // Can call MyClass::MyMethod() here. +// } + +#define FRIEND_TEST(test_case_name, test_name)\ +friend class test_case_name##_##test_name##_Test + +#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// + +#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ +#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ + +#include +#include + +namespace testing { + +// A copyable object representing the result of a test part (i.e. an +// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). +// +// Don't inherit from TestPartResult as its destructor is not virtual. +class GTEST_API_ TestPartResult { + public: + // The possible outcomes of a test part (i.e. an assertion or an + // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). + enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure // Failed and the test should be terminated. + }; + + // C'tor. TestPartResult does NOT have a default constructor. + // Always use this constructor (with parameters) to create a + // TestPartResult object. + TestPartResult(Type a_type, + const char* a_file_name, + int a_line_number, + const char* a_message) + : type_(a_type), + file_name_(a_file_name == NULL ? "" : a_file_name), + line_number_(a_line_number), + summary_(ExtractSummary(a_message)), + message_(a_message) { + } + + // Gets the outcome of the test part. + Type type() const { return type_; } + + // Gets the name of the source file where the test part took place, or + // NULL if it's unknown. + const char* file_name() const { + return file_name_.empty() ? NULL : file_name_.c_str(); + } + + // Gets the line in the source file where the test part took place, + // or -1 if it's unknown. + int line_number() const { return line_number_; } + + // Gets the summary of the failure message. + const char* summary() const { return summary_.c_str(); } + + // Gets the message associated with the test part. + const char* message() const { return message_.c_str(); } + + // Returns true iff the test part passed. + bool passed() const { return type_ == kSuccess; } + + // Returns true iff the test part failed. + bool failed() const { return type_ != kSuccess; } + + // Returns true iff the test part non-fatally failed. + bool nonfatally_failed() const { return type_ == kNonFatalFailure; } + + // Returns true iff the test part fatally failed. + bool fatally_failed() const { return type_ == kFatalFailure; } + + private: + Type type_; + + // Gets the summary of the failure message by omitting the stack + // trace in it. + static std::string ExtractSummary(const char* message); + + // The name of the source file where the test part took place, or + // "" if the source file is unknown. + std::string file_name_; + // The line in the source file where the test part took place, or -1 + // if the line number is unknown. + int line_number_; + std::string summary_; // The test failure summary. + std::string message_; // The test failure message. +}; + +// Prints a TestPartResult object. +std::ostream& operator<<(std::ostream& os, const TestPartResult& result); + +// An array of TestPartResult objects. +// +// Don't inherit from TestPartResultArray as its destructor is not +// virtual. +class GTEST_API_ TestPartResultArray { + public: + TestPartResultArray() {} + + // Appends the given TestPartResult to the array. + void Append(const TestPartResult& result); + + // Returns the TestPartResult at the given index (0-based). + const TestPartResult& GetTestPartResult(int index) const; + + // Returns the number of TestPartResult objects in the array. + int size() const; + + private: + std::vector array_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); +}; + +// This interface knows how to report a test part result. +class TestPartResultReporterInterface { + public: + virtual ~TestPartResultReporterInterface() {} + + virtual void ReportTestPartResult(const TestPartResult& result) = 0; +}; + +namespace internal { + +// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a +// statement generates new fatal failures. To do so it registers itself as the +// current test part result reporter. Besides checking if fatal failures were +// reported, it only delegates the reporting to the former result reporter. +// The original result reporter is restored in the destructor. +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +class GTEST_API_ HasNewFatalFailureHelper + : public TestPartResultReporterInterface { + public: + HasNewFatalFailureHelper(); + virtual ~HasNewFatalFailureHelper(); + virtual void ReportTestPartResult(const TestPartResult& result); + bool has_new_fatal_failure() const { return has_new_fatal_failure_; } + private: + bool has_new_fatal_failure_; + TestPartResultReporterInterface* original_reporter_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); +}; + +} // namespace internal + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ + +// This header implements typed tests and type-parameterized tests. + +// Typed (aka type-driven) tests repeat the same test for types in a +// list. You must know which types you want to test with when writing +// typed tests. Here's how you do it: + +#if 0 + +// First, define a fixture class template. It should be parameterized +// by a type. Remember to derive it from testing::Test. +template +class FooTest : public testing::Test { + public: + ... + typedef std::list List; + static T shared_; + T value_; +}; + +// Next, associate a list of types with the test case, which will be +// repeated for each type in the list. The typedef is necessary for +// the macro to parse correctly. +typedef testing::Types MyTypes; +TYPED_TEST_CASE(FooTest, MyTypes); + +// If the type list contains only one type, you can write that type +// directly without Types<...>: +// TYPED_TEST_CASE(FooTest, int); + +// Then, use TYPED_TEST() instead of TEST_F() to define as many typed +// tests for this test case as you want. +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + // Since we are inside a derived class template, C++ requires use to + // visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the TestFixture:: + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the "typename + // TestFixture::" prefix. + typename TestFixture::List values; + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } + +#endif // 0 + +// Type-parameterized tests are abstract test patterns parameterized +// by a type. Compared with typed tests, type-parameterized tests +// allow you to define the test pattern without knowing what the type +// parameters are. The defined pattern can be instantiated with +// different types any number of times, in any number of translation +// units. +// +// If you are designing an interface or concept, you can define a +// suite of type-parameterized tests to verify properties that any +// valid implementation of the interface/concept should have. Then, +// each implementation can easily instantiate the test suite to verify +// that it conforms to the requirements, without having to write +// similar tests repeatedly. Here's an example: + +#if 0 + +// First, define a fixture class template. It should be parameterized +// by a type. Remember to derive it from testing::Test. +template +class FooTest : public testing::Test { + ... +}; + +// Next, declare that you will define a type-parameterized test case +// (the _P suffix is for "parameterized" or "pattern", whichever you +// prefer): +TYPED_TEST_CASE_P(FooTest); + +// Then, use TYPED_TEST_P() to define as many type-parameterized tests +// for this type-parameterized test case as you want. +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } + +// Now the tricky part: you need to register all test patterns before +// you can instantiate them. The first argument of the macro is the +// test case name; the rest are the names of the tests in this test +// case. +REGISTER_TYPED_TEST_CASE_P(FooTest, + DoesBlah, HasPropertyA); + +// Finally, you are free to instantiate the pattern with the types you +// want. If you put the above code in a header file, you can #include +// it in multiple C++ source files and instantiate it multiple times. +// +// To distinguish different instances of the pattern, the first +// argument to the INSTANTIATE_* macro is a prefix that will be added +// to the actual test case name. Remember to pick unique prefixes for +// different instances. +typedef testing::Types MyTypes; +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); + +// If the type list contains only one type, you can write that type +// directly without Types<...>: +// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); + +#endif // 0 + + +// Implements typed tests. + +#if GTEST_HAS_TYPED_TEST + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the name of the typedef for the type parameters of the +// given test case. +# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ + +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types) +# define TYPED_TEST_CASE(CaseName, Types) \ + typedef ::testing::internal::TypeList< Types >::type \ + GTEST_TYPE_PARAMS_(CaseName) + +# define TYPED_TEST(CaseName, TestName) \ + template \ + class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ + : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTest< \ + CaseName, \ + ::testing::internal::TemplateSel< \ + GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ + GTEST_TYPE_PARAMS_(CaseName)>::Register(\ + "", #CaseName, #TestName, 0); \ + template \ + void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() + +#endif // GTEST_HAS_TYPED_TEST + +// Implements type-parameterized tests. + +#if GTEST_HAS_TYPED_TEST_P + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the namespace name that the type-parameterized tests for +// the given type-parameterized test case are defined in. The exact +// name of the namespace is subject to change without notice. +# define GTEST_CASE_NAMESPACE_(TestCaseName) \ + gtest_case_##TestCaseName##_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the name of the variable used to remember the names of +// the defined tests in the given test case. +# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ + gtest_typed_test_case_p_state_##TestCaseName##_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. +// +// Expands to the name of the variable used to remember the names of +// the registered tests in the given test case. +# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ + gtest_registered_test_names_##TestCaseName##_ + +// The variables defined in the type-parameterized test macros are +// static as typically these macros are used in a .h file that can be +// #included in multiple translation units linked together. +# define TYPED_TEST_CASE_P(CaseName) \ + static ::testing::internal::TypedTestCasePState \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) + +# define TYPED_TEST_P(CaseName, TestName) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + template \ + class TestName : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ + __FILE__, __LINE__, #CaseName, #TestName); \ + } \ + template \ + void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() + +# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ + } \ + static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ + __FILE__, __LINE__, #__VA_ARGS__) + +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types) +# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ + bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTestCase::type>::Register(\ + #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) + +#endif // GTEST_HAS_TYPED_TEST_P + +#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ + +// Depending on the platform, different string classes are available. +// On Linux, in addition to ::std::string, Google also makes use of +// class ::string, which has the same interface as ::std::string, but +// has a different implementation. +// +// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that +// ::string is available AND is a distinct type to ::std::string, or +// define it to 0 to indicate otherwise. +// +// If the user's ::std::string and ::string are the same class due to +// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. +// +// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined +// heuristically. + +namespace testing { + +// Declares the flags. + +// This flag temporary enables the disabled tests. +GTEST_DECLARE_bool_(also_run_disabled_tests); + +// This flag brings the debugger on an assertion failure. +GTEST_DECLARE_bool_(break_on_failure); + +// This flag controls whether Google Test catches all test-thrown exceptions +// and logs them as failures. +GTEST_DECLARE_bool_(catch_exceptions); + +// This flag enables using colors in terminal output. Available values are +// "yes" to enable colors, "no" (disable colors), or "auto" (the default) +// to let Google Test decide. +GTEST_DECLARE_string_(color); + +// This flag sets up the filter to select by name using a glob pattern +// the tests to run. If the filter is not given all tests are executed. +GTEST_DECLARE_string_(filter); + +// This flag causes the Google Test to list tests. None of the tests listed +// are actually run if the flag is provided. +GTEST_DECLARE_bool_(list_tests); + +// This flag controls whether Google Test emits a detailed XML report to a file +// in addition to its normal textual output. +GTEST_DECLARE_string_(output); + +// This flags control whether Google Test prints the elapsed time for each +// test. +GTEST_DECLARE_bool_(print_time); + +// This flag specifies the random number seed. +GTEST_DECLARE_int32_(random_seed); + +// This flag sets how many times the tests are repeated. The default value +// is 1. If the value is -1 the tests are repeating forever. +GTEST_DECLARE_int32_(repeat); + +// This flag controls whether Google Test includes Google Test internal +// stack frames in failure stack traces. +GTEST_DECLARE_bool_(show_internal_stack_frames); + +// When this flag is specified, tests' order is randomized on every iteration. +GTEST_DECLARE_bool_(shuffle); + +// This flag specifies the maximum number of stack frames to be +// printed in a failure message. +GTEST_DECLARE_int32_(stack_trace_depth); + +// When this flag is specified, a failed assertion will throw an +// exception if exceptions are enabled, or exit the program with a +// non-zero code otherwise. +GTEST_DECLARE_bool_(throw_on_failure); + +// When this flag is set with a "host:port" string, on supported +// platforms test results are streamed to the specified port on +// the specified host machine. +GTEST_DECLARE_string_(stream_result_to); + +// The upper limit for valid stack trace depths. +const int kMaxStackTraceDepth = 100; + +namespace internal { + +class AssertHelper; +class DefaultGlobalTestPartResultReporter; +class ExecDeathTest; +class NoExecDeathTest; +class FinalSuccessChecker; +class GTestFlagSaver; +class StreamingListenerTest; +class TestResultAccessor; +class TestEventListenersAccessor; +class TestEventRepeater; +class UnitTestRecordPropertyTestHelper; +class WindowsDeathTest; +class UnitTestImpl* GetUnitTestImpl(); +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, + const std::string& message); + +} // namespace internal + +// The friend relationship of some of these classes is cyclic. +// If we don't forward declare them the compiler might confuse the classes +// in friendship clauses with same named classes on the scope. +class Test; +class TestCase; +class TestInfo; +class UnitTest; + +// A class for indicating whether an assertion was successful. When +// the assertion wasn't successful, the AssertionResult object +// remembers a non-empty message that describes how it failed. +// +// To create an instance of this class, use one of the factory functions +// (AssertionSuccess() and AssertionFailure()). +// +// This class is useful for two purposes: +// 1. Defining predicate functions to be used with Boolean test assertions +// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts +// 2. Defining predicate-format functions to be +// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). +// +// For example, if you define IsEven predicate: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) +// will print the message +// +// Value of: IsEven(Fib(5)) +// Actual: false (5 is odd) +// Expected: true +// +// instead of a more opaque +// +// Value of: IsEven(Fib(5)) +// Actual: false +// Expected: true +// +// in case IsEven is a simple Boolean predicate. +// +// If you expect your predicate to be reused and want to support informative +// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up +// about half as often as positive ones in our tests), supply messages for +// both success and failure cases: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess() << n << " is even"; +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print +// +// Value of: IsEven(Fib(6)) +// Actual: true (8 is even) +// Expected: false +// +// NB: Predicates that support negative Boolean assertions have reduced +// performance in positive ones so be careful not to use them in tests +// that have lots (tens of thousands) of positive Boolean assertions. +// +// To use this class with EXPECT_PRED_FORMAT assertions such as: +// +// // Verifies that Foo() returns an even number. +// EXPECT_PRED_FORMAT1(IsEven, Foo()); +// +// you need to define: +// +// testing::AssertionResult IsEven(const char* expr, int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() +// << "Expected: " << expr << " is even\n Actual: it's " << n; +// } +// +// If Foo() returns 5, you will see the following message: +// +// Expected: Foo() is even +// Actual: it's 5 +// +class GTEST_API_ AssertionResult { + public: + // Copy constructor. + // Used in EXPECT_TRUE/FALSE(assertion_result). + AssertionResult(const AssertionResult& other); + // Used in the EXPECT_TRUE/FALSE(bool_expression). + explicit AssertionResult(bool success) : success_(success) {} + + // Returns true iff the assertion succeeded. + operator bool() const { return success_; } // NOLINT + + // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. + AssertionResult operator!() const; + + // Returns the text streamed into this AssertionResult. Test assertions + // use it when they fail (i.e., the predicate's outcome doesn't match the + // assertion's expectation). When nothing has been streamed into the + // object, returns an empty string. + const char* message() const { + return message_.get() != NULL ? message_->c_str() : ""; + } + // TODO(vladl@google.com): Remove this after making sure no clients use it. + // Deprecated; please use message() instead. + const char* failure_message() const { return message(); } + + // Streams a custom failure message into this object. + template AssertionResult& operator<<(const T& value) { + AppendMessage(Message() << value); + return *this; + } + + // Allows streaming basic output manipulators such as endl or flush into + // this object. + AssertionResult& operator<<( + ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { + AppendMessage(Message() << basic_manipulator); + return *this; + } + + private: + // Appends the contents of message to message_. + void AppendMessage(const Message& a_message) { + if (message_.get() == NULL) + message_.reset(new ::std::string); + message_->append(a_message.GetString().c_str()); + } + + // Stores result of the assertion predicate. + bool success_; + // Stores the message describing the condition in case the expectation + // construct is not satisfied with the predicate's outcome. + // Referenced via a pointer to avoid taking too much stack frame space + // with test assertions. + internal::scoped_ptr< ::std::string> message_; + + GTEST_DISALLOW_ASSIGN_(AssertionResult); +}; + +// Makes a successful assertion result. +GTEST_API_ AssertionResult AssertionSuccess(); + +// Makes a failed assertion result. +GTEST_API_ AssertionResult AssertionFailure(); + +// Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << msg. +GTEST_API_ AssertionResult AssertionFailure(const Message& msg); + +// The abstract class that all tests inherit from. +// +// In Google Test, a unit test program contains one or many TestCases, and +// each TestCase contains one or many Tests. +// +// When you define a test using the TEST macro, you don't need to +// explicitly derive from Test - the TEST macro automatically does +// this for you. +// +// The only time you derive from Test is when defining a test fixture +// to be used a TEST_F. For example: +// +// class FooTest : public testing::Test { +// protected: +// virtual void SetUp() { ... } +// virtual void TearDown() { ... } +// ... +// }; +// +// TEST_F(FooTest, Bar) { ... } +// TEST_F(FooTest, Baz) { ... } +// +// Test is not copyable. +class GTEST_API_ Test { + public: + friend class TestInfo; + + // Defines types for pointers to functions that set up and tear down + // a test case. + typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; + typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; + + // The d'tor is virtual as we intend to inherit from Test. + virtual ~Test(); + + // Sets up the stuff shared by all tests in this test case. + // + // Google Test will call Foo::SetUpTestCase() before running the first + // test in test case Foo. Hence a sub-class can define its own + // SetUpTestCase() method to shadow the one defined in the super + // class. + static void SetUpTestCase() {} + + // Tears down the stuff shared by all tests in this test case. + // + // Google Test will call Foo::TearDownTestCase() after running the last + // test in test case Foo. Hence a sub-class can define its own + // TearDownTestCase() method to shadow the one defined in the super + // class. + static void TearDownTestCase() {} + + // Returns true iff the current test has a fatal failure. + static bool HasFatalFailure(); + + // Returns true iff the current test has a non-fatal failure. + static bool HasNonfatalFailure(); + + // Returns true iff the current test has a (either fatal or + // non-fatal) failure. + static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } + + // Logs a property for the current test, test case, or for the entire + // invocation of the test program when used outside of the context of a + // test case. Only the last value for a given key is remembered. These + // are public static so they can be called from utility functions that are + // not members of the test fixture. Calls to RecordProperty made during + // lifespan of the test (from the moment its constructor starts to the + // moment its destructor finishes) will be output in XML as attributes of + // the element. Properties recorded from fixture's + // SetUpTestCase or TearDownTestCase are logged as attributes of the + // corresponding element. Calls to RecordProperty made in the + // global context (before or after invocation of RUN_ALL_TESTS and from + // SetUp/TearDown method of Environment objects registered with Google + // Test) will be output as attributes of the element. + static void RecordProperty(const std::string& key, const std::string& value); + static void RecordProperty(const std::string& key, int value); + + protected: + // Creates a Test object. + Test(); + + // Sets up the test fixture. + virtual void SetUp(); + + // Tears down the test fixture. + virtual void TearDown(); + + private: + // Returns true iff the current test has the same fixture class as + // the first test in the current test case. + static bool HasSameFixtureClass(); + + // Runs the test after the test fixture has been set up. + // + // A sub-class must implement this to define the test logic. + // + // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. + // Instead, use the TEST or TEST_F macro. + virtual void TestBody() = 0; + + // Sets up, executes, and tears down the test. + void Run(); + + // Deletes self. We deliberately pick an unusual name for this + // internal method to avoid clashing with names used in user TESTs. + void DeleteSelf_() { delete this; } + + // Uses a GTestFlagSaver to save and restore all Google Test flags. + const internal::GTestFlagSaver* const gtest_flag_saver_; + + // Often a user mis-spells SetUp() as Setup() and spends a long time + // wondering why it is never called by Google Test. The declaration of + // the following method is solely for catching such an error at + // compile time: + // + // - The return type is deliberately chosen to be not void, so it + // will be a conflict if a user declares void Setup() in his test + // fixture. + // + // - This method is private, so it will be another compiler error + // if a user calls it from his test fixture. + // + // DO NOT OVERRIDE THIS FUNCTION. + // + // If you see an error about overriding the following function or + // about it being private, you have mis-spelled SetUp() as Setup(). + struct Setup_should_be_spelled_SetUp {}; + virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } + + // We disallow copying Tests. + GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); +}; + +typedef internal::TimeInMillis TimeInMillis; + +// A copyable object representing a user specified test property which can be +// output as a key/value string pair. +// +// Don't inherit from TestProperty as its destructor is not virtual. +class TestProperty { + public: + // C'tor. TestProperty does NOT have a default constructor. + // Always use this constructor (with parameters) to create a + // TestProperty object. + TestProperty(const std::string& a_key, const std::string& a_value) : + key_(a_key), value_(a_value) { + } + + // Gets the user supplied key. + const char* key() const { + return key_.c_str(); + } + + // Gets the user supplied value. + const char* value() const { + return value_.c_str(); + } + + // Sets a new value, overriding the one supplied in the constructor. + void SetValue(const std::string& new_value) { + value_ = new_value; + } + + private: + // The key supplied by the user. + std::string key_; + // The value supplied by the user. + std::string value_; +}; + +// The result of a single Test. This includes a list of +// TestPartResults, a list of TestProperties, a count of how many +// death tests there are in the Test, and how much time it took to run +// the Test. +// +// TestResult is not copyable. +class GTEST_API_ TestResult { + public: + // Creates an empty TestResult. + TestResult(); + + // D'tor. Do not inherit from TestResult. + ~TestResult(); + + // Gets the number of all test parts. This is the sum of the number + // of successful test parts and the number of failed test parts. + int total_part_count() const; + + // Returns the number of the test properties. + int test_property_count() const; + + // Returns true iff the test passed (i.e. no test part failed). + bool Passed() const { return !Failed(); } + + // Returns true iff the test failed. + bool Failed() const; + + // Returns true iff the test fatally failed. + bool HasFatalFailure() const; + + // Returns true iff the test has a non-fatal failure. + bool HasNonfatalFailure() const; + + // Returns the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns the i-th test part result among all the results. i can range + // from 0 to test_property_count() - 1. If i is not in that range, aborts + // the program. + const TestPartResult& GetTestPartResult(int i) const; + + // Returns the i-th test property. i can range from 0 to + // test_property_count() - 1. If i is not in that range, aborts the + // program. + const TestProperty& GetTestProperty(int i) const; + + private: + friend class TestInfo; + friend class TestCase; + friend class UnitTest; + friend class internal::DefaultGlobalTestPartResultReporter; + friend class internal::ExecDeathTest; + friend class internal::TestResultAccessor; + friend class internal::UnitTestImpl; + friend class internal::WindowsDeathTest; + + // Gets the vector of TestPartResults. + const std::vector& test_part_results() const { + return test_part_results_; + } + + // Gets the vector of TestProperties. + const std::vector& test_properties() const { + return test_properties_; + } + + // Sets the elapsed time. + void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } + + // Adds a test property to the list. The property is validated and may add + // a non-fatal failure if invalid (e.g., if it conflicts with reserved + // key names). If a property is already recorded for the same key, the + // value will be updated, rather than storing multiple values for the same + // key. xml_element specifies the element for which the property is being + // recorded and is used for validation. + void RecordProperty(const std::string& xml_element, + const TestProperty& test_property); + + // Adds a failure if the key is a reserved attribute of Google Test + // testcase tags. Returns true if the property is valid. + // TODO(russr): Validate attribute names are legal and human readable. + static bool ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property); + + // Adds a test part result to the list. + void AddTestPartResult(const TestPartResult& test_part_result); + + // Returns the death test count. + int death_test_count() const { return death_test_count_; } + + // Increments the death test count, returning the new count. + int increment_death_test_count() { return ++death_test_count_; } + + // Clears the test part results. + void ClearTestPartResults(); + + // Clears the object. + void Clear(); + + // Protects mutable state of the property vector and of owned + // properties, whose values may be updated. + internal::Mutex test_properites_mutex_; + + // The vector of TestPartResults + std::vector test_part_results_; + // The vector of TestProperties + std::vector test_properties_; + // Running count of death tests. + int death_test_count_; + // The elapsed time, in milliseconds. + TimeInMillis elapsed_time_; + + // We disallow copying TestResult. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); +}; // class TestResult + +// A TestInfo object stores the following information about a test: +// +// Test case name +// Test name +// Whether the test should be run +// A function pointer that creates the test object when invoked +// Test result +// +// The constructor of TestInfo registers itself with the UnitTest +// singleton such that the RUN_ALL_TESTS() macro knows which tests to +// run. +class GTEST_API_ TestInfo { + public: + // Destructs a TestInfo object. This function is not virtual, so + // don't inherit from TestInfo. + ~TestInfo(); + + // Returns the test case name. + const char* test_case_name() const { return test_case_name_.c_str(); } + + // Returns the test name. + const char* name() const { return name_.c_str(); } + + // Returns the name of the parameter type, or NULL if this is not a typed + // or a type-parameterized test. + const char* type_param() const { + if (type_param_.get() != NULL) + return type_param_->c_str(); + return NULL; + } + + // Returns the text representation of the value parameter, or NULL if this + // is not a value-parameterized test. + const char* value_param() const { + if (value_param_.get() != NULL) + return value_param_->c_str(); + return NULL; + } + + // Returns true if this test should run, that is if the test is not + // disabled (or it is disabled but the also_run_disabled_tests flag has + // been specified) and its full name matches the user-specified filter. + // + // Google Test allows the user to filter the tests by their full names. + // The full name of a test Bar in test case Foo is defined as + // "Foo.Bar". Only the tests that match the filter will run. + // + // A filter is a colon-separated list of glob (not regex) patterns, + // optionally followed by a '-' and a colon-separated list of + // negative patterns (tests to exclude). A test is run if it + // matches one of the positive patterns and does not match any of + // the negative patterns. + // + // For example, *A*:Foo.* is a filter that matches any string that + // contains the character 'A' or starts with "Foo.". + bool should_run() const { return should_run_; } + + // Returns true iff this test will appear in the XML report. + bool is_reportable() const { + // For now, the XML report includes all tests matching the filter. + // In the future, we may trim tests that are excluded because of + // sharding. + return matches_filter_; + } + + // Returns the result of the test. + const TestResult* result() const { return &result_; } + + private: +#if GTEST_HAS_DEATH_TEST + friend class internal::DefaultDeathTestFactory; +#endif // GTEST_HAS_DEATH_TEST + friend class Test; + friend class TestCase; + friend class internal::UnitTestImpl; + friend class internal::StreamingListenerTest; + friend TestInfo* internal::MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + internal::TypeId fixture_class_id, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, + internal::TestFactoryBase* factory); + + // Constructs a TestInfo object. The newly constructed instance assumes + // ownership of the factory object. + TestInfo(const std::string& test_case_name, + const std::string& name, + const char* a_type_param, // NULL if not a type-parameterized test + const char* a_value_param, // NULL if not a value-parameterized test + internal::TypeId fixture_class_id, + internal::TestFactoryBase* factory); + + // Increments the number of death tests encountered in this test so + // far. + int increment_death_test_count() { + return result_.increment_death_test_count(); + } + + // Creates the test object, runs it, records its result, and then + // deletes it. + void Run(); + + static void ClearTestResult(TestInfo* test_info) { + test_info->result_.Clear(); + } + + // These fields are immutable properties of the test. + const std::string test_case_name_; // Test case name + const std::string name_; // Test name + // Name of the parameter type, or NULL if this is not a typed or a + // type-parameterized test. + const internal::scoped_ptr type_param_; + // Text representation of the value parameter, or NULL if this is not a + // value-parameterized test. + const internal::scoped_ptr value_param_; + const internal::TypeId fixture_class_id_; // ID of the test fixture class + bool should_run_; // True iff this test should run + bool is_disabled_; // True iff this test is disabled + bool matches_filter_; // True if this test matches the + // user-specified filter. + internal::TestFactoryBase* const factory_; // The factory that creates + // the test object + + // This field is mutable and needs to be reset before running the + // test for the second time. + TestResult result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); +}; + +// A test case, which consists of a vector of TestInfos. +// +// TestCase is not copyable. +class GTEST_API_ TestCase { + public: + // Creates a TestCase with the given name. + // + // TestCase does NOT have a default constructor. Always use this + // constructor to create a TestCase object. + // + // Arguments: + // + // name: name of the test case + // a_type_param: the name of the test's type parameter, or NULL if + // this is not a type-parameterized test. + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + TestCase(const char* name, const char* a_type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc); + + // Destructor of TestCase. + virtual ~TestCase(); + + // Gets the name of the TestCase. + const char* name() const { return name_.c_str(); } + + // Returns the name of the parameter type, or NULL if this is not a + // type-parameterized test case. + const char* type_param() const { + if (type_param_.get() != NULL) + return type_param_->c_str(); + return NULL; + } + + // Returns true if any test in this test case should run. + bool should_run() const { return should_run_; } + + // Gets the number of successful tests in this test case. + int successful_test_count() const; + + // Gets the number of failed tests in this test case. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests in this test case. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Get the number of tests in this test case that should run. + int test_to_run_count() const; + + // Gets the number of all tests in this test case. + int total_test_count() const; + + // Returns true iff the test case passed. + bool Passed() const { return !Failed(); } + + // Returns true iff the test case failed. + bool Failed() const { return failed_test_count() > 0; } + + // Returns the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns the i-th test among all the tests. i can range from 0 to + // total_test_count() - 1. If i is not in that range, returns NULL. + const TestInfo* GetTestInfo(int i) const; + + // Returns the TestResult that holds test properties recorded during + // execution of SetUpTestCase and TearDownTestCase. + const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } + + private: + friend class Test; + friend class internal::UnitTestImpl; + + // Gets the (mutable) vector of TestInfos in this TestCase. + std::vector& test_info_list() { return test_info_list_; } + + // Gets the (immutable) vector of TestInfos in this TestCase. + const std::vector& test_info_list() const { + return test_info_list_; + } + + // Returns the i-th test among all the tests. i can range from 0 to + // total_test_count() - 1. If i is not in that range, returns NULL. + TestInfo* GetMutableTestInfo(int i); + + // Sets the should_run member. + void set_should_run(bool should) { should_run_ = should; } + + // Adds a TestInfo to this test case. Will delete the TestInfo upon + // destruction of the TestCase object. + void AddTestInfo(TestInfo * test_info); + + // Clears the results of all tests in this test case. + void ClearResult(); + + // Clears the results of all tests in the given test case. + static void ClearTestCaseResult(TestCase* test_case) { + test_case->ClearResult(); + } + + // Runs every test in this TestCase. + void Run(); + + // Runs SetUpTestCase() for this TestCase. This wrapper is needed + // for catching exceptions thrown from SetUpTestCase(). + void RunSetUpTestCase() { (*set_up_tc_)(); } + + // Runs TearDownTestCase() for this TestCase. This wrapper is + // needed for catching exceptions thrown from TearDownTestCase(). + void RunTearDownTestCase() { (*tear_down_tc_)(); } + + // Returns true iff test passed. + static bool TestPassed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Passed(); + } + + // Returns true iff test failed. + static bool TestFailed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Failed(); + } + + // Returns true iff the test is disabled and will be reported in the XML + // report. + static bool TestReportableDisabled(const TestInfo* test_info) { + return test_info->is_reportable() && test_info->is_disabled_; + } + + // Returns true iff test is disabled. + static bool TestDisabled(const TestInfo* test_info) { + return test_info->is_disabled_; + } + + // Returns true iff this test will appear in the XML report. + static bool TestReportable(const TestInfo* test_info) { + return test_info->is_reportable(); + } + + // Returns true if the given test should run. + static bool ShouldRunTest(const TestInfo* test_info) { + return test_info->should_run(); + } + + // Shuffles the tests in this test case. + void ShuffleTests(internal::Random* random); + + // Restores the test order to before the first shuffle. + void UnshuffleTests(); + + // Name of the test case. + std::string name_; + // Name of the parameter type, or NULL if this is not a typed or a + // type-parameterized test. + const internal::scoped_ptr type_param_; + // The vector of TestInfos in their original order. It owns the + // elements in the vector. + std::vector test_info_list_; + // Provides a level of indirection for the test list to allow easy + // shuffling and restoring the test order. The i-th element in this + // vector is the index of the i-th test in the shuffled test list. + std::vector test_indices_; + // Pointer to the function that sets up the test case. + Test::SetUpTestCaseFunc set_up_tc_; + // Pointer to the function that tears down the test case. + Test::TearDownTestCaseFunc tear_down_tc_; + // True iff any test in this test case should run. + bool should_run_; + // Elapsed time, in milliseconds. + TimeInMillis elapsed_time_; + // Holds test properties recorded during execution of SetUpTestCase and + // TearDownTestCase. + TestResult ad_hoc_test_result_; + + // We disallow copying TestCases. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); +}; + +// An Environment object is capable of setting up and tearing down an +// environment. The user should subclass this to define his own +// environment(s). +// +// An Environment object does the set-up and tear-down in virtual +// methods SetUp() and TearDown() instead of the constructor and the +// destructor, as: +// +// 1. You cannot safely throw from a destructor. This is a problem +// as in some cases Google Test is used where exceptions are enabled, and +// we may want to implement ASSERT_* using exceptions where they are +// available. +// 2. You cannot use ASSERT_* directly in a constructor or +// destructor. +class Environment { + public: + // The d'tor is virtual as we need to subclass Environment. + virtual ~Environment() {} + + // Override this to define how to set up the environment. + virtual void SetUp() {} + + // Override this to define how to tear down the environment. + virtual void TearDown() {} + private: + // If you see an error about overriding the following function or + // about it being private, you have mis-spelled SetUp() as Setup(). + struct Setup_should_be_spelled_SetUp {}; + virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } +}; + +// The interface for tracing execution of tests. The methods are organized in +// the order the corresponding events are fired. +class TestEventListener { + public: + virtual ~TestEventListener() {} + + // Fired before any test activity starts. + virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; + + // Fired before each iteration of tests starts. There may be more than + // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration + // index, starting from 0. + virtual void OnTestIterationStart(const UnitTest& unit_test, + int iteration) = 0; + + // Fired before environment set-up for each iteration of tests starts. + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; + + // Fired after environment set-up for each iteration of tests ends. + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; + + // Fired before the test case starts. + virtual void OnTestCaseStart(const TestCase& test_case) = 0; + + // Fired before the test starts. + virtual void OnTestStart(const TestInfo& test_info) = 0; + + // Fired after a failed assertion or a SUCCEED() invocation. + virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; + + // Fired after the test ends. + virtual void OnTestEnd(const TestInfo& test_info) = 0; + + // Fired after the test case ends. + virtual void OnTestCaseEnd(const TestCase& test_case) = 0; + + // Fired before environment tear-down for each iteration of tests starts. + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; + + // Fired after environment tear-down for each iteration of tests ends. + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; + + // Fired after each iteration of tests finishes. + virtual void OnTestIterationEnd(const UnitTest& unit_test, + int iteration) = 0; + + // Fired after all test activities have ended. + virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; +}; + +// The convenience class for users who need to override just one or two +// methods and are not concerned that a possible change to a signature of +// the methods they override will not be caught during the build. For +// comments about each method please see the definition of TestEventListener +// above. +class EmptyTestEventListener : public TestEventListener { + public: + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} + virtual void OnTestStart(const TestInfo& /*test_info*/) {} + virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} + virtual void OnTestEnd(const TestInfo& /*test_info*/) {} + virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} + virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} +}; + +// TestEventListeners lets users add listeners to track events in Google Test. +class GTEST_API_ TestEventListeners { + public: + TestEventListeners(); + ~TestEventListeners(); + + // Appends an event listener to the end of the list. Google Test assumes + // the ownership of the listener (i.e. it will delete the listener when + // the test program finishes). + void Append(TestEventListener* listener); + + // Removes the given event listener from the list and returns it. It then + // becomes the caller's responsibility to delete the listener. Returns + // NULL if the listener is not found in the list. + TestEventListener* Release(TestEventListener* listener); + + // Returns the standard listener responsible for the default console + // output. Can be removed from the listeners list to shut down default + // console output. Note that removing this object from the listener list + // with Release transfers its ownership to the caller and makes this + // function return NULL the next time. + TestEventListener* default_result_printer() const { + return default_result_printer_; + } + + // Returns the standard listener responsible for the default XML output + // controlled by the --gtest_output=xml flag. Can be removed from the + // listeners list by users who want to shut down the default XML output + // controlled by this flag and substitute it with custom one. Note that + // removing this object from the listener list with Release transfers its + // ownership to the caller and makes this function return NULL the next + // time. + TestEventListener* default_xml_generator() const { + return default_xml_generator_; + } + + private: + friend class TestCase; + friend class TestInfo; + friend class internal::DefaultGlobalTestPartResultReporter; + friend class internal::NoExecDeathTest; + friend class internal::TestEventListenersAccessor; + friend class internal::UnitTestImpl; + + // Returns repeater that broadcasts the TestEventListener events to all + // subscribers. + TestEventListener* repeater(); + + // Sets the default_result_printer attribute to the provided listener. + // The listener is also added to the listener list and previous + // default_result_printer is removed from it and deleted. The listener can + // also be NULL in which case it will not be added to the list. Does + // nothing if the previous and the current listener objects are the same. + void SetDefaultResultPrinter(TestEventListener* listener); + + // Sets the default_xml_generator attribute to the provided listener. The + // listener is also added to the listener list and previous + // default_xml_generator is removed from it and deleted. The listener can + // also be NULL in which case it will not be added to the list. Does + // nothing if the previous and the current listener objects are the same. + void SetDefaultXmlGenerator(TestEventListener* listener); + + // Controls whether events will be forwarded by the repeater to the + // listeners in the list. + bool EventForwardingEnabled() const; + void SuppressEventForwarding(); + + // The actual list of listeners. + internal::TestEventRepeater* repeater_; + // Listener responsible for the standard result output. + TestEventListener* default_result_printer_; + // Listener responsible for the creation of the XML output file. + TestEventListener* default_xml_generator_; + + // We disallow copying TestEventListeners. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); +}; + +// A UnitTest consists of a vector of TestCases. +// +// This is a singleton class. The only instance of UnitTest is +// created when UnitTest::GetInstance() is first called. This +// instance is never deleted. +// +// UnitTest is not copyable. +// +// This class is thread-safe as long as the methods are called +// according to their specification. +class GTEST_API_ UnitTest { + public: + // Gets the singleton UnitTest object. The first time this method + // is called, a UnitTest object is constructed and returned. + // Consecutive calls will return the same object. + static UnitTest* GetInstance(); + + // Runs all tests in this UnitTest object and prints the result. + // Returns 0 if successful, or 1 otherwise. + // + // This method can only be called from the main thread. + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + int Run() GTEST_MUST_USE_RESULT_; + + // Returns the working directory when the first TEST() or TEST_F() + // was executed. The UnitTest object owns the string. + const char* original_working_dir() const; + + // Returns the TestCase object for the test that's currently running, + // or NULL if no test is running. + const TestCase* current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_); + + // Returns the TestInfo object for the test that's currently running, + // or NULL if no test is running. + const TestInfo* current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_); + + // Returns the random seed used at the start of the current test run. + int random_seed() const; + +#if GTEST_HAS_PARAM_TEST + // Returns the ParameterizedTestCaseRegistry object used to keep track of + // value-parameterized tests and instantiate and register them. + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_); +#endif // GTEST_HAS_PARAM_TEST + + // Gets the number of successful test cases. + int successful_test_case_count() const; + + // Gets the number of failed test cases. + int failed_test_case_count() const; + + // Gets the number of all test cases. + int total_test_case_count() const; + + // Gets the number of all test cases that contain at least one test + // that should run. + int test_case_to_run_count() const; + + // Gets the number of successful tests. + int successful_test_count() const; + + // Gets the number of failed tests. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Gets the number of all tests. + int total_test_count() const; + + // Gets the number of tests that should run. + int test_to_run_count() const; + + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const; + + // Gets the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const; + + // Returns true iff the unit test passed (i.e. all test cases passed). + bool Passed() const; + + // Returns true iff the unit test failed (i.e. some test case failed + // or something outside of all tests failed). + bool Failed() const; + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + const TestCase* GetTestCase(int i) const; + + // Returns the TestResult containing information on test failures and + // properties logged outside of individual test cases. + const TestResult& ad_hoc_test_result() const; + + // Returns the list of event listeners that can be used to track events + // inside Google Test. + TestEventListeners& listeners(); + + private: + // Registers and returns a global test environment. When a test + // program is run, all global test environments will be set-up in + // the order they were registered. After all tests in the program + // have finished, all global test environments will be torn-down in + // the *reverse* order they were registered. + // + // The UnitTest object takes ownership of the given environment. + // + // This method can only be called from the main thread. + Environment* AddEnvironment(Environment* env); + + // Adds a TestPartResult to the current TestResult object. All + // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) + // eventually call this to report their results. The user code + // should use the assertion macros instead of calling this directly. + void AddTestPartResult(TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Adds a TestProperty to the current TestResult object when invoked from + // inside a test, to current TestCase's ad_hoc_test_result_ when invoked + // from SetUpTestCase or TearDownTestCase, or to the global property set + // when invoked elsewhere. If the result already contains a property with + // the same key, the value will be updated. + void RecordProperty(const std::string& key, const std::string& value); + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + TestCase* GetMutableTestCase(int i); + + // Accessors for the implementation object. + internal::UnitTestImpl* impl() { return impl_; } + const internal::UnitTestImpl* impl() const { return impl_; } + + // These classes and funcions are friends as they need to access private + // members of UnitTest. + friend class Test; + friend class internal::AssertHelper; + friend class internal::ScopedTrace; + friend class internal::StreamingListenerTest; + friend class internal::UnitTestRecordPropertyTestHelper; + friend Environment* AddGlobalTestEnvironment(Environment* env); + friend internal::UnitTestImpl* internal::GetUnitTestImpl(); + friend void internal::ReportFailureInUnknownLocation( + TestPartResult::Type result_type, + const std::string& message); + + // Creates an empty UnitTest. + UnitTest(); + + // D'tor + virtual ~UnitTest(); + + // Pushes a trace defined by SCOPED_TRACE() on to the per-thread + // Google Test trace stack. + void PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Pops a trace from the per-thread Google Test trace stack. + void PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_); + + // Protects mutable state in *impl_. This is mutable as some const + // methods need to lock it too. + mutable internal::Mutex mutex_; + + // Opaque implementation object. This field is never changed once + // the object is constructed. We don't mark it as const here, as + // doing so will cause a warning in the constructor of UnitTest. + // Mutable state in *impl_ is protected by mutex_. + internal::UnitTestImpl* impl_; + + // We disallow copying UnitTest. + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); +}; + +// A convenient wrapper for adding an environment for the test +// program. +// +// You should call this before RUN_ALL_TESTS() is called, probably in +// main(). If you use gtest_main, you need to call this before main() +// starts for it to take effect. For example, you can define a global +// variable like this: +// +// testing::Environment* const foo_env = +// testing::AddGlobalTestEnvironment(new FooEnvironment); +// +// However, we strongly recommend you to write your own main() and +// call AddGlobalTestEnvironment() there, as relying on initialization +// of global variables makes the code harder to read and may cause +// problems when you register multiple environments from different +// translation units and the environments have dependencies among them +// (remember that the compiler doesn't guarantee the order in which +// global variables from different translation units are initialized). +inline Environment* AddGlobalTestEnvironment(Environment* env) { + return UnitTest::GetInstance()->AddEnvironment(env); +} + +// Initializes Google Test. This must be called before calling +// RUN_ALL_TESTS(). In particular, it parses a command line for the +// flags that Google Test recognizes. Whenever a Google Test flag is +// seen, it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Test flag variables are +// updated. +// +// Calling the function for the second time has no user-visible effect. +GTEST_API_ void InitGoogleTest(int* argc, char** argv); + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); + +namespace internal { + +// FormatForComparison::Format(value) formats a +// value of type ToPrint that is an operand of a comparison assertion +// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in +// the comparison, and is used to help determine the best way to +// format the value. In particular, when the value is a C string +// (char pointer) and the other operand is an STL string object, we +// want to format the C string as a string, since we know it is +// compared by value with the string object. If the value is a char +// pointer but the other operand is not an STL string object, we don't +// know whether the pointer is supposed to point to a NUL-terminated +// string, and thus want to print it as a pointer to be safe. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// The default case. +template +class FormatForComparison { + public: + static ::std::string Format(const ToPrint& value) { + return ::testing::PrintToString(value); + } +}; + +// Array. +template +class FormatForComparison { + public: + static ::std::string Format(const ToPrint* value) { + return FormatForComparison::Format(value); + } +}; + +// By default, print C string as pointers to be safe, as we don't know +// whether they actually point to a NUL-terminated string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ + template \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(static_cast(value)); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ + +// If a C string is compared with an STL string object, we know it's meant +// to point to a NUL-terminated string, and thus can print it as a string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ + template <> \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(value); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); + +#if GTEST_HAS_GLOBAL_STRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string); +#endif + +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring); +#endif + +#if GTEST_HAS_STD_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); +#endif + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_ + +// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) +// operand to be used in a failure message. The type (but not value) +// of the other operand may affect the format. This allows us to +// print a char* as a raw pointer when it is compared against another +// char* or void*, and print it as a C string when it is compared +// against an std::string object, for example. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template +std::string FormatForComparisonFailureMessage( + const T1& value, const T2& /* other_operand */) { + return FormatForComparison::Format(value); +} + +// The helper function for {ASSERT|EXPECT}_EQ. +template +AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + const T1& expected, + const T2& actual) { +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4389) // Temporarily disables warning on + // signed/unsigned mismatch. +#endif + + if (expected == actual) { + return AssertionSuccess(); + } + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif + + return EqFailure(expected_expression, + actual_expression, + FormatForComparisonFailureMessage(expected, actual), + FormatForComparisonFailureMessage(actual, expected), + false); +} + +// With this overloaded version, we allow anonymous enums to be used +// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums +// can be implicitly cast to BiggestInt. +GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual); + +// The helper class for {ASSERT|EXPECT}_EQ. The template argument +// lhs_is_null_literal is true iff the first argument to ASSERT_EQ() +// is a null pointer literal. The following default implementation is +// for lhs_is_null_literal being false. +template +class EqHelper { + public: + // This templatized version is for the general case. + template + static AssertionResult Compare(const char* expected_expression, + const char* actual_expression, + const T1& expected, + const T2& actual) { + return CmpHelperEQ(expected_expression, actual_expression, expected, + actual); + } + + // With this overloaded version, we allow anonymous enums to be used + // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous + // enums can be implicitly cast to BiggestInt. + // + // Even though its body looks the same as the above version, we + // cannot merge the two, as it will make anonymous enums unhappy. + static AssertionResult Compare(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual) { + return CmpHelperEQ(expected_expression, actual_expression, expected, + actual); + } +}; + +// This specialization is used when the first argument to ASSERT_EQ() +// is a null pointer literal, like NULL, false, or 0. +template <> +class EqHelper { + public: + // We define two overloaded versions of Compare(). The first + // version will be picked when the second argument to ASSERT_EQ() is + // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or + // EXPECT_EQ(false, a_bool). + template + static AssertionResult Compare( + const char* expected_expression, + const char* actual_expression, + const T1& expected, + const T2& actual, + // The following line prevents this overload from being considered if T2 + // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) + // expands to Compare("", "", NULL, my_ptr), which requires a conversion + // to match the Secret* in the other overload, which would otherwise make + // this template match better. + typename EnableIf::value>::type* = 0) { + return CmpHelperEQ(expected_expression, actual_expression, expected, + actual); + } + + // This version will be picked when the second argument to ASSERT_EQ() is a + // pointer, e.g. ASSERT_EQ(NULL, a_pointer). + template + static AssertionResult Compare( + const char* expected_expression, + const char* actual_expression, + // We used to have a second template parameter instead of Secret*. That + // template parameter would deduce to 'long', making this a better match + // than the first overload even without the first overload's EnableIf. + // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to + // non-pointer argument" (even a deduced integral argument), so the old + // implementation caused warnings in user code. + Secret* /* expected (NULL) */, + T* actual) { + // We already know that 'expected' is a null pointer. + return CmpHelperEQ(expected_expression, actual_expression, + static_cast(NULL), actual); + } +}; + +// A macro for implementing the helper functions needed to implement +// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste +// of similar code. +// +// For each templatized helper function, we also define an overloaded +// version for BiggestInt in order to reduce code bloat and allow +// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled +// with gcc 4. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ +template \ +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + const T1& val1, const T2& val2) {\ + if (val1 op val2) {\ + return AssertionSuccess();\ + } else {\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ + << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ + << " vs " << FormatForComparisonFailureMessage(val2, val1);\ + }\ +}\ +GTEST_API_ AssertionResult CmpHelper##op_name(\ + const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) + +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// Implements the helper function for {ASSERT|EXPECT}_NE +GTEST_IMPL_CMP_HELPER_(NE, !=); +// Implements the helper function for {ASSERT|EXPECT}_LE +GTEST_IMPL_CMP_HELPER_(LE, <=); +// Implements the helper function for {ASSERT|EXPECT}_LT +GTEST_IMPL_CMP_HELPER_(LT, <); +// Implements the helper function for {ASSERT|EXPECT}_GE +GTEST_IMPL_CMP_HELPER_(GE, >=); +// Implements the helper function for {ASSERT|EXPECT}_GT +GTEST_IMPL_CMP_HELPER_(GT, >); + +#undef GTEST_IMPL_CMP_HELPER_ + +// The helper function for {ASSERT|EXPECT}_STREQ. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual); + +// The helper function for {ASSERT|EXPECT}_STRCASEEQ. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual); + +// The helper function for {ASSERT|EXPECT}_STRNE. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + +// The helper function for {ASSERT|EXPECT}_STRCASENE. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + + +// Helper function for *_STREQ on wide strings. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const wchar_t* expected, + const wchar_t* actual); + +// Helper function for *_STRNE on wide strings. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2); + +} // namespace internal + +// IsSubstring() and IsNotSubstring() are intended to be used as the +// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by +// themselves. They check whether needle is a substring of haystack +// (NULL is considered a substring of itself only), and return an +// appropriate error message when they fail. +// +// The {needle,haystack}_expr arguments are the stringified +// expressions that generated the two real arguments. +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack); +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack); +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); + +#if GTEST_HAS_STD_WSTRING +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); +#endif // GTEST_HAS_STD_WSTRING + +namespace internal { + +// Helper template function for comparing floating-points. +// +// Template parameter: +// +// RawType: the raw floating-point type (either float or double) +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template +AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, + const char* actual_expression, + RawType expected, + RawType actual) { + const FloatingPoint lhs(expected), rhs(actual); + + if (lhs.AlmostEquals(rhs)) { + return AssertionSuccess(); + } + + ::std::stringstream expected_ss; + expected_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << expected; + + ::std::stringstream actual_ss; + actual_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << actual; + + return EqFailure(expected_expression, + actual_expression, + StringStreamToString(&expected_ss), + StringStreamToString(&actual_ss), + false); +} + +// Helper function for implementing ASSERT_NEAR. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error); + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// A class that enables one to stream messages to assertion macros +class GTEST_API_ AssertHelper { + public: + // Constructor. + AssertHelper(TestPartResult::Type type, + const char* file, + int line, + const char* message); + ~AssertHelper(); + + // Message assignment is a semantic trick to enable assertion + // streaming; see the GTEST_MESSAGE_ macro below. + void operator=(const Message& message) const; + + private: + // We put our data in a struct so that the size of the AssertHelper class can + // be as small as possible. This is important because gcc is incapable of + // re-using stack space even for temporary variables, so every EXPECT_EQ + // reserves stack space for another AssertHelper. + struct AssertHelperData { + AssertHelperData(TestPartResult::Type t, + const char* srcfile, + int line_num, + const char* msg) + : type(t), file(srcfile), line(line_num), message(msg) { } + + TestPartResult::Type const type; + const char* const file; + int const line; + std::string const message; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); + }; + + AssertHelperData* const data_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); +}; + +} // namespace internal + +#if GTEST_HAS_PARAM_TEST +// The pure interface class that all value-parameterized tests inherit from. +// A value-parameterized class must inherit from both ::testing::Test and +// ::testing::WithParamInterface. In most cases that just means inheriting +// from ::testing::TestWithParam, but more complicated test hierarchies +// may need to inherit from Test and WithParamInterface at different levels. +// +// This interface has support for accessing the test parameter value via +// the GetParam() method. +// +// Use it with one of the parameter generator defining functions, like Range(), +// Values(), ValuesIn(), Bool(), and Combine(). +// +// class FooTest : public ::testing::TestWithParam { +// protected: +// FooTest() { +// // Can use GetParam() here. +// } +// virtual ~FooTest() { +// // Can use GetParam() here. +// } +// virtual void SetUp() { +// // Can use GetParam() here. +// } +// virtual void TearDown { +// // Can use GetParam() here. +// } +// }; +// TEST_P(FooTest, DoesBar) { +// // Can use GetParam() method here. +// Foo foo; +// ASSERT_TRUE(foo.DoesBar(GetParam())); +// } +// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); + +template +class WithParamInterface { + public: + typedef T ParamType; + virtual ~WithParamInterface() {} + + // The current parameter value. Is also available in the test fixture's + // constructor. This member function is non-static, even though it only + // references static data, to reduce the opportunity for incorrect uses + // like writing 'WithParamInterface::GetParam()' for a test that + // uses a fixture whose parameter type is int. + const ParamType& GetParam() const { + GTEST_CHECK_(parameter_ != NULL) + << "GetParam() can only be called inside a value-parameterized test " + << "-- did you intend to write TEST_P instead of TEST_F?"; + return *parameter_; + } + + private: + // Sets parameter value. The caller is responsible for making sure the value + // remains alive and unchanged throughout the current test. + static void SetParam(const ParamType* parameter) { + parameter_ = parameter; + } + + // Static value used for accessing parameter during a test lifetime. + static const ParamType* parameter_; + + // TestClass must be a subclass of WithParamInterface and Test. + template friend class internal::ParameterizedTestFactory; +}; + +template +const T* WithParamInterface::parameter_ = NULL; + +// Most value-parameterized classes can ignore the existence of +// WithParamInterface, and can just inherit from ::testing::TestWithParam. + +template +class TestWithParam : public Test, public WithParamInterface { +}; + +#endif // GTEST_HAS_PARAM_TEST + +// Macros for indicating success/failure in test code. + +// ADD_FAILURE unconditionally adds a failure to the current test. +// SUCCEED generates a success - it doesn't automatically make the +// current test successful, as a test is only successful when it has +// no failure. +// +// EXPECT_* verifies that a certain condition is satisfied. If not, +// it behaves like ADD_FAILURE. In particular: +// +// EXPECT_TRUE verifies that a Boolean condition is true. +// EXPECT_FALSE verifies that a Boolean condition is false. +// +// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except +// that they will also abort the current function on failure. People +// usually want the fail-fast behavior of FAIL and ASSERT_*, but those +// writing data-driven tests often find themselves using ADD_FAILURE +// and EXPECT_* more. + +// Generates a nonfatal failure with a generic message. +#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") + +// Generates a nonfatal failure at the given source file location with +// a generic message. +#define ADD_FAILURE_AT(file, line) \ + GTEST_MESSAGE_AT_(file, line, "Failed", \ + ::testing::TestPartResult::kNonFatalFailure) + +// Generates a fatal failure with a generic message. +#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") + +// Define this macro to 1 to omit the definition of FAIL(), which is a +// generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_FAIL +# define FAIL() GTEST_FAIL() +#endif + +// Generates a success with a generic message. +#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") + +// Define this macro to 1 to omit the definition of SUCCEED(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_SUCCEED +# define SUCCEED() GTEST_SUCCEED() +#endif + +// Macros for testing exceptions. +// +// * {ASSERT|EXPECT}_THROW(statement, expected_exception): +// Tests that the statement throws the expected exception. +// * {ASSERT|EXPECT}_NO_THROW(statement): +// Tests that the statement doesn't throw any exception. +// * {ASSERT|EXPECT}_ANY_THROW(statement): +// Tests that the statement throws an exception. + +#define EXPECT_THROW(statement, expected_exception) \ + GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) +#define EXPECT_NO_THROW(statement) \ + GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define EXPECT_ANY_THROW(statement) \ + GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define ASSERT_THROW(statement, expected_exception) \ + GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) +#define ASSERT_NO_THROW(statement) \ + GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) +#define ASSERT_ANY_THROW(statement) \ + GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) + +// Boolean assertions. Condition can be either a Boolean expression or an +// AssertionResult. For more information on how to use AssertionResult with +// these macros see comments on that class. +#define EXPECT_TRUE(condition) \ + GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ + GTEST_NONFATAL_FAILURE_) +#define EXPECT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ + GTEST_NONFATAL_FAILURE_) +#define ASSERT_TRUE(condition) \ + GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ + GTEST_FATAL_FAILURE_) +#define ASSERT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ + GTEST_FATAL_FAILURE_) + +// Includes the auto-generated header that implements a family of +// generic predicate assertion macros. +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command +// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! +// +// Implements a family of generic predicate assertion macros. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ + +// Makes sure this header is not included before gtest.h. +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ +# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. +#endif // GTEST_INCLUDE_GTEST_GTEST_H_ + +// This header implements a family of generic predicate assertion +// macros: +// +// ASSERT_PRED_FORMAT1(pred_format, v1) +// ASSERT_PRED_FORMAT2(pred_format, v1, v2) +// ... +// +// where pred_format is a function or functor that takes n (in the +// case of ASSERT_PRED_FORMATn) values and their source expression +// text, and returns a testing::AssertionResult. See the definition +// of ASSERT_EQ in gtest.h for an example. +// +// If you don't care about formatting, you can use the more +// restrictive version: +// +// ASSERT_PRED1(pred, v1) +// ASSERT_PRED2(pred, v1, v2) +// ... +// +// where pred is an n-ary function or functor that returns bool, +// and the values v1, v2, ..., must support the << operator for +// streaming to std::ostream. +// +// We also define the EXPECT_* variations. +// +// For now we only support predicates whose arity is at most 5. +// Please email googletestframework@googlegroups.com if you need +// support for higher arities. + +// GTEST_ASSERT_ is the basic statement to which all of the assertions +// in this file reduce. Don't use this in your code. + +#define GTEST_ASSERT_(expression, on_failure) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar = (expression)) \ + ; \ + else \ + on_failure(gtest_ar.failure_message()) + + +// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use +// this in your code. +template +AssertionResult AssertPred1Helper(const char* pred_text, + const char* e1, + Pred pred, + const T1& v1) { + if (pred(v1)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. +// Don't use this in your code. +#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, v1), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use +// this in your code. +#define GTEST_PRED1_(pred, v1, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ + #v1, \ + pred, \ + v1), on_failure) + +// Unary predicate assertion macros. +#define EXPECT_PRED_FORMAT1(pred_format, v1) \ + GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED1(pred, v1) \ + GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT1(pred_format, v1) \ + GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED1(pred, v1) \ + GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use +// this in your code. +template +AssertionResult AssertPred2Helper(const char* pred_text, + const char* e1, + const char* e2, + Pred pred, + const T1& v1, + const T2& v2) { + if (pred(v1, v2)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. +// Don't use this in your code. +#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use +// this in your code. +#define GTEST_PRED2_(pred, v1, v2, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ + #v1, \ + #v2, \ + pred, \ + v1, \ + v2), on_failure) + +// Binary predicate assertion macros. +#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ + GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED2(pred, v1, v2) \ + GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ + GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED2(pred, v1, v2) \ + GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use +// this in your code. +template +AssertionResult AssertPred3Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3) { + if (pred(v1, v2, v3)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. +// Don't use this in your code. +#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use +// this in your code. +#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + pred, \ + v1, \ + v2, \ + v3), on_failure) + +// Ternary predicate assertion macros. +#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ + GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED3(pred, v1, v2, v3) \ + GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ + GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED3(pred, v1, v2, v3) \ + GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use +// this in your code. +template +AssertionResult AssertPred4Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + const char* e4, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3, + const T4& v4) { + if (pred(v1, v2, v3, v4)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. +// Don't use this in your code. +#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use +// this in your code. +#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + #v4, \ + pred, \ + v1, \ + v2, \ + v3, \ + v4), on_failure) + +// 4-ary predicate assertion macros. +#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ + GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ + GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ + GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ + GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use +// this in your code. +template +AssertionResult AssertPred5Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + const char* e4, + const char* e5, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3, + const T4& v4, + const T5& v5) { + if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ", " + << e5 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4 + << "\n" << e5 << " evaluates to " << v5; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. +// Don't use this in your code. +#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use +// this in your code. +#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + #v4, \ + #v5, \ + pred, \ + v1, \ + v2, \ + v3, \ + v4, \ + v5), on_failure) + +// 5-ary predicate assertion macros. +#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ + GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ + GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ + GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ + GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) + + + +#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ + +// Macros for testing equalities and inequalities. +// +// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual +// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 +// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 +// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 +// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 +// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 +// +// When they are not, Google Test prints both the tested expressions and +// their actual values. The values must be compatible built-in types, +// or you will get a compiler error. By "compatible" we mean that the +// values can be compared by the respective operator. +// +// Note: +// +// 1. It is possible to make a user-defined type work with +// {ASSERT|EXPECT}_??(), but that requires overloading the +// comparison operators and is thus discouraged by the Google C++ +// Usage Guide. Therefore, you are advised to use the +// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are +// equal. +// +// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on +// pointers (in particular, C strings). Therefore, if you use it +// with two C strings, you are testing how their locations in memory +// are related, not how their content is related. To compare two C +// strings by content, use {ASSERT|EXPECT}_STR*(). +// +// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to +// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you +// what the actual value is when it fails, and similarly for the +// other comparisons. +// +// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() +// evaluate their arguments, which is undefined. +// +// 5. These macros evaluate their arguments exactly once. +// +// Examples: +// +// EXPECT_NE(5, Foo()); +// EXPECT_EQ(NULL, a_pointer); +// ASSERT_LT(i, array_size); +// ASSERT_GT(records.size(), 0) << "There is no record left."; + +#define EXPECT_EQ(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal:: \ + EqHelper::Compare, \ + expected, actual) +#define EXPECT_NE(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) +#define EXPECT_LE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define EXPECT_LT(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define EXPECT_GE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define EXPECT_GT(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + +#define GTEST_ASSERT_EQ(expected, actual) \ + ASSERT_PRED_FORMAT2(::testing::internal:: \ + EqHelper::Compare, \ + expected, actual) +#define GTEST_ASSERT_NE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) +#define GTEST_ASSERT_LE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define GTEST_ASSERT_LT(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define GTEST_ASSERT_GE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define GTEST_ASSERT_GT(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + +// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of +// ASSERT_XY(), which clashes with some users' own code. + +#if !GTEST_DONT_DEFINE_ASSERT_EQ +# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_NE +# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LE +# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LT +# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GE +# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GT +# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +#endif + +// C-string Comparisons. All tests treat NULL and any non-NULL string +// as different. Two NULLs are equal. +// +// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 +// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 +// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case +// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case +// +// For wide or narrow string objects, you can use the +// {ASSERT|EXPECT}_??() macros. +// +// Don't depend on the order in which the arguments are evaluated, +// which is undefined. +// +// These macros evaluate their arguments exactly once. + +#define EXPECT_STREQ(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) +#define EXPECT_STRNE(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define EXPECT_STRCASEEQ(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) +#define EXPECT_STRCASENE(s1, s2)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +#define ASSERT_STREQ(expected, actual) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) +#define ASSERT_STRNE(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define ASSERT_STRCASEEQ(expected, actual) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) +#define ASSERT_STRCASENE(s1, s2)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +// Macros for comparing floating-point numbers. +// +// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): +// Tests that two float values are almost equal. +// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): +// Tests that two double values are almost equal. +// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): +// Tests that v1 and v2 are within the given distance to each other. +// +// Google Test uses ULP-based comparison to automatically pick a default +// error bound that is appropriate for the operands. See the +// FloatingPoint template class in gtest-internal.h if you are +// interested in the implementation details. + +#define EXPECT_FLOAT_EQ(expected, actual)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define EXPECT_DOUBLE_EQ(expected, actual)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define ASSERT_FLOAT_EQ(expected, actual)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define ASSERT_DOUBLE_EQ(expected, actual)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define EXPECT_NEAR(val1, val2, abs_error)\ + EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ + val1, val2, abs_error) + +#define ASSERT_NEAR(val1, val2, abs_error)\ + ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ + val1, val2, abs_error) + +// These predicate format functions work on floating-point values, and +// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. +// +// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2); +GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2); + + +#if GTEST_OS_WINDOWS + +// Macros that test for HRESULT failure and success, these are only useful +// on Windows, and rely on Windows SDK macros and APIs to compile. +// +// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) +// +// When expr unexpectedly fails or succeeds, Google Test prints the +// expected result and the actual result with both a human-readable +// string representation of the error, if available, as well as the +// hex result code. +# define EXPECT_HRESULT_SUCCEEDED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) + +# define ASSERT_HRESULT_SUCCEEDED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) + +# define EXPECT_HRESULT_FAILED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) + +# define ASSERT_HRESULT_FAILED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) + +#endif // GTEST_OS_WINDOWS + +// Macros that execute statement and check that it doesn't generate new fatal +// failures in the current thread. +// +// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); +// +// Examples: +// +// EXPECT_NO_FATAL_FAILURE(Process()); +// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; +// +#define ASSERT_NO_FATAL_FAILURE(statement) \ + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) +#define EXPECT_NO_FATAL_FAILURE(statement) \ + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) + +// Causes a trace (including the source file path, the current line +// number, and the given message) to be included in every test failure +// message generated by code in the current scope. The effect is +// undone when the control leaves the current scope. +// +// The message argument can be anything streamable to std::ostream. +// +// In the implementation, we include the current line number as part +// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s +// to appear in the same block - as long as they are on different +// lines. +#define SCOPED_TRACE(message) \ + ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ + __FILE__, __LINE__, ::testing::Message() << (message)) + +// Compile-time assertion for type equality. +// StaticAssertTypeEq() compiles iff type1 and type2 are +// the same type. The value it returns is not interesting. +// +// Instead of making StaticAssertTypeEq a class template, we make it a +// function template that invokes a helper class template. This +// prevents a user from misusing StaticAssertTypeEq by +// defining objects of that type. +// +// CAVEAT: +// +// When used inside a method of a class template, +// StaticAssertTypeEq() is effective ONLY IF the method is +// instantiated. For example, given: +// +// template class Foo { +// public: +// void Bar() { testing::StaticAssertTypeEq(); } +// }; +// +// the code: +// +// void Test1() { Foo foo; } +// +// will NOT generate a compiler error, as Foo::Bar() is never +// actually instantiated. Instead, you need: +// +// void Test2() { Foo foo; foo.Bar(); } +// +// to cause a compiler error. +template +bool StaticAssertTypeEq() { + (void)internal::StaticAssertTypeEqHelper(); + return true; +} + +// Defines a test. +// +// The first parameter is the name of the test case, and the second +// parameter is the name of the test within the test case. +// +// The convention is to end the test case name with "Test". For +// example, a test case for the Foo class can be named FooTest. +// +// The user should put his test code between braces after using this +// macro. Example: +// +// TEST(FooTest, InitializesCorrectly) { +// Foo foo; +// EXPECT_TRUE(foo.StatusIsOK()); +// } + +// Note that we call GetTestTypeId() instead of GetTypeId< +// ::testing::Test>() here to get the type ID of testing::Test. This +// is to work around a suspected linker bug when using Google Test as +// a framework on Mac OS X. The bug causes GetTypeId< +// ::testing::Test>() to return different values depending on whether +// the call is from the Google Test framework itself or from user test +// code. GetTestTypeId() is guaranteed to always return the same +// value, as it always calls GetTypeId<>() from the Google Test +// framework. +#define GTEST_TEST(test_case_name, test_name)\ + GTEST_TEST_(test_case_name, test_name, \ + ::testing::Test, ::testing::internal::GetTestTypeId()) + +// Define this macro to 1 to omit the definition of TEST(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_TEST +# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +#endif + +// Defines a test that uses a test fixture. +// +// The first parameter is the name of the test fixture class, which +// also doubles as the test case name. The second parameter is the +// name of the test within the test case. +// +// A test fixture class must be declared earlier. The user should put +// his test code between braces after using this macro. Example: +// +// class FooTest : public testing::Test { +// protected: +// virtual void SetUp() { b_.AddElement(3); } +// +// Foo a_; +// Foo b_; +// }; +// +// TEST_F(FooTest, InitializesCorrectly) { +// EXPECT_TRUE(a_.StatusIsOK()); +// } +// +// TEST_F(FooTest, ReturnsElementCountCorrectly) { +// EXPECT_EQ(0, a_.size()); +// EXPECT_EQ(1, b_.size()); +// } + +#define TEST_F(test_fixture, test_name)\ + GTEST_TEST_(test_fixture, test_name, test_fixture, \ + ::testing::internal::GetTypeId()) + +} // namespace testing + +// Use this function in main() to run all tests. It returns 0 if all +// tests are successful, or 1 otherwise. +// +// RUN_ALL_TESTS() should be invoked after the command line has been +// parsed by InitGoogleTest(). +// +// This function was formerly a macro; thus, it is in the global +// namespace and has an all-caps name. +int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; + +inline int RUN_ALL_TESTS() { + return ::testing::UnitTest::GetInstance()->Run(); +} + +#endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/src/ext/gtest/gtest_main.cc b/src/ext/gtest/gtest_main.cc new file mode 100644 index 00000000..96223e21 --- /dev/null +++ b/src/ext/gtest/gtest_main.cc @@ -0,0 +1,41 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +#include +#include + +GTEST_API_ int main(int argc, char **argv) { + google::InitGoogleLogging(argv[0]); + FLAGS_stderrthreshold = 1; // Warning and above. + printf("Running main() from gtest_main.cc\n"); + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/ext/lodepng/lodepng.cpp b/src/ext/lodepng/lodepng.cpp new file mode 100644 index 00000000..8c78758f --- /dev/null +++ b/src/ext/lodepng/lodepng.cpp @@ -0,0 +1,6224 @@ +/* +LodePNG version 20160501 + +Copyright (c) 2005-2016 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +/* +The manual and changelog are in the header file "lodepng.h" +Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C. +*/ + +#include "lodepng.h" + +#include +#include +#include + +#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ +#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ +#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ +#endif /*_MSC_VER */ + +const char* LODEPNG_VERSION_STRING = "20160501"; + +/* +This source file is built up in the following large parts. The code sections +with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. +-Tools for C and common code for PNG and Zlib +-C Code for Zlib (huffman, deflate, ...) +-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) +-The C++ wrapper around all of the above +*/ + +/*The malloc, realloc and free functions defined here with "lodepng_" in front +of the name, so that you can easily change them to others related to your +platform if needed. Everything else in the code calls these. Pass +-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out +#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and +define them in your own project's source files without needing to change +lodepng source code. Don't forget to remove "static" if you copypaste them +from here.*/ + +#ifdef LODEPNG_COMPILE_ALLOCATORS +static void* lodepng_malloc(size_t size) +{ + return malloc(size); +} + +static void* lodepng_realloc(void* ptr, size_t new_size) +{ + return realloc(ptr, new_size); +} + +static void lodepng_free(void* ptr) +{ + free(ptr); +} +#else /*LODEPNG_COMPILE_ALLOCATORS*/ +void* lodepng_malloc(size_t size); +void* lodepng_realloc(void* ptr, size_t new_size); +void lodepng_free(void* ptr); +#endif /*LODEPNG_COMPILE_ALLOCATORS*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // Tools for C, and common code for PNG and Zlib. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/* +Often in case of an error a value is assigned to a variable and then it breaks +out of a loop (to go to the cleanup phase of a function). This macro does that. +It makes the error handling code shorter and more readable. + +Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); +*/ +#define CERROR_BREAK(errorvar, code)\ +{\ + errorvar = code;\ + break;\ +} + +/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ +#define ERROR_BREAK(code) CERROR_BREAK(error, code) + +/*Set error var to the error code, and return it.*/ +#define CERROR_RETURN_ERROR(errorvar, code)\ +{\ + errorvar = code;\ + return code;\ +} + +/*Try the code, if it returns error, also return the error.*/ +#define CERROR_TRY_RETURN(call)\ +{\ + unsigned error = call;\ + if(error) return error;\ +} + +/*Set error var to the error code, and return from the void function.*/ +#define CERROR_RETURN(errorvar, code)\ +{\ + errorvar = code;\ + return;\ +} + +/* +About uivector, ucvector and string: +-All of them wrap dynamic arrays or text strings in a similar way. +-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. +-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. +-They're not used in the interface, only internally in this file as static functions. +-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. +*/ + +#ifdef LODEPNG_COMPILE_ZLIB +/*dynamic vector of unsigned ints*/ +typedef struct uivector +{ + unsigned* data; + size_t size; /*size in number of unsigned longs*/ + size_t allocsize; /*allocated size in bytes*/ +} uivector; + +static void uivector_cleanup(void* p) +{ + ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; + lodepng_free(((uivector*)p)->data); + ((uivector*)p)->data = NULL; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_reserve(uivector* p, size_t allocsize) +{ + if(allocsize > p->allocsize) + { + size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); + void* data = lodepng_realloc(p->data, newsize); + if(data) + { + p->allocsize = newsize; + p->data = (unsigned*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_resize(uivector* p, size_t size) +{ + if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; + p->size = size; + return 1; /*success*/ +} + +/*resize and give all new elements the value*/ +static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) +{ + size_t oldsize = p->size, i; + if(!uivector_resize(p, size)) return 0; + for(i = oldsize; i < size; ++i) p->data[i] = value; + return 1; +} + +static void uivector_init(uivector* p) +{ + p->data = NULL; + p->size = p->allocsize = 0; +} + +#ifdef LODEPNG_COMPILE_ENCODER +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_push_back(uivector* p, unsigned c) +{ + if(!uivector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* /////////////////////////////////////////////////////////////////////////// */ + +/*dynamic vector of unsigned chars*/ +typedef struct ucvector +{ + unsigned char* data; + size_t size; /*used size*/ + size_t allocsize; /*allocated size*/ +} ucvector; + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_reserve(ucvector* p, size_t allocsize) +{ + if(allocsize > p->allocsize) + { + size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); + void* data = lodepng_realloc(p->data, newsize); + if(data) + { + p->allocsize = newsize; + p->data = (unsigned char*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_resize(ucvector* p, size_t size) +{ + if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0; + p->size = size; + return 1; /*success*/ +} + +#ifdef LODEPNG_COMPILE_PNG + +static void ucvector_cleanup(void* p) +{ + ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; + lodepng_free(((ucvector*)p)->data); + ((ucvector*)p)->data = NULL; +} + +static void ucvector_init(ucvector* p) +{ + p->data = NULL; + p->size = p->allocsize = 0; +} +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ZLIB +/*you can both convert from vector to buffer&size and vica versa. If you use +init_buffer to take over a buffer and size, it is not needed to use cleanup*/ +static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) +{ + p->data = buffer; + p->allocsize = p->size = size; +} +#endif /*LODEPNG_COMPILE_ZLIB*/ + +#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER) +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_push_back(ucvector* p, unsigned char c) +{ + if(!ucvector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ + + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned string_resize(char** out, size_t size) +{ + char* data = (char*)lodepng_realloc(*out, size + 1); + if(data) + { + data[size] = 0; /*null termination char*/ + *out = data; + } + return data != 0; +} + +/*init a {char*, size_t} pair for use as string*/ +static void string_init(char** out) +{ + *out = NULL; + string_resize(out, 0); +} + +/*free the above pair again*/ +static void string_cleanup(char** out) +{ + lodepng_free(*out); + *out = NULL; +} + +static void string_set(char** out, const char* in) +{ + size_t insize = strlen(in), i; + if(string_resize(out, insize)) + { + for(i = 0; i != insize; ++i) + { + (*out)[i] = in[i]; + } + } +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +unsigned lodepng_read32bitInt(const unsigned char* buffer) +{ + return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); +} + +#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) +/*buffer must have at least 4 allocated bytes available*/ +static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) +{ + buffer[0] = (unsigned char)((value >> 24) & 0xff); + buffer[1] = (unsigned char)((value >> 16) & 0xff); + buffer[2] = (unsigned char)((value >> 8) & 0xff); + buffer[3] = (unsigned char)((value ) & 0xff); +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ + +#ifdef LODEPNG_COMPILE_ENCODER +static void lodepng_add32bitInt(ucvector* buffer, unsigned value) +{ + ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ + lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / File IO / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DISK + +/* returns negative value on error. This should be pure C compatible, so no fstat. */ +static long lodepng_filesize(const char* filename) +{ + FILE* file; + long size; + file = fopen(filename, "rb"); + if(!file) return -1; + + if(fseek(file, 0, SEEK_END) != 0) + { + fclose(file); + return -1; + } + + size = ftell(file); + /* It may give LONG_MAX as directory size, this is invalid for us. */ + if(size == LONG_MAX) size = -1; + + fclose(file); + return size; +} + +/* load file into buffer that already has the correct allocated size. Returns error code.*/ +static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) +{ + FILE* file; + size_t readsize; + file = fopen(filename, "rb"); + if(!file) return 78; + + readsize = fread(out, 1, size, file); + fclose(file); + + if (readsize != size) return 78; + return 0; +} + +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) +{ + long size = lodepng_filesize(filename); + if (size < 0) return 78; + *outsize = (size_t)size; + + *out = (unsigned char*)lodepng_malloc((size_t)size); + if(!(*out) && size > 0) return 83; /*the above malloc failed*/ + + return lodepng_buffer_file(*out, (size_t)size, filename); +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) +{ + FILE* file; + file = fopen(filename, "wb" ); + if(!file) return 79; + fwrite((char*)buffer , 1 , buffersize, file); + fclose(file); + return 0; +} + +#endif /*LODEPNG_COMPILE_DISK*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of common code and tools. Begin of Zlib related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_ENCODER +/*TODO: this ignores potential out of memory errors*/ +#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\ +{\ + /*add a new byte at the end*/\ + if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\ + /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\ + (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\ + ++(*bitpointer);\ +} + +static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) +{ + size_t i; + for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1)); +} + +static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) +{ + size_t i; + for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1)); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1) + +static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) +{ + unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream)); + ++(*bitpointer); + return result; +} + +static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) +{ + unsigned result = 0, i; + for(i = 0; i != nbits; ++i) + { + result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; + ++(*bitpointer); + } + return result; +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflate - Huffman / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#define FIRST_LENGTH_CODE_INDEX 257 +#define LAST_LENGTH_CODE_INDEX 285 +/*256 literals, the end code, some length codes, and 2 unused codes*/ +#define NUM_DEFLATE_CODE_SYMBOLS 288 +/*the distance codes have their own symbols, 30 used, 2 unused*/ +#define NUM_DISTANCE_SYMBOLS 32 +/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ +#define NUM_CODE_LENGTH_CODES 19 + +/*the base lengths represented by codes 257-285*/ +static const unsigned LENGTHBASE[29] + = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, + 67, 83, 99, 115, 131, 163, 195, 227, 258}; + +/*the extra bits used by codes 257-285 (added to base length)*/ +static const unsigned LENGTHEXTRA[29] + = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, 0}; + +/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ +static const unsigned DISTANCEBASE[30] + = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, + 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + +/*the extra bits of backwards distances (added to base)*/ +static const unsigned DISTANCEEXTRA[30] + = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + +/*the order in which "code length alphabet code lengths" are stored, out of this +the huffman tree of the dynamic huffman tree lengths is generated*/ +static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] + = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + +/* ////////////////////////////////////////////////////////////////////////// */ + +/* +Huffman tree struct, containing multiple representations of the tree +*/ +typedef struct HuffmanTree +{ + unsigned* tree2d; + unsigned* tree1d; + unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ + unsigned maxbitlen; /*maximum number of bits a single code can get*/ + unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ +} HuffmanTree; + +/*function used for debug purposes to draw the tree in ascii art with C++*/ +/* +static void HuffmanTree_draw(HuffmanTree* tree) +{ + std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl; + for(size_t i = 0; i != tree->tree1d.size; ++i) + { + if(tree->lengths.data[i]) + std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl; + } + std::cout << std::endl; +}*/ + +static void HuffmanTree_init(HuffmanTree* tree) +{ + tree->tree2d = 0; + tree->tree1d = 0; + tree->lengths = 0; +} + +static void HuffmanTree_cleanup(HuffmanTree* tree) +{ + lodepng_free(tree->tree2d); + lodepng_free(tree->tree1d); + lodepng_free(tree->lengths); +} + +/*the tree representation used by the decoder. return value is error*/ +static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) +{ + unsigned nodefilled = 0; /*up to which node it is filled*/ + unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ + unsigned n, i; + + tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); + if(!tree->tree2d) return 83; /*alloc fail*/ + + /* + convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means + uninited, a value >= numcodes is an address to another bit, a value < numcodes + is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as + many columns as codes - 1. + A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. + Here, the internal nodes are stored (what their 0 and 1 option point to). + There is only memory for such good tree currently, if there are more nodes + (due to too long length codes), error 55 will happen + */ + for(n = 0; n < tree->numcodes * 2; ++n) + { + tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ + } + + for(n = 0; n < tree->numcodes; ++n) /*the codes*/ + { + for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ + { + unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); + /*oversubscribed, see comment in lodepng_error_text*/ + if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; + if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ + { + if(i + 1 == tree->lengths[n]) /*last bit*/ + { + tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ + treepos = 0; + } + else + { + /*put address of the next step in here, first that address has to be found of course + (it's just nodefilled + 1)...*/ + ++nodefilled; + /*addresses encoded with numcodes added to it*/ + tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; + treepos = nodefilled; + } + } + else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; + } + } + + for(n = 0; n < tree->numcodes * 2; ++n) + { + if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ + } + + return 0; +} + +/* +Second step for the ...makeFromLengths and ...makeFromFrequencies functions. +numcodes, lengths and maxbitlen must already be filled in correctly. return +value is error. +*/ +static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) +{ + uivector blcount; + uivector nextcode; + unsigned error = 0; + unsigned bits, n; + + uivector_init(&blcount); + uivector_init(&nextcode); + + tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); + if(!tree->tree1d) error = 83; /*alloc fail*/ + + if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) + || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) + error = 83; /*alloc fail*/ + + if(!error) + { + /*step 1: count number of instances of each code length*/ + for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; + /*step 2: generate the nextcode values*/ + for(bits = 1; bits <= tree->maxbitlen; ++bits) + { + nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; + } + /*step 3: generate all the codes*/ + for(n = 0; n != tree->numcodes; ++n) + { + if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; + } + } + + uivector_cleanup(&blcount); + uivector_cleanup(&nextcode); + + if(!error) return HuffmanTree_make2DTree(tree); + else return error; +} + +/* +given the code lengths (as stored in the PNG file), generate the tree as defined +by Deflate. maxbitlen is the maximum bits that a code in the tree can have. +return value is error. +*/ +static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, + size_t numcodes, unsigned maxbitlen) +{ + unsigned i; + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->maxbitlen = maxbitlen; + return HuffmanTree_makeFromLengths2(tree); +} + +#ifdef LODEPNG_COMPILE_ENCODER + +/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding", +Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ + +/*chain node for boundary package merge*/ +typedef struct BPMNode +{ + int weight; /*the sum of all weights in this chain*/ + unsigned index; /*index of this leaf node (called "count" in the paper)*/ + struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ + int in_use; +} BPMNode; + +/*lists of chains*/ +typedef struct BPMLists +{ + /*memory pool*/ + unsigned memsize; + BPMNode* memory; + unsigned numfree; + unsigned nextfree; + BPMNode** freelist; + /*two heads of lookahead chains per list*/ + unsigned listsize; + BPMNode** chains0; + BPMNode** chains1; +} BPMLists; + +/*creates a new chain node with the given parameters, from the memory in the lists */ +static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) +{ + unsigned i; + BPMNode* result; + + /*memory full, so garbage collect*/ + if(lists->nextfree >= lists->numfree) + { + /*mark only those that are in use*/ + for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; + for(i = 0; i != lists->listsize; ++i) + { + BPMNode* node; + for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; + for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; + } + /*collect those that are free*/ + lists->numfree = 0; + for(i = 0; i != lists->memsize; ++i) + { + if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; + } + lists->nextfree = 0; + } + + result = lists->freelist[lists->nextfree++]; + result->weight = weight; + result->index = index; + result->tail = tail; + return result; +} + +/*sort the leaves with stable mergesort*/ +static void bpmnode_sort(BPMNode* leaves, size_t num) +{ + BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); + size_t width, counter = 0; + for(width = 1; width < num; width *= 2) + { + BPMNode* a = (counter & 1) ? mem : leaves; + BPMNode* b = (counter & 1) ? leaves : mem; + size_t p; + for(p = 0; p < num; p += 2 * width) + { + size_t q = (p + width > num) ? num : (p + width); + size_t r = (p + 2 * width > num) ? num : (p + 2 * width); + size_t i = p, j = q, k; + for(k = p; k < r; k++) + { + if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; + else b[k] = a[j++]; + } + } + counter++; + } + if(counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num); + lodepng_free(mem); +} + +/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ +static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) +{ + unsigned lastindex = lists->chains1[c]->index; + + if(c == 0) + { + if(lastindex >= numpresent) return; + lists->chains0[c] = lists->chains1[c]; + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); + } + else + { + /*sum of the weights of the head nodes of the previous lookahead chains.*/ + int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; + lists->chains0[c] = lists->chains1[c]; + if(lastindex < numpresent && sum > leaves[lastindex].weight) + { + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); + return; + } + lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); + /*in the end we are only interested in the chain of the last list, so no + need to recurse if we're at the last one (this gives measurable speedup)*/ + if(num + 1 < (int)(2 * numpresent - 2)) + { + boundaryPM(lists, leaves, numpresent, c - 1, num); + boundaryPM(lists, leaves, numpresent, c - 1, num); + } + } +} + +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen) +{ + unsigned error = 0; + unsigned i; + size_t numpresent = 0; /*number of symbols with non-zero frequency*/ + BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ + + if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ + if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/ + + leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); + if(!leaves) return 83; /*alloc fail*/ + + for(i = 0; i != numcodes; ++i) + { + if(frequencies[i] > 0) + { + leaves[numpresent].weight = (int)frequencies[i]; + leaves[numpresent].index = i; + ++numpresent; + } + } + + for(i = 0; i != numcodes; ++i) lengths[i] = 0; + + /*ensure at least two present symbols. There should be at least one symbol + according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To + make these work as well ensure there are at least two symbols. The + Package-Merge code below also doesn't work correctly if there's only one + symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ + if(numpresent == 0) + { + lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ + } + else if(numpresent == 1) + { + lengths[leaves[0].index] = 1; + lengths[leaves[0].index == 0 ? 1 : 0] = 1; + } + else + { + BPMLists lists; + BPMNode* node; + + bpmnode_sort(leaves, numpresent); + + lists.listsize = maxbitlen; + lists.memsize = 2 * maxbitlen * (maxbitlen + 1); + lists.nextfree = 0; + lists.numfree = lists.memsize; + lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); + lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); + lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ + + if(!error) + { + for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; + + bpmnode_create(&lists, leaves[0].weight, 1, 0); + bpmnode_create(&lists, leaves[1].weight, 2, 0); + + for(i = 0; i != lists.listsize; ++i) + { + lists.chains0[i] = &lists.memory[0]; + lists.chains1[i] = &lists.memory[1]; + } + + /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ + for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i); + + for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) + { + for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; + } + } + + lodepng_free(lists.memory); + lodepng_free(lists.freelist); + lodepng_free(lists.chains0); + lodepng_free(lists.chains1); + } + + lodepng_free(leaves); + return error; +} + +/*Create the Huffman tree given the symbol frequencies*/ +static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, + size_t mincodes, size_t numcodes, unsigned maxbitlen) +{ + unsigned error = 0; + while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ + tree->maxbitlen = maxbitlen; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + /*initialize all lengths to 0*/ + memset(tree->lengths, 0, numcodes * sizeof(unsigned)); + + error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); + if(!error) error = HuffmanTree_makeFromLengths2(tree); + return error; +} + +static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) +{ + return tree->tree1d[index]; +} + +static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) +{ + return tree->lengths[index]; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ +static unsigned generateFixedLitLenTree(HuffmanTree* tree) +{ + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ + for(i = 0; i <= 143; ++i) bitlen[i] = 8; + for(i = 144; i <= 255; ++i) bitlen[i] = 9; + for(i = 256; i <= 279; ++i) bitlen[i] = 7; + for(i = 280; i <= 287; ++i) bitlen[i] = 8; + + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ +static unsigned generateFixedDistanceTree(HuffmanTree* tree) +{ + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*there are 32 distance codes, but 30-31 are unused*/ + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* +returns the code, or (unsigned)(-1) if error happened +inbitlength is the length of the complete buffer, in bits (so its byte length times 8) +*/ +static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, + const HuffmanTree* codetree, size_t inbitlength) +{ + unsigned treepos = 0, ct; + for(;;) + { + if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ + /* + decode the symbol from the tree. The "readBitFromStream" code is inlined in + the expression below because this is the biggest bottleneck while decoding + */ + ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; + ++(*bp); + if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ + else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ + + if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ + } +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Inflator (Decompressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ +static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) +{ + /*TODO: check for out of memory errors*/ + generateFixedLitLenTree(tree_ll); + generateFixedDistanceTree(tree_d); +} + +/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ +static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, + const unsigned char* in, size_t* bp, size_t inlength) +{ + /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ + unsigned error = 0; + unsigned n, HLIT, HDIST, HCLEN, i; + size_t inbitlength = inlength * 8; + + /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ + unsigned* bitlen_ll = 0; /*lit,len code lengths*/ + unsigned* bitlen_d = 0; /*dist code lengths*/ + /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ + unsigned* bitlen_cl = 0; + HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ + + if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/ + + /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ + HLIT = readBitsFromStream(bp, in, 5) + 257; + /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ + HDIST = readBitsFromStream(bp, in, 5) + 1; + /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ + HCLEN = readBitsFromStream(bp, in, 4) + 4; + + if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/ + + HuffmanTree_init(&tree_cl); + + while(!error) + { + /*read the code length codes out of 3 * (amount of code length codes) bits*/ + + bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); + if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); + + for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) + { + if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); + else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ + } + + error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); + if(error) break; + + /*now we can use this tree to read the lengths for the tree that this function will return*/ + bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0; + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0; + + /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ + i = 0; + while(i < HLIT + HDIST) + { + unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); + if(code <= 15) /*a length code*/ + { + if(i < HLIT) bitlen_ll[i] = code; + else bitlen_d[i - HLIT] = code; + ++i; + } + else if(code == 16) /*repeat previous*/ + { + unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ + unsigned value; /*set value to the previous code*/ + + if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ + + if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 2); + + if(i < HLIT + 1) value = bitlen_ll[i - 1]; + else value = bitlen_d[i - HLIT - 1]; + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ + if(i < HLIT) bitlen_ll[i] = value; + else bitlen_d[i - HLIT] = value; + ++i; + } + } + else if(code == 17) /*repeat "0" 3-10 times*/ + { + unsigned replength = 3; /*read in the bits that indicate repeat length*/ + if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 3); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } + else if(code == 18) /*repeat "0" 11-138 times*/ + { + unsigned replength = 11; /*read in the bits that indicate repeat length*/ + if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 7); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } + else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + if(code == (unsigned)(-1)) + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = (*bp) > inbitlength ? 10 : 11; + } + else error = 16; /*unexisting code, this can never happen*/ + break; + } + } + if(error) break; + + if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ + + /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ + error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); + if(error) break; + error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); + + break; /*end of error-while*/ + } + + lodepng_free(bitlen_cl); + lodepng_free(bitlen_ll); + lodepng_free(bitlen_d); + HuffmanTree_cleanup(&tree_cl); + + return error; +} + +/*inflate a block with dynamic of fixed Huffman tree*/ +static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp, + size_t* pos, size_t inlength, unsigned btype) +{ + unsigned error = 0; + HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ + HuffmanTree tree_d; /*the huffman tree for distance codes*/ + size_t inbitlength = inlength * 8; + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); + else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); + + while(!error) /*decode all symbols until end reached, breaks at end code*/ + { + /*code_ll is literal, length or end code*/ + unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); + if(code_ll <= 255) /*literal symbol*/ + { + /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ + if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); + out->data[*pos] = (unsigned char)code_ll; + ++(*pos); + } + else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ + { + unsigned code_d, distance; + unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ + size_t start, forward, backward, length; + + /*part 1: get length base*/ + length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; + + /*part 2: get extra bits and add the value of that to length*/ + numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; + if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ + length += readBitsFromStream(bp, in, numextrabits_l); + + /*part 3: get distance code*/ + code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); + if(code_d > 29) + { + if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = (*bp) > inlength * 8 ? 10 : 11; + } + else error = 18; /*error: invalid distance code (30-31 are never used)*/ + break; + } + distance = DISTANCEBASE[code_d]; + + /*part 4: get extra bits from distance*/ + numextrabits_d = DISTANCEEXTRA[code_d]; + if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ + distance += readBitsFromStream(bp, in, numextrabits_d); + + /*part 5: fill in all the out[n] values based on the length and dist*/ + start = (*pos); + if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ + backward = start - distance; + + if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); + if (distance < length) { + for(forward = 0; forward < length; ++forward) + { + out->data[(*pos)++] = out->data[backward++]; + } + } else { + memcpy(out->data + *pos, out->data + backward, length); + *pos += length; + } + } + else if(code_ll == 256) + { + break; /*end code, break the loop*/ + } + else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = ((*bp) > inlength * 8) ? 10 : 11; + break; + } + } + + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) +{ + size_t p; + unsigned LEN, NLEN, n, error = 0; + + /*go to first boundary of byte*/ + while(((*bp) & 0x7) != 0) ++(*bp); + p = (*bp) / 8; /*byte position*/ + + /*read LEN (2 bytes) and NLEN (2 bytes)*/ + if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/ + LEN = in[p] + 256u * in[p + 1]; p += 2; + NLEN = in[p] + 256u * in[p + 1]; p += 2; + + /*check if 16-bit NLEN is really the one's complement of LEN*/ + if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ + + if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ + + /*read the literal data: LEN bytes are now stored in the out buffer*/ + if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ + for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++]; + + (*bp) = p * 8; + + return error; +} + +static unsigned lodepng_inflatev(ucvector* out, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) +{ + /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ + size_t bp = 0; + unsigned BFINAL = 0; + size_t pos = 0; /*byte position in the out buffer*/ + unsigned error = 0; + + (void)settings; + + while(!BFINAL) + { + unsigned BTYPE; + if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ + BFINAL = readBitFromStream(&bp, in); + BTYPE = 1u * readBitFromStream(&bp, in); + BTYPE += 2u * readBitFromStream(&bp, in); + + if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ + else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ + else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ + + if(error) return error; + } + + return error; +} + +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) +{ + unsigned error; + ucvector v; + ucvector_init_buffer(&v, *out, *outsize); + error = lodepng_inflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) +{ + if(settings->custom_inflate) + { + return settings->custom_inflate(out, outsize, in, insize, settings); + } + else + { + return lodepng_inflate(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflator (Compressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; + +/*bitlen is the size in bits of the code*/ +static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) +{ + addBitsToStreamReversed(bp, compressed, code, bitlen); +} + +/*search the index in the array, that has the largest value smaller than or equal to the given value, +given array must be sorted (if no value is smaller, it returns the size of the given array)*/ +static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) +{ + /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ + size_t left = 1; + size_t right = array_size - 1; + + while(left <= right) { + size_t mid = (left + right) >> 1; + if (array[mid] >= value) right = mid - 1; + else left = mid + 1; + } + if(left >= array_size || array[left] > value) left--; + return left; +} + +static void addLengthDistance(uivector* values, size_t length, size_t distance) +{ + /*values in encoded vector are those used by deflate: + 0-255: literal bytes + 256: end + 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) + 286-287: invalid*/ + + unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); + unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); + unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); + unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); + + uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); + uivector_push_back(values, extra_length); + uivector_push_back(values, dist_code); + uivector_push_back(values, extra_distance); +} + +/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 +bytes as input because 3 is the minimum match length for deflate*/ +static const unsigned HASH_NUM_VALUES = 65536; +static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ + +typedef struct Hash +{ + int* head; /*hash value to head circular pos - can be outdated if went around window*/ + /*circular pos to prev circular pos*/ + unsigned short* chain; + int* val; /*circular pos to hash value*/ + + /*TODO: do this not only for zeros but for any repeated byte. However for PNG + it's always going to be the zeros that dominate, so not important for PNG*/ + int* headz; /*similar to head, but for chainz*/ + unsigned short* chainz; /*those with same amount of zeros*/ + unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ +} Hash; + +static unsigned hash_init(Hash* hash, unsigned windowsize) +{ + unsigned i; + hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); + hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); + hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); + hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) + { + return 83; /*alloc fail*/ + } + + /*initialize hash table*/ + for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; + for(i = 0; i != windowsize; ++i) hash->val[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ + + for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ + + return 0; +} + +static void hash_cleanup(Hash* hash) +{ + lodepng_free(hash->head); + lodepng_free(hash->val); + lodepng_free(hash->chain); + + lodepng_free(hash->zeros); + lodepng_free(hash->headz); + lodepng_free(hash->chainz); +} + + + +static unsigned getHash(const unsigned char* data, size_t size, size_t pos) +{ + unsigned result = 0; + if(pos + 2 < size) + { + /*A simple shift and xor hash is used. Since the data of PNGs is dominated + by zeroes due to the filters, a better hash does not have a significant + effect on speed in traversing the chain, and causes more time spend on + calculating the hash.*/ + result ^= (unsigned)(data[pos + 0] << 0u); + result ^= (unsigned)(data[pos + 1] << 4u); + result ^= (unsigned)(data[pos + 2] << 8u); + } else { + size_t amount, i; + if(pos >= size) return 0; + amount = size - pos; + for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u)); + } + return result & HASH_BIT_MASK; +} + +static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) +{ + const unsigned char* start = data + pos; + const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; + if(end > data + size) end = data + size; + data = start; + while(data != end && *data == 0) ++data; + /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ + return (unsigned)(data - start); +} + +/*wpos = pos & (windowsize - 1)*/ +static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) +{ + hash->val[wpos] = (int)hashval; + if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; + hash->head[hashval] = wpos; + + hash->zeros[wpos] = numzeros; + if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; + hash->headz[numzeros] = wpos; +} + +/* +LZ77-encode the data. Return value is error code. The input are raw bytes, the output +is in the form of unsigned integers with codes representing for example literal bytes, or +length/distance pairs. +It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a +sliding window (of windowsize) is used, and all past bytes in that window can be used as +the "dictionary". A brute force search through all possible distances would be slow, and +this hash technique is one out of several ways to speed this up. +*/ +static unsigned encodeLZ77(uivector* out, Hash* hash, + const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, + unsigned minmatch, unsigned nicematch, unsigned lazymatching) +{ + size_t pos; + unsigned i, error = 0; + /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ + unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; + unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; + + unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ + unsigned numzeros = 0; + + unsigned offset; /*the offset represents the distance in LZ77 terminology*/ + unsigned length; + unsigned lazy = 0; + unsigned lazylength = 0, lazyoffset = 0; + unsigned hashval; + unsigned current_offset, current_length; + unsigned prev_offset; + const unsigned char *lastptr, *foreptr, *backptr; + unsigned hashpos; + + if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ + if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ + + if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; + + for(pos = inpos; pos < insize; ++pos) + { + size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ + unsigned chainlength = 0; + + hashval = getHash(in, insize, pos); + + if(usezeros && hashval == 0) + { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } + else + { + numzeros = 0; + } + + updateHashChain(hash, wpos, hashval, numzeros); + + /*the length and offset found for the current position*/ + length = 0; + offset = 0; + + hashpos = hash->chain[wpos]; + + lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; + + /*search for the longest string*/ + prev_offset = 0; + for(;;) + { + if(chainlength++ >= maxchainlength) break; + current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; + + if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ + prev_offset = current_offset; + if(current_offset > 0) + { + /*test the next characters*/ + foreptr = &in[pos]; + backptr = &in[pos - current_offset]; + + /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ + if(numzeros >= 3) + { + unsigned skip = hash->zeros[hashpos]; + if(skip > numzeros) skip = numzeros; + backptr += skip; + foreptr += skip; + } + + while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ + { + ++backptr; + ++foreptr; + } + current_length = (unsigned)(foreptr - &in[pos]); + + if(current_length > length) + { + length = current_length; /*the longest length*/ + offset = current_offset; /*the offset that is related to this longest length*/ + /*jump out once a length of max length is found (speed gain). This also jumps + out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ + if(current_length >= nicematch) break; + } + } + + if(hashpos == hash->chain[hashpos]) break; + + if(numzeros >= 3 && length > numzeros) + { + hashpos = hash->chainz[hashpos]; + if(hash->zeros[hashpos] != numzeros) break; + } + else + { + hashpos = hash->chain[hashpos]; + /*outdated hash value, happens if particular value was not encountered in whole last window*/ + if(hash->val[hashpos] != (int)hashval) break; + } + } + + if(lazymatching) + { + if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) + { + lazy = 1; + lazylength = length; + lazyoffset = offset; + continue; /*try the next byte*/ + } + if(lazy) + { + lazy = 0; + if(pos == 0) ERROR_BREAK(81); + if(length > lazylength + 1) + { + /*push the previous character as literal*/ + if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); + } + else + { + length = lazylength; + offset = lazyoffset; + hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ + hash->headz[numzeros] = -1; /*idem*/ + --pos; + } + } + } + if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); + + /*encode it as length/distance pair or literal value*/ + if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ + { + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } + else if(length < minmatch || (length == 3 && offset > 4096)) + { + /*compensate for the fact that longer offsets have more extra bits, a + length of only 3 may be not worth it then*/ + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } + else + { + addLengthDistance(out, length, offset); + for(i = 1; i < length; ++i) + { + ++pos; + wpos = pos & (windowsize - 1); + hashval = getHash(in, insize, pos); + if(usezeros && hashval == 0) + { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } + else + { + numzeros = 0; + } + updateHashChain(hash, wpos, hashval, numzeros); + } + } + } /*end of the loop through each character of input*/ + + return error; +} + +/* /////////////////////////////////////////////////////////////////////////// */ + +static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) +{ + /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, + 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ + + size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; + unsigned datapos = 0; + for(i = 0; i != numdeflateblocks; ++i) + { + unsigned BFINAL, BTYPE, LEN, NLEN; + unsigned char firstbyte; + + BFINAL = (i == numdeflateblocks - 1); + BTYPE = 0; + + firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); + ucvector_push_back(out, firstbyte); + + LEN = 65535; + if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; + NLEN = 65535 - LEN; + + ucvector_push_back(out, (unsigned char)(LEN & 255)); + ucvector_push_back(out, (unsigned char)(LEN >> 8)); + ucvector_push_back(out, (unsigned char)(NLEN & 255)); + ucvector_push_back(out, (unsigned char)(NLEN >> 8)); + + /*Decompressed data*/ + for(j = 0; j < 65535 && datapos < datasize; ++j) + { + ucvector_push_back(out, data[datapos++]); + } + } + + return 0; +} + +/* +write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. +tree_ll: the tree for lit and len codes. +tree_d: the tree for distance codes. +*/ +static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, + const HuffmanTree* tree_ll, const HuffmanTree* tree_d) +{ + size_t i = 0; + for(i = 0; i != lz77_encoded->size; ++i) + { + unsigned val = lz77_encoded->data[i]; + addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); + if(val > 256) /*for a length code, 3 more things have to be added*/ + { + unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; + unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; + unsigned length_extra_bits = lz77_encoded->data[++i]; + + unsigned distance_code = lz77_encoded->data[++i]; + + unsigned distance_index = distance_code; + unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; + unsigned distance_extra_bits = lz77_encoded->data[++i]; + + addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); + addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), + HuffmanTree_getLength(tree_d, distance_code)); + addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); + } + } +} + +/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ +static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, + const unsigned char* data, size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) +{ + unsigned error = 0; + + /* + A block is compressed as follows: The PNG data is lz77 encoded, resulting in + literal bytes and length/distance pairs. This is then huffman compressed with + two huffman trees. One huffman tree is used for the lit and len values ("ll"), + another huffman tree is used for the dist values ("d"). These two trees are + stored using their code lengths, and to compress even more these code lengths + are also run-length encoded and huffman compressed. This gives a huffman tree + of code lengths "cl". The code lenghts used to describe this third tree are + the code length code lengths ("clcl"). + */ + + /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ + uivector lz77_encoded; + HuffmanTree tree_ll; /*tree for lit,len values*/ + HuffmanTree tree_d; /*tree for distance codes*/ + HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ + uivector frequencies_ll; /*frequency of lit,len codes*/ + uivector frequencies_d; /*frequency of dist codes*/ + uivector frequencies_cl; /*frequency of code length codes*/ + uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/ + uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ + /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl + (these are written as is in the file, it would be crazy to compress these using yet another huffman + tree that needs to be represented by yet another set of code lengths)*/ + uivector bitlen_cl; + size_t datasize = dataend - datapos; + + /* + Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: + bitlen_lld is to tree_cl what data is to tree_ll and tree_d. + bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. + bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. + */ + + unsigned BFINAL = final; + size_t numcodes_ll, numcodes_d, i; + unsigned HLIT, HDIST, HCLEN; + + uivector_init(&lz77_encoded); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_cl); + uivector_init(&frequencies_ll); + uivector_init(&frequencies_d); + uivector_init(&frequencies_cl); + uivector_init(&bitlen_lld); + uivector_init(&bitlen_lld_e); + uivector_init(&bitlen_cl); + + /*This while loop never loops due to a break at the end, it is here to + allow breaking out of it to the cleanup phase on error conditions.*/ + while(!error) + { + if(settings->use_lz77) + { + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(error) break; + } + else + { + if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); + for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ + } + + if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); + if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); + + /*Count the frequencies of lit, len and dist codes*/ + for(i = 0; i != lz77_encoded.size; ++i) + { + unsigned symbol = lz77_encoded.data[i]; + ++frequencies_ll.data[symbol]; + if(symbol > 256) + { + unsigned dist = lz77_encoded.data[i + 2]; + ++frequencies_d.data[dist]; + i += 3; + } + } + frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ + + /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ + error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); + if(error) break; + /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ + error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); + if(error) break; + + numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286; + numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30; + /*store the code lengths of both generated trees in bitlen_lld*/ + for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); + for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); + + /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), + 17 (3-10 zeroes), 18 (11-138 zeroes)*/ + for(i = 0; i != (unsigned)bitlen_lld.size; ++i) + { + unsigned j = 0; /*amount of repititions*/ + while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; + + if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ + { + ++j; /*include the first zero*/ + if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ + { + uivector_push_back(&bitlen_lld_e, 17); + uivector_push_back(&bitlen_lld_e, j - 3); + } + else /*repeat code 18 supports max 138 zeroes*/ + { + if(j > 138) j = 138; + uivector_push_back(&bitlen_lld_e, 18); + uivector_push_back(&bitlen_lld_e, j - 11); + } + i += (j - 1); + } + else if(j >= 3) /*repeat code for value other than zero*/ + { + size_t k; + unsigned num = j / 6, rest = j % 6; + uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); + for(k = 0; k < num; ++k) + { + uivector_push_back(&bitlen_lld_e, 16); + uivector_push_back(&bitlen_lld_e, 6 - 3); + } + if(rest >= 3) + { + uivector_push_back(&bitlen_lld_e, 16); + uivector_push_back(&bitlen_lld_e, rest - 3); + } + else j -= rest; + i += j; + } + else /*too short to benefit from repeat code*/ + { + uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); + } + } + + /*generate tree_cl, the huffmantree of huffmantrees*/ + + if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != bitlen_lld_e.size; ++i) + { + ++frequencies_cl.data[bitlen_lld_e.data[i]]; + /*after a repeat code come the bits that specify the number of repetitions, + those don't need to be in the frequencies_cl calculation*/ + if(bitlen_lld_e.data[i] >= 16) ++i; + } + + error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, + frequencies_cl.size, frequencies_cl.size, 7); + if(error) break; + + if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != tree_cl.numcodes; ++i) + { + /*lenghts of code length tree is in the order as specified by deflate*/ + bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); + } + while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) + { + /*remove zeros at the end, but minimum size must be 4*/ + if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); + } + if(error) break; + + /* + Write everything into the output + + After the BFINAL and BTYPE, the dynamic block consists out of the following: + - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN + - (HCLEN+4)*3 bits code lengths of code length alphabet + - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - HDIST + 1 code lengths of distance alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - compressed data + - 256 (end code) + */ + + /*Write block type*/ + addBitToStream(bp, out, BFINAL); + addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ + addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ + + /*write the HLIT, HDIST and HCLEN values*/ + HLIT = (unsigned)(numcodes_ll - 257); + HDIST = (unsigned)(numcodes_d - 1); + HCLEN = (unsigned)bitlen_cl.size - 4; + /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ + while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN; + addBitsToStream(bp, out, HLIT, 5); + addBitsToStream(bp, out, HDIST, 5); + addBitsToStream(bp, out, HCLEN, 4); + + /*write the code lenghts of the code length alphabet*/ + for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); + + /*write the lenghts of the lit/len AND the dist alphabet*/ + for(i = 0; i != bitlen_lld_e.size; ++i) + { + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), + HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); + /*extra bits of repeat codes*/ + if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); + else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); + else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); + } + + /*write the compressed data symbols*/ + writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); + /*error: the length of the end code 256 must be larger than 0*/ + if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); + + /*write the end code*/ + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); + + break; /*end of error-while*/ + } + + /*cleanup*/ + uivector_cleanup(&lz77_encoded); + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + HuffmanTree_cleanup(&tree_cl); + uivector_cleanup(&frequencies_ll); + uivector_cleanup(&frequencies_d); + uivector_cleanup(&frequencies_cl); + uivector_cleanup(&bitlen_lld_e); + uivector_cleanup(&bitlen_lld); + uivector_cleanup(&bitlen_cl); + + return error; +} + +static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, + const unsigned char* data, + size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) +{ + HuffmanTree tree_ll; /*tree for literal values and length codes*/ + HuffmanTree tree_d; /*tree for distance codes*/ + + unsigned BFINAL = final; + unsigned error = 0; + size_t i; + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + generateFixedLitLenTree(&tree_ll); + generateFixedDistanceTree(&tree_d); + + addBitToStream(bp, out, BFINAL); + addBitToStream(bp, out, 1); /*first bit of BTYPE*/ + addBitToStream(bp, out, 0); /*second bit of BTYPE*/ + + if(settings->use_lz77) /*LZ77 encoded*/ + { + uivector lz77_encoded; + uivector_init(&lz77_encoded); + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); + uivector_cleanup(&lz77_encoded); + } + else /*no LZ77, but still will be Huffman compressed*/ + { + for(i = datapos; i < dataend; ++i) + { + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); + } + } + /*add END code*/ + if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); + + /*cleanup*/ + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) +{ + unsigned error = 0; + size_t i, blocksize, numdeflateblocks; + size_t bp = 0; /*the bit pointer*/ + Hash hash; + + if(settings->btype > 2) return 61; + else if(settings->btype == 0) return deflateNoCompression(out, in, insize); + else if(settings->btype == 1) blocksize = insize; + else /*if(settings->btype == 2)*/ + { + /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ + blocksize = insize / 8 + 8; + if(blocksize < 65536) blocksize = 65536; + if(blocksize > 262144) blocksize = 262144; + } + + numdeflateblocks = (insize + blocksize - 1) / blocksize; + if(numdeflateblocks == 0) numdeflateblocks = 1; + + error = hash_init(&hash, settings->windowsize); + if(error) return error; + + for(i = 0; i != numdeflateblocks && !error; ++i) + { + unsigned final = (i == numdeflateblocks - 1); + size_t start = i * blocksize; + size_t end = start + blocksize; + if(end > insize) end = insize; + + if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); + else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); + } + + hash_cleanup(&hash); + + return error; +} + +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) +{ + unsigned error; + ucvector v; + ucvector_init_buffer(&v, *out, *outsize); + error = lodepng_deflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) +{ + if(settings->custom_deflate) + { + return settings->custom_deflate(out, outsize, in, insize, settings); + } + else + { + return lodepng_deflate(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Adler32 */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) +{ + unsigned s1 = adler & 0xffff; + unsigned s2 = (adler >> 16) & 0xffff; + + while(len > 0) + { + /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/ + unsigned amount = len > 5550 ? 5550 : len; + len -= amount; + while(amount > 0) + { + s1 += (*data++); + s2 += s1; + --amount; + } + s1 %= 65521; + s2 %= 65521; + } + + return (s2 << 16) | s1; +} + +/*Return the adler32 of the bytes data[0..len-1]*/ +static unsigned adler32(const unsigned char* data, unsigned len) +{ + return update_adler32(1L, data, len); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Zlib / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DECODER + +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) +{ + unsigned error = 0; + unsigned CM, CINFO, FDICT; + + if(insize < 2) return 53; /*error, size of zlib data too small*/ + /*read information from zlib header*/ + if((in[0] * 256 + in[1]) % 31 != 0) + { + /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ + return 24; + } + + CM = in[0] & 15; + CINFO = (in[0] >> 4) & 15; + /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ + FDICT = (in[1] >> 5) & 1; + /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ + + if(CM != 8 || CINFO > 7) + { + /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ + return 25; + } + if(FDICT != 0) + { + /*error: the specification of PNG says about the zlib stream: + "The additional flags shall not specify a preset dictionary."*/ + return 26; + } + + error = inflate(out, outsize, in + 2, insize - 2, settings); + if(error) return error; + + if(!settings->ignore_adler32) + { + unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); + unsigned checksum = adler32(*out, (unsigned)(*outsize)); + if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ + } + + return 0; /*no error*/ +} + +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) +{ + if(settings->custom_zlib) + { + return settings->custom_zlib(out, outsize, in, insize, settings); + } + else + { + return lodepng_zlib_decompress(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) +{ + /*initially, *out must be NULL and outsize 0, if you just give some random *out + that's pointing to a non allocated buffer, this'll crash*/ + ucvector outv; + size_t i; + unsigned error; + unsigned char* deflatedata = 0; + size_t deflatesize = 0; + + /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ + unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ + unsigned FLEVEL = 0; + unsigned FDICT = 0; + unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; + unsigned FCHECK = 31 - CMFFLG % 31; + CMFFLG += FCHECK; + + /*ucvector-controlled version of the output buffer, for dynamic array*/ + ucvector_init_buffer(&outv, *out, *outsize); + + ucvector_push_back(&outv, (unsigned char)(CMFFLG >> 8)); + ucvector_push_back(&outv, (unsigned char)(CMFFLG & 255)); + + error = deflate(&deflatedata, &deflatesize, in, insize, settings); + + if(!error) + { + unsigned ADLER32 = adler32(in, (unsigned)insize); + for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); + lodepng_free(deflatedata); + lodepng_add32bitInt(&outv, ADLER32); + } + + *out = outv.data; + *outsize = outv.size; + + return error; +} + +/* compress using the default or custom zlib function */ +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) +{ + if(settings->custom_zlib) + { + return settings->custom_zlib(out, outsize, in, insize, settings); + } + else + { + return lodepng_zlib_compress(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#else /*no LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DECODER +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) +{ + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) +{ + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/*this is a good tradeoff between speed and compression ratio*/ +#define DEFAULT_WINDOWSIZE 2048 + +void lodepng_compress_settings_init(LodePNGCompressSettings* settings) +{ + /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ + settings->btype = 2; + settings->use_lz77 = 1; + settings->windowsize = DEFAULT_WINDOWSIZE; + settings->minmatch = 3; + settings->nicematch = 128; + settings->lazymatching = 1; + + settings->custom_zlib = 0; + settings->custom_deflate = 0; + settings->custom_context = 0; +} + +const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; + + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) +{ + settings->ignore_adler32 = 0; + + settings->custom_zlib = 0; + settings->custom_inflate = 0; + settings->custom_context = 0; +} + +const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0}; + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of Zlib related code. Begin of PNG related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / CRC32 / */ +/* ////////////////////////////////////////////////////////////////////////// */ + + +#ifndef LODEPNG_NO_COMPILE_CRC +/* CRC polynomial: 0xedb88320 */ +static unsigned lodepng_crc32_table[256] = { + 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, + 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, + 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, + 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, + 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, + 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, + 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, + 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, + 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, + 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, + 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, + 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, + 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, + 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, + 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, + 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, + 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, + 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, + 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, + 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, + 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, + 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, + 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, + 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, + 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, + 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, + 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, + 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, + 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, + 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, + 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, + 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u +}; + +/*Return the CRC of the bytes buf[0..len-1].*/ +unsigned lodepng_crc32(const unsigned char* data, size_t length) +{ + unsigned r = 0xffffffffu; + size_t i; + for(i = 0; i < length; ++i) + { + r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8); + } + return r ^ 0xffffffffu; +} +#else /* !LODEPNG_NO_COMPILE_CRC */ +unsigned lodepng_crc32(const unsigned char* data, size_t length); +#endif /* !LODEPNG_NO_COMPILE_CRC */ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Reading and writing single bits and bytes from/to stream for LodePNG / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) +{ + unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); + ++(*bitpointer); + return result; +} + +static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) +{ + unsigned result = 0; + size_t i; + for(i = 0 ; i < nbits; ++i) + { + result <<= 1; + result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); + } + return result; +} + +#ifdef LODEPNG_COMPILE_DECODER +static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) +{ + /*the current bit in bitstream must be 0 for this to work*/ + if(bit) + { + /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ + bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); + } + ++(*bitpointer); +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) +{ + /*the current bit in bitstream may be 0 or 1 for this to work*/ + if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7)))); + else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); + ++(*bitpointer); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG chunks / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +unsigned lodepng_chunk_length(const unsigned char* chunk) +{ + return lodepng_read32bitInt(&chunk[0]); +} + +void lodepng_chunk_type(char type[5], const unsigned char* chunk) +{ + unsigned i; + for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; + type[4] = 0; /*null termination char*/ +} + +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) +{ + if(strlen(type) != 4) return 0; + return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); +} + +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) +{ + return((chunk[4] & 32) != 0); +} + +unsigned char lodepng_chunk_private(const unsigned char* chunk) +{ + return((chunk[6] & 32) != 0); +} + +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) +{ + return((chunk[7] & 32) != 0); +} + +unsigned char* lodepng_chunk_data(unsigned char* chunk) +{ + return &chunk[8]; +} + +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) +{ + return &chunk[8]; +} + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk) +{ + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); + /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ + unsigned checksum = lodepng_crc32(&chunk[4], length + 4); + if(CRC != checksum) return 1; + else return 0; +} + +void lodepng_chunk_generate_crc(unsigned char* chunk) +{ + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_crc32(&chunk[4], length + 4); + lodepng_set32bitInt(chunk + 8 + length, CRC); +} + +unsigned char* lodepng_chunk_next(unsigned char* chunk) +{ + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + return &chunk[total_chunk_length]; +} + +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) +{ + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + return &chunk[total_chunk_length]; +} + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) +{ + unsigned i; + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + unsigned char *chunk_start, *new_buffer; + size_t new_length = (*outlength) + total_chunk_length; + if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ + + new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outlength) = new_length; + chunk_start = &(*out)[new_length - total_chunk_length]; + + for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; + + return 0; +} + +unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, + const char* type, const unsigned char* data) +{ + unsigned i; + unsigned char *chunk, *new_buffer; + size_t new_length = (*outlength) + length + 12; + if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ + new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outlength) = new_length; + chunk = &(*out)[(*outlength) - length - 12]; + + /*1: length*/ + lodepng_set32bitInt(chunk, (unsigned)length); + + /*2: chunk name (4 letters)*/ + chunk[4] = (unsigned char)type[0]; + chunk[5] = (unsigned char)type[1]; + chunk[6] = (unsigned char)type[2]; + chunk[7] = (unsigned char)type[3]; + + /*3: the data*/ + for(i = 0; i != length; ++i) chunk[8 + i] = data[i]; + + /*4: CRC (of the chunkname characters and the data)*/ + lodepng_chunk_generate_crc(chunk); + + return 0; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Color types and such / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*return type is a LodePNG error code*/ +static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ +{ + switch(colortype) + { + case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ + case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/ + case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/ + case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/ + case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/ + default: return 31; + } + return 0; /*allowed color type / bits combination*/ +} + +static unsigned getNumColorChannels(LodePNGColorType colortype) +{ + switch(colortype) + { + case 0: return 1; /*grey*/ + case 2: return 3; /*RGB*/ + case 3: return 1; /*palette*/ + case 4: return 2; /*grey + alpha*/ + case 6: return 4; /*RGBA*/ + } + return 0; /*unexisting color type*/ +} + +static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) +{ + /*bits per pixel is amount of channels * bits per channel*/ + return getNumColorChannels(colortype) * bitdepth; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +void lodepng_color_mode_init(LodePNGColorMode* info) +{ + info->key_defined = 0; + info->key_r = info->key_g = info->key_b = 0; + info->colortype = LCT_RGBA; + info->bitdepth = 8; + info->palette = 0; + info->palettesize = 0; +} + +void lodepng_color_mode_cleanup(LodePNGColorMode* info) +{ + lodepng_palette_clear(info); +} + +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) +{ + size_t i; + lodepng_color_mode_cleanup(dest); + *dest = *source; + if(source->palette) + { + dest->palette = (unsigned char*)lodepng_malloc(1024); + if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ + for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; + } + return 0; +} + +static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) +{ + size_t i; + if(a->colortype != b->colortype) return 0; + if(a->bitdepth != b->bitdepth) return 0; + if(a->key_defined != b->key_defined) return 0; + if(a->key_defined) + { + if(a->key_r != b->key_r) return 0; + if(a->key_g != b->key_g) return 0; + if(a->key_b != b->key_b) return 0; + } + /*if one of the palette sizes is 0, then we consider it to be the same as the + other: it means that e.g. the palette was not given by the user and should be + considered the same as the palette inside the PNG.*/ + if(1/*a->palettesize != 0 && b->palettesize != 0*/) { + if(a->palettesize != b->palettesize) return 0; + for(i = 0; i != a->palettesize * 4; ++i) + { + if(a->palette[i] != b->palette[i]) return 0; + } + } + return 1; +} + +void lodepng_palette_clear(LodePNGColorMode* info) +{ + if(info->palette) lodepng_free(info->palette); + info->palette = 0; + info->palettesize = 0; +} + +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + unsigned char* data; + /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with + the max of 256 colors, it'll have the exact alloc size*/ + if(!info->palette) /*allocate palette if empty*/ + { + /*room for 256 colors with 4 bytes each*/ + data = (unsigned char*)lodepng_realloc(info->palette, 1024); + if(!data) return 83; /*alloc fail*/ + else info->palette = data; + } + info->palette[4 * info->palettesize + 0] = r; + info->palette[4 * info->palettesize + 1] = g; + info->palette[4 * info->palettesize + 2] = b; + info->palette[4 * info->palettesize + 3] = a; + ++info->palettesize; + return 0; +} + +unsigned lodepng_get_bpp(const LodePNGColorMode* info) +{ + /*calculate bits per pixel out of colortype and bitdepth*/ + return lodepng_get_bpp_lct(info->colortype, info->bitdepth); +} + +unsigned lodepng_get_channels(const LodePNGColorMode* info) +{ + return getNumColorChannels(info->colortype); +} + +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) +{ + return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; +} + +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) +{ + return (info->colortype & 4) != 0; /*4 or 6*/ +} + +unsigned lodepng_is_palette_type(const LodePNGColorMode* info) +{ + return info->colortype == LCT_PALETTE; +} + +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) +{ + size_t i; + for(i = 0; i != info->palettesize; ++i) + { + if(info->palette[i * 4 + 3] < 255) return 1; + } + return 0; +} + +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) +{ + return info->key_defined + || lodepng_is_alpha_type(info) + || lodepng_has_palette_alpha(info); +} + +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) +{ + /*will not overflow for any color type if roughly w * h < 268435455*/ + size_t bpp = lodepng_get_bpp(color); + size_t n = w * h; + return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; +} + +size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) +{ + /*will not overflow for any color type if roughly w * h < 268435455*/ + size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); + size_t n = w * h; + return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; +} + + +#ifdef LODEPNG_COMPILE_PNG +#ifdef LODEPNG_COMPILE_DECODER +/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/ +static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) +{ + /*will not overflow for any color type if roughly w * h < 268435455*/ + size_t bpp = lodepng_get_bpp(color); + size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8; + return h * line; +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static void LodePNGUnknownChunks_init(LodePNGInfo* info) +{ + unsigned i; + for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; + for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; +} + +static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) +{ + unsigned i; + for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); +} + +static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) +{ + unsigned i; + + LodePNGUnknownChunks_cleanup(dest); + + for(i = 0; i != 3; ++i) + { + size_t j; + dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; + dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); + if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ + for(j = 0; j < src->unknown_chunks_size[i]; ++j) + { + dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; + } + } + + return 0; +} + +/******************************************************************************/ + +static void LodePNGText_init(LodePNGInfo* info) +{ + info->text_num = 0; + info->text_keys = NULL; + info->text_strings = NULL; +} + +static void LodePNGText_cleanup(LodePNGInfo* info) +{ + size_t i; + for(i = 0; i != info->text_num; ++i) + { + string_cleanup(&info->text_keys[i]); + string_cleanup(&info->text_strings[i]); + } + lodepng_free(info->text_keys); + lodepng_free(info->text_strings); +} + +static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) +{ + size_t i = 0; + dest->text_keys = 0; + dest->text_strings = 0; + dest->text_num = 0; + for(i = 0; i != source->text_num; ++i) + { + CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); + } + return 0; +} + +void lodepng_clear_text(LodePNGInfo* info) +{ + LodePNGText_cleanup(info); +} + +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) +{ + char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); + if(!new_keys || !new_strings) + { + lodepng_free(new_keys); + lodepng_free(new_strings); + return 83; /*alloc fail*/ + } + + ++info->text_num; + info->text_keys = new_keys; + info->text_strings = new_strings; + + string_init(&info->text_keys[info->text_num - 1]); + string_set(&info->text_keys[info->text_num - 1], key); + + string_init(&info->text_strings[info->text_num - 1]); + string_set(&info->text_strings[info->text_num - 1], str); + + return 0; +} + +/******************************************************************************/ + +static void LodePNGIText_init(LodePNGInfo* info) +{ + info->itext_num = 0; + info->itext_keys = NULL; + info->itext_langtags = NULL; + info->itext_transkeys = NULL; + info->itext_strings = NULL; +} + +static void LodePNGIText_cleanup(LodePNGInfo* info) +{ + size_t i; + for(i = 0; i != info->itext_num; ++i) + { + string_cleanup(&info->itext_keys[i]); + string_cleanup(&info->itext_langtags[i]); + string_cleanup(&info->itext_transkeys[i]); + string_cleanup(&info->itext_strings[i]); + } + lodepng_free(info->itext_keys); + lodepng_free(info->itext_langtags); + lodepng_free(info->itext_transkeys); + lodepng_free(info->itext_strings); +} + +static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) +{ + size_t i = 0; + dest->itext_keys = 0; + dest->itext_langtags = 0; + dest->itext_transkeys = 0; + dest->itext_strings = 0; + dest->itext_num = 0; + for(i = 0; i != source->itext_num; ++i) + { + CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], + source->itext_transkeys[i], source->itext_strings[i])); + } + return 0; +} + +void lodepng_clear_itext(LodePNGInfo* info) +{ + LodePNGIText_cleanup(info); +} + +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str) +{ + char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); + char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); + char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); + if(!new_keys || !new_langtags || !new_transkeys || !new_strings) + { + lodepng_free(new_keys); + lodepng_free(new_langtags); + lodepng_free(new_transkeys); + lodepng_free(new_strings); + return 83; /*alloc fail*/ + } + + ++info->itext_num; + info->itext_keys = new_keys; + info->itext_langtags = new_langtags; + info->itext_transkeys = new_transkeys; + info->itext_strings = new_strings; + + string_init(&info->itext_keys[info->itext_num - 1]); + string_set(&info->itext_keys[info->itext_num - 1], key); + + string_init(&info->itext_langtags[info->itext_num - 1]); + string_set(&info->itext_langtags[info->itext_num - 1], langtag); + + string_init(&info->itext_transkeys[info->itext_num - 1]); + string_set(&info->itext_transkeys[info->itext_num - 1], transkey); + + string_init(&info->itext_strings[info->itext_num - 1]); + string_set(&info->itext_strings[info->itext_num - 1], str); + + return 0; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +void lodepng_info_init(LodePNGInfo* info) +{ + lodepng_color_mode_init(&info->color); + info->interlace_method = 0; + info->compression_method = 0; + info->filter_method = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + info->background_defined = 0; + info->background_r = info->background_g = info->background_b = 0; + + LodePNGText_init(info); + LodePNGIText_init(info); + + info->time_defined = 0; + info->phys_defined = 0; + + LodePNGUnknownChunks_init(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +void lodepng_info_cleanup(LodePNGInfo* info) +{ + lodepng_color_mode_cleanup(&info->color); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + LodePNGText_cleanup(info); + LodePNGIText_cleanup(info); + + LodePNGUnknownChunks_cleanup(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) +{ + lodepng_info_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->color); + CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); + CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); + + LodePNGUnknownChunks_init(dest); + CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + return 0; +} + +void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b) +{ + LodePNGInfo temp = *a; + *a = *b; + *b = temp; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ +static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) +{ + unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ + /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ + unsigned p = index & m; + in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ + in = in << (bits * (m - p)); + if(p == 0) out[index * bits / 8] = in; + else out[index * bits / 8] |= in; +} + +typedef struct ColorTree ColorTree; + +/* +One node of a color tree +This is the data structure used to count the number of unique colors and to get a palette +index for a color. It's like an octree, but because the alpha channel is used too, each +node has 16 instead of 8 children. +*/ +struct ColorTree +{ + ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ + int index; /*the payload. Only has a meaningful value if this is in the last level*/ +}; + +static void color_tree_init(ColorTree* tree) +{ + int i; + for(i = 0; i != 16; ++i) tree->children[i] = 0; + tree->index = -1; +} + +static void color_tree_cleanup(ColorTree* tree) +{ + int i; + for(i = 0; i != 16; ++i) + { + if(tree->children[i]) + { + color_tree_cleanup(tree->children[i]); + lodepng_free(tree->children[i]); + } + } +} + +/*returns -1 if color not present, its index otherwise*/ +static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + int bit = 0; + for(bit = 0; bit < 8; ++bit) + { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) return -1; + else tree = tree->children[i]; + } + return tree ? tree->index : -1; +} + +#ifdef LODEPNG_COMPILE_ENCODER +static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + return color_tree_get(tree, r, g, b, a) >= 0; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*color is not allowed to already exist. +Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/ +static void color_tree_add(ColorTree* tree, + unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) +{ + int bit; + for(bit = 0; bit < 8; ++bit) + { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) + { + tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); + color_tree_init(tree->children[i]); + } + tree = tree->children[i]; + } + tree->index = (int)index; +} + +/*put a pixel, given its RGBA color, into image of any color type*/ +static unsigned rgba8ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + if(mode->colortype == LCT_GREY) + { + unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; + if(mode->bitdepth == 8) out[i] = grey; + else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; + else + { + /*take the most significant bits of grey*/ + grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); + addColorBits(out, i, mode->bitdepth, grey); + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + out[i * 3 + 0] = r; + out[i * 3 + 1] = g; + out[i * 3 + 2] = b; + } + else + { + out[i * 6 + 0] = out[i * 6 + 1] = r; + out[i * 6 + 2] = out[i * 6 + 3] = g; + out[i * 6 + 4] = out[i * 6 + 5] = b; + } + } + else if(mode->colortype == LCT_PALETTE) + { + int index = color_tree_get(tree, r, g, b, a); + if(index < 0) return 82; /*color not in palette*/ + if(mode->bitdepth == 8) out[i] = index; + else addColorBits(out, i, mode->bitdepth, (unsigned)index); + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; + if(mode->bitdepth == 8) + { + out[i * 2 + 0] = grey; + out[i * 2 + 1] = a; + } + else if(mode->bitdepth == 16) + { + out[i * 4 + 0] = out[i * 4 + 1] = grey; + out[i * 4 + 2] = out[i * 4 + 3] = a; + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + out[i * 4 + 0] = r; + out[i * 4 + 1] = g; + out[i * 4 + 2] = b; + out[i * 4 + 3] = a; + } + else + { + out[i * 8 + 0] = out[i * 8 + 1] = r; + out[i * 8 + 2] = out[i * 8 + 3] = g; + out[i * 8 + 4] = out[i * 8 + 5] = b; + out[i * 8 + 6] = out[i * 8 + 7] = a; + } + } + + return 0; /*no error*/ +} + +/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ +static void rgba16ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, + unsigned short r, unsigned short g, unsigned short b, unsigned short a) +{ + if(mode->colortype == LCT_GREY) + { + unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; + out[i * 2 + 0] = (grey >> 8) & 255; + out[i * 2 + 1] = grey & 255; + } + else if(mode->colortype == LCT_RGB) + { + out[i * 6 + 0] = (r >> 8) & 255; + out[i * 6 + 1] = r & 255; + out[i * 6 + 2] = (g >> 8) & 255; + out[i * 6 + 3] = g & 255; + out[i * 6 + 4] = (b >> 8) & 255; + out[i * 6 + 5] = b & 255; + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; + out[i * 4 + 0] = (grey >> 8) & 255; + out[i * 4 + 1] = grey & 255; + out[i * 4 + 2] = (a >> 8) & 255; + out[i * 4 + 3] = a & 255; + } + else if(mode->colortype == LCT_RGBA) + { + out[i * 8 + 0] = (r >> 8) & 255; + out[i * 8 + 1] = r & 255; + out[i * 8 + 2] = (g >> 8) & 255; + out[i * 8 + 3] = g & 255; + out[i * 8 + 4] = (b >> 8) & 255; + out[i * 8 + 5] = b & 255; + out[i * 8 + 6] = (a >> 8) & 255; + out[i * 8 + 7] = a & 255; + } +} + +/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ +static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, + unsigned char* b, unsigned char* a, + const unsigned char* in, size_t i, + const LodePNGColorMode* mode) +{ + if(mode->colortype == LCT_GREY) + { + if(mode->bitdepth == 8) + { + *r = *g = *b = in[i]; + if(mode->key_defined && *r == mode->key_r) *a = 0; + else *a = 255; + } + else if(mode->bitdepth == 16) + { + *r = *g = *b = in[i * 2 + 0]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 255; + } + else + { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = i * mode->bitdepth; + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + *r = *g = *b = (value * 255) / highest; + if(mode->key_defined && value == mode->key_r) *a = 0; + else *a = 255; + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; + if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; + else *a = 255; + } + else + { + *r = in[i * 6 + 0]; + *g = in[i * 6 + 2]; + *b = in[i * 6 + 4]; + if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 255; + } + } + else if(mode->colortype == LCT_PALETTE) + { + unsigned index; + if(mode->bitdepth == 8) index = in[i]; + else + { + size_t j = i * mode->bitdepth; + index = readBitsFromReversedStream(&j, in, mode->bitdepth); + } + + if(index >= mode->palettesize) + { + /*This is an error according to the PNG spec, but common PNG decoders make it black instead. + Done here too, slightly faster due to no error handling needed.*/ + *r = *g = *b = 0; + *a = 255; + } + else + { + *r = mode->palette[index * 4 + 0]; + *g = mode->palette[index * 4 + 1]; + *b = mode->palette[index * 4 + 2]; + *a = mode->palette[index * 4 + 3]; + } + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + if(mode->bitdepth == 8) + { + *r = *g = *b = in[i * 2 + 0]; + *a = in[i * 2 + 1]; + } + else + { + *r = *g = *b = in[i * 4 + 0]; + *a = in[i * 4 + 2]; + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + *r = in[i * 4 + 0]; + *g = in[i * 4 + 1]; + *b = in[i * 4 + 2]; + *a = in[i * 4 + 3]; + } + else + { + *r = in[i * 8 + 0]; + *g = in[i * 8 + 2]; + *b = in[i * 8 + 4]; + *a = in[i * 8 + 6]; + } + } +} + +/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color +mode test cases, optimized to convert the colors much faster, when converting +to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with +enough memory, if has_alpha is true the output is RGBA. mode has the color mode +of the input buffer.*/ +static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, + unsigned has_alpha, const unsigned char* in, + const LodePNGColorMode* mode) +{ + unsigned num_channels = has_alpha ? 4 : 3; + size_t i; + if(mode->colortype == LCT_GREY) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i]; + if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; + } + } + else if(mode->bitdepth == 16) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; + } + } + else + { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; + } + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 3 + 0]; + buffer[1] = in[i * 3 + 1]; + buffer[2] = in[i * 3 + 2]; + if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r + && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + if(has_alpha) buffer[3] = mode->key_defined + && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; + } + } + } + else if(mode->colortype == LCT_PALETTE) + { + unsigned index; + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + if(mode->bitdepth == 8) index = in[i]; + else index = readBitsFromReversedStream(&j, in, mode->bitdepth); + + if(index >= mode->palettesize) + { + /*This is an error according to the PNG spec, but most PNG decoders make it black instead. + Done here too, slightly faster due to no error handling needed.*/ + buffer[0] = buffer[1] = buffer[2] = 0; + if(has_alpha) buffer[3] = 255; + } + else + { + buffer[0] = mode->palette[index * 4 + 0]; + buffer[1] = mode->palette[index * 4 + 1]; + buffer[2] = mode->palette[index * 4 + 2]; + if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; + } + } + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + if(has_alpha) buffer[3] = in[i * 2 + 1]; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + if(has_alpha) buffer[3] = in[i * 4 + 2]; + } + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 4 + 0]; + buffer[1] = in[i * 4 + 1]; + buffer[2] = in[i * 4 + 2]; + if(has_alpha) buffer[3] = in[i * 4 + 3]; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + if(has_alpha) buffer[3] = in[i * 8 + 6]; + } + } + } +} + +/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with +given color type, but the given color type must be 16-bit itself.*/ +static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, + const unsigned char* in, size_t i, const LodePNGColorMode* mode) +{ + if(mode->colortype == LCT_GREY) + { + *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 65535; + } + else if(mode->colortype == LCT_RGB) + { + *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; + *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; + *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; + if(mode->key_defined + && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 65535; + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; + *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; + } + else if(mode->colortype == LCT_RGBA) + { + *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; + *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; + *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; + *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; + } +} + +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h) +{ + size_t i; + ColorTree tree; + size_t numpixels = w * h; + + if(lodepng_color_mode_equal(mode_out, mode_in)) + { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + for(i = 0; i != numbytes; ++i) out[i] = in[i]; + return 0; + } + + if(mode_out->colortype == LCT_PALETTE) + { + size_t palettesize = mode_out->palettesize; + const unsigned char* palette = mode_out->palette; + size_t palsize = 1u << mode_out->bitdepth; + /*if the user specified output palette but did not give the values, assume + they want the values of the input color type (assuming that one is palette). + Note that we never create a new palette ourselves.*/ + if(palettesize == 0) + { + palettesize = mode_in->palettesize; + palette = mode_in->palette; + } + if(palettesize < palsize) palsize = palettesize; + color_tree_init(&tree); + for(i = 0; i != palsize; ++i) + { + const unsigned char* p = &palette[i * 4]; + color_tree_add(&tree, p[0], p[1], p[2], p[3], i); + } + } + + if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) + { + for(i = 0; i != numpixels; ++i) + { + unsigned short r = 0, g = 0, b = 0, a = 0; + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + rgba16ToPixel(out, i, mode_out, r, g, b, a); + } + } + else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) + { + getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); + } + else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) + { + getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); + } + else + { + unsigned char r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + CERROR_TRY_RETURN(rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a)); + } + } + + if(mode_out->colortype == LCT_PALETTE) + { + color_tree_cleanup(&tree); + } + + return 0; /*no error*/ +} + +#ifdef LODEPNG_COMPILE_ENCODER + +void lodepng_color_profile_init(LodePNGColorProfile* profile) +{ + profile->colored = 0; + profile->key = 0; + profile->alpha = 0; + profile->key_r = profile->key_g = profile->key_b = 0; + profile->numcolors = 0; + profile->bits = 1; +} + +/*function used for debug purposes with C++*/ +/*void printColorProfile(LodePNGColorProfile* p) +{ + std::cout << "colored: " << (int)p->colored << ", "; + std::cout << "key: " << (int)p->key << ", "; + std::cout << "key_r: " << (int)p->key_r << ", "; + std::cout << "key_g: " << (int)p->key_g << ", "; + std::cout << "key_b: " << (int)p->key_b << ", "; + std::cout << "alpha: " << (int)p->alpha << ", "; + std::cout << "numcolors: " << (int)p->numcolors << ", "; + std::cout << "bits: " << (int)p->bits << std::endl; +}*/ + +/*Returns how many bits needed to represent given value (max 8 bit)*/ +static unsigned getValueRequiredBits(unsigned char value) +{ + if(value == 0 || value == 255) return 1; + /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ + if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; + return 8; +} + +/*profile must already have been inited with mode. +It's ok to set some parameters of profile to done already.*/ +unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, + const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* mode) +{ + unsigned error = 0; + size_t i; + ColorTree tree; + size_t numpixels = w * h; + + unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; + unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; + unsigned numcolors_done = 0; + unsigned bpp = lodepng_get_bpp(mode); + unsigned bits_done = bpp == 1 ? 1 : 0; + unsigned maxnumcolors = 257; + unsigned sixteen = 0; + if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256)); + + color_tree_init(&tree); + + /*Check if the 16-bit input is truly 16-bit*/ + if(mode->bitdepth == 16) + { + unsigned short r, g, b, a; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || + (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ + { + sixteen = 1; + break; + } + } + } + + if(sixteen) + { + unsigned short r = 0, g = 0, b = 0, a = 0; + profile->bits = 16; + bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ + + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + + if(!colored_done && (r != g || r != b)) + { + profile->colored = 1; + colored_done = 1; + } + + if(!alpha_done) + { + unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); + if(a != 65535 && (a != 0 || (profile->key && !matchkey))) + { + profile->alpha = 1; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + else if(a == 0 && !profile->alpha && !profile->key) + { + profile->key = 1; + profile->key_r = r; + profile->key_g = g; + profile->key_b = b; + } + else if(a == 65535 && profile->key && matchkey) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + alpha_done = 1; + } + } + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + if(profile->key && !profile->alpha) + { + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + alpha_done = 1; + } + } + } + } + else /* < 16-bit */ + { + unsigned char r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); + + if(!bits_done && profile->bits < 8) + { + /*only r is checked, < 8 bits is only relevant for greyscale*/ + unsigned bits = getValueRequiredBits(r); + if(bits > profile->bits) profile->bits = bits; + } + bits_done = (profile->bits >= bpp); + + if(!colored_done && (r != g || r != b)) + { + profile->colored = 1; + colored_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ + } + + if(!alpha_done) + { + unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); + if(a != 255 && (a != 0 || (profile->key && !matchkey))) + { + profile->alpha = 1; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + else if(a == 0 && !profile->alpha && !profile->key) + { + profile->key = 1; + profile->key_r = r; + profile->key_g = g; + profile->key_b = b; + } + else if(a == 255 && profile->key && matchkey) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + + if(!numcolors_done) + { + if(!color_tree_has(&tree, r, g, b, a)) + { + color_tree_add(&tree, r, g, b, a, profile->numcolors); + if(profile->numcolors < 256) + { + unsigned char* p = profile->palette; + unsigned n = profile->numcolors; + p[n * 4 + 0] = r; + p[n * 4 + 1] = g; + p[n * 4 + 2] = b; + p[n * 4 + 3] = a; + } + ++profile->numcolors; + numcolors_done = profile->numcolors >= maxnumcolors; + } + } + + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + if(profile->key && !profile->alpha) + { + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); + if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + alpha_done = 1; + } + } + } + + /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ + profile->key_r += (profile->key_r << 8); + profile->key_g += (profile->key_g << 8); + profile->key_b += (profile->key_b << 8); + } + + color_tree_cleanup(&tree); + return error; +} + +/*Automatically chooses color type that gives smallest amount of bits in the +output image, e.g. grey if there are only greyscale pixels, palette if there +are less than 256 colors, ... +Updates values of mode with a potentially smaller color model. mode_out should +contain the user chosen color model, but will be overwritten with the new chosen one.*/ +unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in) +{ + LodePNGColorProfile prof; + unsigned error = 0; + unsigned i, n, palettebits, grey_ok, palette_ok; + + lodepng_color_profile_init(&prof); + error = lodepng_get_color_profile(&prof, image, w, h, mode_in); + if(error) return error; + mode_out->key_defined = 0; + + if(prof.key && w * h <= 16) + { + prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ + if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/ + n = prof.numcolors; + palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); + palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8; + if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ + if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ + + if(palette_ok) + { + unsigned char* p = prof.palette; + lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ + for(i = 0; i != prof.numcolors; ++i) + { + error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); + if(error) break; + } + + mode_out->colortype = LCT_PALETTE; + mode_out->bitdepth = palettebits; + + if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize + && mode_in->bitdepth == mode_out->bitdepth) + { + /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ + lodepng_color_mode_cleanup(mode_out); + lodepng_color_mode_copy(mode_out, mode_in); + } + } + else /*8-bit or 16-bit per channel*/ + { + mode_out->bitdepth = prof.bits; + mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) + : (prof.colored ? LCT_RGB : LCT_GREY); + + if(prof.key && !prof.alpha) + { + unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ + mode_out->key_r = prof.key_r & mask; + mode_out->key_g = prof.key_g & mask; + mode_out->key_b = prof.key_b & mask; + mode_out->key_defined = 1; + } + } + + return error; +} + +#endif /* #ifdef LODEPNG_COMPILE_ENCODER */ + +/* +Paeth predicter, used by PNG filter type 4 +The parameters are of type short, but should come from unsigned chars, the shorts +are only needed to make the paeth calculation correct. +*/ +static unsigned char paethPredictor(short a, short b, short c) +{ + short pa = abs(b - c); + short pb = abs(a - c); + short pc = abs(a + b - c - c); + + if(pc < pa && pc < pb) return (unsigned char)c; + else if(pb < pa) return (unsigned char)b; + else return (unsigned char)a; +} + +/*shared values used by multiple Adam7 related functions*/ + +static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ +static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ +static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ +static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ + +/* +Outputs various dimensions and positions in the image related to the Adam7 reduced images. +passw: output containing the width of the 7 passes +passh: output containing the height of the 7 passes +filter_passstart: output containing the index of the start and end of each + reduced image with filter bytes +padded_passstart output containing the index of the start and end of each + reduced image when without filter bytes but with padded scanlines +passstart: output containing the index of the start and end of each reduced + image without padding between scanlines, but still padding between the images +w, h: width and height of non-interlaced image +bpp: bits per pixel +"padded" is only relevant if bpp is less than 8 and a scanline or image does not + end at a full byte +*/ +static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], + size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) +{ + /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ + unsigned i; + + /*calculate width and height in pixels of each pass*/ + for(i = 0; i != 7; ++i) + { + passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; + passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; + if(passw[i] == 0) passh[i] = 0; + if(passh[i] == 0) passw[i] = 0; + } + + filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; + for(i = 0; i != 7; ++i) + { + /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ + filter_passstart[i + 1] = filter_passstart[i] + + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); + /*bits padded if needed to fill full byte at end of each scanline*/ + padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); + /*only padded at end of reduced image*/ + passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; + } +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Decoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*read the information from the header and store it in the LodePNGInfo. return value is error*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, + const unsigned char* in, size_t insize) +{ + LodePNGInfo* info = &state->info_png; + if(insize == 0 || in == 0) + { + CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ + } + if(insize < 33) + { + CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ + } + + /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ + lodepng_info_cleanup(info); + lodepng_info_init(info); + + if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) + { + CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ + } + if(lodepng_chunk_length(in + 8) != 13) + { + CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ + } + if(!lodepng_chunk_type_equals(in + 8, "IHDR")) + { + CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ + } + + /*read the values given in the header*/ + *w = lodepng_read32bitInt(&in[16]); + *h = lodepng_read32bitInt(&in[20]); + info->color.bitdepth = in[24]; + info->color.colortype = (LodePNGColorType)in[25]; + info->compression_method = in[26]; + info->filter_method = in[27]; + info->interlace_method = in[28]; + + if(*w == 0 || *h == 0) + { + CERROR_RETURN_ERROR(state->error, 93); + } + + if(!state->decoder.ignore_crc) + { + unsigned CRC = lodepng_read32bitInt(&in[29]); + unsigned checksum = lodepng_crc32(&in[12], 17); + if(CRC != checksum) + { + CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ + } + } + + /*error: only compression method 0 is allowed in the specification*/ + if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); + /*error: only filter method 0 is allowed in the specification*/ + if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); + /*error: only interlace methods 0 and 1 exist in the specification*/ + if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); + + state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); + return state->error; +} + +static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, + size_t bytewidth, unsigned char filterType, size_t length) +{ + /* + For PNG filter method 0 + unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, + the filter works byte per byte (bytewidth = 1) + precon is the previous unfiltered scanline, recon the result, scanline the current one + the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead + recon and scanline MAY be the same memory address! precon must be disjoint. + */ + + size_t i; + switch(filterType) + { + case 0: + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + break; + case 1: + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; + break; + case 2: + if(precon) + { + for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; + } + else + { + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + } + break; + case 3: + if(precon) + { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1); + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1); + } + else + { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1); + } + break; + case 4: + if(precon) + { + for(i = 0; i != bytewidth; ++i) + { + recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ + } + for(i = bytewidth; i < length; ++i) + { + recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); + } + } + else + { + for(i = 0; i != bytewidth; ++i) + { + recon[i] = scanline[i]; + } + for(i = bytewidth; i < length; ++i) + { + /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ + recon[i] = (scanline[i] + recon[i - bytewidth]); + } + } + break; + default: return 36; /*error: unexisting filter type given*/ + } + return 0; +} + +static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) +{ + /* + For PNG filter method 0 + this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) + out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline + w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel + in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) + */ + + unsigned y; + unsigned char* prevline = 0; + + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7) / 8; + size_t linebytes = (w * bpp + 7) / 8; + + for(y = 0; y < h; ++y) + { + size_t outindex = linebytes * y; + size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + unsigned char filterType = in[inindex]; + + CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); + + prevline = &out[outindex]; + } + + return 0; +} + +/* +in: Adam7 interlaced image, with no padding bits between scanlines, but between + reduced images so that each reduced image starts at a byte. +out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h +bpp: bits per pixel +out has the following size in bits: w * h * bpp. +in is possibly bigger due to padding bits between reduced images. +out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation +(because that's likely a little bit faster) +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) +{ + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + size_t bytewidth = bpp / 8; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; + size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + for(b = 0; b < bytewidth; ++b) + { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } + else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + for(b = 0; b < bpp; ++b) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ + setBitOfReversedStream0(&obp, out, bit); + } + } + } + } +} + +static void removePaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) +{ + /* + After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need + to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers + for the Adam7 code, the color convert code and the output to the user. + in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must + have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits + also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 + only useful if (ilinebits - olinebits) is a value in the range 1..7 + */ + unsigned y; + size_t diff = ilinebits - olinebits; + size_t ibp = 0, obp = 0; /*input and output bit pointers*/ + for(y = 0; y < h; ++y) + { + size_t x; + for(x = 0; x < olinebits; ++x) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + ibp += diff; + } +} + +/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from +the IDAT chunks (with filter index bytes and possible padding bits) +return value is error*/ +static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, + unsigned w, unsigned h, const LodePNGInfo* info_png) +{ + /* + This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. + Steps: + *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) + *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace + NOTE: the in buffer will be overwritten with intermediate data! + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + if(bpp == 0) return 31; /*error: invalid colortype*/ + + if(info_png->interlace_method == 0) + { + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) + { + CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); + removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); + } + /*we can immediately filter into the out buffer, no other steps needed*/ + else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); + } + else /*interlace_method is 1 (Adam7)*/ + { + unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + for(i = 0; i != 7; ++i) + { + CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); + /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, + move bytes instead of bits or move not at all*/ + if(bpp < 8) + { + /*remove padding bits in scanlines; after this there still may be padding + bits between the different reduced images: each reduced image still starts nicely at a byte*/ + removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, + ((passw[i] * bpp + 7) / 8) * 8, passh[i]); + } + } + + Adam7_deinterlace(out, in, w, h, bpp); + } + + return 0; +} + +static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) +{ + unsigned pos = 0, i; + if(color->palette) lodepng_free(color->palette); + color->palettesize = chunkLength / 3; + color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize); + if(!color->palette && color->palettesize) + { + color->palettesize = 0; + return 83; /*alloc fail*/ + } + if(color->palettesize > 256) return 38; /*error: palette too big*/ + + for(i = 0; i != color->palettesize; ++i) + { + color->palette[4 * i + 0] = data[pos++]; /*R*/ + color->palette[4 * i + 1] = data[pos++]; /*G*/ + color->palette[4 * i + 2] = data[pos++]; /*B*/ + color->palette[4 * i + 3] = 255; /*alpha*/ + } + + return 0; /* OK */ +} + +static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) +{ + unsigned i; + if(color->colortype == LCT_PALETTE) + { + /*error: more alpha values given than there are palette entries*/ + if(chunkLength > color->palettesize) return 38; + + for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; + } + else if(color->colortype == LCT_GREY) + { + /*error: this chunk must be 2 bytes for greyscale image*/ + if(chunkLength != 2) return 30; + + color->key_defined = 1; + color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; + } + else if(color->colortype == LCT_RGB) + { + /*error: this chunk must be 6 bytes for RGB image*/ + if(chunkLength != 6) return 41; + + color->key_defined = 1; + color->key_r = 256u * data[0] + data[1]; + color->key_g = 256u * data[2] + data[3]; + color->key_b = 256u * data[4] + data[5]; + } + else return 42; /*error: tRNS chunk not allowed for other color models*/ + + return 0; /* OK */ +} + + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*background color chunk (bKGD)*/ +static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + if(info->color.colortype == LCT_PALETTE) + { + /*error: this chunk must be 1 byte for indexed color image*/ + if(chunkLength != 1) return 43; + + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = data[0]; + } + else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) + { + /*error: this chunk must be 2 bytes for greyscale image*/ + if(chunkLength != 2) return 44; + + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; + } + else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) + { + /*error: this chunk must be 6 bytes for greyscale image*/ + if(chunkLength != 6) return 45; + + info->background_defined = 1; + info->background_r = 256u * data[0] + data[1]; + info->background_g = 256u * data[2] + data[3]; + info->background_b = 256u * data[4] + data[5]; + } + + return 0; /* OK */ +} + +/*text chunk (tEXt)*/ +static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + unsigned error = 0; + char *key = 0, *str = 0; + unsigned i; + + while(!error) /*not really a while loop, only used to break on error*/ + { + unsigned length, string2_begin; + + length = 0; + while(length < chunkLength && data[length] != 0) ++length; + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; + + string2_begin = length + 1; /*skip keyword null terminator*/ + + length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; + str = (char*)lodepng_malloc(length + 1); + if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ + + str[length] = 0; + for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i]; + + error = lodepng_add_text(info, key, str); + + break; + } + + lodepng_free(key); + lodepng_free(str); + + return error; +} + +/*compressed text chunk (zTXt)*/ +static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) +{ + unsigned error = 0; + unsigned i; + + unsigned length, string2_begin; + char *key = 0; + ucvector decoded; + + ucvector_init(&decoded); + + while(!error) /*not really a while loop, only used to break on error*/ + { + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; + + if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + string2_begin = length + 2; + if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + + length = chunkLength - string2_begin; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&decoded.data, &decoded.size, + (unsigned char*)(&data[string2_begin]), + length, zlibsettings); + if(error) break; + ucvector_push_back(&decoded, 0); + + error = lodepng_add_text(info, key, (char*)decoded.data); + + break; + } + + lodepng_free(key); + ucvector_cleanup(&decoded); + + return error; +} + +/*international text chunk (iTXt)*/ +static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) +{ + unsigned error = 0; + unsigned i; + + unsigned length, begin, compressed; + char *key = 0, *langtag = 0, *transkey = 0; + ucvector decoded; + ucvector_init(&decoded); + + while(!error) /*not really a while loop, only used to break on error*/ + { + /*Quick check if the chunk length isn't too small. Even without check + it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ + if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ + + /*read the key*/ + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; + + /*read the compression method*/ + compressed = data[length + 1]; + if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty for the next 3 texts*/ + + /*read the langtag*/ + begin = length + 3; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + langtag = (char*)lodepng_malloc(length + 1); + if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ + + langtag[length] = 0; + for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i]; + + /*read the transkey*/ + begin += length + 1; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + transkey = (char*)lodepng_malloc(length + 1); + if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ + + transkey[length] = 0; + for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i]; + + /*read the actual text*/ + begin += length + 1; + + length = chunkLength < begin ? 0 : chunkLength - begin; + + if(compressed) + { + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&decoded.data, &decoded.size, + (unsigned char*)(&data[begin]), + length, zlibsettings); + if(error) break; + if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; + ucvector_push_back(&decoded, 0); + } + else + { + if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); + + decoded.data[length] = 0; + for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i]; + } + + error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); + + break; + } + + lodepng_free(key); + lodepng_free(langtag); + lodepng_free(transkey); + ucvector_cleanup(&decoded); + + return error; +} + +static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ + + info->time_defined = 1; + info->time.year = 256u * data[0] + data[1]; + info->time.month = data[2]; + info->time.day = data[3]; + info->time.hour = data[4]; + info->time.minute = data[5]; + info->time.second = data[6]; + + return 0; /* OK */ +} + +static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ + + info->phys_defined = 1; + info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; + info->phys_unit = data[8]; + + return 0; /* OK */ +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ +static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) +{ + unsigned char IEND = 0; + const unsigned char* chunk; + size_t i; + ucvector idat; /*the data from idat chunks*/ + ucvector scanlines; + size_t predict; + size_t numpixels; + size_t outsize = 0; + + /*for unknown chunk order*/ + unsigned unknown = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + + /*provide some proper output values if error will happen*/ + *out = 0; + + state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ + if(state->error) return; + + numpixels = *w * *h; + + /*multiplication overflow*/ + if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92); + /*multiplication overflow possible further below. Allows up to 2^31-1 pixel + bytes with 16-bit RGBA, the rest is room for filter bytes.*/ + if(numpixels > 268435455) CERROR_RETURN(state->error, 92); + + ucvector_init(&idat); + chunk = &in[33]; /*first byte of the first chunk after the header*/ + + /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. + IDAT data is put at the start of the in buffer*/ + while(!IEND && !state->error) + { + unsigned chunkLength; + const unsigned char* data; /*the data in the chunk*/ + + /*error: size of the in buffer too small to contain next chunk*/ + if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30); + + /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ + chunkLength = lodepng_chunk_length(chunk); + /*error: chunk length larger than the max PNG chunk size*/ + if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63); + + if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) + { + CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ + } + + data = lodepng_chunk_data_const(chunk); + + /*IDAT chunk, containing compressed image data*/ + if(lodepng_chunk_type_equals(chunk, "IDAT")) + { + size_t oldsize = idat.size; + if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); + for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 3; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + /*IEND chunk*/ + else if(lodepng_chunk_type_equals(chunk, "IEND")) + { + IEND = 1; + } + /*palette chunk (PLTE)*/ + else if(lodepng_chunk_type_equals(chunk, "PLTE")) + { + state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 2; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + /*palette transparency chunk (tRNS)*/ + else if(lodepng_chunk_type_equals(chunk, "tRNS")) + { + state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); + if(state->error) break; + } +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*background color chunk (bKGD)*/ + else if(lodepng_chunk_type_equals(chunk, "bKGD")) + { + state->error = readChunk_bKGD(&state->info_png, data, chunkLength); + if(state->error) break; + } + /*text chunk (tEXt)*/ + else if(lodepng_chunk_type_equals(chunk, "tEXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_tEXt(&state->info_png, data, chunkLength); + if(state->error) break; + } + } + /*compressed text chunk (zTXt)*/ + else if(lodepng_chunk_type_equals(chunk, "zTXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } + /*international text chunk (iTXt)*/ + else if(lodepng_chunk_type_equals(chunk, "iTXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } + else if(lodepng_chunk_type_equals(chunk, "tIME")) + { + state->error = readChunk_tIME(&state->info_png, data, chunkLength); + if(state->error) break; + } + else if(lodepng_chunk_type_equals(chunk, "pHYs")) + { + state->error = readChunk_pHYs(&state->info_png, data, chunkLength); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + else /*it's not an implemented chunk type, so ignore it: skip over the data*/ + { + /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ + if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69); + + unknown = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(state->decoder.remember_unknown_chunks) + { + state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], + &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + + if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ + { + if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ + } + + if(!IEND) chunk = lodepng_chunk_next_const(chunk); + } + + ucvector_init(&scanlines); + /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. + If the decompressed size does not match the prediction, the image must be corrupt.*/ + if(state->info_png.interlace_method == 0) + { + /*The extra *h is added because this are the filter bytes every scanline starts with*/ + predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; + } + else + { + /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ + const LodePNGColorMode* color = &state->info_png.color; + predict = 0; + predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); + if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); + predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3); + if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2); + predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2); + if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1); + predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1); + } + if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, + idat.size, &state->decoder.zlibsettings); + if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ + } + ucvector_cleanup(&idat); + + if(!state->error) + { + outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!*out) state->error = 83; /*alloc fail*/ + } + if(!state->error) + { + for(i = 0; i < outsize; i++) (*out)[i] = 0; + state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png); + } + ucvector_cleanup(&scanlines); +} + +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) +{ + *out = 0; + decodeGeneric(out, w, h, state, in, insize); + if(state->error) return state->error; + if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) + { + /*same color type, no copying or converting of data needed*/ + /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype + the raw image has to the end user*/ + if(!state->decoder.color_convert) + { + state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); + if(state->error) return state->error; + } + } + else + { + /*color conversion needed; sort of copy of the data*/ + unsigned char* data = *out; + size_t outsize; + + /*TODO: check if this works according to the statement in the documentation: "The converter can convert + from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ + if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) + && !(state->info_raw.bitdepth == 8)) + { + return 56; /*unsupported color mode conversion*/ + } + + outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!(*out)) + { + state->error = 83; /*alloc fail*/ + } + else state->error = lodepng_convert(*out, data, &state->info_raw, + &state->info_png.color, *w, *h); + lodepng_free(data); + } + return state->error; +} + +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + error = lodepng_decode(out, w, h, &state, in, insize); + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) +{ + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); +} + +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) +{ + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, + LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer = 0; + size_t buffersize; + unsigned error; + error = lodepng_load_file(&buffer, &buffersize, filename); + if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) +{ + return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); +} + +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) +{ + return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) +{ + settings->color_convert = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->read_text_chunks = 1; + settings->remember_unknown_chunks = 0; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + settings->ignore_crc = 0; + lodepng_decompress_settings_init(&settings->zlibsettings); +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) + +void lodepng_state_init(LodePNGState* state) +{ +#ifdef LODEPNG_COMPILE_DECODER + lodepng_decoder_settings_init(&state->decoder); +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + lodepng_encoder_settings_init(&state->encoder); +#endif /*LODEPNG_COMPILE_ENCODER*/ + lodepng_color_mode_init(&state->info_raw); + lodepng_info_init(&state->info_png); + state->error = 1; +} + +void lodepng_state_cleanup(LodePNGState* state) +{ + lodepng_color_mode_cleanup(&state->info_raw); + lodepng_info_cleanup(&state->info_png); +} + +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) +{ + lodepng_state_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->info_raw); + lodepng_info_init(&dest->info_png); + dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; + dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; +} + +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Encoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*chunkName must be string of 4 characters*/ +static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) +{ + CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); + out->allocsize = out->size; /*fix the allocsize again*/ + return 0; +} + +static void writeSignature(ucvector* out) +{ + /*8 bytes PNG signature, aka the magic bytes*/ + ucvector_push_back(out, 137); + ucvector_push_back(out, 80); + ucvector_push_back(out, 78); + ucvector_push_back(out, 71); + ucvector_push_back(out, 13); + ucvector_push_back(out, 10); + ucvector_push_back(out, 26); + ucvector_push_back(out, 10); +} + +static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) +{ + unsigned error = 0; + ucvector header; + ucvector_init(&header); + + lodepng_add32bitInt(&header, w); /*width*/ + lodepng_add32bitInt(&header, h); /*height*/ + ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/ + ucvector_push_back(&header, (unsigned char)colortype); /*color type*/ + ucvector_push_back(&header, 0); /*compression method*/ + ucvector_push_back(&header, 0); /*filter method*/ + ucvector_push_back(&header, interlace_method); /*interlace method*/ + + error = addChunk(out, "IHDR", header.data, header.size); + ucvector_cleanup(&header); + + return error; +} + +static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) +{ + unsigned error = 0; + size_t i; + ucvector PLTE; + ucvector_init(&PLTE); + for(i = 0; i != info->palettesize * 4; ++i) + { + /*add all channels except alpha channel*/ + if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); + } + error = addChunk(out, "PLTE", PLTE.data, PLTE.size); + ucvector_cleanup(&PLTE); + + return error; +} + +static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) +{ + unsigned error = 0; + size_t i; + ucvector tRNS; + ucvector_init(&tRNS); + if(info->colortype == LCT_PALETTE) + { + size_t amount = info->palettesize; + /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ + for(i = info->palettesize; i != 0; --i) + { + if(info->palette[4 * (i - 1) + 3] == 255) --amount; + else break; + } + /*add only alpha channel*/ + for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); + } + else if(info->colortype == LCT_GREY) + { + if(info->key_defined) + { + ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255)); + } + } + else if(info->colortype == LCT_RGB) + { + if(info->key_defined) + { + ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255)); + } + } + + error = addChunk(out, "tRNS", tRNS.data, tRNS.size); + ucvector_cleanup(&tRNS); + + return error; +} + +static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, + LodePNGCompressSettings* zlibsettings) +{ + ucvector zlibdata; + unsigned error = 0; + + /*compress with the Zlib compressor*/ + ucvector_init(&zlibdata); + error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); + if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); + ucvector_cleanup(&zlibdata); + + return error; +} + +static unsigned addChunk_IEND(ucvector* out) +{ + unsigned error = 0; + error = addChunk(out, "IEND", 0, 0); + return error; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) +{ + unsigned error = 0; + size_t i; + ucvector text; + ucvector_init(&text); + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&text, 0); /*0 termination char*/ + for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]); + error = addChunk(out, "tEXt", text.data, text.size); + ucvector_cleanup(&text); + + return error; +} + +static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, + LodePNGCompressSettings* zlibsettings) +{ + unsigned error = 0; + ucvector data, compressed; + size_t i, textsize = strlen(textstring); + + ucvector_init(&data); + ucvector_init(&compressed); + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&data, 0); /*0 termination char*/ + ucvector_push_back(&data, 0); /*compression method: 0*/ + + error = zlib_compress(&compressed.data, &compressed.size, + (unsigned char*)textstring, textsize, zlibsettings); + if(!error) + { + for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); + error = addChunk(out, "zTXt", data.data, data.size); + } + + ucvector_cleanup(&compressed); + ucvector_cleanup(&data); + return error; +} + +static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, + const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) +{ + unsigned error = 0; + ucvector data; + size_t i, textsize = strlen(textstring); + + ucvector_init(&data); + + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&data, 0); /*null termination char*/ + ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ + ucvector_push_back(&data, 0); /*compression method*/ + for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]); + ucvector_push_back(&data, 0); /*null termination char*/ + for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]); + ucvector_push_back(&data, 0); /*null termination char*/ + + if(compressed) + { + ucvector compressed_data; + ucvector_init(&compressed_data); + error = zlib_compress(&compressed_data.data, &compressed_data.size, + (unsigned char*)textstring, textsize, zlibsettings); + if(!error) + { + for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); + } + ucvector_cleanup(&compressed_data); + } + else /*not compressed*/ + { + for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]); + } + + if(!error) error = addChunk(out, "iTXt", data.data, data.size); + ucvector_cleanup(&data); + return error; +} + +static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) +{ + unsigned error = 0; + ucvector bKGD; + ucvector_init(&bKGD); + if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) + { + ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); + } + else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) + { + ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_g >> 8)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_g & 255)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_b >> 8)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_b & 255)); + } + else if(info->color.colortype == LCT_PALETTE) + { + ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/ + } + + error = addChunk(out, "bKGD", bKGD.data, bKGD.size); + ucvector_cleanup(&bKGD); + + return error; +} + +static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) +{ + unsigned error = 0; + unsigned char* data = (unsigned char*)lodepng_malloc(7); + if(!data) return 83; /*alloc fail*/ + data[0] = (unsigned char)(time->year >> 8); + data[1] = (unsigned char)(time->year & 255); + data[2] = (unsigned char)time->month; + data[3] = (unsigned char)time->day; + data[4] = (unsigned char)time->hour; + data[5] = (unsigned char)time->minute; + data[6] = (unsigned char)time->second; + error = addChunk(out, "tIME", data, 7); + lodepng_free(data); + return error; +} + +static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) +{ + unsigned error = 0; + ucvector data; + ucvector_init(&data); + + lodepng_add32bitInt(&data, info->phys_x); + lodepng_add32bitInt(&data, info->phys_y); + ucvector_push_back(&data, info->phys_unit); + + error = addChunk(out, "pHYs", data.data, data.size); + ucvector_cleanup(&data); + + return error; +} + +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, + size_t length, size_t bytewidth, unsigned char filterType) +{ + size_t i; + switch(filterType) + { + case 0: /*None*/ + for(i = 0; i != length; ++i) out[i] = scanline[i]; + break; + case 1: /*Sub*/ + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; + break; + case 2: /*Up*/ + if(prevline) + { + for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; + } + else + { + for(i = 0; i != length; ++i) out[i] = scanline[i]; + } + break; + case 3: /*Average*/ + if(prevline) + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); + } + else + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); + } + break; + case 4: /*Paeth*/ + if(prevline) + { + /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ + for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); + for(i = bytewidth; i < length; ++i) + { + out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); + } + } + else + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ + for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); + } + break; + default: return; /*unexisting filter type given*/ + } +} + +/* log2 approximation. A slight bit faster than std::log. */ +static float flog2(float f) +{ + float result = 0; + while(f > 32) { result += 4; f /= 16; } + while(f > 2) { ++result; f /= 2; } + return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); +} + +static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) +{ + /* + For PNG filter method 0 + out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are + the scanlines with 1 extra byte per scanline + */ + + unsigned bpp = lodepng_get_bpp(info); + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = (w * bpp + 7) / 8; + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7) / 8; + const unsigned char* prevline = 0; + unsigned x, y; + unsigned error = 0; + LodePNGFilterStrategy strategy = settings->filter_strategy; + + /* + There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: + * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. + use fixed filtering, with the filter None). + * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is + not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply + all five filters and select the filter that produces the smallest sum of absolute values per row. + This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. + + If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, + but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum + heuristic is used. + */ + if(settings->filter_palette_zero && + (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; + + if(bpp == 0) return 31; /*error: invalid color type*/ + + if(strategy == LFS_ZERO) + { + for(y = 0; y != h; ++y) + { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + out[outindex] = 0; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); + prevline = &in[inindex]; + } + } + else if(strategy == LFS_MINSUM) + { + /*adaptive filtering*/ + size_t sum[5]; + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned char type, bestType = 0; + + for(type = 0; type != 5; ++type) + { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) return 83; /*alloc fail*/ + } + + if(!error) + { + for(y = 0; y != h; ++y) + { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) + { + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + + /*calculate the sum of the result*/ + sum[type] = 0; + if(type == 0) + { + for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]); + } + else + { + for(x = 0; x != linebytes; ++x) + { + /*For differences, each byte should be treated as signed, values above 127 are negative + (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. + This means filtertype 0 is almost never chosen, but that is justified.*/ + unsigned char s = attempt[type][x]; + sum[type] += s < 128 ? s : (255U - s); + } + } + + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum[type] < smallest) + { + bestType = type; + smallest = sum[type]; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else if(strategy == LFS_ENTROPY) + { + float sum[5]; + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + float smallest = 0; + unsigned type, bestType = 0; + unsigned count[256]; + + for(type = 0; type != 5; ++type) + { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) return 83; /*alloc fail*/ + } + + for(y = 0; y != h; ++y) + { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) + { + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + for(x = 0; x != 256; ++x) count[x] = 0; + for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; + ++count[type]; /*the filter type itself is part of the scanline*/ + sum[type] = 0; + for(x = 0; x != 256; ++x) + { + float p = count[x] / (float)(linebytes + 1); + sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; + } + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum[type] < smallest) + { + bestType = type; + smallest = sum[type]; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else if(strategy == LFS_PREDEFINED) + { + for(y = 0; y != h; ++y) + { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + unsigned char type = settings->predefined_filters[y]; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } + else if(strategy == LFS_BRUTE_FORCE) + { + /*brute force filter chooser. + deflate the scanline after every filter attempt to see which one deflates best. + This is very slow and gives only slightly smaller, sometimes even larger, result*/ + size_t size[5]; + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned type = 0, bestType = 0; + unsigned char* dummy; + LodePNGCompressSettings zlibsettings = settings->zlibsettings; + /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, + to simulate the true case where the tree is the same for the whole image. Sometimes it gives + better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare + cases better compression. It does make this a bit less slow, so it's worth doing this.*/ + zlibsettings.btype = 1; + /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG + images only, so disable it*/ + zlibsettings.custom_zlib = 0; + zlibsettings.custom_deflate = 0; + for(type = 0; type != 5; ++type) + { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) return 83; /*alloc fail*/ + } + for(y = 0; y != h; ++y) /*try the 5 filter types*/ + { + for(type = 0; type != 5; ++type) + { + unsigned testsize = linebytes; + /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ + + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + size[type] = 0; + dummy = 0; + zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); + lodepng_free(dummy); + /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || size[type] < smallest) + { + bestType = type; + smallest = size[type]; + } + } + prevline = &in[y * linebytes]; + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else return 88; /* unknown filter strategy */ + + return error; +} + +static void addPaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) +{ + /*The opposite of the removePaddingBits function + olinebits must be >= ilinebits*/ + unsigned y; + size_t diff = olinebits - ilinebits; + size_t obp = 0, ibp = 0; /*bit pointers*/ + for(y = 0; y != h; ++y) + { + size_t x; + for(x = 0; x < ilinebits; ++x) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + /*obp += diff; --> no, fill in some value in the padding bits too, to avoid + "Use of uninitialised value of size ###" warning from valgrind*/ + for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); + } +} + +/* +in: non-interlaced image with size w*h +out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with + no padding bits between scanlines, but between reduced images so that each + reduced image starts at a byte. +bpp: bits per pixel +there are no padding bits, not between scanlines, not between reduced images +in has the following size in bits: w * h * bpp. +out is possibly bigger due to padding bits between reduced images +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) +{ + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + size_t bytewidth = bpp / 8; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; + for(b = 0; b < bytewidth; ++b) + { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } + else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + for(b = 0; b < bpp; ++b) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } +} + +/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. +return value is error**/ +static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) +{ + /* + This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: + *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter + *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + unsigned error = 0; + + if(info_png->interlace_method == 0) + { + *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ + + if(!error) + { + /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) + { + unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8)); + if(!padded) error = 83; /*alloc fail*/ + if(!error) + { + addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); + error = filter(*out, padded, w, h, &info_png->color, settings); + } + lodepng_free(padded); + } + else + { + /*we can immediately filter into the out buffer, no other steps needed*/ + error = filter(*out, in, w, h, &info_png->color, settings); + } + } + } + else /*interlace_method is 1 (Adam7)*/ + { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned char* adam7; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out)) error = 83; /*alloc fail*/ + + adam7 = (unsigned char*)lodepng_malloc(passstart[7]); + if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ + + if(!error) + { + unsigned i; + + Adam7_interlace(adam7, in, w, h, bpp); + for(i = 0; i != 7; ++i) + { + if(bpp < 8) + { + unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); + if(!padded) ERROR_BREAK(83); /*alloc fail*/ + addPaddingBits(padded, &adam7[passstart[i]], + ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); + error = filter(&(*out)[filter_passstart[i]], padded, + passw[i], passh[i], &info_png->color, settings); + lodepng_free(padded); + } + else + { + error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], + passw[i], passh[i], &info_png->color, settings); + } + + if(error) break; + } + } + + lodepng_free(adam7); + } + + return error; +} + +/* +palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA... +returns 0 if the palette is opaque, +returns 1 if the palette has a single color with alpha 0 ==> color key +returns 2 if the palette is semi-translucent. +*/ +static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) +{ + size_t i; + unsigned key = 0; + unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ + for(i = 0; i != palettesize; ++i) + { + if(!key && palette[4 * i + 3] == 0) + { + r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; + key = 1; + i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ + } + else if(palette[4 * i + 3] != 255) return 2; + /*when key, no opaque RGB may have key's RGB*/ + else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; + } + return key; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) +{ + unsigned char* inchunk = data; + while((size_t)(inchunk - data) < datasize) + { + CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); + out->allocsize = out->size; /*fix the allocsize again*/ + inchunk = lodepng_chunk_next(inchunk); + } + return 0; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state) +{ + LodePNGInfo info; + ucvector outv; + unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ + size_t datasize = 0; + + /*provide some proper output values if error will happen*/ + *out = 0; + *outsize = 0; + state->error = 0; + + lodepng_info_init(&info); + lodepng_info_copy(&info, &state->info_png); + + if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette) + && (info.color.palettesize == 0 || info.color.palettesize > 256)) + { + state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ + return state->error; + } + + if(state->encoder.auto_convert) + { + state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); + } + if(state->error) return state->error; + + if(state->encoder.zlibsettings.btype > 2) + { + CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/ + } + if(state->info_png.interlace_method > 1) + { + CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/ + } + + state->error = checkColorValidity(info.color.colortype, info.color.bitdepth); + if(state->error) return state->error; /*error: unexisting color type given*/ + state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); + if(state->error) return state->error; /*error: unexisting color type given*/ + + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) + { + unsigned char* converted; + size_t size = (w * h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; + + converted = (unsigned char*)lodepng_malloc(size); + if(!converted && size) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + } + if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); + lodepng_free(converted); + } + else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); + + ucvector_init(&outv); + while(!state->error) /*while only executed once, to break on error*/ + { +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + size_t i; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*write signature and chunks*/ + writeSignature(&outv); + /*IHDR*/ + addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*unknown chunks between IHDR and PLTE*/ + if(info.unknown_chunks_data[0]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*PLTE*/ + if(info.color.colortype == LCT_PALETTE) + { + addChunk_PLTE(&outv, &info.color); + } + if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) + { + addChunk_PLTE(&outv, &info.color); + } + /*tRNS*/ + if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) + { + addChunk_tRNS(&outv, &info.color); + } + if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) + { + addChunk_tRNS(&outv, &info.color); + } +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*bKGD (must come between PLTE and the IDAt chunks*/ + if(info.background_defined) addChunk_bKGD(&outv, &info); + /*pHYs (must come before the IDAT chunks)*/ + if(info.phys_defined) addChunk_pHYs(&outv, &info); + + /*unknown chunks between PLTE and IDAT*/ + if(info.unknown_chunks_data[1]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*IDAT (multiple IDAT chunks must be consecutive)*/ + state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*tIME*/ + if(info.time_defined) addChunk_tIME(&outv, &info.time); + /*tEXt and/or zTXt*/ + for(i = 0; i != info.text_num; ++i) + { + if(strlen(info.text_keys[i]) > 79) + { + state->error = 66; /*text chunk too large*/ + break; + } + if(strlen(info.text_keys[i]) < 1) + { + state->error = 67; /*text chunk too small*/ + break; + } + if(state->encoder.text_compression) + { + addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); + } + else + { + addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); + } + } + /*LodePNG version id in text chunk*/ + if(state->encoder.add_id) + { + unsigned alread_added_id_text = 0; + for(i = 0; i != info.text_num; ++i) + { + if(!strcmp(info.text_keys[i], "LodePNG")) + { + alread_added_id_text = 1; + break; + } + } + if(alread_added_id_text == 0) + { + addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ + } + } + /*iTXt*/ + for(i = 0; i != info.itext_num; ++i) + { + if(strlen(info.itext_keys[i]) > 79) + { + state->error = 66; /*text chunk too large*/ + break; + } + if(strlen(info.itext_keys[i]) < 1) + { + state->error = 67; /*text chunk too small*/ + break; + } + addChunk_iTXt(&outv, state->encoder.text_compression, + info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], + &state->encoder.zlibsettings); + } + + /*unknown chunks between IDAT and IEND*/ + if(info.unknown_chunks_data[2]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + addChunk_IEND(&outv); + + break; /*this isn't really a while loop; no error happened so break out now!*/ + } + + lodepng_info_cleanup(&info); + lodepng_free(data); + /*instead of cleaning the vector up, give it to the output*/ + *out = outv.data; + *outsize = outv.size; + + return state->error; +} + +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, + unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + state.info_png.color.colortype = colortype; + state.info_png.color.bitdepth = bitdepth; + lodepng_encode(out, outsize, image, w, h, &state); + error = state.error; + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); + if(!error) error = lodepng_save_file(buffer, buffersize, filename); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) +{ + lodepng_compress_settings_init(&settings->zlibsettings); + settings->filter_palette_zero = 1; + settings->filter_strategy = LFS_MINSUM; + settings->auto_convert = 1; + settings->force_palette = 0; + settings->predefined_filters = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->add_id = 0; + settings->text_compression = 1; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/* +This returns the description of a numerical error code in English. This is also +the documentation of all the error codes. +*/ +const char* lodepng_error_text(unsigned code) +{ + switch(code) + { + case 0: return "no error, everything went ok"; + case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ + case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ + case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ + case 13: return "problem while processing dynamic deflate block"; + case 14: return "problem while processing dynamic deflate block"; + case 15: return "problem while processing dynamic deflate block"; + case 16: return "unexisting code while processing dynamic deflate block"; + case 17: return "end of out buffer memory reached while inflating"; + case 18: return "invalid distance code while inflating"; + case 19: return "end of out buffer memory reached while inflating"; + case 20: return "invalid deflate block BTYPE encountered while decoding"; + case 21: return "NLEN is not ones complement of LEN in a deflate block"; + /*end of out buffer memory reached while inflating: + This can happen if the inflated deflate data is longer than the amount of bytes required to fill up + all the pixels of the image, given the color depth and image dimensions. Something that doesn't + happen in a normal, well encoded, PNG image.*/ + case 22: return "end of out buffer memory reached while inflating"; + case 23: return "end of in buffer memory reached while inflating"; + case 24: return "invalid FCHECK in zlib header"; + case 25: return "invalid compression method in zlib header"; + case 26: return "FDICT encountered in zlib header while it's not used for PNG"; + case 27: return "PNG file is smaller than a PNG header"; + /*Checks the magic file header, the first 8 bytes of the PNG file*/ + case 28: return "incorrect PNG signature, it's no PNG or corrupted"; + case 29: return "first chunk is not the header chunk"; + case 30: return "chunk length too large, chunk broken off at end of file"; + case 31: return "illegal PNG color type or bpp"; + case 32: return "illegal PNG compression method"; + case 33: return "illegal PNG filter method"; + case 34: return "illegal PNG interlace method"; + case 35: return "chunk length of a chunk is too large or the chunk too small"; + case 36: return "illegal PNG filter type encountered"; + case 37: return "illegal bit depth for this color type given"; + case 38: return "the palette is too big"; /*more than 256 colors*/ + case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette"; + case 40: return "tRNS chunk has wrong size for greyscale image"; + case 41: return "tRNS chunk has wrong size for RGB image"; + case 42: return "tRNS chunk appeared while it was not allowed for this color type"; + case 43: return "bKGD chunk has wrong size for palette image"; + case 44: return "bKGD chunk has wrong size for greyscale image"; + case 45: return "bKGD chunk has wrong size for RGB image"; + case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?"; + case 49: return "jumped past memory while generating dynamic huffman tree"; + case 50: return "jumped past memory while generating dynamic huffman tree"; + case 51: return "jumped past memory while inflating huffman block"; + case 52: return "jumped past memory while inflating"; + case 53: return "size of zlib data too small"; + case 54: return "repeat symbol in tree while there was no value symbol yet"; + /*jumped past tree while generating huffman tree, this could be when the + tree will have more leaves than symbols after generating it out of the + given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ + case 55: return "jumped past tree while generating huffman tree"; + case 56: return "given output image colortype or bitdepth not supported for color conversion"; + case 57: return "invalid CRC encountered (checking CRC can be disabled)"; + case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; + case 59: return "requested color conversion not supported"; + case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; + case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; + /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ + case 62: return "conversion from color to greyscale not supported"; + case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ + /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ + case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; + case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; + case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; + case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; + case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; + case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)"; + case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; + case 73: return "invalid tIME chunk size"; + case 74: return "invalid pHYs chunk size"; + /*length could be wrong, or data chopped off*/ + case 75: return "no null termination char found while decoding text chunk"; + case 76: return "iTXt chunk too short to contain required bytes"; + case 77: return "integer overflow in buffer size"; + case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ + case 79: return "failed to open file for writing"; + case 80: return "tried creating a tree of 0 symbols"; + case 81: return "lazy matching at pos 0 is impossible"; + case 82: return "color conversion to palette requested while a color isn't in palette"; + case 83: return "memory allocation failed"; + case 84: return "given image too small to contain all pixels to be encoded"; + case 86: return "impossible offset in lz77 encoding (internal bug)"; + case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; + case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; + case 89: return "text chunk keyword too short or long: must have size 1-79"; + /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ + case 90: return "windowsize must be a power of two"; + case 91: return "invalid decompressed idat size"; + case 92: return "too many pixels, not supported"; + case 93: return "zero width or height is invalid"; + case 94: return "header chunk must have a size of 13 bytes"; + } + return "unknown error code"; +} +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // C++ Wrapper // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng +{ + +#ifdef LODEPNG_COMPILE_DISK +unsigned load_file(std::vector& buffer, const std::string& filename) +{ + long size = lodepng_filesize(filename.c_str()); + if(size < 0) return 78; + buffer.resize((size_t)size); + return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str()); +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned save_file(const std::vector& buffer, const std::string& filename) +{ + return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); +} +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings) +{ + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings) +{ + return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings) +{ + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings) +{ + return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_ZLIB */ + + +#ifdef LODEPNG_COMPILE_PNG + +State::State() +{ + lodepng_state_init(this); +} + +State::State(const State& other) +{ + lodepng_state_init(this); + lodepng_state_copy(this, &other); +} + +State::~State() +{ + lodepng_state_cleanup(this); +} + +State& State::operator=(const State& other) +{ + lodepng_state_copy(this, &other); + return *this; +} + +#ifdef LODEPNG_COMPILE_DECODER + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); + if(buffer && !error) + { + State state; + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) +{ + return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize) +{ + unsigned char* buffer = NULL; + unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); + if(buffer && !error) + { + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + } + lodepng_free(buffer); + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in) +{ + return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, + LodePNGColorType colortype, unsigned bitdepth) +{ + std::vector buffer; + unsigned error = load_file(buffer, filename); + if(error) return error; + return decode(out, w, h, buffer, colortype, bitdepth); +} +#endif /* LODEPNG_COMPILE_DECODER */ +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} + +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state) +{ + if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, state); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + std::vector buffer; + unsigned error = encode(buffer, in, w, h, colortype, bitdepth); + if(!error) error = save_file(buffer, filename); + return error; +} + +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_PNG */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ diff --git a/src/ext/lodepng/lodepng.h b/src/ext/lodepng/lodepng.h new file mode 100644 index 00000000..94e81955 --- /dev/null +++ b/src/ext/lodepng/lodepng.h @@ -0,0 +1,1759 @@ +/* +LodePNG version 20160501 + +Copyright (c) 2005-2016 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef LODEPNG_H +#define LODEPNG_H + +#include /*for size_t*/ + +extern const char* LODEPNG_VERSION_STRING; + +/* +The following #defines are used to create code sections. They can be disabled +to disable code sections, which can give faster compile time and smaller binary. +The "NO_COMPILE" defines are designed to be used to pass as defines to the +compiler command to disable them without modifying this header, e.g. +-DLODEPNG_NO_COMPILE_ZLIB for gcc. +In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to +allow implementing a custom lodepng_crc32. +*/ +/*deflate & zlib. If disabled, you must specify alternative zlib functions in +the custom_zlib field of the compress and decompress settings*/ +#ifndef LODEPNG_NO_COMPILE_ZLIB +#define LODEPNG_COMPILE_ZLIB +#endif +/*png encoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_PNG +#define LODEPNG_COMPILE_PNG +#endif +/*deflate&zlib decoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_DECODER +#define LODEPNG_COMPILE_DECODER +#endif +/*deflate&zlib encoder and png encoder*/ +#ifndef LODEPNG_NO_COMPILE_ENCODER +#define LODEPNG_COMPILE_ENCODER +#endif +/*the optional built in harddisk file loading and saving functions*/ +#ifndef LODEPNG_NO_COMPILE_DISK +#define LODEPNG_COMPILE_DISK +#endif +/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ +#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS +#define LODEPNG_COMPILE_ANCILLARY_CHUNKS +#endif +/*ability to convert error numerical codes to English text string*/ +#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT +#define LODEPNG_COMPILE_ERROR_TEXT +#endif +/*Compile the default allocators (C's free, malloc and realloc). If you disable this, +you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your +source files with custom allocators.*/ +#ifndef LODEPNG_NO_COMPILE_ALLOCATORS +#define LODEPNG_COMPILE_ALLOCATORS +#endif +/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ +#ifdef __cplusplus +#ifndef LODEPNG_NO_COMPILE_CPP +#define LODEPNG_COMPILE_CPP +#endif +#endif + +#ifdef LODEPNG_COMPILE_CPP +#include +#include +#endif /*LODEPNG_COMPILE_CPP*/ + +#ifdef LODEPNG_COMPILE_PNG +/*The PNG color types (also used for raw).*/ +typedef enum LodePNGColorType +{ + LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ + LCT_RGB = 2, /*RGB: 8,16 bit*/ + LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ + LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ + LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ +} LodePNGColorType; + +#ifdef LODEPNG_COMPILE_DECODER +/* +Converts PNG data in memory to raw pixel data. +out: Output parameter. Pointer to buffer that will contain the raw pixel data. + After decoding, its size is w * h * (bytes per pixel) bytes larger than + initially. Bytes per pixel depends on colortype and bitdepth. + Must be freed after usage with free(*out). + Note: for 16-bit per channel colors, uses big endian format like PNG does. +w: Output parameter. Pointer to width of pixel data. +h: Output parameter. Pointer to height of pixel data. +in: Memory buffer with the PNG file. +insize: size of the in buffer. +colortype: the desired color type for the raw output image. See explanation on PNG color types. +bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +#ifdef LODEPNG_COMPILE_DISK +/* +Load PNG from disk, from file with given name. +Same as the other decode functions, but instead takes a filename as input. +*/ +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); + +/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_DECODER*/ + + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Converts raw pixel data into a PNG image in memory. The colortype and bitdepth + of the output PNG image cannot be chosen, they are automatically determined + by the colortype, bitdepth and content of the input pixel data. + Note: for 16-bit per channel colors, needs big endian format like PNG does. +out: Output parameter. Pointer to buffer that will contain the PNG image data. + Must be freed after usage with free(*out). +outsize: Output parameter. Pointer to the size in bytes of the out buffer. +image: The raw pixel data to encode. The size of this buffer should be + w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. +w: width of the raw pixel data in pixels. +h: height of the raw pixel data in pixels. +colortype: the color type of the raw input image. See explanation on PNG color types. +bitdepth: the bit depth of the raw input image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DISK +/* +Converts raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. +NOTE: This overwrites existing files without warning! +*/ +unsigned lodepng_encode_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng +{ +#ifdef LODEPNG_COMPILE_DECODER +/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype +is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts PNG file from disk to raw pixel data in memory. +Same as the other decode functions, but instead takes a filename as input. +*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::string& filename, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype +is that of the raw input data. The output PNG color type will be auto chosen.*/ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts 32-bit RGBA raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. +NOTE: This overwrites existing files without warning! +*/ +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_ENCODER */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/*Returns an English description of the numerical error code.*/ +const char* lodepng_error_text(unsigned code); +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Settings for zlib decompression*/ +typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; +struct LodePNGDecompressSettings +{ + unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ + + /*use custom zlib decoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + /*use custom deflate decoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned (*custom_inflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGDecompressSettings lodepng_default_decompress_settings; +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Settings for zlib compression. Tweaking these settings tweaks the balance +between speed and compression ratio. +*/ +typedef struct LodePNGCompressSettings LodePNGCompressSettings; +struct LodePNGCompressSettings /*deflate = compress*/ +{ + /*LZ77 related settings*/ + unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ + unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ + unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ + unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ + unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ + unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ + + /*use custom zlib encoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + /*use custom deflate encoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned (*custom_deflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGCompressSettings lodepng_default_compress_settings; +void lodepng_compress_settings_init(LodePNGCompressSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_PNG +/* +Color mode of an image. Contains all information required to decode the pixel +bits to RGBA colors. This information is the same as used in the PNG file +format, and is used both for PNG and raw image data in LodePNG. +*/ +typedef struct LodePNGColorMode +{ + /*header (IHDR)*/ + LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ + unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ + + /* + palette (PLTE and tRNS) + + Dynamically allocated with the colors of the palette, including alpha. + When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use + lodepng_palette_clear, then for each color use lodepng_palette_add. + If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. + + When decoding, by default you can ignore this palette, since LodePNG already + fills the palette colors in the pixels of the raw RGBA output. + + The palette is only supported for color type 3. + */ + unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ + size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ + + /* + transparent color key (tRNS) + + This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. + For greyscale PNGs, r, g and b will all 3 be set to the same. + + When decoding, by default you can ignore this information, since LodePNG sets + pixels with this key to transparent already in the raw RGBA output. + + The color key is only supported for color types 0 and 2. + */ + unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ + unsigned key_r; /*red/greyscale component of color key*/ + unsigned key_g; /*green component of color key*/ + unsigned key_b; /*blue component of color key*/ +} LodePNGColorMode; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_color_mode_init(LodePNGColorMode* info); +void lodepng_color_mode_cleanup(LodePNGColorMode* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); + +void lodepng_palette_clear(LodePNGColorMode* info); +/*add 1 color to the palette*/ +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a); + +/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ +unsigned lodepng_get_bpp(const LodePNGColorMode* info); +/*get the amount of color channels used, based on colortype in the struct. +If a palette is used, it counts as 1 channel.*/ +unsigned lodepng_get_channels(const LodePNGColorMode* info); +/*is it a greyscale type? (only colortype 0 or 4)*/ +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); +/*has it got an alpha channel? (only colortype 2 or 6)*/ +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); +/*has it got a palette? (only colortype 3)*/ +unsigned lodepng_is_palette_type(const LodePNGColorMode* info); +/*only returns true if there is a palette and there is a value in the palette with alpha < 255. +Loops through the palette to check this.*/ +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); +/* +Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. +Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). +Returns false if the image can only have opaque pixels. +In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, +or if "key_defined" is true. +*/ +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); +/*Returns the byte size of a raw image buffer with given width, height and color mode*/ +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*The information of a Time chunk in PNG.*/ +typedef struct LodePNGTime +{ + unsigned year; /*2 bytes used (0-65535)*/ + unsigned month; /*1-12*/ + unsigned day; /*1-31*/ + unsigned hour; /*0-23*/ + unsigned minute; /*0-59*/ + unsigned second; /*0-60 (to allow for leap seconds)*/ +} LodePNGTime; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*Information about the PNG image, except pixels, width and height.*/ +typedef struct LodePNGInfo +{ + /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ + unsigned compression_method;/*compression method of the original file. Always 0.*/ + unsigned filter_method; /*filter method of the original file*/ + unsigned interlace_method; /*interlace method of the original file*/ + LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /* + suggested background color chunk (bKGD) + This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit. + + For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding + the encoder writes the red one. For palette PNGs: When decoding, the RGB value + will be stored, not a palette index. But when encoding, specify the index of + the palette in background_r, the other two are then ignored. + + The decoder does not use this background color to edit the color of pixels. + */ + unsigned background_defined; /*is a suggested background color given?*/ + unsigned background_r; /*red component of suggested background color*/ + unsigned background_g; /*green component of suggested background color*/ + unsigned background_b; /*blue component of suggested background color*/ + + /* + non-international text chunks (tEXt and zTXt) + + The char** arrays each contain num strings. The actual messages are in + text_strings, while text_keys are keywords that give a short description what + the actual text represents, e.g. Title, Author, Description, or anything else. + + A keyword is minimum 1 character and maximum 79 characters long. It's + discouraged to use a single line length longer than 79 characters for texts. + + Don't allocate these text buffers yourself. Use the init/cleanup functions + correctly and use lodepng_add_text and lodepng_clear_text. + */ + size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ + char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ + char** text_strings; /*the actual text*/ + + /* + international text chunks (iTXt) + Similar to the non-international text chunks, but with additional strings + "langtags" and "transkeys". + */ + size_t itext_num; /*the amount of international texts in this PNG*/ + char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ + char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ + char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ + char** itext_strings; /*the actual international text - UTF-8 string*/ + + /*time chunk (tIME)*/ + unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ + LodePNGTime time; + + /*phys chunk (pHYs)*/ + unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ + unsigned phys_x; /*pixels per unit in x direction*/ + unsigned phys_y; /*pixels per unit in y direction*/ + unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ + + /* + unknown chunks + There are 3 buffers, one for each position in the PNG where unknown chunks can appear + each buffer contains all unknown chunks for that position consecutively + The 3 buffers are the unknown chunks between certain critical chunks: + 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND + Do not allocate or traverse this data yourself. Use the chunk traversing functions declared + later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. + */ + unsigned char* unknown_chunks_data[3]; + size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGInfo; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_info_init(LodePNGInfo* info); +void lodepng_info_cleanup(LodePNGInfo* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ + +void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/* +Converts raw buffer from one color type to another color type, based on +LodePNGColorMode structs to describe the input and output color type. +See the reference manual at the end of this header file to see which color conversions are supported. +return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) +The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel +of the output color type (lodepng_get_bpp). +For < 8 bpp images, there should not be padding bits at the end of scanlines. +For 16-bit per channel colors, uses big endian format like PNG does. +Return value is LodePNG error code +*/ +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DECODER +/* +Settings for the decoder. This contains settings for the PNG and the Zlib +decoder, but not the Info settings from the Info structs. +*/ +typedef struct LodePNGDecoderSettings +{ + LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ + + unsigned ignore_crc; /*ignore CRC checksums*/ + + unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ + /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ + unsigned remember_unknown_chunks; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGDecoderSettings; + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ +typedef enum LodePNGFilterStrategy +{ + /*every filter at zero*/ + LFS_ZERO, + /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ + LFS_MINSUM, + /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending + on the image, this is better or worse than minsum.*/ + LFS_ENTROPY, + /* + Brute-force-search PNG filters by compressing each filter for each scanline. + Experimental, very slow, and only rarely gives better compression than MINSUM. + */ + LFS_BRUTE_FORCE, + /*use predefined_filters buffer: you specify the filter type for each scanline*/ + LFS_PREDEFINED +} LodePNGFilterStrategy; + +/*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding. +Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ +typedef struct LodePNGColorProfile +{ + unsigned colored; /*not greyscale*/ + unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/ + unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/ + unsigned short key_g; + unsigned short key_b; + unsigned alpha; /*alpha channel or alpha palette required*/ + unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ + unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ + unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ +} LodePNGColorProfile; + +void lodepng_color_profile_init(LodePNGColorProfile* profile); + +/*Get a LodePNGColorProfile of the image.*/ +unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in); +/*The function LodePNG uses internally to decide the PNG color with auto_convert. +Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/ +unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in); + +/*Settings for the encoder.*/ +typedef struct LodePNGEncoderSettings +{ + LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ + + unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ + + /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than + 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to + completely follow the official PNG heuristic, filter_palette_zero must be true and + filter_strategy must be LFS_MINSUM*/ + unsigned filter_palette_zero; + /*Which filter strategy to use when not using zeroes due to filter_palette_zero. + Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ + LodePNGFilterStrategy filter_strategy; + /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with + the same length as the amount of scanlines in the image, and each value must <= 5. You + have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero + must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ + const unsigned char* predefined_filters; + + /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). + If colortype is 3, PLTE is _always_ created.*/ + unsigned force_palette; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*add LodePNG identifier and version as a text chunk, for debugging*/ + unsigned add_id; + /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ + unsigned text_compression; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGEncoderSettings; + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) +/*The settings, state and information for extended encoding and decoding.*/ +typedef struct LodePNGState +{ +#ifdef LODEPNG_COMPILE_DECODER + LodePNGDecoderSettings decoder; /*the decoding settings*/ +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + LodePNGEncoderSettings encoder; /*the encoding settings*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ + LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ + unsigned error; +#ifdef LODEPNG_COMPILE_CPP + /* For the lodepng::State subclass. */ + virtual ~LodePNGState(){} +#endif +} LodePNGState; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_state_init(LodePNGState* state); +void lodepng_state_cleanup(LodePNGState* state); +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_DECODER +/* +Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and +getting much more information about the PNG image and color mode. +*/ +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); + +/* +Read the PNG header, but not the actual data. This returns only the information +that is in the header chunk of the PNG, such as width, height and color type. The +information is placed in the info_png field of the LodePNGState. +*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); +#endif /*LODEPNG_COMPILE_DECODER*/ + + +#ifdef LODEPNG_COMPILE_ENCODER +/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/* +The lodepng_chunk functions are normally not needed, except to traverse the +unknown chunks stored in the LodePNGInfo struct, or add new ones to it. +It also allows traversing the chunks of an encoded PNG file yourself. + +PNG standard chunk naming conventions: +First byte: uppercase = critical, lowercase = ancillary +Second byte: uppercase = public, lowercase = private +Third byte: must be uppercase +Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy +*/ + +/* +Gets the length of the data of the chunk. Total chunk length has 12 bytes more. +There must be at least 4 bytes to read from. If the result value is too large, +it may be corrupt data. +*/ +unsigned lodepng_chunk_length(const unsigned char* chunk); + +/*puts the 4-byte type in null terminated string*/ +void lodepng_chunk_type(char type[5], const unsigned char* chunk); + +/*check if the type is the given type*/ +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); + +/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); + +/*0: public, 1: private (see PNG standard)*/ +unsigned char lodepng_chunk_private(const unsigned char* chunk); + +/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); + +/*get pointer to the data of the chunk, where the input points to the header of the chunk*/ +unsigned char* lodepng_chunk_data(unsigned char* chunk); +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); + +/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ +unsigned lodepng_chunk_check_crc(const unsigned char* chunk); + +/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ +void lodepng_chunk_generate_crc(unsigned char* chunk); + +/*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/ +unsigned char* lodepng_chunk_next(unsigned char* chunk); +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk); + +/* +Appends chunk to the data in out. The given chunk should already have its chunk header. +The out variable and outlength are updated to reflect the new reallocated buffer. +Returns error code (0 if it went ok) +*/ +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk); + +/* +Appends new chunk to out. The chunk to append is given by giving its length, type +and data separately. The type is a 4-letter string. +The out variable and outlength are updated to reflect the new reallocated buffer. +Returne error code (0 if it went ok) +*/ +unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, + const char* type, const unsigned char* data); + + +/*Calculate CRC32 of buffer*/ +unsigned lodepng_crc32(const unsigned char* buf, size_t len); +#endif /*LODEPNG_COMPILE_PNG*/ + + +#ifdef LODEPNG_COMPILE_ZLIB +/* +This zlib part can be used independently to zlib compress and decompress a +buffer. It cannot be used to create gzip files however, and it only supports the +part of zlib that is required for PNG, it does not support dictionaries. +*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); + +/* +Decompresses Zlib data. Reallocates the out buffer and appends the data. The +data must be according to the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Compresses data with Zlib. Reallocates the out buffer and appends the data. +Zlib adds a small header and trailer around the deflate data. +The data is output in the format of the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +/* +Find length-limited Huffman code for given frequencies. This function is in the +public interface only for tests, it's used internally by lodepng_deflate. +*/ +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen); + +/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into buffer. The function allocates the out buffer, and +after usage you should free it. +out: output parameter, contains pointer to loaded buffer. +outsize: output parameter, size of the allocated out buffer +filename: the path to the file to load +return value: error code (0 means ok) +*/ +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); + +/* +Save a file from buffer to disk. Warning, if it exists, this function overwrites +the file without warning! +buffer: the buffer to write +buffersize: size of the buffer to write +filename: the path to the file to save to +return value: error code (0 means ok) +*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ + +#ifdef LODEPNG_COMPILE_CPP +/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ +namespace lodepng +{ +#ifdef LODEPNG_COMPILE_PNG +class State : public LodePNGState +{ + public: + State(); + State(const State& other); + virtual ~State(); + State& operator=(const State& other); +}; + +#ifdef LODEPNG_COMPILE_DECODER +/* Same as other lodepng::decode, but using a State for more settings and information. */ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* Same as other lodepng::encode, but using a State for more settings and information. */ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into an std::vector. +return value: error code (0 means ok) +*/ +unsigned load_file(std::vector& buffer, const std::string& filename); + +/* +Save the binary data in an std::vector to a file on disk. The file is overwritten +without warning. +*/ +unsigned save_file(const std::vector& buffer, const std::string& filename); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_PNG */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +/* Zlib-decompress an unsigned char buffer */ +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); + +/* Zlib-decompress an std::vector */ +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +/* Zlib-compress an unsigned char buffer */ +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); + +/* Zlib-compress an std::vector */ +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_ZLIB */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ + +/* +TODO: +[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often +[.] check compatibility with various compilers - done but needs to be redone for every newer version +[X] converting color to 16-bit per channel types +[ ] read all public PNG chunk types (but never let the color profile and gamma ones touch RGB values) +[ ] make sure encoder generates no chunks with size > (2^31)-1 +[ ] partial decoding (stream processing) +[X] let the "isFullyOpaque" function check color keys and transparent palettes too +[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" +[ ] don't stop decoding on errors like 69, 57, 58 (make warnings) +[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes +[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... +[ ] allow user to give data (void*) to custom allocator +*/ + +#endif /*LODEPNG_H inclusion guard*/ + +/* +LodePNG Documentation +--------------------- + +0. table of contents +-------------------- + + 1. about + 1.1. supported features + 1.2. features not supported + 2. C and C++ version + 3. security + 4. decoding + 5. encoding + 6. color conversions + 6.1. PNG color types + 6.2. color conversions + 6.3. padding bits + 6.4. A note about 16-bits per channel and endianness + 7. error values + 8. chunks and PNG editing + 9. compiler support + 10. examples + 10.1. decoder C++ example + 10.2. decoder C example + 11. state settings reference + 12. changes + 13. contact information + + +1. about +-------- + +PNG is a file format to store raster images losslessly with good compression, +supporting different color types and alpha channel. + +LodePNG is a PNG codec according to the Portable Network Graphics (PNG) +Specification (Second Edition) - W3C Recommendation 10 November 2003. + +The specifications used are: + +*) Portable Network Graphics (PNG) Specification (Second Edition): + http://www.w3.org/TR/2003/REC-PNG-20031110 +*) RFC 1950 ZLIB Compressed Data Format version 3.3: + http://www.gzip.org/zlib/rfc-zlib.html +*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: + http://www.gzip.org/zlib/rfc-deflate.html + +The most recent version of LodePNG can currently be found at +http://lodev.org/lodepng/ + +LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds +extra functionality. + +LodePNG exists out of two files: +-lodepng.h: the header file for both C and C++ +-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage + +If you want to start using LodePNG right away without reading this doc, get the +examples from the LodePNG website to see how to use it in code, or check the +smaller examples in chapter 13 here. + +LodePNG is simple but only supports the basic requirements. To achieve +simplicity, the following design choices were made: There are no dependencies +on any external library. There are functions to decode and encode a PNG with +a single function call, and extended versions of these functions taking a +LodePNGState struct allowing to specify or get more information. By default +the colors of the raw image are always RGB or RGBA, no matter what color type +the PNG file uses. To read and write files, there are simple functions to +convert the files to/from buffers in memory. + +This all makes LodePNG suitable for loading textures in games, demos and small +programs, ... It's less suitable for full fledged image editors, loading PNGs +over network (it requires all the image data to be available before decoding can +begin), life-critical systems, ... + +1.1. supported features +----------------------- + +The following features are supported by the decoder: + +*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, + or the same color type as the PNG +*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image +*) Adam7 interlace and deinterlace for any color type +*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk +*) support for alpha channels, including RGBA color model, translucent palettes and color keying +*) zlib decompression (inflate) +*) zlib compression (deflate) +*) CRC32 and ADLER32 checksums +*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. +*) the following chunks are supported (generated/interpreted) by both encoder and decoder: + IHDR: header information + PLTE: color palette + IDAT: pixel data + IEND: the final chunk + tRNS: transparency for palettized images + tEXt: textual information + zTXt: compressed textual information + iTXt: international textual information + bKGD: suggested background color + pHYs: physical dimensions + tIME: modification time + +1.2. features not supported +--------------------------- + +The following features are _not_ supported: + +*) some features needed to make a conformant PNG-Editor might be still missing. +*) partial loading/stream processing. All data must be available and is processed in one call. +*) The following public chunks are not supported but treated as unknown chunks by LodePNG + cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT + Some of these are not supported on purpose: LodePNG wants to provide the RGB values + stored in the pixels, not values modified by system dependent gamma or color models. + + +2. C and C++ version +-------------------- + +The C version uses buffers allocated with alloc that you need to free() +yourself. You need to use init and cleanup functions for each struct whenever +using a struct from the C version to avoid exploits and memory leaks. + +The C++ version has extra functions with std::vectors in the interface and the +lodepng::State class which is a LodePNGState with constructor and destructor. + +These files work without modification for both C and C++ compilers because all +the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers +ignore it, and the C code is made to compile both with strict ISO C90 and C++. + +To use the C++ version, you need to rename the source file to lodepng.cpp +(instead of lodepng.c), and compile it with a C++ compiler. + +To use the C version, you need to rename the source file to lodepng.c (instead +of lodepng.cpp), and compile it with a C compiler. + + +3. Security +----------- + +Even if carefully designed, it's always possible that LodePNG contains possible +exploits. If you discover one, please let me know, and it will be fixed. + +When using LodePNG, care has to be taken with the C version of LodePNG, as well +as the C-style structs when working with C++. The following conventions are used +for all C-style structs: + +-if a struct has a corresponding init function, always call the init function when making a new one +-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks +-if a struct has a corresponding copy function, use the copy function instead of "=". + The destination must also be inited already. + + +4. Decoding +----------- + +Decoding converts a PNG compressed image to a raw pixel buffer. + +Most documentation on using the decoder is at its declarations in the header +above. For C, simple decoding can be done with functions such as +lodepng_decode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_decode. For C++, all decoding can be done with the +various lodepng::decode functions, and lodepng::State can be used for advanced +features. + +When using the LodePNGState, it uses the following fields for decoding: +*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here +*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get +*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use + +LodePNGInfo info_png +-------------------- + +After decoding, this contains extra information of the PNG image, except the actual +pixels, width and height because these are already gotten directly from the decoder +functions. + +It contains for example the original color type of the PNG image, text comments, +suggested background color, etc... More details about the LodePNGInfo struct are +at its declaration documentation. + +LodePNGColorMode info_raw +------------------------- + +When decoding, here you can specify which color type you want +the resulting raw image to be. If this is different from the colortype of the +PNG, then the decoder will automatically convert the result. This conversion +always works, except if you want it to convert a color PNG to greyscale or to +a palette with missing colors. + +By default, 32-bit color is used for the result. + +LodePNGDecoderSettings decoder +------------------------------ + +The settings can be used to ignore the errors created by invalid CRC and Adler32 +chunks, and to disable the decoding of tEXt chunks. + +There's also a setting color_convert, true by default. If false, no conversion +is done, the resulting data will be as it was in the PNG (after decompression) +and you'll have to puzzle the colors of the pixels together yourself using the +color type information in the LodePNGInfo. + + +5. Encoding +----------- + +Encoding converts a raw pixel buffer to a PNG compressed image. + +Most documentation on using the encoder is at its declarations in the header +above. For C, simple encoding can be done with functions such as +lodepng_encode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_encode. For C++, all encoding can be done with the +various lodepng::encode functions, and lodepng::State can be used for advanced +features. + +Like the decoder, the encoder can also give errors. However it gives less errors +since the encoder input is trusted, the decoder input (a PNG image that could +be forged by anyone) is not trusted. + +When using the LodePNGState, it uses the following fields for encoding: +*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. +*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has +*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use + +LodePNGInfo info_png +-------------------- + +When encoding, you use this the opposite way as when decoding: for encoding, +you fill in the values you want the PNG to have before encoding. By default it's +not needed to specify a color type for the PNG since it's automatically chosen, +but it's possible to choose it yourself given the right settings. + +The encoder will not always exactly match the LodePNGInfo struct you give, +it tries as close as possible. Some things are ignored by the encoder. The +encoder uses, for example, the following settings from it when applicable: +colortype and bitdepth, text chunks, time chunk, the color key, the palette, the +background color, the interlace method, unknown chunks, ... + +When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. +If the palette contains any colors for which the alpha channel is not 255 (so +there are translucent colors in the palette), it'll add a tRNS chunk. + +LodePNGColorMode info_raw +------------------------- + +You specify the color type of the raw image that you give to the input here, +including a possible transparent color key and palette you happen to be using in +your raw image data. + +By default, 32-bit color is assumed, meaning your input has to be in RGBA +format with 4 bytes (unsigned chars) per pixel. + +LodePNGEncoderSettings encoder +------------------------------ + +The following settings are supported (some are in sub-structs): +*) auto_convert: when this option is enabled, the encoder will +automatically choose the smallest possible color mode (including color key) that +can encode the colors of all pixels without information loss. +*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, + 2 = dynamic huffman tree (best compression). Should be 2 for proper + compression. +*) use_lz77: whether or not to use LZ77 for compressed block types. Should be + true for proper compression. +*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value + 2048 by default, but can be set to 32768 for better, but slow, compression. +*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE + chunk if force_palette is true. This can used as suggested palette to convert + to by viewers that don't support more than 256 colors (if those still exist) +*) add_id: add text chunk "Encoder: LodePNG " to the image. +*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. + zTXt chunks use zlib compression on the text. This gives a smaller result on + large texts but a larger result on small texts (such as a single program name). + It's all tEXt or all zTXt though, there's no separate setting per text yet. + + +6. color conversions +-------------------- + +An important thing to note about LodePNG, is that the color type of the PNG, and +the color type of the raw image, are completely independent. By default, when +you decode a PNG, you get the result as a raw image in the color type you want, +no matter whether the PNG was encoded with a palette, greyscale or RGBA color. +And if you encode an image, by default LodePNG will automatically choose the PNG +color type that gives good compression based on the values of colors and amount +of colors in the image. It can be configured to let you control it instead as +well, though. + +To be able to do this, LodePNG does conversions from one color mode to another. +It can convert from almost any color type to any other color type, except the +following conversions: RGB to greyscale is not supported, and converting to a +palette when the palette doesn't have a required color is not supported. This is +not supported on purpose: this is information loss which requires a color +reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey +is easy, but there are multiple ways if you want to give some channels more +weight). + +By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB +color, no matter what color type the PNG has. And by default when encoding, +LodePNG automatically picks the best color model for the output PNG, and expects +the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control +the color format of the images yourself, you can skip this chapter. + +6.1. PNG color types +-------------------- + +A PNG image can have many color types, ranging from 1-bit color to 64-bit color, +as well as palettized color modes. After the zlib decompression and unfiltering +in the PNG image is done, the raw pixel data will have that color type and thus +a certain amount of bits per pixel. If you want the output raw image after +decoding to have another color type, a conversion is done by LodePNG. + +The PNG specification gives the following color types: + +0: greyscale, bit depths 1, 2, 4, 8, 16 +2: RGB, bit depths 8 and 16 +3: palette, bit depths 1, 2, 4 and 8 +4: greyscale with alpha, bit depths 8 and 16 +6: RGBA, bit depths 8 and 16 + +Bit depth is the amount of bits per pixel per color channel. So the total amount +of bits per pixel is: amount of channels * bitdepth. + +6.2. color conversions +---------------------- + +As explained in the sections about the encoder and decoder, you can specify +color types and bit depths in info_png and info_raw to change the default +behaviour. + +If, when decoding, you want the raw image to be something else than the default, +you need to set the color type and bit depth you want in the LodePNGColorMode, +or the parameters colortype and bitdepth of the simple decoding function. + +If, when encoding, you use another color type than the default in the raw input +image, you need to specify its color type and bit depth in the LodePNGColorMode +of the raw image, or use the parameters colortype and bitdepth of the simple +encoding function. + +If, when encoding, you don't want LodePNG to choose the output PNG color type +but control it yourself, you need to set auto_convert in the encoder settings +to false, and specify the color type you want in the LodePNGInfo of the +encoder (including palette: it can generate a palette if auto_convert is true, +otherwise not). + +If the input and output color type differ (whether user chosen or auto chosen), +LodePNG will do a color conversion, which follows the rules below, and may +sometimes result in an error. + +To avoid some confusion: +-the decoder converts from PNG to raw image +-the encoder converts from raw image to PNG +-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image +-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG +-when encoding, the color type in LodePNGInfo is ignored if auto_convert + is enabled, it is automatically generated instead +-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original + PNG image, but it can be ignored since the raw image has the color type you requested instead +-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion + between the color types is done if the color types are supported. If it is not + supported, an error is returned. If the types are the same, no conversion is done. +-even though some conversions aren't supported, LodePNG supports loading PNGs from any + colortype and saving PNGs to any colortype, sometimes it just requires preparing + the raw image correctly before encoding. +-both encoder and decoder use the same color converter. + +Non supported color conversions: +-color to greyscale: no error is thrown, but the result will look ugly because +only the red channel is taken +-anything to palette when that palette does not have that color in it: in this +case an error is thrown + +Supported color conversions: +-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA +-any grey or grey+alpha, to grey or grey+alpha +-anything to a palette, as long as the palette has the requested colors in it +-removing alpha channel +-higher to smaller bitdepth, and vice versa + +If you want no color conversion to be done (e.g. for speed or control): +-In the encoder, you can make it save a PNG with any color type by giving the +raw color mode and LodePNGInfo the same color mode, and setting auto_convert to +false. +-In the decoder, you can make it store the pixel data in the same color type +as the PNG has, by setting the color_convert setting to false. Settings in +info_raw are then ignored. + +The function lodepng_convert does the color conversion. It is available in the +interface but normally isn't needed since the encoder and decoder already call +it. + +6.3. padding bits +----------------- + +In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines +have a bit amount that isn't a multiple of 8, then padding bits are used so that each +scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. +The raw input image you give to the encoder, and the raw output image you get from the decoder +will NOT have these padding bits, e.g. in the case of a 1-bit image with a width +of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte, +not the first bit of a new byte. + +6.4. A note about 16-bits per channel and endianness +---------------------------------------------------- + +LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like +for any other color format. The 16-bit values are stored in big endian (most +significant byte first) in these arrays. This is the opposite order of the +little endian used by x86 CPU's. + +LodePNG always uses big endian because the PNG file format does so internally. +Conversions to other formats than PNG uses internally are not supported by +LodePNG on purpose, there are myriads of formats, including endianness of 16-bit +colors, the order in which you store R, G, B and A, and so on. Supporting and +converting to/from all that is outside the scope of LodePNG. + +This may mean that, depending on your use case, you may want to convert the big +endian output of LodePNG to little endian with a for loop. This is certainly not +always needed, many applications and libraries support big endian 16-bit colors +anyway, but it means you cannot simply cast the unsigned char* buffer to an +unsigned short* buffer on x86 CPUs. + + +7. error values +--------------- + +All functions in LodePNG that return an error code, return 0 if everything went +OK, or a non-zero code if there was an error. + +The meaning of the LodePNG error values can be retrieved with the function +lodepng_error_text: given the numerical error code, it returns a description +of the error in English as a string. + +Check the implementation of lodepng_error_text to see the meaning of each code. + + +8. chunks and PNG editing +------------------------- + +If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG +editor that should follow the rules about handling of unknown chunks, or if your +program is able to read other types of chunks than the ones handled by LodePNG, +then that's possible with the chunk functions of LodePNG. + +A PNG chunk has the following layout: + +4 bytes length +4 bytes type name +length bytes data +4 bytes CRC + +8.1. iterating through chunks +----------------------------- + +If you have a buffer containing the PNG image data, then the first chunk (the +IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the +signature of the PNG and are not part of a chunk. But if you start at byte 8 +then you have a chunk, and can check the following things of it. + +NOTE: none of these functions check for memory buffer boundaries. To avoid +exploits, always make sure the buffer contains all the data of the chunks. +When using lodepng_chunk_next, make sure the returned value is within the +allocated memory. + +unsigned lodepng_chunk_length(const unsigned char* chunk): + +Get the length of the chunk's data. The total chunk length is this length + 12. + +void lodepng_chunk_type(char type[5], const unsigned char* chunk): +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): + +Get the type of the chunk or compare if it's a certain type + +unsigned char lodepng_chunk_critical(const unsigned char* chunk): +unsigned char lodepng_chunk_private(const unsigned char* chunk): +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): + +Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). +Check if the chunk is private (public chunks are part of the standard, private ones not). +Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical +chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your +program doesn't handle that type of unknown chunk. + +unsigned char* lodepng_chunk_data(unsigned char* chunk): +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): + +Get a pointer to the start of the data of the chunk. + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk): +void lodepng_chunk_generate_crc(unsigned char* chunk): + +Check if the crc is correct or generate a correct one. + +unsigned char* lodepng_chunk_next(unsigned char* chunk): +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): + +Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these +functions do no boundary checking of the allocated data whatsoever, so make sure there is enough +data available in the buffer to be able to go to the next chunk. + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk): +unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, + const char* type, const unsigned char* data): + +These functions are used to create new chunks that are appended to the data in *out that has +length *outlength. The append function appends an existing chunk to the new data. The create +function creates a new chunk with the given parameters and appends it. Type is the 4-letter +name of the chunk. + +8.2. chunks in info_png +----------------------- + +The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 +buffers (each with size) to contain 3 types of unknown chunks: +the ones that come before the PLTE chunk, the ones that come between the PLTE +and the IDAT chunks, and the ones that come after the IDAT chunks. +It's necessary to make the distionction between these 3 cases because the PNG +standard forces to keep the ordering of unknown chunks compared to the critical +chunks, but does not force any other ordering rules. + +info_png.unknown_chunks_data[0] is the chunks before PLTE +info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT +info_png.unknown_chunks_data[2] is the chunks after IDAT + +The chunks in these 3 buffers can be iterated through and read by using the same +way described in the previous subchapter. + +When using the decoder to decode a PNG, you can make it store all unknown chunks +if you set the option settings.remember_unknown_chunks to 1. By default, this +option is off (0). + +The encoder will always encode unknown chunks that are stored in the info_png. +If you need it to add a particular chunk that isn't known by LodePNG, you can +use lodepng_chunk_append or lodepng_chunk_create to the chunk data in +info_png.unknown_chunks_data[x]. + +Chunks that are known by LodePNG should not be added in that way. E.g. to make +LodePNG add a bKGD chunk, set background_defined to true and add the correct +parameters there instead. + + +9. compiler support +------------------- + +No libraries other than the current standard C library are needed to compile +LodePNG. For the C++ version, only the standard C++ library is needed on top. +Add the files lodepng.c(pp) and lodepng.h to your project, include +lodepng.h where needed, and your program can read/write PNG files. + +It is compatible with C90 and up, and C++03 and up. + +If performance is important, use optimization when compiling! For both the +encoder and decoder, this makes a large difference. + +Make sure that LodePNG is compiled with the same compiler of the same version +and with the same settings as the rest of the program, or the interfaces with +std::vectors and std::strings in C++ can be incompatible. + +CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. + +*) gcc and g++ + +LodePNG is developed in gcc so this compiler is natively supported. It gives no +warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ +version 4.7.1 on Linux, 32-bit and 64-bit. + +*) Clang + +Fully supported and warning-free. + +*) Mingw + +The Mingw compiler (a port of gcc for Windows) should be fully supported by +LodePNG. + +*) Visual Studio and Visual C++ Express Edition + +LodePNG should be warning-free with warning level W4. Two warnings were disabled +with pragmas though: warning 4244 about implicit conversions, and warning 4996 +where it wants to use a non-standard function fopen_s instead of the standard C +fopen. + +Visual Studio may want "stdafx.h" files to be included in each source file and +give an error "unexpected end of file while looking for precompiled header". +This is not standard C++ and will not be added to the stock LodePNG. You can +disable it for lodepng.cpp only by right clicking it, Properties, C/C++, +Precompiled Headers, and set it to Not Using Precompiled Headers there. + +NOTE: Modern versions of VS should be fully supported, but old versions, e.g. +VS6, are not guaranteed to work. + +*) Compilers on Macintosh + +LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for +C and C++. + +*) Other Compilers + +If you encounter problems on any compilers, feel free to let me know and I may +try to fix it if the compiler is modern and standards complient. + + +10. examples +------------ + +This decoder example shows the most basic usage of LodePNG. More complex +examples can be found on the LodePNG website. + +10.1. decoder C++ example +------------------------- + +#include "lodepng.h" +#include + +int main(int argc, char *argv[]) +{ + const char* filename = argc > 1 ? argv[1] : "test.png"; + + //load and decode + std::vector image; + unsigned width, height; + unsigned error = lodepng::decode(image, width, height, filename); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... +} + +10.2. decoder C example +----------------------- + +#include "lodepng.h" + +int main(int argc, char *argv[]) +{ + unsigned error; + unsigned char* image; + size_t width, height; + const char* filename = argc > 1 ? argv[1] : "test.png"; + + error = lodepng_decode32_file(&image, &width, &height, filename); + + if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); + + / * use image here * / + + free(image); + return 0; +} + +11. state settings reference +---------------------------- + +A quick reference of some settings to set on the LodePNGState + +For decoding: + +state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums +state.decoder.zlibsettings.custom_...: use custom inflate function +state.decoder.ignore_crc: ignore CRC checksums +state.decoder.color_convert: convert internal PNG color to chosen one +state.decoder.read_text_chunks: whether to read in text metadata chunks +state.decoder.remember_unknown_chunks: whether to read in unknown chunks +state.info_raw.colortype: desired color type for decoded image +state.info_raw.bitdepth: desired bit depth for decoded image +state.info_raw....: more color settings, see struct LodePNGColorMode +state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo + +For encoding: + +state.encoder.zlibsettings.btype: disable compression by setting it to 0 +state.encoder.zlibsettings.use_lz77: use LZ77 in compression +state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize +state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match +state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching +state.encoder.zlibsettings.lazymatching: try one more LZ77 matching +state.encoder.zlibsettings.custom_...: use custom deflate function +state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png +state.encoder.filter_palette_zero: PNG filter strategy for palette +state.encoder.filter_strategy: PNG filter strategy to encode with +state.encoder.force_palette: add palette even if not encoding to one +state.encoder.add_id: add LodePNG identifier and version as a text chunk +state.encoder.text_compression: use compressed text chunks for metadata +state.info_raw.colortype: color type of raw input image you provide +state.info_raw.bitdepth: bit depth of raw input image you provide +state.info_raw: more color settings, see struct LodePNGColorMode +state.info_png.color.colortype: desired color type if auto_convert is false +state.info_png.color.bitdepth: desired bit depth if auto_convert is false +state.info_png.color....: more color settings, see struct LodePNGColorMode +state.info_png....: more PNG related settings, see struct LodePNGInfo + + +12. changes +----------- + +The version number of LodePNG is the date of the change given in the format +yyyymmdd. + +Some changes aren't backwards compatible. Those are indicated with a (!) +symbol. + +*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). +*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within + the limits of pure C90). +*) 08 dec 2015: Made load_file function return error if file can't be opened. +*) 24 okt 2015: Bugfix with decoding to palette output. +*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. +*) 23 aug 2014: Reduced needless memory usage of decoder. +*) 28 jun 2014: Removed fix_png setting, always support palette OOB for + simplicity. Made ColorProfile public. +*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. +*) 22 dec 2013: Power of two windowsize required for optimization. +*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. +*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). +*) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_" + prefix for the custom allocators and made it possible with a new #define to + use custom ones in your project without needing to change lodepng's code. +*) 28 jan 2013: Bugfix with color key. +*) 27 okt 2012: Tweaks in text chunk keyword length error handling. +*) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode. + (no palette). Better deflate tree encoding. New compression tweak settings. + Faster color conversions while decoding. Some internal cleanups. +*) 23 sep 2012: Reduced warnings in Visual Studio a little bit. +*) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions + and made it work with function pointers instead. +*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc + and free functions and toggle #defines from compiler flags. Small fixes. +*) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible. +*) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed + redundant C++ codec classes. Reduced amount of structs. Everything changed, + but it is cleaner now imho and functionality remains the same. Also fixed + several bugs and shrunk the implementation code. Made new samples. +*) 6 nov 2011 (!): By default, the encoder now automatically chooses the best + PNG color model and bit depth, based on the amount and type of colors of the + raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. +*) 9 okt 2011: simpler hash chain implementation for the encoder. +*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. +*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. + A bug with the PNG filtertype heuristic was fixed, so that it chooses much + better ones (it's quite significant). A setting to do an experimental, slow, + brute force search for PNG filter types is added. +*) 17 aug 2011 (!): changed some C zlib related function names. +*) 16 aug 2011: made the code less wide (max 120 characters per line). +*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. +*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. +*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman + to optimize long sequences of zeros. +*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and + LodePNG_InfoColor_canHaveAlpha functions for convenience. +*) 7 nov 2010: added LodePNG_error_text function to get error code description. +*) 30 okt 2010: made decoding slightly faster +*) 26 okt 2010: (!) changed some C function and struct names (more consistent). + Reorganized the documentation and the declaration order in the header. +*) 08 aug 2010: only changed some comments and external samples. +*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. +*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. +*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could + read by ignoring the problem but windows apps couldn't. +*) 06 jun 2008: added more error checks for out of memory cases. +*) 26 apr 2008: added a few more checks here and there to ensure more safety. +*) 06 mar 2008: crash with encoding of strings fixed +*) 02 feb 2008: support for international text chunks added (iTXt) +*) 23 jan 2008: small cleanups, and #defines to divide code in sections +*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. +*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. +*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added + Also various fixes, such as in the deflate and the padding bits code. +*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved + filtering code of encoder. +*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A + C++ wrapper around this provides an interface almost identical to before. + Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code + are together in these files but it works both for C and C++ compilers. +*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks +*) 30 aug 2007: bug fixed which makes this Borland C++ compatible +*) 09 aug 2007: some VS2005 warnings removed again +*) 21 jul 2007: deflate code placed in new namespace separate from zlib code +*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images +*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing + invalid std::vector element [0] fixed, and level 3 and 4 warnings removed +*) 02 jun 2007: made the encoder add a tag with version by default +*) 27 may 2007: zlib and png code separated (but still in the same file), + simple encoder/decoder functions added for more simple usage cases +*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), + moved some examples from here to lodepng_examples.cpp +*) 12 may 2007: palette decoding bug fixed +*) 24 apr 2007: changed the license from BSD to the zlib license +*) 11 mar 2007: very simple addition: ability to encode bKGD chunks. +*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding + palettized PNG images. Plus little interface change with palette and texts. +*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. + Fixed a bug where the end code of a block had length 0 in the Huffman tree. +*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented + and supported by the encoder, resulting in smaller PNGs at the output. +*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. +*) 24 jan 2007: gave encoder an error interface. Added color conversion from any + greyscale type to 8-bit greyscale with or without alpha. +*) 21 jan 2007: (!) Totally changed the interface. It allows more color types + to convert to and is more uniform. See the manual for how it works now. +*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: + encode/decode custom tEXt chunks, separate classes for zlib & deflate, and + at last made the decoder give errors for incorrect Adler32 or Crc. +*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. +*) 29 dec 2006: Added support for encoding images without alpha channel, and + cleaned out code as well as making certain parts faster. +*) 28 dec 2006: Added "Settings" to the encoder. +*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. + Removed some code duplication in the decoder. Fixed little bug in an example. +*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. + Fixed a bug of the decoder with 16-bit per color. +*) 15 okt 2006: Changed documentation structure +*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the + given image buffer, however for now it's not compressed. +*) 08 sep 2006: (!) Changed to interface with a Decoder class +*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different + way. Renamed decodePNG to decodePNGGeneric. +*) 29 jul 2006: (!) Changed the interface: image info is now returned as a + struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. +*) 28 jul 2006: Cleaned the code and added new error checks. + Corrected terminology "deflate" into "inflate". +*) 23 jun 2006: Added SDL example in the documentation in the header, this + example allows easy debugging by displaying the PNG and its transparency. +*) 22 jun 2006: (!) Changed way to obtain error value. Added + loadFile function for convenience. Made decodePNG32 faster. +*) 21 jun 2006: (!) Changed type of info vector to unsigned. + Changed position of palette in info vector. Fixed an important bug that + happened on PNGs with an uncompressed block. +*) 16 jun 2006: Internally changed unsigned into unsigned where + needed, and performed some optimizations. +*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them + in LodePNG namespace. Changed the order of the parameters. Rewrote the + documentation in the header. Renamed files to lodepng.cpp and lodepng.h +*) 22 apr 2006: Optimized and improved some code +*) 07 sep 2005: (!) Changed to std::vector interface +*) 12 aug 2005: Initial release (C++, decoder only) + + +13. contact information +----------------------- + +Feel free to contact me with suggestions, problems, comments, ... concerning +LodePNG. If you encounter a PNG image that doesn't work properly with this +decoder, feel free to send it and I'll use it to find and fix the problem. + +My email address is (puzzle the account and domain together with an @ symbol): +Domain: gmail dot com. +Account: lode dot vandevenne. + + +Copyright (c) 2005-2016 Lode Vandevenne +*/ diff --git a/src/ext/openexr b/src/ext/openexr new file mode 160000 index 00000000..5cfb5dab --- /dev/null +++ b/src/ext/openexr @@ -0,0 +1 @@ +Subproject commit 5cfb5dab6dfada731586b0281bdb15ee75e26782 diff --git a/src/ext/ptex b/src/ext/ptex new file mode 160000 index 00000000..77b38740 --- /dev/null +++ b/src/ext/ptex @@ -0,0 +1 @@ +Subproject commit 77b387406028d0dd6fea76d59d51e17aafe53358 diff --git a/src/ext/rply/rply.cpp b/src/ext/rply/rply.cpp new file mode 100644 index 00000000..95326471 --- /dev/null +++ b/src/ext/rply/rply.cpp @@ -0,0 +1,1612 @@ + +// ext/rply.cpp* +/* ---------------------------------------------------------------------- + * RPly library, read/write PLY files + * Diego Nehab, IMPA + * http://www.impa.br/~diego/software/rply + * + * This library is distributed under the MIT License. See notice + * at the end of this file. + * ---------------------------------------------------------------------- */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rply.h" + +/* ---------------------------------------------------------------------- + * Make sure we get our integer types right + * ---------------------------------------------------------------------- */ +#if defined(_MSC_VER) && (_MSC_VER < 1600) +/* C99 stdint.h only supported in MSVC++ 10.0 and up */ +typedef __int8 t_ply_int8; +typedef __int16 t_ply_int16; +typedef __int32 t_ply_int32; +typedef unsigned __int8 t_ply_uint8; +typedef unsigned __int16 t_ply_uint16; +typedef unsigned __int32 t_ply_uint32; +#define PLY_INT8_MAX (127) +#define PLY_INT8_MIN (-PLY_INT8_MAX - 1) +#define PLY_INT16_MAX (32767) +#define PLY_INT16_MIN (-PLY_INT16_MAX - 1) +#define PLY_INT32_MAX (2147483647) +#define PLY_INT32_MIN (-PLY_INT32_MAX - 1) +#define PLY_UINT8_MAX (255) +#define PLY_UINT16_MAX (65535) +#define PLY_UINT32_MAX (4294967295) +#else +#define __STDC_LIMIT_MACROS +#include +typedef int8_t t_ply_int8; +typedef int16_t t_ply_int16; +typedef int32_t t_ply_int32; +typedef uint8_t t_ply_uint8; +typedef uint16_t t_ply_uint16; +typedef uint32_t t_ply_uint32; +#define PLY_INT8_MIN INT8_MIN +#define PLY_INT8_MAX INT8_MAX +#define PLY_INT16_MIN INT16_MIN +#define PLY_INT16_MAX INT16_MAX +#define PLY_INT32_MIN INT32_MIN +#define PLY_INT32_MAX INT32_MAX +#define PLY_UINT8_MAX UINT8_MAX +#define PLY_UINT16_MAX UINT16_MAX +#define PLY_UINT32_MAX UINT32_MAX +#endif + +/* ---------------------------------------------------------------------- + * Constants + * ---------------------------------------------------------------------- */ +#define WORDSIZE 256 +#define LINESIZE 1024 +#define BUFFERSIZE (8 * 1024) + +typedef enum e_ply_io_mode_ { PLY_READ, PLY_WRITE } e_ply_io_mode; + +static const char *const ply_storage_mode_list[] = { + "binary_big_endian", "binary_little_endian", "ascii", + NULL}; /* order matches e_ply_storage_mode enum */ + +static const char *const ply_type_list[] = { + "int8", "uint8", "int16", "uint16", "int32", "uint32", "float32", + "float64", "char", "uchar", "short", "ushort", "int", "uint", + "float", "double", "list", NULL}; /* order matches e_ply_type enum */ + +/* ---------------------------------------------------------------------- + * Property reading callback argument + * + * element: name of element being processed + * property: name of property being processed + * nelements: number of elements of this kind in file + * instance_index: index current element of this kind being processed + * length: number of values in current list (or 1 for scalars) + * value_index: index of current value int this list (or 0 for scalars) + * value: value of property + * pdata/idata: user data defined with ply_set_cb + * + * Returns handle to PLY file if succesful, NULL otherwise. + * ---------------------------------------------------------------------- */ +typedef struct t_ply_argument_ { + p_ply_element element; + long instance_index; + p_ply_property property; + long length, value_index; + double value; + void *pdata; + long idata; +} t_ply_argument; + +/* ---------------------------------------------------------------------- + * Property information + * + * name: name of this property + * type: type of this property (list or type of scalar value) + * length_type, value_type: type of list property count and values + * read_cb: function to be called when this property is called + * + * Returns 1 if should continue processing file, 0 if should abort. + * ---------------------------------------------------------------------- */ +typedef struct t_ply_property_ { + char name[WORDSIZE]; + e_ply_type type, value_type, length_type; + p_ply_read_cb read_cb; + void *pdata; + long idata; +} t_ply_property; + +/* ---------------------------------------------------------------------- + * Element information + * + * name: name of this property + * ninstances: number of elements of this type in file + * property: property descriptions for this element + * nproperty: number of properties in this element + * + * Returns 1 if should continue processing file, 0 if should abort. + * ---------------------------------------------------------------------- */ +typedef struct t_ply_element_ { + char name[WORDSIZE]; + long ninstances; + p_ply_property property; + long nproperties; +} t_ply_element; + +/* ---------------------------------------------------------------------- + * Input/output driver + * + * Depending on file mode, different functions are used to read/write + * property fields. The drivers make it transparent to read/write in ascii, + * big endian or little endian cases. + * ---------------------------------------------------------------------- */ +typedef int (*p_ply_ihandler)(p_ply ply, double *value); +typedef int (*p_ply_ichunk)(p_ply ply, void *anydata, size_t size); +typedef struct t_ply_idriver_ { + p_ply_ihandler ihandler[16]; + p_ply_ichunk ichunk; + const char *name; +} t_ply_idriver; +typedef t_ply_idriver *p_ply_idriver; + +typedef int (*p_ply_ohandler)(p_ply ply, double value); +typedef int (*p_ply_ochunk)(p_ply ply, void *anydata, size_t size); +typedef struct t_ply_odriver_ { + p_ply_ohandler ohandler[16]; + p_ply_ochunk ochunk; + const char *name; +} t_ply_odriver; +typedef t_ply_odriver *p_ply_odriver; + +/* ---------------------------------------------------------------------- + * Ply file handle. + * + * io_mode: read or write (from e_ply_io_mode) + * storage_mode: mode of file associated with handle (from e_ply_storage_mode) + * element: elements description for this file + * nelement: number of different elements in file + * comment: comments for this file + * ncomments: number of comments in file + * obj_info: obj_info items for this file + * nobj_infos: number of obj_info items in file + * fp: file pointer associated with ply file + * rn: skip extra char after end_header? + * buffer: last word/chunck of data read from ply file + * buffer_first, buffer_last: interval of untouched good data in buffer + * buffer_token: start of parsed token (line or word) in buffer + * idriver, odriver: input driver used to get property fields from file + * argument: storage space for callback arguments + * welement, wproperty: element/property type being written + * winstance_index: index of instance of current element being written + * wvalue_index: index of list property value being written + * wlength: number of values in list property being written + * error_cb: error callback + * pdata/idata: user data defined with ply_open/ply_create + * ---------------------------------------------------------------------- */ +typedef struct t_ply_ { + e_ply_io_mode io_mode; + e_ply_storage_mode storage_mode; + p_ply_element element; + long nelements; + char *comment; + long ncomments; + char *obj_info; + long nobj_infos; + FILE *fp; + int rn; + char buffer[BUFFERSIZE]; + size_t buffer_first, buffer_token, buffer_last; + p_ply_idriver idriver; + p_ply_odriver odriver; + t_ply_argument argument; + long welement, wproperty; + long winstance_index, wvalue_index, wlength; + p_ply_error_cb error_cb; + void *pdata; + long idata; +} t_ply; + +/* ---------------------------------------------------------------------- + * I/O functions and drivers + * ---------------------------------------------------------------------- */ +namespace { +extern t_ply_idriver ply_idriver_ascii; +extern t_ply_idriver ply_idriver_binary; +extern t_ply_idriver ply_idriver_binary_reverse; +extern t_ply_odriver ply_odriver_ascii; +extern t_ply_odriver ply_odriver_binary; +extern t_ply_odriver ply_odriver_binary_reverse; +}; + +static int ply_read_word(p_ply ply); +static int ply_check_word(p_ply ply); +static void ply_finish_word(p_ply ply, size_t size); +static int ply_read_line(p_ply ply); +static int ply_check_line(p_ply ply); +static int ply_read_chunk(p_ply ply, void *anybuffer, size_t size); +static int ply_read_chunk_reverse(p_ply ply, void *anybuffer, size_t size); +static int ply_write_chunk(p_ply ply, void *anybuffer, size_t size); +static int ply_write_chunk_reverse(p_ply ply, void *anybuffer, size_t size); +static void ply_reverse(void *anydata, size_t size); + +/* ---------------------------------------------------------------------- + * String functions + * ---------------------------------------------------------------------- */ +static int ply_find_string(const char *item, const char *const list[]); +static p_ply_element ply_find_element(p_ply ply, const char *name); +static p_ply_property ply_find_property(p_ply_element element, + const char *name); + +/* ---------------------------------------------------------------------- + * Header parsing + * ---------------------------------------------------------------------- */ +static int ply_read_header_magic(p_ply ply); +static int ply_read_header_format(p_ply ply); +static int ply_read_header_comment(p_ply ply); +static int ply_read_header_obj_info(p_ply ply); +static int ply_read_header_property(p_ply ply); +static int ply_read_header_element(p_ply ply); + +/* ---------------------------------------------------------------------- + * Error handling + * ---------------------------------------------------------------------- */ +static void ply_error_cb(p_ply ply, const char *message); +static void ply_ferror(p_ply ply, const char *fmt, ...); + +/* ---------------------------------------------------------------------- + * Memory allocation and initialization + * ---------------------------------------------------------------------- */ +static void ply_init(p_ply ply); +static void ply_element_init(p_ply_element element); +static void ply_property_init(p_ply_property property); +static p_ply ply_alloc(void); +static p_ply_element ply_grow_element(p_ply ply); +static p_ply_property ply_grow_property(p_ply ply, p_ply_element element); +static void *ply_grow_array(p_ply ply, void **pointer, long *nmemb, long size); + +/* ---------------------------------------------------------------------- + * Special functions + * ---------------------------------------------------------------------- */ +static e_ply_storage_mode ply_arch_endian(void); +static int ply_type_check(void); + +/* ---------------------------------------------------------------------- + * Auxiliary read functions + * ---------------------------------------------------------------------- */ +static int ply_read_element(p_ply ply, p_ply_element element, + p_ply_argument argument); +static int ply_read_property(p_ply ply, p_ply_element element, + p_ply_property property, p_ply_argument argument); +static int ply_read_list_property(p_ply ply, p_ply_element element, + p_ply_property property, + p_ply_argument argument); +static int ply_read_scalar_property(p_ply ply, p_ply_element element, + p_ply_property property, + p_ply_argument argument); + +/* ---------------------------------------------------------------------- + * Buffer support functions + * ---------------------------------------------------------------------- */ +/* pointers to tokenized word and line in buffer */ +#define BWORD(p) (p->buffer + p->buffer_token) +#define BLINE(p) (p->buffer + p->buffer_token) + +/* pointer to start of untouched bytes in buffer */ +#define BFIRST(p) (p->buffer + p->buffer_first) + +/* number of bytes untouched in buffer */ +#define BSIZE(p) (p->buffer_last - p->buffer_first) + +/* consumes data from buffer */ +#define BSKIP(p, s) (p->buffer_first += s) + +/* refills the buffer */ +static int BREFILL(p_ply ply) { + /* move untouched data to beginning of buffer */ + size_t size = BSIZE(ply); + memmove(ply->buffer, BFIRST(ply), size); + ply->buffer_last = size; + ply->buffer_first = ply->buffer_token = 0; + /* fill remaining with new data */ + size = fread(ply->buffer + size, 1, BUFFERSIZE - size - 1, ply->fp); + /* place sentinel so we can use str* functions with buffer */ + ply->buffer[BUFFERSIZE - 1] = '\0'; + /* check if read failed */ + if (size <= 0) return 0; + /* increase size to account for new data */ + ply->buffer_last += size; + return 1; +} + +/* We don't care about end-of-line, generally, because we + * separate words by any white-space character. + * Unfortunately, in binary mode, right after 'end_header', + * we have to know *exactly* how many characters to skip */ +/* We use the end-of-line marker after the 'ply' magic + * number to figure out what to do */ +static int ply_read_header_magic(p_ply ply) { + char *magic = ply->buffer; + if (!BREFILL(ply)) { + ply->error_cb(ply, "Unable to read magic number from file"); + return 0; + } + /* check if it is ply */ + if (magic[0] != 'p' || magic[1] != 'l' || magic[2] != 'y' || + !isspace(magic[3])) { + ply->error_cb(ply, "Wrong magic number. Expected 'ply'"); + return 0; + } + /* figure out if we have to skip the extra character + * after header when we reach the binary part of file */ + ply->rn = magic[3] == '\r' && magic[4] == '\n'; + BSKIP(ply, 3); + return 1; +} + +/* ---------------------------------------------------------------------- + * Exported functions + * ---------------------------------------------------------------------- */ +/* ---------------------------------------------------------------------- + * Read support functions + * ---------------------------------------------------------------------- */ +p_ply ply_open(const char *name, p_ply_error_cb error_cb, long idata, + void *pdata) { + FILE *fp = NULL; + p_ply ply = ply_alloc(); + if (error_cb == NULL) error_cb = ply_error_cb; + if (!ply) { + error_cb(NULL, "Out of memory"); + return NULL; + } + ply->idata = idata; + ply->pdata = pdata; + ply->io_mode = PLY_READ; + ply->error_cb = error_cb; + if (!ply_type_check()) { + error_cb(ply, "Incompatible type system"); + free(ply); + return NULL; + } + assert(name); + fp = fopen(name, "rb"); + if (!fp) { + error_cb(ply, "Unable to open file"); + free(ply); + return NULL; + } + ply->fp = fp; + return ply; +} + +int ply_read_header(p_ply ply) { + assert(ply && ply->fp && ply->io_mode == PLY_READ); + if (!ply_read_header_magic(ply)) return 0; + if (!ply_read_word(ply)) return 0; + /* parse file format */ + if (!ply_read_header_format(ply)) { + ply_ferror(ply, "Invalid file format"); + return 0; + } + /* parse elements, comments or obj_infos until the end of header */ + while (strcmp(BWORD(ply), "end_header")) { + if (!ply_read_header_comment(ply) && !ply_read_header_element(ply) && + !ply_read_header_obj_info(ply)) { + ply_ferror(ply, "Unexpected token '%s'", BWORD(ply)); + return 0; + } + } + /* skip extra character? */ + if (ply->rn) { + if (BSIZE(ply) < 1 && !BREFILL(ply)) { + ply_ferror(ply, "Unexpected end of file"); + return 0; + } + BSKIP(ply, 1); + } + return 1; +} + +long ply_set_read_cb(p_ply ply, const char *element_name, + const char *property_name, p_ply_read_cb read_cb, + void *pdata, long idata) { + p_ply_element element = NULL; + p_ply_property property = NULL; + assert(ply && element_name && property_name); + element = ply_find_element(ply, element_name); + if (!element) return 0; + property = ply_find_property(element, property_name); + if (!property) return 0; + property->read_cb = read_cb; + property->pdata = pdata; + property->idata = idata; + return (int)element->ninstances; +} + +int ply_read(p_ply ply) { + long i; + p_ply_argument argument; + assert(ply && ply->fp && ply->io_mode == PLY_READ); + argument = &ply->argument; + /* for each element type */ + for (i = 0; i < ply->nelements; i++) { + p_ply_element element = &ply->element[i]; + argument->element = element; + if (!ply_read_element(ply, element, argument)) return 0; + } + return 1; +} + +/* ---------------------------------------------------------------------- + * Write support functions + * ---------------------------------------------------------------------- */ +p_ply ply_create(const char *name, e_ply_storage_mode storage_mode, + p_ply_error_cb error_cb, long idata, void *pdata) { + FILE *fp = NULL; + p_ply ply = ply_alloc(); + if (error_cb == NULL) error_cb = ply_error_cb; + if (!ply) { + error_cb(NULL, "Out of memory"); + return NULL; + } + if (!ply_type_check()) { + error_cb(ply, "Incompatible type system"); + free(ply); + return NULL; + } + assert(name && storage_mode <= PLY_DEFAULT); + fp = fopen(name, "wb"); + if (!fp) { + error_cb(ply, "Unable to create file"); + free(ply); + return NULL; + } + ply->idata = idata; + ply->pdata = pdata; + ply->io_mode = PLY_WRITE; + if (storage_mode == PLY_DEFAULT) storage_mode = ply_arch_endian(); + if (storage_mode == PLY_ASCII) + ply->odriver = &ply_odriver_ascii; + else if (storage_mode == ply_arch_endian()) + ply->odriver = &ply_odriver_binary; + else + ply->odriver = &ply_odriver_binary_reverse; + ply->storage_mode = storage_mode; + ply->fp = fp; + ply->error_cb = error_cb; + return ply; +} + +int ply_add_element(p_ply ply, const char *name, long ninstances) { + p_ply_element element = NULL; + assert(ply && ply->fp && ply->io_mode == PLY_WRITE); + assert(name && strlen(name) < WORDSIZE && ninstances >= 0); + if (strlen(name) >= WORDSIZE || ninstances < 0) { + ply_ferror(ply, "Invalid arguments"); + return 0; + } + element = ply_grow_element(ply); + if (!element) return 0; + strcpy(element->name, name); + element->ninstances = ninstances; + return 1; +} + +int ply_add_scalar_property(p_ply ply, const char *name, e_ply_type type) { + p_ply_element element = NULL; + p_ply_property property = NULL; + assert(ply && ply->fp && ply->io_mode == PLY_WRITE); + assert(name && strlen(name) < WORDSIZE); + assert(type < PLY_LIST); + if (strlen(name) >= WORDSIZE || type >= PLY_LIST) { + ply_ferror(ply, "Invalid arguments"); + return 0; + } + element = &ply->element[ply->nelements - 1]; + property = ply_grow_property(ply, element); + if (!property) return 0; + strcpy(property->name, name); + property->type = type; + return 1; +} + +int ply_add_list_property(p_ply ply, const char *name, e_ply_type length_type, + e_ply_type value_type) { + p_ply_element element = NULL; + p_ply_property property = NULL; + assert(ply && ply->fp && ply->io_mode == PLY_WRITE); + assert(name && strlen(name) < WORDSIZE); + if (strlen(name) >= WORDSIZE) { + ply_ferror(ply, "Invalid arguments"); + return 0; + } + assert(length_type < PLY_LIST); + assert(value_type < PLY_LIST); + if (length_type >= PLY_LIST || value_type >= PLY_LIST) { + ply_ferror(ply, "Invalid arguments"); + return 0; + } + element = &ply->element[ply->nelements - 1]; + property = ply_grow_property(ply, element); + if (!property) return 0; + strcpy(property->name, name); + property->type = PLY_LIST; + property->length_type = length_type; + property->value_type = value_type; + return 1; +} + +int ply_add_property(p_ply ply, const char *name, e_ply_type type, + e_ply_type length_type, e_ply_type value_type) { + if (type == PLY_LIST) + return ply_add_list_property(ply, name, length_type, value_type); + else + return ply_add_scalar_property(ply, name, type); +} + +int ply_add_comment(p_ply ply, const char *comment) { + char *new_comment = NULL; + assert(ply && comment && strlen(comment) < LINESIZE); + if (!comment || strlen(comment) >= LINESIZE) { + ply_ferror(ply, "Invalid arguments"); + return 0; + } + new_comment = (char *)ply_grow_array(ply, (void **)&ply->comment, + &ply->ncomments, LINESIZE); + if (!new_comment) return 0; + strcpy(new_comment, comment); + return 1; +} + +int ply_add_obj_info(p_ply ply, const char *obj_info) { + char *new_obj_info = NULL; + assert(ply && obj_info && strlen(obj_info) < LINESIZE); + if (!obj_info || strlen(obj_info) >= LINESIZE) { + ply_ferror(ply, "Invalid arguments"); + return 0; + } + new_obj_info = (char *)ply_grow_array(ply, (void **)&ply->obj_info, + &ply->nobj_infos, LINESIZE); + if (!new_obj_info) return 0; + strcpy(new_obj_info, obj_info); + return 1; +} + +int ply_write_header(p_ply ply) { + long i, j; + assert(ply && ply->fp && ply->io_mode == PLY_WRITE); + assert(ply->element || ply->nelements == 0); + assert(!ply->element || ply->nelements > 0); + if (fprintf(ply->fp, "ply\nformat %s 1.0\n", + ply_storage_mode_list[ply->storage_mode]) <= 0) + goto error; + for (i = 0; i < ply->ncomments; i++) + if (fprintf(ply->fp, "comment %s\n", ply->comment + LINESIZE * i) <= 0) + goto error; + for (i = 0; i < ply->nobj_infos; i++) + if (fprintf(ply->fp, "obj_info %s\n", ply->obj_info + LINESIZE * i) <= + 0) + goto error; + for (i = 0; i < ply->nelements; i++) { + p_ply_element element = &ply->element[i]; + assert(element->property || element->nproperties == 0); + assert(!element->property || element->nproperties > 0); + if (fprintf(ply->fp, "element %s %ld\n", element->name, + element->ninstances) <= 0) + goto error; + for (j = 0; j < element->nproperties; j++) { + p_ply_property property = &element->property[j]; + if (property->type == PLY_LIST) { + if (fprintf(ply->fp, "property list %s %s %s\n", + ply_type_list[property->length_type], + ply_type_list[property->value_type], + property->name) <= 0) + goto error; + } else { + if (fprintf(ply->fp, "property %s %s\n", + ply_type_list[property->type], property->name) <= 0) + goto error; + } + } + } + return fprintf(ply->fp, "end_header\n") > 0; +error: + ply_ferror(ply, "Error writing to file"); + return 0; +} + +int ply_write(p_ply ply, double value) { + p_ply_element element = NULL; + p_ply_property property = NULL; + int type = -1; + int breakafter = 0; + int spaceafter = 1; + if (ply->welement > ply->nelements) return 0; + element = &ply->element[ply->welement]; + if (ply->wproperty > element->nproperties) return 0; + property = &element->property[ply->wproperty]; + if (property->type == PLY_LIST) { + if (ply->wvalue_index == 0) { + type = property->length_type; + ply->wlength = (long)value; + } else + type = property->value_type; + } else { + type = property->type; + ply->wlength = 0; + } + if (!ply->odriver->ohandler[type](ply, value)) { + ply_ferror(ply, "Failed writing %s of %s %d (%s: %s)", property->name, + element->name, ply->winstance_index, ply->odriver->name, + ply_type_list[type]); + return 0; + } + ply->wvalue_index++; + if (ply->wvalue_index > ply->wlength) { + ply->wvalue_index = 0; + ply->wproperty++; + } + if (ply->wproperty >= element->nproperties) { + ply->wproperty = 0; + ply->winstance_index++; + breakafter = 1; + spaceafter = 0; + } + if (ply->winstance_index >= element->ninstances) { + ply->winstance_index = 0; + do { + ply->welement++; + element = &ply->element[ply->welement]; + } while (ply->welement < ply->nelements && !element->ninstances); + } + if (ply->storage_mode == PLY_ASCII) { + return (!spaceafter || putc(' ', ply->fp) > 0) && + (!breakafter || putc('\n', ply->fp) > 0); + } else { + return 1; + } +} + +int ply_close(p_ply ply) { + long i; + assert(ply && ply->fp); + assert(ply->element || ply->nelements == 0); + assert(!ply->element || ply->nelements > 0); + /* write last chunk to file */ + if (ply->io_mode == PLY_WRITE && + fwrite(ply->buffer, 1, ply->buffer_last, ply->fp) < ply->buffer_last) { + ply_ferror(ply, "Error closing up"); + return 0; + } + fclose(ply->fp); + /* free all memory used by handle */ + if (ply->element) { + for (i = 0; i < ply->nelements; i++) { + p_ply_element element = &ply->element[i]; + if (element->property) free(element->property); + } + free(ply->element); + } + if (ply->obj_info) free(ply->obj_info); + if (ply->comment) free(ply->comment); + free(ply); + return 1; +} + +/* ---------------------------------------------------------------------- + * Query support functions + * ---------------------------------------------------------------------- */ +p_ply_element ply_get_next_element(p_ply ply, p_ply_element last) { + assert(ply); + if (!last) return ply->element; + last++; + if (last < ply->element + ply->nelements) + return last; + else + return NULL; +} + +int ply_get_element_info(p_ply_element element, const char **name, + long *ninstances) { + assert(element); + if (name) *name = element->name; + if (ninstances) *ninstances = (long)element->ninstances; + return 1; +} + +p_ply_property ply_get_next_property(p_ply_element element, + p_ply_property last) { + assert(element); + if (!last) return element->property; + last++; + if (last < element->property + element->nproperties) + return last; + else + return NULL; +} + +int ply_get_property_info(p_ply_property property, const char **name, + e_ply_type *type, e_ply_type *length_type, + e_ply_type *value_type) { + assert(property); + if (name) *name = property->name; + if (type) *type = property->type; + if (length_type) *length_type = property->length_type; + if (value_type) *value_type = property->value_type; + return 1; +} + +const char *ply_get_next_comment(p_ply ply, const char *last) { + assert(ply); + if (!last) return ply->comment; + last += LINESIZE; + if (last < ply->comment + LINESIZE * ply->ncomments) + return last; + else + return NULL; +} + +const char *ply_get_next_obj_info(p_ply ply, const char *last) { + assert(ply); + if (!last) return ply->obj_info; + last += LINESIZE; + if (last < ply->obj_info + LINESIZE * ply->nobj_infos) + return last; + else + return NULL; +} + +/* ---------------------------------------------------------------------- + * Callback argument support functions + * ---------------------------------------------------------------------- */ +int ply_get_argument_element(p_ply_argument argument, p_ply_element *element, + long *instance_index) { + assert(argument); + if (!argument) return 0; + if (element) *element = argument->element; + if (instance_index) *instance_index = argument->instance_index; + return 1; +} + +int ply_get_argument_property(p_ply_argument argument, p_ply_property *property, + long *length, long *value_index) { + assert(argument); + if (!argument) return 0; + if (property) *property = argument->property; + if (length) *length = argument->length; + if (value_index) *value_index = argument->value_index; + return 1; +} + +int ply_get_argument_user_data(p_ply_argument argument, void **pdata, + long *idata) { + assert(argument); + if (!argument) return 0; + if (pdata) *pdata = argument->pdata; + if (idata) *idata = argument->idata; + return 1; +} + +double ply_get_argument_value(p_ply_argument argument) { + assert(argument); + if (!argument) return 0.0; + return argument->value; +} + +int ply_get_ply_user_data(p_ply ply, void **pdata, long *idata) { + assert(ply); + if (!ply) return 0; + if (pdata) *pdata = ply->pdata; + if (idata) *idata = ply->idata; + return 1; +} + +/* ---------------------------------------------------------------------- + * Internal functions + * ---------------------------------------------------------------------- */ +static int ply_read_list_property(p_ply ply, p_ply_element element, + p_ply_property property, + p_ply_argument argument) { + int l; + p_ply_read_cb read_cb = property->read_cb; + p_ply_ihandler *driver = ply->idriver->ihandler; + /* get list length */ + p_ply_ihandler handler = driver[property->length_type]; + double length; + if (!handler(ply, &length)) { + ply_ferror(ply, "Error reading '%s' of '%s' number %d", property->name, + element->name, argument->instance_index); + return 0; + } + /* invoke callback to pass length in value field */ + argument->length = (long)length; + argument->value_index = -1; + argument->value = length; + if (read_cb && !read_cb(argument)) { + ply_ferror(ply, "Aborted by user"); + return 0; + } + /* read list values */ + handler = driver[property->value_type]; + /* for each value in list */ + for (l = 0; l < (long)length; l++) { + /* read value from file */ + argument->value_index = l; + if (!handler(ply, &argument->value)) { + ply_ferror(ply, + "Error reading value number %d of '%s' of " + "'%s' number %d", + l + 1, property->name, element->name, + argument->instance_index); + return 0; + } + /* invoke callback to pass value */ + if (read_cb && !read_cb(argument)) { + ply_ferror(ply, "Aborted by user"); + return 0; + } + } + return 1; +} + +static int ply_read_scalar_property(p_ply ply, p_ply_element element, + p_ply_property property, + p_ply_argument argument) { + p_ply_read_cb read_cb = property->read_cb; + p_ply_ihandler *driver = ply->idriver->ihandler; + p_ply_ihandler handler = driver[property->type]; + argument->length = 1; + argument->value_index = 0; + if (!handler(ply, &argument->value)) { + ply_ferror(ply, "Error reading '%s' of '%s' number %d", property->name, + element->name, argument->instance_index); + return 0; + } + if (read_cb && !read_cb(argument)) { + ply_ferror(ply, "Aborted by user"); + return 0; + } + return 1; +} + +static int ply_read_property(p_ply ply, p_ply_element element, + p_ply_property property, p_ply_argument argument) { + if (property->type == PLY_LIST) + return ply_read_list_property(ply, element, property, argument); + else + return ply_read_scalar_property(ply, element, property, argument); +} + +static int ply_read_element(p_ply ply, p_ply_element element, + p_ply_argument argument) { + long j, k; + /* for each element of this type */ + for (j = 0; j < element->ninstances; j++) { + argument->instance_index = j; + /* for each property */ + for (k = 0; k < element->nproperties; k++) { + p_ply_property property = &element->property[k]; + argument->property = property; + argument->pdata = property->pdata; + argument->idata = property->idata; + if (!ply_read_property(ply, element, property, argument)) return 0; + } + } + return 1; +} + +static int ply_find_string(const char *item, const char *const list[]) { + int i; + assert(item && list); + for (i = 0; list[i]; i++) + if (!strcmp(list[i], item)) return i; + return -1; +} + +static p_ply_element ply_find_element(p_ply ply, const char *name) { + p_ply_element element; + int i, nelements; + assert(ply && name); + element = ply->element; + nelements = ply->nelements; + assert(element || nelements == 0); + assert(!element || nelements > 0); + for (i = 0; i < nelements; i++) + if (!strcmp(element[i].name, name)) return &element[i]; + return NULL; +} + +static p_ply_property ply_find_property(p_ply_element element, + const char *name) { + p_ply_property property; + int i, nproperties; + assert(element && name); + property = element->property; + nproperties = element->nproperties; + assert(property || nproperties == 0); + assert(!property || nproperties > 0); + for (i = 0; i < nproperties; i++) + if (!strcmp(property[i].name, name)) return &property[i]; + return NULL; +} + +static int ply_check_word(p_ply ply) { + size_t size = strlen(BWORD(ply)); + if (size >= WORDSIZE) { + ply_ferror(ply, "Word too long"); + return 0; + } else if (size == 0) { + ply_ferror(ply, "Unexpected end of file"); + return 0; + } + return 1; +} + +static int ply_read_word(p_ply ply) { + size_t t = 0; + assert(ply && ply->fp && ply->io_mode == PLY_READ); + /* skip leading blanks */ + while (1) { + t = strspn(BFIRST(ply), " \n\r\t"); + /* check if all buffer was made of blanks */ + if (t >= BSIZE(ply)) { + if (!BREFILL(ply)) { + ply_ferror(ply, "Unexpected end of file"); + return 0; + } + } else + break; + } + BSKIP(ply, t); + /* look for a space after the current word */ + t = strcspn(BFIRST(ply), " \n\r\t"); + /* if we didn't reach the end of the buffer, we are done */ + if (t < BSIZE(ply)) { + ply_finish_word(ply, t); + return ply_check_word(ply); + } + /* otherwise, try to refill buffer */ + if (!BREFILL(ply)) { + /* if we reached the end of file, try to do with what we have */ + ply_finish_word(ply, t); + return ply_check_word(ply); + /* ply_ferror(ply, "Unexpected end of file"); */ + /* return 0; */ + } + /* keep looking from where we left */ + t += strcspn(BFIRST(ply) + t, " \n\r\t"); + /* check if the token is too large for our buffer */ + if (t >= BSIZE(ply)) { + ply_ferror(ply, "Token too large"); + return 0; + } + /* we are done */ + ply_finish_word(ply, t); + return ply_check_word(ply); +} + +static void ply_finish_word(p_ply ply, size_t size) { + ply->buffer_token = ply->buffer_first; + BSKIP(ply, size); + *BFIRST(ply) = '\0'; + BSKIP(ply, 1); +} + +static int ply_check_line(p_ply ply) { + if (strlen(BLINE(ply)) >= LINESIZE) { + ply_ferror(ply, "Line too long"); + return 0; + } + return 1; +} + +static int ply_read_line(p_ply ply) { + const char *end = NULL; + assert(ply && ply->fp && ply->io_mode == PLY_READ); + /* look for a end of line */ + end = strchr(BFIRST(ply), '\n'); + /* if we didn't reach the end of the buffer, we are done */ + if (end) { + ply->buffer_token = ply->buffer_first; + BSKIP(ply, end - BFIRST(ply)); + *BFIRST(ply) = '\0'; + BSKIP(ply, 1); + return ply_check_line(ply); + } else { + end = ply->buffer + BSIZE(ply); + /* otherwise, try to refill buffer */ + if (!BREFILL(ply)) { + ply_ferror(ply, "Unexpected end of file"); + return 0; + } + } + /* keep looking from where we left */ + end = strchr(end, '\n'); + /* check if the token is too large for our buffer */ + if (!end) { + ply_ferror(ply, "Token too large"); + return 0; + } + /* we are done */ + ply->buffer_token = ply->buffer_first; + BSKIP(ply, end - BFIRST(ply)); + *BFIRST(ply) = '\0'; + BSKIP(ply, 1); + return ply_check_line(ply); +} + +static int ply_read_chunk(p_ply ply, void *anybuffer, size_t size) { + char *buffer = (char *)anybuffer; + size_t i = 0; + assert(ply && ply->fp && ply->io_mode == PLY_READ); + assert(ply->buffer_first <= ply->buffer_last); + while (i < size) { + if (ply->buffer_first < ply->buffer_last) { + buffer[i] = ply->buffer[ply->buffer_first]; + ply->buffer_first++; + i++; + } else { + ply->buffer_first = 0; + ply->buffer_last = fread(ply->buffer, 1, BUFFERSIZE, ply->fp); + if (ply->buffer_last <= 0) return 0; + } + } + return 1; +} + +static int ply_write_chunk(p_ply ply, void *anybuffer, size_t size) { + char *buffer = (char *)anybuffer; + size_t i = 0; + assert(ply && ply->fp && ply->io_mode == PLY_WRITE); + assert(ply->buffer_last <= BUFFERSIZE); + while (i < size) { + if (ply->buffer_last < BUFFERSIZE) { + ply->buffer[ply->buffer_last] = buffer[i]; + ply->buffer_last++; + i++; + } else { + ply->buffer_last = 0; + if (fwrite(ply->buffer, 1, BUFFERSIZE, ply->fp) < BUFFERSIZE) + return 0; + } + } + return 1; +} + +static int ply_write_chunk_reverse(p_ply ply, void *anybuffer, size_t size) { + int ret = 0; + ply_reverse(anybuffer, size); + ret = ply_write_chunk(ply, anybuffer, size); + ply_reverse(anybuffer, size); + return ret; +} + +static int ply_read_chunk_reverse(p_ply ply, void *anybuffer, size_t size) { + if (!ply_read_chunk(ply, anybuffer, size)) return 0; + ply_reverse(anybuffer, size); + return 1; +} + +static void ply_reverse(void *anydata, size_t size) { + char *data = (char *)anydata; + char temp; + size_t i; + for (i = 0; i < size / 2; i++) { + temp = data[i]; + data[i] = data[size - i - 1]; + data[size - i - 1] = temp; + } +} + +static void ply_init(p_ply ply) { + ply->element = NULL; + ply->nelements = 0; + ply->comment = NULL; + ply->ncomments = 0; + ply->obj_info = NULL; + ply->nobj_infos = 0; + ply->idriver = NULL; + ply->odriver = NULL; + ply->buffer[0] = '\0'; + ply->buffer_first = ply->buffer_last = ply->buffer_token = 0; + ply->welement = 0; + ply->wproperty = 0; + ply->winstance_index = 0; + ply->wlength = 0; + ply->wvalue_index = 0; +} + +static void ply_element_init(p_ply_element element) { + element->name[0] = '\0'; + element->ninstances = 0; + element->property = NULL; + element->nproperties = 0; +} + +static void ply_property_init(p_ply_property property) { + property->name[0] = '\0'; + property->type = (e_ply_type)-1; + property->length_type = (e_ply_type)-1; + property->value_type = (e_ply_type)-1; + property->read_cb = (p_ply_read_cb)NULL; + property->pdata = NULL; + property->idata = 0; +} + +static p_ply ply_alloc(void) { + p_ply ply = (p_ply)calloc(1, sizeof(t_ply)); + if (!ply) return NULL; + ply_init(ply); + return ply; +} + +static void *ply_grow_array(p_ply ply, void **pointer, long *nmemb, long size) { + void *temp = *pointer; + long count = *nmemb + 1; + if (!temp) + temp = malloc(count * size); + else + temp = realloc(temp, count * size); + if (!temp) { + ply_ferror(ply, "Out of memory"); + return NULL; + } + *pointer = temp; + *nmemb = count; + return (char *)temp + (count - 1) * size; +} + +static p_ply_element ply_grow_element(p_ply ply) { + p_ply_element element = NULL; + assert(ply); + assert(ply->element || ply->nelements == 0); + assert(!ply->element || ply->nelements > 0); + element = (p_ply_element)ply_grow_array( + ply, (void **)&ply->element, &ply->nelements, sizeof(t_ply_element)); + if (!element) return NULL; + ply_element_init(element); + return element; +} + +static p_ply_property ply_grow_property(p_ply ply, p_ply_element element) { + p_ply_property property = NULL; + assert(ply); + assert(element); + assert(element->property || element->nproperties == 0); + assert(!element->property || element->nproperties > 0); + property = (p_ply_property)ply_grow_array(ply, (void **)&element->property, + &element->nproperties, + sizeof(t_ply_property)); + if (!property) return NULL; + ply_property_init(property); + return property; +} + +static int ply_read_header_format(p_ply ply) { + assert(ply && ply->fp && ply->io_mode == PLY_READ); + if (strcmp(BWORD(ply), "format")) return 0; + if (!ply_read_word(ply)) return 0; + ply->storage_mode = + (e_ply_storage_mode)ply_find_string(BWORD(ply), ply_storage_mode_list); + if (ply->storage_mode == (e_ply_storage_mode)(-1)) return 0; + if (ply->storage_mode == PLY_ASCII) + ply->idriver = &ply_idriver_ascii; + else if (ply->storage_mode == ply_arch_endian()) + ply->idriver = &ply_idriver_binary; + else + ply->idriver = &ply_idriver_binary_reverse; + if (!ply_read_word(ply)) return 0; + if (strcmp(BWORD(ply), "1.0")) return 0; + if (!ply_read_word(ply)) return 0; + return 1; +} + +static int ply_read_header_comment(p_ply ply) { + assert(ply && ply->fp && ply->io_mode == PLY_READ); + if (strcmp(BWORD(ply), "comment")) return 0; + if (!ply_read_line(ply)) return 0; + if (!ply_add_comment(ply, BLINE(ply))) return 0; + if (!ply_read_word(ply)) return 0; + return 1; +} + +static int ply_read_header_obj_info(p_ply ply) { + assert(ply && ply->fp && ply->io_mode == PLY_READ); + if (strcmp(BWORD(ply), "obj_info")) return 0; + if (!ply_read_line(ply)) return 0; + if (!ply_add_obj_info(ply, BLINE(ply))) return 0; + if (!ply_read_word(ply)) return 0; + return 1; +} + +static int ply_read_header_property(p_ply ply) { + p_ply_element element = NULL; + p_ply_property property = NULL; + /* make sure it is a property */ + if (strcmp(BWORD(ply), "property")) return 0; + element = &ply->element[ply->nelements - 1]; + property = ply_grow_property(ply, element); + if (!property) return 0; + /* get property type */ + if (!ply_read_word(ply)) return 0; + property->type = (e_ply_type)ply_find_string(BWORD(ply), ply_type_list); + if (property->type == (e_ply_type)(-1)) return 0; + if (property->type == PLY_LIST) { + /* if it's a list, we need the base types */ + if (!ply_read_word(ply)) return 0; + property->length_type = + (e_ply_type)ply_find_string(BWORD(ply), ply_type_list); + if (property->length_type == (e_ply_type)(-1)) return 0; + if (!ply_read_word(ply)) return 0; + property->value_type = + (e_ply_type)ply_find_string(BWORD(ply), ply_type_list); + if (property->value_type == (e_ply_type)(-1)) return 0; + } + /* get property name */ + if (!ply_read_word(ply)) return 0; + strcpy(property->name, BWORD(ply)); + if (!ply_read_word(ply)) return 0; + return 1; +} + +static int ply_read_header_element(p_ply ply) { + p_ply_element element = NULL; + long dummy; + assert(ply && ply->fp && ply->io_mode == PLY_READ); + if (strcmp(BWORD(ply), "element")) return 0; + /* allocate room for new element */ + element = ply_grow_element(ply); + if (!element) return 0; + /* get element name */ + if (!ply_read_word(ply)) return 0; + strcpy(element->name, BWORD(ply)); + /* get number of elements of this type */ + if (!ply_read_word(ply)) return 0; + if (sscanf(BWORD(ply), "%ld", &dummy) != 1) { + ply_ferror(ply, "Expected number got '%s'", BWORD(ply)); + return 0; + } + element->ninstances = dummy; + /* get all properties for this element */ + if (!ply_read_word(ply)) return 0; + while (ply_read_header_property(ply) || ply_read_header_comment(ply) || + ply_read_header_obj_info(ply)) + /* do nothing */; + return 1; +} + +static void ply_error_cb(p_ply ply, const char *message) { + (void)ply; + fprintf(stderr, "RPly: %s\n", message); +} + +static void ply_ferror(p_ply ply, const char *fmt, ...) { + char buffer[1024]; + va_list ap; + va_start(ap, fmt); + vsprintf(buffer, fmt, ap); + va_end(ap); + ply->error_cb(ply, buffer); +} + +static e_ply_storage_mode ply_arch_endian(void) { + unsigned long i = 1; + unsigned char *s = (unsigned char *)&i; + if (*s == 1) + return PLY_LITTLE_ENDIAN; + else + return PLY_BIG_ENDIAN; +} + +static int ply_type_check(void) { + assert(sizeof(t_ply_int8) == 1); + assert(sizeof(t_ply_uint8) == 1); + assert(sizeof(t_ply_int16) == 2); + assert(sizeof(t_ply_uint16) == 2); + assert(sizeof(t_ply_int32) == 4); + assert(sizeof(t_ply_uint32) == 4); + assert(sizeof(float) == 4); + assert(sizeof(double) == 8); + if (sizeof(t_ply_int8) != 1) return 0; + if (sizeof(t_ply_uint8) != 1) return 0; + if (sizeof(t_ply_int16) != 2) return 0; + if (sizeof(t_ply_uint16) != 2) return 0; + if (sizeof(t_ply_int32) != 4) return 0; + if (sizeof(t_ply_uint32) != 4) return 0; + if (sizeof(float) != 4) return 0; + if (sizeof(double) != 8) return 0; + return 1; +} + +/* ---------------------------------------------------------------------- + * Output handlers + * ---------------------------------------------------------------------- */ +static int oascii_int8(p_ply ply, double value) { + if (value > PLY_INT8_MAX || value < PLY_INT8_MIN) return 0; + return fprintf(ply->fp, "%d", (t_ply_int8)value) > 0; +} + +static int oascii_uint8(p_ply ply, double value) { + if (value > PLY_UINT8_MAX || value < 0) return 0; + return fprintf(ply->fp, "%d", (t_ply_uint8)value) > 0; +} + +static int oascii_int16(p_ply ply, double value) { + if (value > PLY_INT16_MAX || value < PLY_INT16_MIN) return 0; + return fprintf(ply->fp, "%d", (t_ply_int16)value) > 0; +} + +static int oascii_uint16(p_ply ply, double value) { + if (value > PLY_UINT16_MAX || value < 0) return 0; + return fprintf(ply->fp, "%d", (t_ply_uint16)value) > 0; +} + +static int oascii_int32(p_ply ply, double value) { + if (value > PLY_INT32_MAX || value < PLY_INT32_MIN) return 0; + return fprintf(ply->fp, "%d", (t_ply_int32)value) > 0; +} + +static int oascii_uint32(p_ply ply, double value) { + if (value > PLY_UINT32_MAX || value < 0) return 0; + return fprintf(ply->fp, "%d", (t_ply_uint32)value) > 0; +} + +static int oascii_float32(p_ply ply, double value) { + if (value < -FLT_MAX || value > FLT_MAX) return 0; + return fprintf(ply->fp, "%g", (float)value) > 0; +} + +static int oascii_float64(p_ply ply, double value) { + if (value < -DBL_MAX || value > DBL_MAX) return 0; + return fprintf(ply->fp, "%g", value) > 0; +} + +static int obinary_int8(p_ply ply, double value) { + t_ply_int8 int8 = (t_ply_int8)value; + if (value > PLY_INT8_MAX || value < PLY_INT8_MIN) return 0; + return ply->odriver->ochunk(ply, &int8, sizeof(int8)); +} + +static int obinary_uint8(p_ply ply, double value) { + t_ply_uint8 uint8 = (t_ply_uint8)value; + if (value > PLY_UINT8_MAX || value < 0) return 0; + return ply->odriver->ochunk(ply, &uint8, sizeof(uint8)); +} + +static int obinary_int16(p_ply ply, double value) { + t_ply_int16 int16 = (t_ply_int16)value; + if (value > PLY_INT16_MAX || value < PLY_INT16_MIN) return 0; + return ply->odriver->ochunk(ply, &int16, sizeof(int16)); +} + +static int obinary_uint16(p_ply ply, double value) { + t_ply_uint16 uint16 = (t_ply_uint16)value; + if (value > PLY_UINT16_MAX || value < 0) return 0; + return ply->odriver->ochunk(ply, &uint16, sizeof(uint16)); +} + +static int obinary_int32(p_ply ply, double value) { + t_ply_int32 int32 = (t_ply_int32)value; + if (value > PLY_INT32_MAX || value < PLY_INT32_MIN) return 0; + return ply->odriver->ochunk(ply, &int32, sizeof(int32)); +} + +static int obinary_uint32(p_ply ply, double value) { + t_ply_uint32 uint32 = (t_ply_uint32)value; + if (value > PLY_UINT32_MAX || value < 0) return 0; + return ply->odriver->ochunk(ply, &uint32, sizeof(uint32)); +} + +static int obinary_float32(p_ply ply, double value) { + float float32 = (float)value; + if (value > FLT_MAX || value < -FLT_MAX) return 0; + return ply->odriver->ochunk(ply, &float32, sizeof(float32)); +} + +static int obinary_float64(p_ply ply, double value) { + return ply->odriver->ochunk(ply, &value, sizeof(value)); +} + +/* ---------------------------------------------------------------------- + * Input handlers + * ---------------------------------------------------------------------- */ +static int iascii_int8(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtol(BWORD(ply), &end, 10); + if (*end || *value > PLY_INT8_MAX || *value < PLY_INT8_MIN) return 0; + return 1; +} + +static int iascii_uint8(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtol(BWORD(ply), &end, 10); + if (*end || *value > PLY_UINT8_MAX || *value < 0) return 0; + return 1; +} + +static int iascii_int16(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtol(BWORD(ply), &end, 10); + if (*end || *value > PLY_INT16_MAX || *value < PLY_INT16_MIN) return 0; + return 1; +} + +static int iascii_uint16(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtol(BWORD(ply), &end, 10); + if (*end || *value > PLY_UINT16_MAX || *value < 0) return 0; + return 1; +} + +static int iascii_int32(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtol(BWORD(ply), &end, 10); + if (*end || *value > PLY_INT32_MAX || *value < PLY_INT32_MIN) return 0; + return 1; +} + +static int iascii_uint32(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtol(BWORD(ply), &end, 10); + if (*end || *value > PLY_UINT32_MAX || *value < 0) return 0; + return 1; +} + +static int iascii_float32(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtod(BWORD(ply), &end); + if (*end || *value < -FLT_MAX || *value > FLT_MAX) return 0; + return 1; +} + +static int iascii_float64(p_ply ply, double *value) { + char *end; + if (!ply_read_word(ply)) return 0; + *value = strtod(BWORD(ply), &end); + if (*end || *value < -DBL_MAX || *value > DBL_MAX) return 0; + return 1; +} + +static int ibinary_int8(p_ply ply, double *value) { + t_ply_int8 int8; + if (!ply->idriver->ichunk(ply, &int8, 1)) return 0; + *value = int8; + return 1; +} + +static int ibinary_uint8(p_ply ply, double *value) { + t_ply_uint8 uint8; + if (!ply->idriver->ichunk(ply, &uint8, 1)) return 0; + *value = uint8; + return 1; +} + +static int ibinary_int16(p_ply ply, double *value) { + t_ply_int16 int16; + if (!ply->idriver->ichunk(ply, &int16, sizeof(int16))) return 0; + *value = int16; + return 1; +} + +static int ibinary_uint16(p_ply ply, double *value) { + t_ply_uint16 uint16; + if (!ply->idriver->ichunk(ply, &uint16, sizeof(uint16))) return 0; + *value = uint16; + return 1; +} + +static int ibinary_int32(p_ply ply, double *value) { + t_ply_int32 int32; + if (!ply->idriver->ichunk(ply, &int32, sizeof(int32))) return 0; + *value = int32; + return 1; +} + +static int ibinary_uint32(p_ply ply, double *value) { + t_ply_uint32 uint32; + if (!ply->idriver->ichunk(ply, &uint32, sizeof(uint32))) return 0; + *value = uint32; + return 1; +} + +static int ibinary_float32(p_ply ply, double *value) { + float float32; + if (!ply->idriver->ichunk(ply, &float32, sizeof(float32))) return 0; + *value = float32; + return 1; +} + +static int ibinary_float64(p_ply ply, double *value) { + return ply->idriver->ichunk(ply, value, sizeof(double)); +} + +/* ---------------------------------------------------------------------- + * Constants + * ---------------------------------------------------------------------- */ + +namespace { +t_ply_idriver ply_idriver_ascii = { + {iascii_int8, iascii_uint8, iascii_int16, iascii_uint16, iascii_int32, + iascii_uint32, iascii_float32, iascii_float64, iascii_int8, iascii_uint8, + iascii_int16, iascii_uint16, iascii_int32, iascii_uint32, iascii_float32, + iascii_float64}, /* order matches e_ply_type enum */ + NULL, + "ascii input"}; + +t_ply_idriver ply_idriver_binary = { + {ibinary_int8, ibinary_uint8, ibinary_int16, ibinary_uint16, ibinary_int32, + ibinary_uint32, ibinary_float32, ibinary_float64, ibinary_int8, + ibinary_uint8, ibinary_int16, ibinary_uint16, ibinary_int32, + ibinary_uint32, ibinary_float32, + ibinary_float64}, /* order matches e_ply_type enum */ + ply_read_chunk, + "binary input"}; + +t_ply_idriver ply_idriver_binary_reverse = { + {ibinary_int8, ibinary_uint8, ibinary_int16, ibinary_uint16, ibinary_int32, + ibinary_uint32, ibinary_float32, ibinary_float64, ibinary_int8, + ibinary_uint8, ibinary_int16, ibinary_uint16, ibinary_int32, + ibinary_uint32, ibinary_float32, + ibinary_float64}, /* order matches e_ply_type enum */ + ply_read_chunk_reverse, + "reverse binary input"}; + +t_ply_odriver ply_odriver_ascii = { + {oascii_int8, oascii_uint8, oascii_int16, oascii_uint16, oascii_int32, + oascii_uint32, oascii_float32, oascii_float64, oascii_int8, oascii_uint8, + oascii_int16, oascii_uint16, oascii_int32, oascii_uint32, oascii_float32, + oascii_float64}, /* order matches e_ply_type enum */ + NULL, + "ascii output"}; + +t_ply_odriver ply_odriver_binary = { + {obinary_int8, obinary_uint8, obinary_int16, obinary_uint16, obinary_int32, + obinary_uint32, obinary_float32, obinary_float64, obinary_int8, + obinary_uint8, obinary_int16, obinary_uint16, obinary_int32, + obinary_uint32, obinary_float32, + obinary_float64}, /* order matches e_ply_type enum */ + ply_write_chunk, + "binary output"}; + +t_ply_odriver ply_odriver_binary_reverse = { + {obinary_int8, obinary_uint8, obinary_int16, obinary_uint16, obinary_int32, + obinary_uint32, obinary_float32, obinary_float64, obinary_int8, + obinary_uint8, obinary_int16, obinary_uint16, obinary_int32, + obinary_uint32, obinary_float32, + obinary_float64}, /* order matches e_ply_type enum */ + ply_write_chunk_reverse, + "reverse binary output"}; +}; + +/* ---------------------------------------------------------------------- + * Copyright (C) 2003-2011 Diego Nehab. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * ---------------------------------------------------------------------- */ diff --git a/src/ext/rply/rply.h b/src/ext/rply/rply.h new file mode 100644 index 00000000..ca738d6a --- /dev/null +++ b/src/ext/rply/rply.h @@ -0,0 +1,389 @@ +#if defined(_MSC_VER) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#endif + +#ifndef PBRT_EXT_RPLY_H +#define PBRT_EXT_RPLY_H + +// ext/rply.h* +/* ---------------------------------------------------------------------- + * RPly library, read/write PLY files + * Diego Nehab, IMPA + * http://www.impa.br/~diego/software/rply + * + * This library is distributed under the MIT License. See notice + * at the end of this file. + * ---------------------------------------------------------------------- */ + +#define RPLY_VERSION "RPly 1.1.3" +#define RPLY_COPYRIGHT "Copyright (C) 2003-2013 Diego Nehab" +#define RPLY_AUTHORS "Diego Nehab" + +/* ---------------------------------------------------------------------- + * Types + * ---------------------------------------------------------------------- */ +/* structures are opaque */ +typedef struct t_ply_ *p_ply; +typedef struct t_ply_element_ *p_ply_element; +typedef struct t_ply_property_ *p_ply_property; +typedef struct t_ply_argument_ *p_ply_argument; + +/* ply format mode type */ +typedef enum e_ply_storage_mode_ { + PLY_BIG_ENDIAN, + PLY_LITTLE_ENDIAN, + PLY_ASCII, + PLY_DEFAULT /* has to be the last in enum */ +} e_ply_storage_mode; /* order matches ply_storage_mode_list */ + +/* ply data type */ +typedef enum e_ply_type { + PLY_INT8, + PLY_UINT8, + PLY_INT16, + PLY_UINT16, + PLY_INT32, + PLY_UIN32, + PLY_FLOAT32, + PLY_FLOAT64, + PLY_CHAR, + PLY_UCHAR, + PLY_SHORT, + PLY_USHORT, + PLY_INT, + PLY_UINT, + PLY_FLOAT, + PLY_DOUBLE, + PLY_LIST /* has to be the last in enum */ +} e_ply_type; /* order matches ply_type_list */ + +/* ---------------------------------------------------------------------- + * Error callback prototype + * + * message: error message + * ply: handle returned by ply_open or ply_create + * ---------------------------------------------------------------------- */ +typedef void (*p_ply_error_cb)(p_ply ply, const char *message); + +/* ---------------------------------------------------------------------- + * Gets user data from within an error callback + * + * ply: handle returned by ply_open or ply_create + * idata,pdata: contextual information set in ply_open or ply_create + * ---------------------------------------------------------------------- */ +int ply_get_ply_user_data(p_ply ply, void **pdata, long *idata); + +/* ---------------------------------------------------------------------- + * Opens a PLY file for reading (fails if file is not a PLY file) + * + * name: file name + * error_cb: error callback function + * idata,pdata: contextual information available to users + * + * Returns 1 if successful, 0 otherwise + * ---------------------------------------------------------------------- */ +p_ply ply_open(const char *name, p_ply_error_cb error_cb, long idata, + void *pdata); + +/* ---------------------------------------------------------------------- + * Reads and parses the header of a PLY file returned by ply_open + * + * ply: handle returned by ply_open + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_read_header(p_ply ply); + +/* ---------------------------------------------------------------------- + * Property reading callback prototype + * + * argument: parameters for property being processed when callback is called + * + * Returns 1 if should continue processing file, 0 if should abort. + * ---------------------------------------------------------------------- */ +typedef int (*p_ply_read_cb)(p_ply_argument argument); + +/* ---------------------------------------------------------------------- + * Sets up callbacks for property reading after header was parsed + * + * ply: handle returned by ply_open + * element_name: element where property is + * property_name: property to associate element with + * read_cb: function to be called for each property value + * pdata/idata: user data that will be passed to callback + * + * Returns 0 if no element or no property in element, returns the + * number of element instances otherwise. + * ---------------------------------------------------------------------- */ +long ply_set_read_cb(p_ply ply, const char *element_name, + const char *property_name, p_ply_read_cb read_cb, + void *pdata, long idata); + +/* ---------------------------------------------------------------------- + * Returns information about the element originating a callback + * + * argument: handle to argument + * element: receives a the element handle (if non-null) + * instance_index: receives the index of the current element instance + * (if non-null) + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_get_argument_element(p_ply_argument argument, p_ply_element *element, + long *instance_index); + +/* ---------------------------------------------------------------------- + * Returns information about the property originating a callback + * + * argument: handle to argument + * property: receives the property handle (if non-null) + * length: receives the number of values in this property (if non-null) + * value_index: receives the index of current property value (if non-null) + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_get_argument_property(p_ply_argument argument, p_ply_property *property, + long *length, long *value_index); + +/* ---------------------------------------------------------------------- + * Returns user data associated with callback + * + * pdata: receives a copy of user custom data pointer (if non-null) + * idata: receives a copy of user custom data integer (if non-null) + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_get_argument_user_data(p_ply_argument argument, void **pdata, + long *idata); + +/* ---------------------------------------------------------------------- + * Returns the value associated with a callback + * + * argument: handle to argument + * + * Returns the current data item + * ---------------------------------------------------------------------- */ +double ply_get_argument_value(p_ply_argument argument); + +/* ---------------------------------------------------------------------- + * Reads all elements and properties calling the callbacks defined with + * calls to ply_set_read_cb + * + * ply: handle returned by ply_open + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_read(p_ply ply); + +/* ---------------------------------------------------------------------- + * Iterates over all elements by returning the next element. + * Call with NULL to return handle to first element. + * + * ply: handle returned by ply_open + * last: handle of last element returned (NULL for first element) + * + * Returns element if successfull or NULL if no more elements + * ---------------------------------------------------------------------- */ +p_ply_element ply_get_next_element(p_ply ply, p_ply_element last); + +/* ---------------------------------------------------------------------- + * Iterates over all comments by returning the next comment. + * Call with NULL to return pointer to first comment. + * + * ply: handle returned by ply_open + * last: pointer to last comment returned (NULL for first comment) + * + * Returns comment if successfull or NULL if no more comments + * ---------------------------------------------------------------------- */ +const char *ply_get_next_comment(p_ply ply, const char *last); + +/* ---------------------------------------------------------------------- + * Iterates over all obj_infos by returning the next obj_info. + * Call with NULL to return pointer to first obj_info. + * + * ply: handle returned by ply_open + * last: pointer to last obj_info returned (NULL for first obj_info) + * + * Returns obj_info if successfull or NULL if no more obj_infos + * ---------------------------------------------------------------------- */ +const char *ply_get_next_obj_info(p_ply ply, const char *last); + +/* ---------------------------------------------------------------------- + * Returns information about an element + * + * element: element of interest + * name: receives a pointer to internal copy of element name (if non-null) + * ninstances: receives the number of instances of this element (if non-null) + * + * Returns 1 if successfull or 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_get_element_info(p_ply_element element, const char **name, + long *ninstances); + +/* ---------------------------------------------------------------------- + * Iterates over all properties by returning the next property. + * Call with NULL to return handle to first property. + * + * element: handle of element with the properties of interest + * last: handle of last property returned (NULL for first property) + * + * Returns element if successfull or NULL if no more properties + * ---------------------------------------------------------------------- */ +p_ply_property ply_get_next_property(p_ply_element element, + p_ply_property last); + +/* ---------------------------------------------------------------------- + * Returns information about a property + * + * property: handle to property of interest + * name: receives a pointer to internal copy of property name (if non-null) + * type: receives the property type (if non-null) + * length_type: for list properties, receives the scalar type of + * the length field (if non-null) + * value_type: for list properties, receives the scalar type of the value + * fields (if non-null) + * + * Returns 1 if successfull or 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_get_property_info(p_ply_property property, const char **name, + e_ply_type *type, e_ply_type *length_type, + e_ply_type *value_type); + +/* ---------------------------------------------------------------------- + * Creates new PLY file + * + * name: file name + * storage_mode: file format mode + * + * Returns handle to PLY file if successfull, NULL otherwise + * ---------------------------------------------------------------------- */ +p_ply ply_create(const char *name, e_ply_storage_mode storage_mode, + p_ply_error_cb error_cb, long idata, void *pdata); + +/* ---------------------------------------------------------------------- + * Adds a new element to the PLY file created by ply_create + * + * ply: handle returned by ply_create + * name: name of new element + * ninstances: number of element of this time in file + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_add_element(p_ply ply, const char *name, long ninstances); + +/* ---------------------------------------------------------------------- + * Adds a new property to the last element added by ply_add_element + * + * ply: handle returned by ply_create + * name: name of new property + * type: property type + * length_type: scalar type of length field of a list property + * value_type: scalar type of value fields of a list property + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_add_property(p_ply ply, const char *name, e_ply_type type, + e_ply_type length_type, e_ply_type value_type); + +/* ---------------------------------------------------------------------- + * Adds a new list property to the last element added by ply_add_element + * + * ply: handle returned by ply_create + * name: name of new property + * length_type: scalar type of length field of a list property + * value_type: scalar type of value fields of a list property + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_add_list_property(p_ply ply, const char *name, e_ply_type length_type, + e_ply_type value_type); + +/* ---------------------------------------------------------------------- + * Adds a new property to the last element added by ply_add_element + * + * ply: handle returned by ply_create + * name: name of new property + * type: property type + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_add_scalar_property(p_ply ply, const char *name, e_ply_type type); + +/* ---------------------------------------------------------------------- + * Adds a new comment item + * + * ply: handle returned by ply_create + * comment: pointer to string with comment text + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_add_comment(p_ply ply, const char *comment); + +/* ---------------------------------------------------------------------- + * Adds a new obj_info item + * + * ply: handle returned by ply_create + * comment: pointer to string with obj_info data + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_add_obj_info(p_ply ply, const char *obj_info); + +/* ---------------------------------------------------------------------- + * Writes the PLY file header after all element and properties have been + * defined by calls to ply_add_element and ply_add_property + * + * ply: handle returned by ply_create + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_write_header(p_ply ply); + +/* ---------------------------------------------------------------------- + * Writes one property value, in the order they should be written to the + * file. For each element type, write all elements of that type in order. + * For each element, write all its properties in order. For scalar + * properties, just write the value. For list properties, write the length + * and then each of the values. + * + * ply: handle returned by ply_create + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_write(p_ply ply, double value); + +/* ---------------------------------------------------------------------- + * Closes a PLY file handle. Releases all memory used by handle + * + * ply: handle to be closed. + * + * Returns 1 if successfull, 0 otherwise + * ---------------------------------------------------------------------- */ +int ply_close(p_ply ply); + +/* ---------------------------------------------------------------------- + * Copyright (C) 2003-2011 Diego Nehab. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * ---------------------------------------------------------------------- */ + +#endif // PBRT_EXT_RPLY_H diff --git a/src/ext/skymodel/ArHosekSkyModel.c b/src/ext/skymodel/ArHosekSkyModel.c new file mode 100644 index 00000000..8f37ca8b --- /dev/null +++ b/src/ext/skymodel/ArHosekSkyModel.c @@ -0,0 +1,825 @@ +/* +This source is published under the following 3-clause BSD license. + +Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * None of the names of the contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* ============================================================================ + +This file is part of a sample implementation of the analytical skylight and +solar radiance models presented in the SIGGRAPH 2012 paper + + + "An Analytic Model for Full Spectral Sky-Dome Radiance" + +and the 2013 IEEE CG&A paper + + "Adding a Solar Radiance Function to the Hosek Skylight Model" + + both by + + Lukas Hosek and Alexander Wilkie + Charles University in Prague, Czech Republic + + + Version: 1.4a, February 22nd, 2013 + +Version history: + +1.4a February 22nd, 2013 + Removed unnecessary and counter-intuitive solar radius parameters + from the interface of the colourspace sky dome initialisation functions. + +1.4 February 11th, 2013 + Fixed a bug which caused the relative brightness of the solar disc + and the sky dome to be off by a factor of about 6. The sun was too + bright: this affected both normal and alien sun scenarios. The + coefficients of the solar radiance function were changed to fix this. + +1.3 January 21st, 2013 (not released to the public) + Added support for solar discs that are not exactly the same size as + the terrestrial sun. Also added support for suns with a different + emission spectrum ("Alien World" functionality). + +1.2a December 18th, 2012 + Fixed a mistake and some inaccuracies in the solar radiance function + explanations found in ArHosekSkyModel.h. The actual source code is + unchanged compared to version 1.2. + +1.2 December 17th, 2012 + Native RGB data and a solar radiance function that matches the turbidity + conditions were added. + +1.1 September 2012 + The coefficients of the spectral model are now scaled so that the output + is given in physical units: W / (m^-2 * sr * nm). Also, the output of the + XYZ model is now no longer scaled to the range [0...1]. Instead, it is + the result of a simple conversion from spectral data via the CIE 2 degree + standard observer matching functions. Therefore, after multiplication + with 683 lm / W, the Y channel now corresponds to luminance in lm. + +1.0 May 11th, 2012 + Initial release. + + +Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if +an updated version of this code has been published! + +============================================================================ */ + +/* + +All instructions on how to use this code are in the accompanying header file. + +*/ + +#include "ArHosekSkyModel.h" +#include "ArHosekSkyModelData_Spectral.h" +#include "ArHosekSkyModelData_CIEXYZ.h" +#include "ArHosekSkyModelData_RGB.h" +#include +#include +#include +#include + +// Some macro definitions that occur elsewhere in ART, and that have to be +// replicated to make this a stand-alone module. + +#ifndef NIL +#define NIL 0 +#endif + +#ifndef MATH_PI +#define MATH_PI 3.141592653589793 +#endif + +#ifndef MATH_DEG_TO_RAD +#define MATH_DEG_TO_RAD ( MATH_PI / 180.0 ) +#endif + +#ifndef MATH_RAD_TO_DEG +#define MATH_RAD_TO_DEG ( 180.0 / MATH_PI ) +#endif + +#ifndef DEGREES +#define DEGREES * MATH_DEG_TO_RAD +#endif + +#ifndef TERRESTRIAL_SOLAR_RADIUS +#define TERRESTRIAL_SOLAR_RADIUS ( ( 0.51 DEGREES ) / 2.0 ) +#endif + +#ifndef ALLOC +#define ALLOC(_struct) ((_struct *)malloc(sizeof(_struct))) +#endif + +// internal definitions + +typedef double *ArHosekSkyModel_Dataset; +typedef double *ArHosekSkyModel_Radiance_Dataset; + +// internal functions + +void ArHosekSkyModel_CookConfiguration( + ArHosekSkyModel_Dataset dataset, + ArHosekSkyModelConfiguration config, + double turbidity, + double albedo, + double solar_elevation + ) +{ + double * elev_matrix; + + int int_turbidity = (int)turbidity; + double turbidity_rem = turbidity - (double)int_turbidity; + + solar_elevation = pow(solar_elevation / (MATH_PI / 2.0), (1.0 / 3.0)); + + // alb 0 low turb + + elev_matrix = dataset + ( 9 * 6 * (int_turbidity-1) ); + + unsigned int i; + for( i = 0; i < 9; ++i ) + { + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + config[i] = + (1.0-albedo) * (1.0 - turbidity_rem) + * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + + 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + + pow(solar_elevation, 5.0) * elev_matrix[i+45]); + } + + // alb 1 low turb + elev_matrix = dataset + (9*6*10 + 9*6*(int_turbidity-1)); + for( i = 0; i < 9; ++i) + { + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + config[i] += + (albedo) * (1.0 - turbidity_rem) + * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + + 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + + pow(solar_elevation, 5.0) * elev_matrix[i+45]); + } + + if(int_turbidity == 10) + return; + + // alb 0 high turb + elev_matrix = dataset + (9*6*(int_turbidity)); + for( i = 0; i < 9; ++i) + { + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + config[i] += + (1.0-albedo) * (turbidity_rem) + * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + + 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + + pow(solar_elevation, 5.0) * elev_matrix[i+45]); + } + + // alb 1 high turb + elev_matrix = dataset + (9*6*10 + 9*6*(int_turbidity)); + for( i = 0; i < 9; ++i) + { + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + config[i] += + (albedo) * (turbidity_rem) + * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i] + + 5.0 * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] + + pow(solar_elevation, 5.0) * elev_matrix[i+45]); + } +} + +double ArHosekSkyModel_CookRadianceConfiguration( + ArHosekSkyModel_Radiance_Dataset dataset, + double turbidity, + double albedo, + double solar_elevation + ) +{ + double* elev_matrix; + + int int_turbidity = (int)turbidity; + double turbidity_rem = turbidity - (double)int_turbidity; + double res; + solar_elevation = pow(solar_elevation / (MATH_PI / 2.0), (1.0 / 3.0)); + + // alb 0 low turb + elev_matrix = dataset + (6*(int_turbidity-1)); + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + res = (1.0-albedo) * (1.0 - turbidity_rem) * + ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + + 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + + pow(solar_elevation, 5.0) * elev_matrix[5]); + + // alb 1 low turb + elev_matrix = dataset + (6*10 + 6*(int_turbidity-1)); + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + res += (albedo) * (1.0 - turbidity_rem) * + ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + + 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + + pow(solar_elevation, 5.0) * elev_matrix[5]); + if(int_turbidity == 10) + return res; + + // alb 0 high turb + elev_matrix = dataset + (6*(int_turbidity)); + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + res += (1.0-albedo) * (turbidity_rem) * + ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + + 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + + pow(solar_elevation, 5.0) * elev_matrix[5]); + + // alb 1 high turb + elev_matrix = dataset + (6*10 + 6*(int_turbidity)); + //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4; + res += (albedo) * (turbidity_rem) * + ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] + + 5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] + + 10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] + + 10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] + + 5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] + + pow(solar_elevation, 5.0) * elev_matrix[5]); + return res; +} + +double ArHosekSkyModel_GetRadianceInternal( + ArHosekSkyModelConfiguration configuration, + double theta, + double gamma + ) +{ + const double expM = exp(configuration[4] * gamma); + const double rayM = cos(gamma)*cos(gamma); + const double mieM = (1.0 + cos(gamma)*cos(gamma)) / pow((1.0 + configuration[8]*configuration[8] - 2.0*configuration[8]*cos(gamma)), 1.5); + const double zenith = sqrt(cos(theta)); + + return (1.0 + configuration[0] * exp(configuration[1] / (cos(theta) + 0.01))) * + (configuration[2] + configuration[3] * expM + configuration[5] * rayM + configuration[6] * mieM + configuration[7] * zenith); +} + +// spectral version + +ArHosekSkyModelState * arhosekskymodelstate_alloc_init( + const double solar_elevation, + const double atmospheric_turbidity, + const double ground_albedo + ) +{ + ArHosekSkyModelState * state = ALLOC(ArHosekSkyModelState); + + state->solar_radius = ( 0.51 DEGREES ) / 2.0; + state->turbidity = atmospheric_turbidity; + state->albedo = ground_albedo; + state->elevation = solar_elevation; + + unsigned int wl; + for( wl = 0; wl < 11; ++wl ) + { + ArHosekSkyModel_CookConfiguration( + datasets[wl], + state->configs[wl], + atmospheric_turbidity, + ground_albedo, + solar_elevation + ); + + state->radiances[wl] = + ArHosekSkyModel_CookRadianceConfiguration( + datasetsRad[wl], + atmospheric_turbidity, + ground_albedo, + solar_elevation + ); + + state->emission_correction_factor_sun[wl] = 1.0; + state->emission_correction_factor_sky[wl] = 1.0; + } + + return state; +} + +// 'blackbody_scaling_factor' +// +// Fudge factor, computed in Mathematica, to scale the results of the +// following function to match the solar radiance spectrum used in the +// original simulation. The scaling is done so their integrals over the +// range from 380.0 to 720.0 nanometers match for a blackbody temperature +// of 5800 K. +// Which leaves the original spectrum being less bright overall than the 5.8k +// blackbody radiation curve if the ultra-violet part of the spectrum is +// also considered. But the visible brightness should be very similar. + +const double blackbody_scaling_factor = 3.19992 * 10E-11; + +// 'art_blackbody_dd_value()' function +// +// Blackbody radiance, Planck's formula + +double art_blackbody_dd_value( + const double temperature, + const double lambda + ) +{ + double c1 = 3.74177 * 10E-17; + double c2 = 0.0143878; + double value; + + value = ( c1 / ( pow( lambda, 5.0 ) ) ) + * ( 1.0 / ( exp( c2 / ( lambda * temperature ) ) - 1.0 ) ); + + return value; +} + +// 'originalSolarRadianceTable[]' +// +// The solar spectrum incident at the top of the atmosphere, as it was used +// in the brute force path tracer that generated the reference results the +// model was fitted to. We need this as the yardstick to compare any altered +// Blackbody emission spectra for alien world stars to. + +// This is just the data from the Preetham paper, extended into the UV range. + +const double originalSolarRadianceTable[] = +{ + 7500.0, + 12500.0, + 21127.5, + 26760.5, + 30663.7, + 27825.0, + 25503.8, + 25134.2, + 23212.1, + 21526.7, + 19870.8 +}; + +ArHosekSkyModelState * arhosekskymodelstate_alienworld_alloc_init( + const double solar_elevation, + const double solar_intensity, + const double solar_surface_temperature_kelvin, + const double atmospheric_turbidity, + const double ground_albedo + ) +{ + ArHosekSkyModelState * state = ALLOC(ArHosekSkyModelState); + + state->turbidity = atmospheric_turbidity; + state->albedo = ground_albedo; + state->elevation = solar_elevation; + + unsigned int wl; + for( wl = 0; wl < 11; ++wl ) + { + // Basic init as for the normal scenario + + ArHosekSkyModel_CookConfiguration( + datasets[wl], + state->configs[wl], + atmospheric_turbidity, + ground_albedo, + solar_elevation + ); + + state->radiances[wl] = + ArHosekSkyModel_CookRadianceConfiguration( + datasetsRad[wl], + atmospheric_turbidity, + ground_albedo, + solar_elevation + ); + + // The wavelength of this band in nanometers + + double owl = ( 320.0 + 40.0 * wl ) * 10E-10; + + // The original intensity we just computed + + double osr = originalSolarRadianceTable[wl]; + + // The intensity of a blackbody with the desired temperature + // The fudge factor described above is used to make sure the BB + // function matches the used radiance data reasonably well + // in magnitude. + + double nsr = + art_blackbody_dd_value(solar_surface_temperature_kelvin, owl) + * blackbody_scaling_factor; + + // Correction factor for this waveband is simply the ratio of + // the two. + + state->emission_correction_factor_sun[wl] = nsr / osr; + } + + // We then compute the average correction factor of all wavebands. + + // Theoretically, some weighting to favour wavelengths human vision is + // more sensitive to could be introduced here - think V(lambda). But + // given that the whole effort is not *that* accurate to begin with (we + // are talking about the appearance of alien worlds, after all), simple + // averaging over the visible wavelenghts (! - this is why we start at + // WL #2, and only use 2-11) seems like a sane first approximation. + + double correctionFactor = 0.0; + + unsigned int i; + for ( i = 2; i < 11; i++ ) + { + correctionFactor += + state->emission_correction_factor_sun[i]; + } + + // This is the average ratio in emitted energy between our sun, and an + // equally large sun with the blackbody spectrum we requested. + + // Division by 9 because we only used 9 of the 11 wavelengths for this + // (see above). + + double ratio = correctionFactor / 9.0; + + // This ratio is then used to determine the radius of the alien sun + // on the sky dome. The additional factor 'solar_intensity' can be used + // to make the alien sun brighter or dimmer compared to our sun. + + state->solar_radius = + ( sqrt( solar_intensity ) * TERRESTRIAL_SOLAR_RADIUS ) + / sqrt( ratio ); + + // Finally, we have to reduce the scaling factor of the sky by the + // ratio used to scale the solar disc size. The rationale behind this is + // that the scaling factors apply to the new blackbody spectrum, which + // can be more or less bright than the one our sun emits. However, we + // just scaled the size of the alien solar disc so it is roughly as + // bright (in terms of energy emitted) as the terrestrial sun. So the sky + // dome has to be reduced in brightness appropriately - but not in an + // uniform fashion across wavebands. If we did that, the sky colour would + // be wrong. + + for ( i = 0; i < 11; i++ ) + { + state->emission_correction_factor_sky[i] = + solar_intensity + * state->emission_correction_factor_sun[i] / ratio; + } + + return state; +} + +void arhosekskymodelstate_free( + ArHosekSkyModelState * state + ) +{ + free(state); +} + +double arhosekskymodel_radiance( + ArHosekSkyModelState * state, + double theta, + double gamma, + double wavelength + ) +{ + int low_wl = (wavelength - 320.0 ) / 40.0; + + if ( low_wl < 0 || low_wl >= 11 ) + return 0.0f; + + double interp = fmod((wavelength - 320.0 ) / 40.0, 1.0); + + double val_low = + ArHosekSkyModel_GetRadianceInternal( + state->configs[low_wl], + theta, + gamma + ) + * state->radiances[low_wl] + * state->emission_correction_factor_sky[low_wl]; + + if ( interp < 1e-6 ) + return val_low; + + double result = ( 1.0 - interp ) * val_low; + + if ( low_wl+1 < 11 ) + { + result += + interp + * ArHosekSkyModel_GetRadianceInternal( + state->configs[low_wl+1], + theta, + gamma + ) + * state->radiances[low_wl+1] + * state->emission_correction_factor_sky[low_wl+1]; + } + + return result; +} + + +// xyz and rgb versions + +ArHosekSkyModelState * arhosek_xyz_skymodelstate_alloc_init( + const double turbidity, + const double albedo, + const double elevation + ) +{ + ArHosekSkyModelState * state = ALLOC(ArHosekSkyModelState); + + state->solar_radius = TERRESTRIAL_SOLAR_RADIUS; + state->turbidity = turbidity; + state->albedo = albedo; + state->elevation = elevation; + + unsigned int channel; + for( channel = 0; channel < 3; ++channel ) + { + ArHosekSkyModel_CookConfiguration( + datasetsXYZ[channel], + state->configs[channel], + turbidity, + albedo, + elevation + ); + + state->radiances[channel] = + ArHosekSkyModel_CookRadianceConfiguration( + datasetsXYZRad[channel], + turbidity, + albedo, + elevation + ); + } + + return state; +} + + +ArHosekSkyModelState * arhosek_rgb_skymodelstate_alloc_init( + const double turbidity, + const double albedo, + const double elevation + ) +{ + ArHosekSkyModelState* state = ALLOC(ArHosekSkyModelState); + + state->solar_radius = TERRESTRIAL_SOLAR_RADIUS; + state->turbidity = turbidity; + state->albedo = albedo; + state->elevation = elevation; + + unsigned int channel; + for( channel = 0; channel < 3; ++channel ) + { + ArHosekSkyModel_CookConfiguration( + datasetsRGB[channel], + state->configs[channel], + turbidity, + albedo, + elevation + ); + + state->radiances[channel] = + ArHosekSkyModel_CookRadianceConfiguration( + datasetsRGBRad[channel], + turbidity, + albedo, + elevation + ); + } + + return state; +} + +double arhosek_tristim_skymodel_radiance( + ArHosekSkyModelState * state, + double theta, + double gamma, + int channel + ) +{ + return + ArHosekSkyModel_GetRadianceInternal( + state->configs[channel], + theta, + gamma + ) + * state->radiances[channel]; +} + +const int pieces = 45; +const int order = 4; + +double arhosekskymodel_sr_internal( + ArHosekSkyModelState * state, + int turbidity, + int wl, + double elevation + ) +{ + int pos = + (int) (pow(2.0*elevation / MATH_PI, 1.0/3.0) * pieces); // floor + + if ( pos > 44 ) pos = 44; + + const double break_x = + pow(((double) pos / (double) pieces), 3.0) * (MATH_PI * 0.5); + + const double * coefs = + solarDatasets[wl] + (order * pieces * turbidity + order * (pos+1) - 1); + + double res = 0.0; + const double x = elevation - break_x; + double x_exp = 1.0; + + int i; + for (i = 0; i < order; ++i) + { + res += x_exp * *coefs--; + x_exp *= x; + } + + return res * state->emission_correction_factor_sun[wl]; +} + +double arhosekskymodel_solar_radiance_internal2( + ArHosekSkyModelState * state, + double wavelength, + double elevation, + double gamma + ) +{ + assert( + wavelength >= 320.0 + && wavelength <= 720.0 + && state->turbidity >= 1.0 + && state->turbidity <= 10.0 + ); + + + // sun distance to diameter ratio, squared + + const double sol_rad_sin = sin(state->solar_radius); + const double ar2 = 1 / ( sol_rad_sin * sol_rad_sin ); + const double singamma = sin(gamma); + double sc2 = 1.0 - ar2 * singamma * singamma; + if (sc2 < 0.0 ) sc2 = 0.0; + double sampleCosine = sqrt (sc2); + if (sampleCosine == 0.) return 0.; + + int turb_low = (int) state->turbidity - 1; + double turb_frac = state->turbidity - (double) (turb_low + 1); + + if ( turb_low == 9 ) + { + turb_low = 8; + turb_frac = 1.0; + } + + int wl_low = (int) ((wavelength - 320.0) / 40.0); + double wl_frac = fmod(wavelength, 40.0) / 40.0; + + if ( wl_low == 10 ) + { + wl_low = 9; + wl_frac = 1.0; + } + + double direct_radiance = + ( 1.0 - turb_frac ) + * ( (1.0 - wl_frac) + * arhosekskymodel_sr_internal( + state, + turb_low, + wl_low, + elevation + ) + + wl_frac + * arhosekskymodel_sr_internal( + state, + turb_low, + wl_low+1, + elevation + ) + ) + + turb_frac + * ( ( 1.0 - wl_frac ) + * arhosekskymodel_sr_internal( + state, + turb_low+1, + wl_low, + elevation + ) + + wl_frac + * arhosekskymodel_sr_internal( + state, + turb_low+1, + wl_low+1, + elevation + ) + ); + + double ldCoefficient[6]; + + int i; + for ( i = 0; i < 6; i++ ) + ldCoefficient[i] = + (1.0 - wl_frac) * limbDarkeningDatasets[wl_low ][i] + + wl_frac * limbDarkeningDatasets[wl_low+1][i]; + + + // The following will be improved in future versions of the model: + // here, we directly use fitted 5th order polynomials provided by the + // astronomical community for the limb darkening effect. Astronomers need + // such accurate fittings for their predictions. However, this sort of + // accuracy is not really needed for CG purposes, so an approximated + // dataset based on quadratic polynomials will be provided in a future + // release. + + double darkeningFactor = + ldCoefficient[0] + + ldCoefficient[1] * sampleCosine + + ldCoefficient[2] * pow( sampleCosine, 2.0 ) + + ldCoefficient[3] * pow( sampleCosine, 3.0 ) + + ldCoefficient[4] * pow( sampleCosine, 4.0 ) + + ldCoefficient[5] * pow( sampleCosine, 5.0 ); + + direct_radiance *= darkeningFactor; + + return direct_radiance; +} + +double arhosekskymodel_solar_radiance( + ArHosekSkyModelState * state, + double theta, + double gamma, + double wavelength + ) +{ + double direct_radiance = + arhosekskymodel_solar_radiance_internal2( + state, + wavelength, + ((MATH_PI/2.0)-theta), + gamma + ); + + double inscattered_radiance = + arhosekskymodel_radiance( + state, + theta, + gamma, + wavelength + ); + + return direct_radiance + inscattered_radiance; +} + diff --git a/src/ext/skymodel/ArHosekSkyModel.h b/src/ext/skymodel/ArHosekSkyModel.h new file mode 100644 index 00000000..19ec82f5 --- /dev/null +++ b/src/ext/skymodel/ArHosekSkyModel.h @@ -0,0 +1,451 @@ +/* +This source is published under the following 3-clause BSD license. + +Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * None of the names of the contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +/* ============================================================================ + +This file is part of a sample implementation of the analytical skylight and +solar radiance models presented in the SIGGRAPH 2012 paper + + + "An Analytic Model for Full Spectral Sky-Dome Radiance" + +and the 2013 IEEE CG&A paper + + "Adding a Solar Radiance Function to the Hosek Skylight Model" + + both by + + Lukas Hosek and Alexander Wilkie + Charles University in Prague, Czech Republic + + + Version: 1.4a, February 22nd, 2013 + +Version history: + +1.4a February 22nd, 2013 + Removed unnecessary and counter-intuitive solar radius parameters + from the interface of the colourspace sky dome initialisation functions. + +1.4 February 11th, 2013 + Fixed a bug which caused the relative brightness of the solar disc + and the sky dome to be off by a factor of about 6. The sun was too + bright: this affected both normal and alien sun scenarios. The + coefficients of the solar radiance function were changed to fix this. + +1.3 January 21st, 2013 (not released to the public) + Added support for solar discs that are not exactly the same size as + the terrestrial sun. Also added support for suns with a different + emission spectrum ("Alien World" functionality). + +1.2a December 18th, 2012 + Fixed a mistake and some inaccuracies in the solar radiance function + explanations found in ArHosekSkyModel.h. The actual source code is + unchanged compared to version 1.2. + +1.2 December 17th, 2012 + Native RGB data and a solar radiance function that matches the turbidity + conditions were added. + +1.1 September 2012 + The coefficients of the spectral model are now scaled so that the output + is given in physical units: W / (m^-2 * sr * nm). Also, the output of the + XYZ model is now no longer scaled to the range [0...1]. Instead, it is + the result of a simple conversion from spectral data via the CIE 2 degree + standard observer matching functions. Therefore, after multiplication + with 683 lm / W, the Y channel now corresponds to luminance in lm. + +1.0 May 11th, 2012 + Initial release. + + +Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if +an updated version of this code has been published! + +============================================================================ */ + + +/* + +This code is taken from ART, a rendering research system written in a +mix of C99 / Objective C. Since ART is not a small system and is intended to +be inter-operable with other libraries, and since C does not have namespaces, +the structures and functions in ART all have to have somewhat wordy +canonical names that begin with Ar.../ar..., like those seen in this example. + +Usage information: +================== + + +Model initialisation +-------------------- + +A separate ArHosekSkyModelState has to be maintained for each spectral +band you want to use the model for. So in a renderer with 'num_channels' +bands, you would need something like + + ArHosekSkyModelState * skymodel_state[num_channels]; + +You then have to allocate and initialise these states. In the following code +snippet, we assume that 'albedo' is defined as + + double albedo[num_channels]; + +with a ground albedo value between [0,1] for each channel. The solar elevation +is given in radians. + + for ( unsigned int i = 0; i < num_channels; i++ ) + skymodel_state[i] = + arhosekskymodelstate_alloc_init( + turbidity, + albedo[i], + solarElevation + ); + +Note that starting with version 1.3, there is also a second initialisation +function which generates skydome states for different solar emission spectra +and solar radii: 'arhosekskymodelstate_alienworld_alloc_init()'. + +See the notes about the "Alien World" functionality provided further down for a +discussion of the usefulness and limits of that second initalisation function. +Sky model states that have been initialised with either function behave in a +completely identical fashion during use and cleanup. + +Using the model to generate skydome samples +------------------------------------------- + +Generating a skydome radiance spectrum "skydome_result" for a given location +on the skydome determined via the angles theta and gamma works as follows: + + double skydome_result[num_channels]; + + for ( unsigned int i = 0; i < num_channels; i++ ) + skydome_result[i] = + arhosekskymodel_radiance( + skymodel_state[i], + theta, + gamma, + channel_center[i] + ); + +The variable "channel_center" is assumed to hold the channel center wavelengths +for each of the num_channels samples of the spectrum we are building. + + +Cleanup after use +----------------- + +After rendering is complete, the content of the sky model states should be +disposed of via + + for ( unsigned int i = 0; i < num_channels; i++ ) + arhosekskymodelstate_free( skymodel_state[i] ); + + +CIE XYZ Version of the Model +---------------------------- + +Usage of the CIE XYZ version of the model is exactly the same, except that +num_channels is of course always 3, and that ArHosekTristimSkyModelState and +arhosek_tristim_skymodel_radiance() have to be used instead of their spectral +counterparts. + +RGB Version of the Model +------------------------ + +The RGB version uses sRGB primaries with a linear gamma ramp. The same set of +functions as with the XYZ data is used, except the model is initialized +by calling arhosek_rgb_skymodelstate_alloc_init. + +Solar Radiance Function +----------------------- + +For each position on the solar disc, this function returns the entire radiance +one sees - direct emission, as well as in-scattered light in the area of the +solar disc. The latter is important for low solar elevations - nice images of +the setting sun would not be possible without this. This is also the reason why +this function, just like the regular sky dome model evaluation function, needs +access to the sky dome data structures, as these provide information on +in-scattered radiance. + +CAVEAT #1: in this release, this function is only provided in spectral form! + RGB/XYZ versions to follow at a later date. + +CAVEAT #2: (fixed from release 1.3 onwards) + +CAVEAT #3: limb darkening renders the brightness of the solar disc + inhomogeneous even for high solar elevations - only taking a single + sample at the centre of the sun will yield an incorrect power + estimate for the solar disc! Always take multiple random samples + across the entire solar disc to estimate its power! + +CAVEAT #4: in this version, the limb darkening calculations still use a fairly + computationally expensive 5th order polynomial that was directly + taken from astronomical literature. For the purposes of Computer + Graphics, this is needlessly accurate, though, and will be replaced + by a cheaper approximation in a future release. + +"Alien World" functionality +--------------------------- + +The Hosek sky model can be used to roughly (!) predict the appearance of +outdoor scenes on earth-like planets, i.e. planets of a similar size and +atmospheric make-up. Since the spectral version of our model predicts sky dome +luminance patterns and solar radiance independently for each waveband, and +since the intensity of each waveband is solely dependent on the input radiance +from the star that the world in question is orbiting, it is trivial to re-scale +the wavebands to match a different star radiance. + +At least in theory, the spectral version of the model has always been capable +of this sort of thing, and the actual sky dome and solar radiance models were +actually not altered at all in this release. All we did was to add some support +functionality for doing this more easily with the existing data and functions, +and to add some explanations. + +Just use 'arhosekskymodelstate_alienworld_alloc_init()' to initialise the sky +model states (you will have to provide values for star temperature and solar +intensity compared to the terrestrial sun), and do everything else as you +did before. + +CAVEAT #1: we assume the emission of the star that illuminates the alien world + to be a perfect blackbody emission spectrum. This is never entirely + realistic - real star emission spectra are considerably more complex + than this, mainly due to absorption effects in the outer layers of + stars. However, blackbody spectra are a reasonable first assumption + in a usage scenario like this, where 100% accuracy is simply not + necessary: for rendering purposes, there are likely no visible + differences between a highly accurate solution based on a more + involved simulation, and this approximation. + +CAVEAT #2: we always use limb darkening data from our own sun to provide this + "appearance feature", even for suns of strongly different + temperature. Which is presumably not very realistic, but (as with + the unaltered blackbody spectrum from caveat #1) probably not a bad + first guess, either. If you need more accuracy than we provide here, + please make inquiries with a friendly astro-physicst of your choice. + +CAVEAT #3: you have to provide a value for the solar intensity of the star + which illuminates the alien world. For this, please bear in mind + that there is very likely a comparatively tight range of absolute + solar irradiance values for which an earth-like planet with an + atmosphere like the one we assume in our model can exist in the + first place! + + Too much irradiance, and the atmosphere probably boils off into + space, too little, it freezes. Which means that stars of + considerably different emission colour than our sun will have to be + fairly different in size from it, to still provide a reasonable and + inhabitable amount of irradiance. Red stars will need to be much + larger than our sun, while white or blue stars will have to be + comparatively tiny. The initialisation function handles this and + computes a plausible solar radius for a given emission spectrum. In + terms of absolute radiometric values, you should probably not stray + all too far from a solar intensity value of 1.0. + +CAVEAT #4: although we now support different solar radii for the actual solar + disc, the sky dome luminance patterns are *not* parameterised by + this value - i.e. the patterns stay exactly the same for different + solar radii! Which is of course not correct. But in our experience, + solar discs up to several degrees in diameter (! - our own sun is + half a degree across) do not cause the luminance patterns on the sky + to change perceptibly. The reason we know this is that we initially + used unrealistically large suns in our brute force path tracer, in + order to improve convergence speeds (which in the beginning were + abysmal). Later, we managed to do the reference renderings much + faster even with realistically small suns, and found that there was + no real difference in skydome appearance anyway. + Conclusion: changing the solar radius should not be over-done, so + close orbits around red supergiants are a no-no. But for the + purposes of getting a fairly credible first impression of what an + alien world with a reasonably sized sun would look like, what we are + doing here is probably still o.k. + +HINT #1: if you want to model the sky of an earth-like planet that orbits + a binary star, just super-impose two of these models with solar + intensity of ~0.5 each, and closely spaced solar positions. Light is + additive, after all. Tattooine, here we come... :-) + + P.S. according to Star Wars canon, Tattooine orbits a binary + that is made up of a G and K class star, respectively. + So ~5500K and ~4200K should be good first guesses for their + temperature. Just in case you were wondering, after reading the + previous paragraph. +*/ + + +#ifndef _ARHOSEK_SKYMODEL_H_ +#define _ARHOSEK_SKYMODEL_H_ + +typedef double ArHosekSkyModelConfiguration[9]; + + +// Spectral version of the model + +/* ---------------------------------------------------------------------------- + + ArHosekSkyModelState struct + --------------------------- + + This struct holds the pre-computation data for one particular albedo value. + Most fields are self-explanatory, but users should never directly + manipulate any of them anyway. The only consistent way to manipulate such + structs is via the functions 'arhosekskymodelstate_alloc_init' and + 'arhosekskymodelstate_free'. + + 'emission_correction_factor_sky' + 'emission_correction_factor_sun' + + The original model coefficients were fitted against the emission of + our local sun. If a different solar emission is desired (i.e. if the + model is being used to predict skydome appearance for an earth-like + planet that orbits a different star), these correction factors, which + are determined during the alloc_init step, are applied to each waveband + separately (they default to 1.0 in normal usage). This is the simplest + way to retrofit this sort of capability to the existing model. The + different factors for sky and sun are needed since the solar disc may + be of a different size compared to the terrestrial sun. + +---------------------------------------------------------------------------- */ + +typedef struct ArHosekSkyModelState +{ + ArHosekSkyModelConfiguration configs[11]; + double radiances[11]; + double turbidity; + double solar_radius; + double emission_correction_factor_sky[11]; + double emission_correction_factor_sun[11]; + double albedo; + double elevation; +} +ArHosekSkyModelState; + +/* ---------------------------------------------------------------------------- + + arhosekskymodelstate_alloc_init() function + ------------------------------------------ + + Initialises an ArHosekSkyModelState struct for a terrestrial setting. + +---------------------------------------------------------------------------- */ + +ArHosekSkyModelState * arhosekskymodelstate_alloc_init( + const double solar_elevation, + const double atmospheric_turbidity, + const double ground_albedo + ); + + +/* ---------------------------------------------------------------------------- + + arhosekskymodelstate_alienworld_alloc_init() function + ----------------------------------------------------- + + Initialises an ArHosekSkyModelState struct for an "alien world" setting + with a sun of a surface temperature given in 'kelvin'. The parameter + 'solar_intensity' controls the overall brightness of the sky, relative + to the solar irradiance on Earth. A value of 1.0 yields a sky dome that + is, on average over the wavelenghts covered in the model (!), as bright + as the terrestrial sky in radiometric terms. + + Which means that the solar radius has to be adjusted, since the + emissivity of a solar surface with a given temperature is more or less + fixed. So hotter suns have to be smaller to be equally bright as the + terrestrial sun, while cooler suns have to be larger. Note that there are + limits to the validity of the luminance patterns of the underlying model: + see the discussion above for more on this. In particular, an alien sun with + a surface temperature of only 2000 Kelvin has to be very large if it is + to be as bright as the terrestrial sun - so large that the luminance + patterns are no longer a really good fit in that case. + + If you need information about the solar radius that the model computes + for a given temperature (say, for light source sampling purposes), you + have to query the 'solar_radius' variable of the sky model state returned + *after* running this function. + +---------------------------------------------------------------------------- */ + +ArHosekSkyModelState * arhosekskymodelstate_alienworld_alloc_init( + const double solar_elevation, + const double solar_intensity, + const double solar_surface_temperature_kelvin, + const double atmospheric_turbidity, + const double ground_albedo + ); + +void arhosekskymodelstate_free( + ArHosekSkyModelState * state + ); + +double arhosekskymodel_radiance( + ArHosekSkyModelState * state, + double theta, + double gamma, + double wavelength + ); + +// CIE XYZ and RGB versions + + +ArHosekSkyModelState * arhosek_xyz_skymodelstate_alloc_init( + const double turbidity, + const double albedo, + const double elevation + ); + + +ArHosekSkyModelState * arhosek_rgb_skymodelstate_alloc_init( + const double turbidity, + const double albedo, + const double elevation + ); + + +double arhosek_tristim_skymodel_radiance( + ArHosekSkyModelState * state, + double theta, + double gamma, + int channel + ); + +// Delivers the complete function: sky + sun, including limb darkening. +// Please read the above description before using this - there are several +// caveats! + +double arhosekskymodel_solar_radiance( + ArHosekSkyModelState * state, + double theta, + double gamma, + double wavelength + ); + + +#endif // _ARHOSEK_SKYMODEL_H_ diff --git a/src/ext/skymodel/ArHosekSkyModelData_CIEXYZ.h b/src/ext/skymodel/ArHosekSkyModelData_CIEXYZ.h new file mode 100644 index 00000000..a720cd9b --- /dev/null +++ b/src/ext/skymodel/ArHosekSkyModelData_CIEXYZ.h @@ -0,0 +1,3863 @@ +/* +This source is published under the following 3-clause BSD license. + +Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * None of the names of the contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +/* ============================================================================ + +This file is part of a sample implementation of the analytical skylight and +solar radiance models presented in the SIGGRAPH 2012 paper + + + "An Analytic Model for Full Spectral Sky-Dome Radiance" + +and the 2013 IEEE CG&A paper + + "Adding a Solar Radiance Function to the Hosek Skylight Model" + + both by + + Lukas Hosek and Alexander Wilkie + Charles University in Prague, Czech Republic + + + Version: 1.4a, February 22nd, 2013 + +Version history: + +1.4a February 22nd, 2013 + Removed unnecessary and counter-intuitive solar radius parameters + from the interface of the colourspace sky dome initialisation functions. + +1.4 February 11th, 2013 + Fixed a bug which caused the relative brightness of the solar disc + and the sky dome to be off by a factor of about 6. The sun was too + bright: this affected both normal and alien sun scenarios. The + coefficients of the solar radiance function were changed to fix this. + +1.3 January 21st, 2013 (not released to the public) + Added support for solar discs that are not exactly the same size as + the terrestrial sun. Also added support for suns with a different + emission spectrum ("Alien World" functionality). + +1.2a December 18th, 2012 + Fixed a mistake and some inaccuracies in the solar radiance function + explanations found in ArHosekSkyModel.h. The actual source code is + unchanged compared to version 1.2. + +1.2 December 17th, 2012 + Native RGB data and a solar radiance function that matches the turbidity + conditions were added. + +1.1 September 2012 + The coefficients of the spectral model are now scaled so that the output + is given in physical units: W / (m^-2 * sr * nm). Also, the output of the + XYZ model is now no longer scaled to the range [0...1]. Instead, it is + the result of a simple conversion from spectral data via the CIE 2 degree + standard observer matching functions. Therefore, after multiplication + with 683 lm / W, the Y channel now corresponds to luminance in lm. + +1.0 May 11th, 2012 + Initial release. + + +Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if +an updated version of this code has been published! + +============================================================================ */ + + +/* + +This file contains the coefficient data for the XYZ colour space version of +the model. + +*/ + +// Uses Sep 9 pattern / Aug 23 mean dataset + +double datasetXYZ1[] = +{ + // albedo 0, turbidity 1 + -1.117001e+000, + -1.867262e-001, + -1.113505e+001, + 1.259865e+001, + -3.937339e-002, + 1.167571e+000, + 7.100686e-003, + 3.592678e+000, + 6.083296e-001, + -1.152006e+000, + -1.926669e-001, + 6.152049e+000, + -4.770802e+000, + -8.704701e-002, + 7.483626e-001, + 3.372718e-002, + 4.464592e+000, + 4.036546e-001, + -1.072371e+000, + -2.696632e-001, + 2.816168e-001, + 1.820571e+000, + -3.742666e-001, + 2.080607e+000, + -7.675295e-002, + -2.835366e+000, + 1.129329e+000, + -1.109935e+000, + -1.532764e-001, + 1.198787e+000, + -9.015183e-001, + 5.173015e-003, + 5.749178e-001, + 1.075633e-001, + 4.387949e+000, + 2.650413e-001, + -1.052297e+000, + -2.229452e-001, + 1.952347e+000, + 5.727205e-001, + -4.885070e+000, + 1.984016e+000, + -1.106197e-001, + -4.898361e-001, + 8.907873e-001, + -1.070108e+000, + -1.600465e-001, + 1.593886e+000, + -4.479251e-005, + -3.306541e+000, + 9.390193e-001, + 9.513168e-002, + 2.343583e+000, + 5.335404e-001, + // albedo 0, turbidity 2 + -1.113253e+000, + -1.699600e-001, + -1.038822e+001, + 1.137513e+001, + -4.040911e-002, + 1.037455e+000, + 4.991792e-002, + 4.801919e+000, + 6.302710e-001, + -1.135747e+000, + -1.678594e-001, + 4.970755e+000, + -4.430230e+000, + -6.657408e-002, + 3.636161e-001, + 1.558009e-001, + 6.013370e+000, + 3.959601e-001, + -1.095892e+000, + -2.732595e-001, + 7.666496e-001, + 1.350731e+000, + -4.401401e-001, + 2.470135e+000, + -1.707929e-001, + -3.260793e+000, + 1.170337e+000, + -1.073668e+000, + -2.603929e-002, + -1.944589e-001, + 4.575207e-001, + 6.878164e-001, + -1.390770e-001, + 3.690299e-001, + 7.885781e+000, + 1.877694e-001, + -1.070091e+000, + -2.798957e-001, + 2.338478e+000, + -2.647221e+000, + -7.387808e+000, + 2.329210e+000, + -1.644639e-001, + -2.003710e+000, + 9.874527e-001, + -1.067120e+000, + -1.418866e-001, + 1.254090e+000, + 6.053048e+000, + -2.918892e+000, + 5.322812e-001, + 1.613053e-001, + 3.018161e+000, + 5.274090e-001, + // albedo 0, turbidity 3 + -1.129483e+000, + -1.890619e-001, + -9.065101e+000, + 9.659923e+000, + -3.607819e-002, + 8.314359e-001, + 8.181661e-002, + 4.768868e+000, + 6.339777e-001, + -1.146420e+000, + -1.883579e-001, + 3.309173e+000, + -3.127882e+000, + -6.938176e-002, + 3.987113e-001, + 1.400581e-001, + 6.283042e+000, + 5.267076e-001, + -1.128348e+000, + -2.641305e-001, + 1.223176e+000, + 5.514952e-002, + -3.490649e-001, + 1.997784e+000, + -4.123709e-002, + -2.251251e+000, + 9.483466e-001, + -1.025820e+000, + 1.404690e-002, + -1.187406e+000, + 2.729900e+000, + 5.877588e-001, + -2.761140e-001, + 4.602633e-001, + 8.305125e+000, + 3.945001e-001, + -1.083957e+000, + -2.606679e-001, + 2.207108e+000, + -7.202803e+000, + -5.968103e+000, + 2.129455e+000, + -7.789512e-002, + -1.137688e+000, + 8.871769e-001, + -1.062465e+000, + -1.512189e-001, + 1.042881e+000, + 1.427839e+001, + -4.242214e+000, + 4.038100e-001, + 1.997780e-001, + 2.814449e+000, + 5.803196e-001, + // albedo 0, turbidity 4 + -1.175099e+000, + -2.410789e-001, + -1.108587e+001, + 1.133404e+001, + -1.819300e-002, + 6.772942e-001, + 9.605043e-002, + 4.231166e+000, + 6.239972e-001, + -1.224207e+000, + -2.883527e-001, + 3.002206e+000, + -2.649612e+000, + -4.795418e-002, + 4.984398e-001, + 3.251434e-002, + 4.851611e+000, + 6.551019e-001, + -1.136955e+000, + -2.423048e-001, + 1.058823e+000, + -2.489236e-001, + -2.462179e-001, + 1.933140e+000, + 9.106828e-002, + -1.905869e-001, + 8.171065e-001, + -1.014535e+000, + -8.262500e-003, + -1.448017e+000, + 2.295788e+000, + 3.510334e-001, + -1.477418e+000, + 5.432449e-001, + 5.762796e+000, + 4.908751e-001, + -1.070666e+000, + -2.379780e-001, + 1.844589e+000, + -5.442448e+000, + -4.012768e+000, + 2.945275e+000, + 9.854725e-003, + 8.455959e-002, + 8.145030e-001, + -1.071525e+000, + -1.777132e-001, + 8.076590e-001, + 9.925865e+000, + -3.324623e+000, + -6.367437e-001, + 2.844581e-001, + 2.248384e+000, + 6.544022e-001, + // albedo 0, turbidity 5 + -1.218818e+000, + -2.952382e-001, + -1.345975e+001, + 1.347153e+001, + -6.814585e-003, + 5.079068e-001, + 1.197230e-001, + 3.776949e+000, + 5.836961e-001, + -1.409868e+000, + -5.114330e-001, + 2.776539e+000, + -2.039001e+000, + -2.673769e-002, + 4.145288e-001, + 7.829342e-004, + 2.275883e+000, + 6.629691e-001, + -1.069151e+000, + -9.434247e-002, + 7.293972e-001, + -1.222473e+000, + -1.533461e-001, + 2.160357e+000, + 4.626837e-002, + 3.852415e+000, + 8.593570e-001, + -1.021306e+000, + -1.149551e-001, + -1.108414e+000, + 4.178343e+000, + 4.013665e-001, + -2.222814e+000, + 6.929462e-001, + 1.392652e+000, + 4.401662e-001, + -1.074251e+000, + -2.224002e-001, + 1.372356e+000, + -8.858704e+000, + -3.922660e+000, + 3.020018e+000, + -1.458724e-002, + 1.511186e+000, + 8.288064e-001, + -1.062048e+000, + -1.526582e-001, + 4.921067e-001, + 1.485522e+001, + -3.229936e+000, + -8.426604e-001, + 3.916243e-001, + 2.678994e+000, + 6.689264e-001, + // albedo 0, turbidity 6 + -1.257023e+000, + -3.364700e-001, + -1.527795e+001, + 1.504223e+001, + 2.717715e-003, + 3.029910e-001, + 1.636851e-001, + 3.561663e+000, + 5.283161e-001, + -1.635124e+000, + -7.329993e-001, + 3.523939e+000, + -2.566337e+000, + -1.902543e-002, + 5.505483e-001, + -6.242176e-002, + 1.065992e+000, + 6.654236e-001, + -9.295823e-001, + 4.845834e-002, + -2.992990e-001, + -2.001327e-001, + -8.019339e-002, + 1.807806e+000, + 9.020277e-002, + 5.095372e+000, + 8.639936e-001, + -1.093740e+000, + -2.148608e-001, + -5.216240e-001, + 2.119777e+000, + 9.506454e-002, + -1.831439e+000, + 6.961204e-001, + 1.102084e-001, + 4.384319e-001, + -1.044181e+000, + -1.849257e-001, + 9.071246e-001, + -4.648901e+000, + -2.279385e+000, + 2.356502e+000, + -4.169147e-002, + 1.932557e+000, + 8.296550e-001, + -1.061451e+000, + -1.458745e-001, + 2.952267e-001, + 8.967214e+000, + -3.726228e+000, + -5.022316e-001, + 5.684877e-001, + 3.102347e+000, + 6.658443e-001, + // albedo 0, turbidity 7 + -1.332391e+000, + -4.127769e-001, + -9.328643e+000, + 9.046194e+000, + 3.457775e-003, + 3.377425e-001, + 1.530909e-001, + 3.301209e+000, + 4.997917e-001, + -1.932002e+000, + -9.947777e-001, + -2.042329e+000, + 3.586940e+000, + -5.642182e-002, + 8.130478e-001, + -8.195988e-002, + 1.118294e-001, + 5.617231e-001, + -8.707374e-001, + 1.286999e-001, + 1.820054e+000, + -4.674706e+000, + 3.317471e-003, + 5.919018e-001, + 1.975278e-001, + 6.686519e+000, + 9.631727e-001, + -1.070378e+000, + -3.030579e-001, + -9.041938e-001, + 6.200201e+000, + 1.232207e-001, + -3.650628e-001, + 5.029403e-001, + -2.903162e+000, + 3.811408e-001, + -1.063035e+000, + -1.637545e-001, + 5.853072e-001, + -7.889906e+000, + -1.200641e+000, + 1.035018e+000, + 1.192093e-001, + 3.267054e+000, + 8.416151e-001, + -1.053655e+000, + -1.562286e-001, + 2.423683e-001, + 1.128575e+001, + -4.363262e+000, + -7.314160e-002, + 5.642088e-001, + 2.514023e+000, + 6.670457e-001, + // albedo 0, turbidity 8 + -1.366112e+000, + -4.718287e-001, + -7.876222e+000, + 7.746900e+000, + -9.182309e-003, + 4.716076e-001, + 8.320252e-002, + 3.165603e+000, + 5.392334e-001, + -2.468204e+000, + -1.336340e+000, + -5.386723e+000, + 7.072672e+000, + -8.329266e-002, + 8.636876e-001, + -1.978177e-002, + -1.326218e-001, + 2.979222e-001, + -9.653522e-001, + -2.373416e-002, + 1.810250e+000, + -6.467262e+000, + 1.410706e-001, + -4.753717e-001, + 3.003095e-001, + 6.551163e+000, + 1.151083e+000, + -8.943186e-001, + -2.487152e-001, + -2.308960e-001, + 8.512648e+000, + 1.298402e-001, + 1.034705e+000, + 2.303509e-001, + -3.924095e+000, + 2.982717e-001, + -1.146999e+000, + -2.318784e-001, + 8.992419e-002, + -9.933614e+000, + -8.860920e-001, + -3.071656e-002, + 2.852012e-001, + 3.046199e+000, + 8.599001e-001, + -1.032399e+000, + -1.645145e-001, + 2.683599e-001, + 1.327701e+001, + -4.407670e+000, + 7.709869e-002, + 4.951727e-001, + 1.957277e+000, + 6.630943e-001, + // albedo 0, turbidity 9 + -1.469070e+000, + -6.135092e-001, + -6.506263e+000, + 6.661315e+000, + -3.835383e-002, + 7.150413e-001, + 7.784318e-003, + 2.820577e+000, + 6.756784e-001, + -2.501583e+000, + -1.247404e+000, + -1.523462e+001, + 1.633191e+001, + -1.204803e-002, + 5.896471e-001, + -2.002023e-002, + 1.144647e+000, + 6.177874e-002, + -2.438672e+000, + -1.127291e+000, + 5.731172e+000, + -1.021350e+001, + 6.165610e-002, + -7.752641e-001, + 4.708254e-001, + 4.176847e+000, + 1.200881e+000, + -1.513427e-001, + 9.792731e-002, + -1.612349e+000, + 9.814289e+000, + 5.188921e-002, + 1.716403e+000, + -7.039255e-002, + -2.815115e+000, + 3.291874e-001, + -1.318511e+000, + -3.650554e-001, + 4.221268e-001, + -9.294529e+000, + -4.397520e-002, + -8.100625e-001, + 3.742719e-001, + 1.834166e+000, + 8.223450e-001, + -1.016009e+000, + -1.820264e-001, + 1.278426e-001, + 1.182696e+001, + -4.801528e+000, + 4.947899e-001, + 4.660378e-001, + 1.601254e+000, + 6.702359e-001, + // albedo 0, turbidity 10 + -1.841310e+000, + -9.781779e-001, + -4.610903e+000, + 4.824662e+000, + -5.100806e-002, + 6.463776e-001, + -6.377724e-006, + 2.216875e+000, + 8.618530e-001, + -2.376373e+000, + -1.108657e+000, + -1.489799e+001, + 1.546458e+001, + 4.091025e-002, + 9.761780e-002, + -1.048958e-002, + 2.165834e+000, + -1.609171e-001, + -4.710318e+000, + -2.261963e+000, + 6.947327e+000, + -1.034828e+001, + -1.325542e-001, + 7.508674e-001, + 2.247553e-001, + 2.873142e+000, + 1.297100e+000, + 2.163750e-001, + -1.944345e-001, + -2.437860e+000, + 1.011314e+001, + 4.450500e-001, + 3.111492e-001, + 2.751323e-001, + -1.627906e+000, + 2.531213e-001, + -1.258794e+000, + -3.524641e-001, + 8.425444e-001, + -1.085313e+001, + -1.154381e+000, + -4.638014e-001, + -2.781115e-003, + 4.344498e-001, + 8.507091e-001, + -1.018938e+000, + -1.804153e-001, + -6.354054e-002, + 1.573150e+001, + -4.386999e+000, + 6.211115e-001, + 5.294648e-001, + 1.580749e+000, + 6.586655e-001, + // albedo 1, turbidity 1 + -1.116416e+000, + -1.917524e-001, + -1.068233e+001, + 1.222221e+001, + -3.668978e-002, + 1.054022e+000, + 1.592132e-002, + 3.180583e+000, + 5.627370e-001, + -1.132341e+000, + -1.671286e-001, + 5.976499e+000, + -4.227366e+000, + -9.542489e-002, + 8.664938e-001, + 8.351793e-003, + 4.876068e+000, + 4.492779e-001, + -1.087635e+000, + -3.173679e-001, + 4.314407e-001, + 1.100555e+000, + -4.410057e-001, + 1.677253e+000, + -3.005925e-002, + -4.201249e+000, + 1.070902e+000, + -1.083031e+000, + -8.847705e-002, + 1.291773e+000, + 4.546776e-001, + 3.091894e-001, + 7.261760e-001, + 4.203659e-002, + 5.990615e+000, + 3.704756e-001, + -1.057899e+000, + -2.246706e-001, + 2.329563e+000, + -1.219656e+000, + -5.335260e+000, + 8.545378e-001, + -3.906209e-002, + -9.025499e-001, + 7.797348e-001, + -1.073305e+000, + -1.522553e-001, + 1.767063e+000, + 1.904280e+000, + -3.101673e+000, + 3.995856e-001, + 2.905192e-002, + 2.563977e+000, + 5.753067e-001, + // albedo 1, turbidity 2 + -1.113674e+000, + -1.759694e-001, + -9.754125e+000, + 1.087391e+001, + -3.841093e-002, + 9.524272e-001, + 5.680219e-002, + 4.227034e+000, + 6.029571e-001, + -1.126496e+000, + -1.680281e-001, + 5.332352e+000, + -4.575579e+000, + -6.761755e-002, + 3.295335e-001, + 1.194896e-001, + 5.570901e+000, + 4.536185e-001, + -1.103074e+000, + -2.681801e-001, + 6.571479e-002, + 2.396522e+000, + -4.551280e-001, + 2.466331e+000, + -1.232022e-001, + -3.023201e+000, + 1.086379e+000, + -1.053299e+000, + -2.697173e-002, + 8.379121e-001, + -9.681458e-001, + 5.890692e-001, + -4.872027e-001, + 2.936929e-001, + 7.510139e+000, + 3.079122e-001, + -1.079553e+000, + -2.710448e-001, + 2.462379e+000, + -3.713554e-001, + -8.534512e+000, + 1.828242e+000, + -1.686398e-001, + -1.961340e+000, + 8.941077e-001, + -1.069741e+000, + -1.396394e-001, + 1.657868e+000, + 3.236313e+000, + -2.706344e+000, + -2.948122e-001, + 1.314816e-001, + 2.868457e+000, + 5.413403e-001, + // albedo 1, turbidity 3 + -1.131649e+000, + -1.954455e-001, + -7.751595e+000, + 8.685861e+000, + -4.910871e-002, + 8.992952e-001, + 4.710143e-002, + 4.254818e+000, + 6.821116e-001, + -1.156689e+000, + -1.884324e-001, + 3.163519e+000, + -3.091522e+000, + -6.613927e-002, + -2.575883e-002, + 1.640065e-001, + 6.073643e+000, + 4.453468e-001, + -1.079224e+000, + -2.621389e-001, + 9.446437e-001, + 1.448479e+000, + -3.969384e-001, + 2.626638e+000, + -8.101186e-002, + -3.016355e+000, + 1.076295e+000, + -1.080832e+000, + 1.033057e-002, + -3.500156e-001, + -3.281419e-002, + 5.655512e-001, + -1.156742e+000, + 4.534710e-001, + 8.774122e+000, + 2.772869e-001, + -1.051202e+000, + -2.679975e-001, + 2.719109e+000, + -2.190316e+000, + -6.878798e+000, + 2.250481e+000, + -2.030252e-001, + -2.026527e+000, + 9.701096e-001, + -1.089849e+000, + -1.598589e-001, + 1.564748e+000, + 6.869187e+000, + -3.053670e+000, + -6.110435e-001, + 1.644472e-001, + 2.370452e+000, + 5.511770e-001, + // albedo 1, turbidity 4 + -1.171419e+000, + -2.429746e-001, + -8.991334e+000, + 9.571216e+000, + -2.772861e-002, + 6.688262e-001, + 7.683478e-002, + 3.785611e+000, + 6.347635e-001, + -1.228554e+000, + -2.917562e-001, + 2.753986e+000, + -2.491780e+000, + -4.663434e-002, + 3.118303e-001, + 7.546506e-002, + 4.463096e+000, + 5.955071e-001, + -1.093124e+000, + -2.447767e-001, + 9.097406e-001, + 5.448296e-001, + -2.957824e-001, + 2.024167e+000, + -5.152333e-004, + -1.069081e+000, + 9.369565e-001, + -1.056994e+000, + 1.569507e-002, + -8.217491e-001, + 1.870818e+000, + 7.061930e-001, + -1.483928e+000, + 5.978206e-001, + 6.864902e+000, + 3.673332e-001, + -1.054871e+000, + -2.758129e-001, + 2.712807e+000, + -5.950110e+000, + -6.554039e+000, + 2.447523e+000, + -1.895171e-001, + -1.454292e+000, + 9.131738e-001, + -1.100218e+000, + -1.746241e-001, + 1.438505e+000, + 1.115481e+001, + -3.266076e+000, + -8.837357e-001, + 1.970100e-001, + 1.991595e+000, + 5.907821e-001, + // albedo 1, turbidity 5 + -1.207267e+000, + -2.913610e-001, + -1.103767e+001, + 1.140724e+001, + -1.416800e-002, + 5.564047e-001, + 8.476262e-002, + 3.371255e+000, + 6.221335e-001, + -1.429698e+000, + -5.374218e-001, + 2.837524e+000, + -2.221936e+000, + -2.422337e-002, + 9.313758e-002, + 7.190250e-002, + 1.869022e+000, + 5.609035e-001, + -1.002274e+000, + -6.972810e-002, + 4.031308e-001, + -3.932997e-001, + -1.521923e-001, + 2.390646e+000, + -6.893990e-002, + 2.999661e+000, + 1.017843e+000, + -1.081168e+000, + -1.178666e-001, + -4.968080e-001, + 3.919299e+000, + 6.046866e-001, + -2.440615e+000, + 7.891538e-001, + 2.140835e+000, + 2.740470e-001, + -1.050727e+000, + -2.307688e-001, + 2.276396e+000, + -9.454407e+000, + -5.505176e+000, + 2.992620e+000, + -2.450942e-001, + 6.078372e-001, + 9.606765e-001, + -1.103752e+000, + -1.810202e-001, + 1.375044e+000, + 1.589095e+001, + -3.438954e+000, + -1.265669e+000, + 2.475172e-001, + 1.680768e+000, + 5.978056e-001, + // albedo 1, turbidity 6 + -1.244324e+000, + -3.378542e-001, + -1.111001e+001, + 1.137784e+001, + -7.896794e-003, + 4.808023e-001, + 9.249904e-002, + 3.025816e+000, + 5.880239e-001, + -1.593165e+000, + -7.027621e-001, + 2.220896e+000, + -1.437709e+000, + -1.534738e-002, + 6.286958e-002, + 6.644555e-002, + 1.091727e+000, + 5.470080e-001, + -9.136506e-001, + 1.344874e-002, + 7.772636e-001, + -1.209396e+000, + -1.408978e-001, + 2.433718e+000, + -1.041938e-001, + 3.791244e+000, + 1.037916e+000, + -1.134968e+000, + -1.803315e-001, + -9.267335e-001, + 4.576670e+000, + 6.851928e-001, + -2.805000e+000, + 8.687208e-001, + 1.161483e+000, + 2.571688e-001, + -1.017037e+000, + -2.053943e-001, + 2.361640e+000, + -9.887818e+000, + -5.122889e+000, + 3.287088e+000, + -2.594102e-001, + 8.578927e-001, + 9.592340e-001, + -1.118723e+000, + -1.934942e-001, + 1.226023e+000, + 1.674140e+001, + -3.277335e+000, + -1.629809e+000, + 2.765232e-001, + 1.637713e+000, + 6.113963e-001, + // albedo 1, turbidity 7 + -1.314779e+000, + -4.119915e-001, + -1.241150e+001, + 1.241578e+001, + 2.344284e-003, + 2.980837e-001, + 1.414613e-001, + 2.781731e+000, + 4.998556e-001, + -1.926199e+000, + -1.020038e+000, + 2.569200e+000, + -1.081159e+000, + -2.266833e-002, + 3.588668e-001, + 8.750078e-003, + -2.452171e-001, + 4.796758e-001, + -7.780002e-001, + 1.850647e-001, + 4.445456e-002, + -2.409297e+000, + -7.816346e-002, + 1.546790e+000, + -2.807227e-002, + 5.998176e+000, + 1.132396e+000, + -1.179326e+000, + -3.578330e-001, + -2.392933e-001, + 6.467883e+000, + 5.904596e-001, + -1.869975e+000, + 8.045839e-001, + -2.498121e+000, + 1.610633e-001, + -1.009956e+000, + -1.311896e-001, + 1.726577e+000, + -1.219356e+001, + -3.466239e+000, + 2.343602e+000, + -2.252205e-001, + 2.573681e+000, + 1.027109e+000, + -1.112460e+000, + -2.063093e-001, + 1.233051e+000, + 2.058946e+001, + -4.578074e+000, + -1.145643e+000, + 3.160192e-001, + 1.420159e+000, + 5.860212e-001, + // albedo 1, turbidity 8 + -1.371689e+000, + -4.914196e-001, + -1.076610e+001, + 1.107405e+001, + -1.485077e-002, + 5.936218e-001, + 3.685482e-002, + 2.599968e+000, + 6.002204e-001, + -2.436997e+000, + -1.377939e+000, + 2.130141e-002, + 1.079593e+000, + -1.796232e-002, + -3.933248e-002, + 1.610711e-001, + -6.901181e-001, + 1.206416e-001, + -8.743368e-001, + 7.331370e-002, + 8.734259e-001, + -3.743126e+000, + -3.151167e-002, + 1.297596e+000, + -7.634926e-002, + 6.532873e+000, + 1.435737e+000, + -9.810197e-001, + -3.521634e-001, + -2.855205e-001, + 7.134674e+000, + 6.839748e-001, + -1.394841e+000, + 6.952036e-001, + -4.633104e+000, + -2.173401e-002, + -1.122958e+000, + -1.691536e-001, + 1.382360e+000, + -1.102913e+001, + -2.608171e+000, + 1.865111e+000, + -1.345154e-001, + 3.112342e+000, + 1.094134e+000, + -1.075586e+000, + -2.077415e-001, + 1.171477e+000, + 1.793270e+001, + -4.656858e+000, + -1.036839e+000, + 3.338295e-001, + 1.042793e+000, + 5.739374e-001, + // albedo 1, turbidity 9 + -1.465871e+000, + -6.364486e-001, + -8.833718e+000, + 9.343650e+000, + -3.223600e-002, + 7.552848e-001, + -3.121341e-006, + 2.249164e+000, + 8.094662e-001, + -2.448924e+000, + -1.270878e+000, + -4.823703e+000, + 5.853058e+000, + -2.149127e-002, + 3.581132e-002, + -1.230276e-003, + 4.892553e-001, + -1.597657e-001, + -2.419809e+000, + -1.071337e+000, + 1.575648e+000, + -4.983580e+000, + 9.545185e-003, + 5.032615e-001, + 4.186266e-001, + 4.634147e+000, + 1.433517e+000, + -1.383278e-001, + -2.797095e-002, + -1.943067e-001, + 6.679623e+000, + 4.118280e-001, + -2.744289e-001, + -2.118722e-002, + -4.337025e+000, + 1.505072e-001, + -1.341872e+000, + -2.518572e-001, + 1.027009e+000, + -6.527103e+000, + -1.081271e+000, + 1.015465e+000, + 2.845789e-001, + 2.470371e+000, + 9.278120e-001, + -1.040640e+000, + -2.367454e-001, + 1.100744e+000, + 8.827253e+000, + -4.560794e+000, + -7.287017e-001, + 2.842503e-001, + 6.336593e-001, + 6.327335e-001, + // albedo 1, turbidity 10 + -1.877993e+000, + -1.025135e+000, + -4.311037e+000, + 4.715016e+000, + -4.711631e-002, + 6.335844e-001, + -7.665398e-006, + 1.788017e+000, + 9.001409e-001, + -2.281540e+000, + -1.137668e+000, + -1.036869e+001, + 1.136254e+001, + 1.961739e-002, + -9.836174e-002, + -6.734567e-003, + 1.320918e+000, + -2.400807e-001, + -4.904054e+000, + -2.315781e+000, + 5.735999e+000, + -8.626257e+000, + -1.255643e-001, + 1.545446e+000, + 1.396860e-001, + 2.972897e+000, + 1.429934e+000, + 4.077067e-001, + -1.833688e-001, + -2.450939e+000, + 9.119433e+000, + 4.505361e-001, + -1.340828e+000, + 3.973690e-001, + -1.785370e+000, + 9.628711e-002, + -1.296052e+000, + -3.250526e-001, + 1.813294e+000, + -1.031485e+001, + -1.388690e+000, + 1.239733e+000, + -8.989196e-002, + -3.389637e-001, + 9.639560e-001, + -1.062181e+000, + -2.423444e-001, + 7.577592e-001, + 1.566938e+001, + -4.462264e+000, + -5.742810e-001, + 3.262259e-001, + 9.461672e-001, + 6.232887e-001, +}; + +double datasetXYZRad1[] = +{ + // albedo 0, turbidity 1 + 1.560219e+000, + 1.417388e+000, + 1.206927e+000, + 1.091949e+001, + 5.931416e+000, + 7.304788e+000, + // albedo 0, turbidity 2 + 1.533049e+000, + 1.560532e+000, + 3.685059e-001, + 1.355040e+001, + 5.543711e+000, + 7.792189e+000, + // albedo 0, turbidity 3 + 1.471043e+000, + 1.746088e+000, + -9.299697e-001, + 1.720362e+001, + 5.473384e+000, + 8.336416e+000, + // albedo 0, turbidity 4 + 1.355991e+000, + 2.109348e+000, + -3.295855e+000, + 2.264843e+001, + 5.454607e+000, + 9.304656e+000, + // albedo 0, turbidity 5 + 1.244963e+000, + 2.547533e+000, + -5.841485e+000, + 2.756879e+001, + 5.576104e+000, + 1.043287e+001, + // albedo 0, turbidity 6 + 1.175532e+000, + 2.784634e+000, + -7.212225e+000, + 2.975347e+001, + 6.472980e+000, + 1.092331e+001, + // albedo 0, turbidity 7 + 1.082973e+000, + 3.118094e+000, + -8.934293e+000, + 3.186879e+001, + 8.473885e+000, + 1.174019e+001, + // albedo 0, turbidity 8 + 9.692500e-001, + 3.349574e+000, + -1.003810e+001, + 3.147654e+001, + 1.338931e+001, + 1.272547e+001, + // albedo 0, turbidity 9 + 8.547044e-001, + 3.151538e+000, + -9.095567e+000, + 2.554995e+001, + 2.273219e+001, + 1.410398e+001, + // albedo 0, turbidity 10 + 7.580340e-001, + 2.311153e+000, + -5.170814e+000, + 1.229669e+001, + 3.686529e+001, + 1.598882e+001, + // albedo 1, turbidity 1 + 1.664273e+000, + 1.574468e+000, + 1.422078e+000, + 9.768247e+000, + 1.447338e+001, + 1.644988e+001, + // albedo 1, turbidity 2 + 1.638295e+000, + 1.719586e+000, + 5.786675e-001, + 1.239846e+001, + 1.415419e+001, + 1.728605e+001, + // albedo 1, turbidity 3 + 1.572623e+000, + 1.921559e+000, + -7.714802e-001, + 1.609246e+001, + 1.420954e+001, + 1.825908e+001, + // albedo 1, turbidity 4 + 1.468395e+000, + 2.211970e+000, + -2.845869e+000, + 2.075027e+001, + 1.524822e+001, + 1.937622e+001, + // albedo 1, turbidity 5 + 1.355047e+000, + 2.556469e+000, + -4.960920e+000, + 2.460237e+001, + 1.648360e+001, + 2.065648e+001, + // albedo 1, turbidity 6 + 1.291642e+000, + 2.742036e+000, + -6.061967e+000, + 2.602002e+001, + 1.819144e+001, + 2.116712e+001, + // albedo 1, turbidity 7 + 1.194565e+000, + 2.972120e+000, + -7.295779e+000, + 2.691805e+001, + 2.124880e+001, + 2.201819e+001, + // albedo 1, turbidity 8 + 1.083631e+000, + 3.047021e+000, + -7.766096e+000, + 2.496261e+001, + 2.744264e+001, + 2.291875e+001, + // albedo 1, turbidity 9 + 9.707994e-001, + 2.736459e+000, + -6.308284e+000, + 1.760860e+001, + 3.776291e+001, + 2.392150e+001, + // albedo 1, turbidity 10 + 8.574294e-001, + 1.865155e+000, + -2.364707e+000, + 4.337793e+000, + 5.092831e+001, + 2.523432e+001, +}; + +double datasetXYZ2[] = +{ + // albedo 0, turbidity 1 + -1.127942e+000, + -1.905548e-001, + -1.252356e+001, + 1.375799e+001, + -3.624732e-002, + 1.055453e+000, + 1.385036e-002, + 4.176970e+000, + 5.928345e-001, + -1.155260e+000, + -1.778135e-001, + 6.216056e+000, + -5.254116e+000, + -8.787445e-002, + 8.434621e-001, + 4.025734e-002, + 6.195322e+000, + 3.111856e-001, + -1.125624e+000, + -3.217593e-001, + 5.043919e-001, + 1.686284e+000, + -3.536071e-001, + 1.476321e+000, + -7.899019e-002, + -4.522531e+000, + 1.271691e+000, + -1.081801e+000, + -1.033234e-001, + 9.995550e-001, + 7.482946e-003, + -6.776018e-002, + 1.463141e+000, + 9.492021e-002, + 5.612723e+000, + 1.298846e-001, + -1.075320e+000, + -2.402711e-001, + 2.141284e+000, + -1.203359e+000, + -4.945188e+000, + 1.437221e+000, + -8.096750e-002, + -1.028378e+000, + 1.004164e+000, + -1.073337e+000, + -1.516517e-001, + 1.639379e+000, + 2.304669e+000, + -3.214244e+000, + 1.286245e+000, + 5.613957e-002, + 2.480902e+000, + 4.999363e-001, + // albedo 0, turbidity 2 + -1.128399e+000, + -1.857793e-001, + -1.089863e+001, + 1.172984e+001, + -3.768099e-002, + 9.439285e-001, + 4.869335e-002, + 4.845114e+000, + 6.119211e-001, + -1.114002e+000, + -1.399280e-001, + 4.963800e+000, + -4.685500e+000, + -7.780879e-002, + 4.049736e-001, + 1.586297e-001, + 7.770264e+000, + 3.449006e-001, + -1.185472e+000, + -3.403543e-001, + 6.588322e-001, + 1.133713e+000, + -4.118674e-001, + 2.061191e+000, + -1.882768e-001, + -4.372586e+000, + 1.223530e+000, + -1.002272e+000, + 2.000703e-002, + 7.073269e-002, + 1.485075e+000, + 5.005589e-001, + 4.301494e-001, + 3.626541e-001, + 7.921098e+000, + 1.574766e-001, + -1.121006e+000, + -3.007777e-001, + 2.242051e+000, + -4.571561e+000, + -7.761071e+000, + 2.053404e+000, + -1.524018e-001, + -1.886162e+000, + 1.018208e+000, + -1.058864e+000, + -1.358673e-001, + 1.389667e+000, + 8.633409e+000, + -3.437249e+000, + 7.295429e-001, + 1.514700e-001, + 2.842513e+000, + 5.014325e-001, + // albedo 0, turbidity 3 + -1.144464e+000, + -2.043799e-001, + -1.020188e+001, + 1.071247e+001, + -3.256693e-002, + 7.860205e-001, + 6.872719e-002, + 4.824771e+000, + 6.259836e-001, + -1.170104e+000, + -2.118626e-001, + 4.391405e+000, + -4.198900e+000, + -7.111559e-002, + 3.890442e-001, + 1.024831e-001, + 6.282535e+000, + 5.365688e-001, + -1.129171e+000, + -2.552880e-001, + 2.238298e-001, + 7.314295e-001, + -3.562730e-001, + 1.881931e+000, + -3.078716e-002, + -1.039120e+000, + 9.096301e-001, + -1.042294e+000, + 4.450203e-003, + -5.116033e-001, + 2.627589e+000, + 6.098996e-001, + -1.264638e-001, + 4.325281e-001, + 7.080503e+000, + 4.583646e-001, + -1.082293e+000, + -2.723056e-001, + 2.065076e+000, + -8.143133e+000, + -7.892212e+000, + 2.142231e+000, + -7.106240e-002, + -1.122398e+000, + 8.338505e-001, + -1.071715e+000, + -1.426568e-001, + 1.095351e+000, + 1.729783e+001, + -3.851931e+000, + 4.360514e-001, + 2.114440e-001, + 2.970832e+000, + 5.944389e-001, + // albedo 0, turbidity 4 + -1.195909e+000, + -2.590449e-001, + -1.191037e+001, + 1.207947e+001, + -1.589842e-002, + 6.297846e-001, + 9.054772e-002, + 4.285959e+000, + 5.933752e-001, + -1.245763e+000, + -3.316637e-001, + 4.293660e+000, + -3.694011e+000, + -4.699947e-002, + 4.843684e-001, + 2.130425e-002, + 4.097549e+000, + 6.530809e-001, + -1.148742e+000, + -1.902509e-001, + -2.393233e-001, + -2.441254e-001, + -2.610918e-001, + 1.846988e+000, + 3.532866e-002, + 2.660106e+000, + 8.358294e-001, + -1.016080e+000, + -7.444960e-002, + -5.053436e-001, + 4.388855e+000, + 6.054987e-001, + -1.208300e+000, + 5.817215e-001, + 2.543570e+000, + 4.726568e-001, + -1.072027e+000, + -2.101440e-001, + 1.518378e+000, + -1.060119e+001, + -6.016546e+000, + 2.649475e+000, + -5.166992e-002, + 1.571269e+000, + 8.344622e-001, + -1.072365e+000, + -1.511201e-001, + 7.478010e-001, + 1.900732e+001, + -3.950387e+000, + -3.473907e-001, + 3.797211e-001, + 2.782949e+000, + 6.296808e-001, + // albedo 0, turbidity 5 + -1.239423e+000, + -3.136289e-001, + -1.351100e+001, + 1.349468e+001, + -7.070423e-003, + 5.012315e-001, + 1.106008e-001, + 3.803619e+000, + 5.577948e-001, + -1.452524e+000, + -5.676944e-001, + 2.993153e+000, + -2.277288e+000, + -2.168954e-002, + 3.056720e-001, + 1.152338e-002, + 1.852697e+000, + 6.427228e-001, + -1.061421e+000, + -4.590521e-002, + 6.057022e-001, + -1.096835e+000, + -1.504952e-001, + 2.344921e+000, + -5.491832e-002, + 5.268322e+000, + 9.082253e-001, + -1.042373e+000, + -1.769498e-001, + -1.075388e+000, + 3.831712e+000, + 3.154140e-001, + -2.416458e+000, + 7.909032e-001, + -1.492892e-002, + 3.854049e-001, + -1.064159e+000, + -1.892684e-001, + 1.438685e+000, + -8.166362e+000, + -3.616364e+000, + 3.275206e+000, + -1.203825e-001, + 2.039491e+000, + 8.688057e-001, + -1.070120e+000, + -1.569508e-001, + 4.124760e-001, + 1.399683e+001, + -3.547085e+000, + -1.046326e+000, + 4.973825e-001, + 2.791231e+000, + 6.503286e-001, + // albedo 0, turbidity 6 + -1.283579e+000, + -3.609518e-001, + -1.335397e+001, + 1.315248e+001, + -4.431938e-004, + 3.769526e-001, + 1.429824e-001, + 3.573613e+000, + 4.998696e-001, + -1.657952e+000, + -7.627948e-001, + 1.958222e+000, + -7.949816e-001, + -2.882837e-002, + 5.356149e-001, + -5.191946e-002, + 8.869955e-001, + 6.263320e-001, + -9.527600e-001, + 6.494189e-002, + 5.361303e-001, + -2.129590e+000, + -9.258630e-002, + 1.604776e+000, + 5.067770e-002, + 6.376055e+000, + 9.138052e-001, + -1.080827e+000, + -2.523120e-001, + -7.154262e-001, + 4.120085e+000, + 1.878228e-001, + -1.492158e+000, + 6.881655e-001, + -1.446611e+000, + 4.040631e-001, + -1.054075e+000, + -1.665498e-001, + 9.191052e-001, + -6.636943e+000, + -1.894826e+000, + 2.107810e+000, + -3.680499e-002, + 2.655452e+000, + 8.413840e-001, + -1.061127e+000, + -1.448849e-001, + 2.667493e-001, + 1.034103e+001, + -4.285769e+000, + -3.874504e-001, + 5.998752e-001, + 3.132426e+000, + 6.652753e-001, + // albedo 0, turbidity 7 + -1.347345e+000, + -4.287832e-001, + -9.305553e+000, + 9.133813e+000, + -3.173527e-003, + 3.977564e-001, + 1.151420e-001, + 3.320564e+000, + 4.998134e-001, + -1.927296e+000, + -9.901372e-001, + -2.593499e+000, + 4.087421e+000, + -5.833993e-002, + 8.158929e-001, + -4.681279e-002, + 2.423716e-001, + 4.938052e-001, + -9.470092e-001, + 7.325237e-002, + 2.064735e+000, + -5.167540e+000, + -1.313751e-002, + 4.832169e-001, + 1.126295e-001, + 6.970522e+000, + 1.035022e+000, + -1.022557e+000, + -2.762616e-001, + -9.375748e-001, + 6.696739e+000, + 2.200765e-001, + -1.133253e-001, + 5.492505e-001, + -3.109391e+000, + 3.321914e-001, + -1.087444e+000, + -1.836263e-001, + 6.225024e-001, + -8.576765e+000, + -1.107637e+000, + 7.859427e-001, + 9.910909e-002, + 3.112938e+000, + 8.596261e-001, + -1.051544e+000, + -1.546262e-001, + 2.371731e-001, + 1.200502e+001, + -4.527291e+000, + 7.268862e-002, + 5.571478e-001, + 2.532873e+000, + 6.662000e-001, + // albedo 0, turbidity 8 + -1.375576e+000, + -4.840019e-001, + -8.121290e+000, + 8.058140e+000, + -1.445661e-002, + 5.123314e-001, + 5.813321e-002, + 3.203219e+000, + 5.442318e-001, + -2.325221e+000, + -1.241463e+000, + -7.063430e+000, + 8.741369e+000, + -7.829950e-002, + 8.844273e-001, + -3.471106e-002, + 1.740583e-001, + 2.814079e-001, + -1.228700e+000, + -2.013412e-001, + 2.949042e+000, + -7.371945e+000, + 1.071753e-001, + -2.491970e-001, + 2.265223e-001, + 6.391504e+000, + 1.172389e+000, + -7.601786e-001, + -1.680631e-001, + -7.584444e-001, + 8.541356e+000, + 8.222291e-002, + 6.729633e-001, + 3.206615e-001, + -3.700940e+000, + 2.710054e-001, + -1.191166e+000, + -2.672347e-001, + 2.927498e-001, + -9.713613e+000, + -4.783721e-001, + 2.352803e-001, + 2.161949e-001, + 2.691481e+000, + 8.745447e-001, + -1.030135e+000, + -1.653301e-001, + 2.263443e-001, + 1.296157e+001, + -4.650644e+000, + 7.055709e-003, + 5.091975e-001, + 2.000370e+000, + 6.603839e-001, + // albedo 0, turbidity 9 + -1.508018e+000, + -6.460933e-001, + -6.402745e+000, + 6.545995e+000, + -3.750320e-002, + 6.921803e-001, + 3.309819e-003, + 2.797527e+000, + 6.978446e-001, + -2.333308e+000, + -1.167837e+000, + -1.746787e+001, + 1.868630e+001, + -8.948229e-003, + 5.621946e-001, + -3.402626e-002, + 1.217943e+000, + 1.149865e-002, + -2.665953e+000, + -1.226307e+000, + 7.169725e+000, + -1.159434e+001, + 3.583420e-002, + -3.074378e-001, + 3.412248e-001, + 4.422122e+000, + 1.283791e+000, + -9.705116e-002, + 8.312991e-002, + -2.160462e+000, + 1.028235e+001, + 3.543357e-002, + 1.032049e+000, + 1.058310e-001, + -2.972898e+000, + 2.418628e-001, + -1.329617e+000, + -3.699557e-001, + 5.560117e-001, + -9.730113e+000, + 9.938865e-002, + -3.071488e-001, + 2.510691e-001, + 1.777111e+000, + 8.705142e-001, + -1.019387e+000, + -1.893247e-001, + 1.194079e-001, + 1.239436e+001, + -4.799224e+000, + 2.940213e-001, + 4.841268e-001, + 1.529724e+000, + 6.582615e-001, + // albedo 0, turbidity 10 + -1.896737e+000, + -1.005442e+000, + -6.411032e+000, + 6.548220e+000, + -3.227596e-002, + 5.717262e-001, + -8.115192e-006, + 2.296704e+000, + 9.000749e-001, + -2.411116e+000, + -1.225587e+000, + -1.753629e+001, + 1.829393e+001, + 1.247555e-002, + 2.364616e-001, + -5.114637e-003, + 1.603778e+000, + -2.224156e-001, + -4.707121e+000, + -2.074977e+000, + 7.942300e+000, + -1.132407e+001, + -5.415654e-002, + 5.446811e-001, + 1.032493e-001, + 4.010235e+000, + 1.369802e+000, + 1.010482e-001, + -4.013305e-001, + -2.674579e+000, + 9.779409e+000, + 1.782506e-001, + 7.053045e-001, + 4.200002e-001, + -2.400671e+000, + 1.953165e-001, + -1.243526e+000, + -3.391255e-001, + 8.848882e-001, + -9.789025e+000, + -3.997324e-001, + -9.546227e-001, + -1.044017e-001, + 6.010593e-001, + 8.714462e-001, + -1.014633e+000, + -1.730009e-001, + -7.738934e-002, + 1.390903e+001, + -4.847307e+000, + 1.076059e+000, + 5.685743e-001, + 1.572992e+000, + 6.561432e-001, + // albedo 1, turbidity 1 + -1.122998e+000, + -1.881183e-001, + -1.030709e+001, + 1.158932e+001, + -4.079495e-002, + 9.603774e-001, + 3.079436e-002, + 4.009235e+000, + 5.060745e-001, + -1.134790e+000, + -1.539688e-001, + 5.478405e+000, + -4.217270e+000, + -1.043858e-001, + 7.165008e-001, + 1.524765e-002, + 6.473623e+000, + 4.207882e-001, + -1.134957e+000, + -3.513318e-001, + 7.393837e-001, + 1.354415e+000, + -4.764078e-001, + 1.690441e+000, + -5.492640e-002, + -5.563523e+000, + 1.145743e+000, + -1.058344e+000, + -5.758503e-002, + 1.168230e+000, + 3.269824e-001, + 1.795193e-001, + 7.849011e-001, + 7.441853e-002, + 6.904804e+000, + 2.818790e-001, + -1.075194e+000, + -2.355813e-001, + 2.463685e+000, + -1.536505e+000, + -7.505771e+000, + 9.619712e-001, + -6.465851e-002, + -1.355492e+000, + 8.489847e-001, + -1.079030e+000, + -1.465328e-001, + 1.773838e+000, + 2.310131e+000, + -3.136065e+000, + 3.507952e-001, + 4.435014e-002, + 2.819225e+000, + 5.689008e-001, + // albedo 1, turbidity 2 + -1.125833e+000, + -1.870849e-001, + -9.555833e+000, + 1.059713e+001, + -4.225402e-002, + 9.164663e-001, + 4.338796e-002, + 4.400980e+000, + 6.056119e-001, + -1.127440e+000, + -1.551891e-001, + 4.755621e+000, + -4.408806e+000, + -7.851763e-002, + 2.268284e-001, + 1.460070e-001, + 7.048003e+000, + 3.525997e-001, + -1.143788e+000, + -3.170178e-001, + 5.480669e-001, + 2.041830e+000, + -4.532139e-001, + 2.302233e+000, + -1.887419e-001, + -4.489221e+000, + 1.250967e+000, + -1.032849e+000, + 7.376031e-003, + 5.666073e-001, + -2.312203e-001, + 4.862894e-001, + -1.748294e-001, + 3.572870e-001, + 8.380522e+000, + 1.302333e-001, + -1.093728e+000, + -2.786977e-001, + 2.641272e+000, + -1.507494e+000, + -8.731243e+000, + 1.684055e+000, + -2.023377e-001, + -2.176398e+000, + 1.013249e+000, + -1.076578e+000, + -1.456205e-001, + 1.693935e+000, + 2.945003e+000, + -2.822673e+000, + -2.520033e-001, + 1.517034e-001, + 2.649109e+000, + 5.179094e-001, + // albedo 1, turbidity 3 + -1.146417e+000, + -2.119353e-001, + -7.187525e+000, + 8.058599e+000, + -5.256438e-002, + 8.375733e-001, + 3.887093e-002, + 4.222111e+000, + 6.695347e-001, + -1.173674e+000, + -2.067025e-001, + 2.899359e+000, + -2.804918e+000, + -8.473899e-002, + 3.944225e-003, + 1.340641e-001, + 6.160887e+000, + 4.527141e-001, + -1.090098e+000, + -2.599633e-001, + 9.180856e-001, + 1.092710e+000, + -4.215019e-001, + 2.427660e+000, + -9.277667e-002, + -2.123523e+000, + 1.058159e+000, + -1.084460e+000, + 8.056181e-003, + -2.453510e-001, + 6.619567e-001, + 4.668118e-001, + -9.526719e-001, + 4.648454e-001, + 8.001572e+000, + 3.054194e-001, + -1.053728e+000, + -2.765784e-001, + 2.792388e+000, + -3.489517e+000, + -8.150535e+000, + 2.195757e+000, + -2.017234e-001, + -2.128017e+000, + 9.326589e-001, + -1.099348e+000, + -1.593939e-001, + 1.568292e+000, + 7.247853e+000, + -2.933000e+000, + -5.890481e-001, + 1.724440e-001, + 2.433484e+000, + 5.736558e-001, + // albedo 1, turbidity 4 + -1.185983e+000, + -2.581184e-001, + -7.761056e+000, + 8.317053e+000, + -3.351773e-002, + 6.676667e-001, + 5.941733e-002, + 3.820727e+000, + 6.324032e-001, + -1.268591e+000, + -3.398067e-001, + 2.348503e+000, + -2.023779e+000, + -5.368458e-002, + 1.083282e-001, + 8.402858e-002, + 3.910254e+000, + 5.577481e-001, + -1.071353e+000, + -1.992459e-001, + 7.878387e-001, + 1.974702e-001, + -3.033058e-001, + 2.335298e+000, + -8.205259e-002, + 7.954454e-001, + 9.972312e-001, + -1.089513e+000, + -3.104364e-002, + -5.995746e-001, + 2.330281e+000, + 6.581939e-001, + -1.821467e+000, + 6.679973e-001, + 5.090195e+000, + 3.125161e-001, + -1.040214e+000, + -2.570934e-001, + 2.660489e+000, + -6.506045e+000, + -7.053586e+000, + 2.763153e+000, + -2.433632e-001, + -7.648176e-001, + 9.452937e-001, + -1.116052e+000, + -1.831993e-001, + 1.457694e+000, + 1.163608e+001, + -3.216426e+000, + -1.045594e+000, + 2.285002e-001, + 1.817407e+000, + 5.810396e-001, + // albedo 1, turbidity 5 + -1.230134e+000, + -3.136264e-001, + -8.909301e+000, + 9.145006e+000, + -1.055387e-002, + 4.467317e-001, + 1.016826e-001, + 3.342964e+000, + 5.633840e-001, + -1.442907e+000, + -5.593147e-001, + 2.156447e+000, + -1.241657e+000, + -3.512130e-002, + 3.050274e-001, + 1.797175e-002, + 1.742358e+000, + 5.977153e-001, + -1.027627e+000, + -6.481539e-002, + 4.351975e-001, + -1.051677e+000, + -2.030672e-001, + 1.942684e+000, + -3.615993e-002, + 4.050266e+000, + 9.801624e-001, + -1.082110e+000, + -1.578209e-001, + -3.397511e-001, + 4.163851e+000, + 6.650368e-001, + -1.841730e+000, + 7.062544e-001, + 6.789881e-001, + 3.172623e-001, + -1.047447e+000, + -1.977560e-001, + 2.183364e+000, + -8.805249e+000, + -5.483962e+000, + 2.551309e+000, + -1.779640e-001, + 1.519501e+000, + 9.212536e-001, + -1.111853e+000, + -1.935736e-001, + 1.394408e+000, + 1.392405e+001, + -3.465430e+000, + -1.068432e+000, + 2.388671e-001, + 1.455336e+000, + 6.233425e-001, + // albedo 1, turbidity 6 + -1.262238e+000, + -3.546341e-001, + -1.008703e+001, + 1.020084e+001, + -1.852187e-003, + 3.537580e-001, + 1.239199e-001, + 3.056093e+000, + 5.132052e-001, + -1.613810e+000, + -7.355585e-001, + 2.760123e+000, + -1.685253e+000, + -2.517552e-002, + 2.914258e-001, + 4.743448e-003, + 8.689596e-001, + 5.674192e-001, + -9.462336e-001, + 2.950767e-002, + -2.613816e-001, + -7.398653e-001, + -1.315558e-001, + 1.901042e+000, + -6.447844e-002, + 4.969341e+000, + 1.027342e+000, + -1.111481e+000, + -2.194054e-001, + -9.004538e-002, + 3.983442e+000, + 4.871278e-001, + -1.965315e+000, + 7.956121e-001, + -2.363225e-001, + 2.718037e-001, + -1.036397e+000, + -1.827106e-001, + 1.964747e+000, + -8.870759e+000, + -4.208011e+000, + 2.461215e+000, + -2.158905e-001, + 1.561676e+000, + 9.436866e-001, + -1.113769e+000, + -1.947819e-001, + 1.300720e+000, + 1.516476e+001, + -4.088732e+000, + -1.069384e+000, + 2.836434e-001, + 1.671451e+000, + 6.229612e-001, + // albedo 1, turbidity 7 + -1.328069e+000, + -4.244047e-001, + -8.417040e+000, + 8.552244e+000, + -6.813504e-003, + 4.127422e-001, + 9.619897e-002, + 2.854227e+000, + 5.059880e-001, + -1.927552e+000, + -1.025290e+000, + 9.529576e-001, + 4.255950e-001, + -3.738779e-002, + 2.584586e-001, + 4.911004e-002, + -2.640913e-001, + 4.138626e-001, + -8.488094e-001, + 1.435988e-001, + 6.356807e-001, + -2.895732e+000, + -8.473961e-002, + 1.701305e+000, + -1.323908e-001, + 6.499338e+000, + 1.210928e+000, + -1.128313e+000, + -3.397048e-001, + -4.043140e-001, + 6.265097e+000, + 5.482395e-001, + -2.057614e+000, + 8.884087e-001, + -2.943879e+000, + 9.760301e-002, + -1.039764e+000, + -1.494772e-001, + 1.781915e+000, + -1.153012e+001, + -3.379232e+000, + 2.517231e+000, + -2.764393e-001, + 2.588849e+000, + 1.052120e+000, + -1.108447e+000, + -2.012251e-001, + 1.198640e+000, + 1.925331e+001, + -4.423892e+000, + -1.257122e+000, + 3.395690e-001, + 1.481220e+000, + 5.880175e-001, + // albedo 1, turbidity 8 + -1.374185e+000, + -4.967434e-001, + -7.401318e+000, + 7.724021e+000, + -2.345723e-002, + 5.979653e-001, + 2.436346e-002, + 2.658970e+000, + 6.014891e-001, + -2.310933e+000, + -1.290290e+000, + -1.301909e+000, + 2.557806e+000, + -3.744449e-002, + 8.982861e-002, + 1.090613e-001, + -4.398363e-001, + 1.184329e-001, + -1.124730e+000, + -9.921830e-002, + 1.366902e+000, + -4.172489e+000, + -5.078016e-002, + 1.393597e+000, + -9.323843e-002, + 6.452721e+000, + 1.435913e+000, + -8.468477e-001, + -2.744819e-001, + -4.347200e-001, + 6.713362e+000, + 6.127133e-001, + -1.685634e+000, + 7.360941e-001, + -4.535502e+000, + -2.920866e-002, + -1.165242e+000, + -2.008697e-001, + 1.438778e+000, + -1.008936e+001, + -2.214771e+000, + 2.102909e+000, + -1.763085e-001, + 2.859075e+000, + 1.093470e+000, + -1.074614e+000, + -2.066374e-001, + 1.131891e+000, + 1.630063e+001, + -4.801441e+000, + -1.112590e+000, + 3.595785e-001, + 1.122227e+000, + 5.794610e-001, + // albedo 1, turbidity 9 + -1.521515e+000, + -6.835604e-001, + -5.571044e+000, + 6.028774e+000, + -4.253715e-002, + 6.875746e-001, + -5.279456e-006, + 2.180150e+000, + 8.487705e-001, + -2.240415e+000, + -1.171166e+000, + -7.182771e+000, + 8.417068e+000, + -1.932866e-002, + 1.101887e-001, + -1.098862e-002, + 6.242195e-001, + -2.393875e-001, + -2.712354e+000, + -1.198830e+000, + 3.180200e+000, + -6.768130e+000, + -2.563386e-003, + 7.984607e-001, + 2.764376e-001, + 4.695358e+000, + 1.557045e+000, + -3.655172e-002, + -2.142321e-002, + -9.138120e-001, + 7.932786e+000, + 3.516542e-001, + -7.994343e-001, + 1.786761e-001, + -4.208399e+000, + 1.820576e-002, + -1.368610e+000, + -2.656212e-001, + 1.249397e+000, + -8.317818e+000, + -8.962772e-001, + 1.423249e+000, + 1.478381e-001, + 2.191660e+000, + 1.007748e+000, + -1.041753e+000, + -2.453366e-001, + 1.061102e+000, + 1.130172e+001, + -4.739312e+000, + -9.223334e-001, + 2.982776e-001, + 6.162931e-001, + 6.080302e-001, + // albedo 1, turbidity 10 + -1.989159e+000, + -1.095160e+000, + -2.915550e+000, + 3.275339e+000, + -5.735765e-002, + 5.742174e-001, + -7.683288e-006, + 1.763400e+000, + 9.001342e-001, + -2.070020e+000, + -1.086338e+000, + -1.095898e+001, + 1.206960e+001, + 3.780123e-002, + -1.774699e-002, + -5.881348e-004, + 1.333819e+000, + -2.605423e-001, + -5.249653e+000, + -2.383040e+000, + 6.160406e+000, + -9.097138e+000, + -1.955319e-001, + 1.651785e+000, + 6.016463e-004, + 3.021824e+000, + 1.493574e+000, + 4.685432e-001, + -2.358662e-001, + -2.666433e+000, + 9.685763e+000, + 5.804928e-001, + -1.521875e+000, + 5.668989e-001, + -1.548136e+000, + 1.688642e-002, + -1.296891e+000, + -3.449031e-001, + 1.928548e+000, + -1.167560e+001, + -1.627615e+000, + 1.355603e+000, + -1.929074e-001, + -6.568952e-001, + 1.009774e+000, + -1.067288e+000, + -2.410392e-001, + 7.147961e-001, + 1.783840e+001, + -4.374399e+000, + -6.588777e-001, + 3.329831e-001, + 1.012066e+000, + 6.118645e-001, +}; + +double datasetXYZRad2[] = +{ + // albedo 0, turbidity 1 + 1.632341e+000, + 1.395230e+000, + 1.375634e+000, + 1.238193e+001, + 5.921102e+000, + 7.766508e+000, + // albedo 0, turbidity 2 + 1.597115e+000, + 1.554617e+000, + 3.932382e-001, + 1.505284e+001, + 5.725234e+000, + 8.158155e+000, + // albedo 0, turbidity 3 + 1.522034e+000, + 1.844545e+000, + -1.322862e+000, + 1.918382e+001, + 5.440769e+000, + 8.837119e+000, + // albedo 0, turbidity 4 + 1.403048e+000, + 2.290852e+000, + -4.013792e+000, + 2.485100e+001, + 5.521888e+000, + 9.845547e+000, + // albedo 0, turbidity 5 + 1.286364e+000, + 2.774498e+000, + -6.648221e+000, + 2.964151e+001, + 5.923777e+000, + 1.097075e+001, + // albedo 0, turbidity 6 + 1.213544e+000, + 3.040195e+000, + -8.092676e+000, + 3.186082e+001, + 6.789782e+000, + 1.158899e+001, + // albedo 0, turbidity 7 + 1.122622e+000, + 3.347465e+000, + -9.649016e+000, + 3.343824e+001, + 9.347715e+000, + 1.231374e+001, + // albedo 0, turbidity 8 + 1.007356e+000, + 3.543858e+000, + -1.053520e+001, + 3.239842e+001, + 1.483962e+001, + 1.331718e+001, + // albedo 0, turbidity 9 + 8.956642e-001, + 3.278700e+000, + -9.254933e+000, + 2.557923e+001, + 2.489677e+001, + 1.476166e+001, + // albedo 0, turbidity 10 + 7.985143e-001, + 2.340404e+000, + -4.928274e+000, + 1.141787e+001, + 3.961501e+001, + 1.682448e+001, + // albedo 1, turbidity 1 + 1.745162e+000, + 1.639467e+000, + 1.342721e+000, + 1.166033e+001, + 1.490124e+001, + 1.774031e+001, + // albedo 1, turbidity 2 + 1.708439e+000, + 1.819144e+000, + 2.834399e-001, + 1.448066e+001, + 1.459214e+001, + 1.858679e+001, + // albedo 1, turbidity 3 + 1.631720e+000, + 2.094799e+000, + -1.378825e+000, + 1.843198e+001, + 1.463173e+001, + 1.962881e+001, + // albedo 1, turbidity 4 + 1.516536e+000, + 2.438729e+000, + -3.624121e+000, + 2.298621e+001, + 1.599782e+001, + 2.070027e+001, + // albedo 1, turbidity 5 + 1.405863e+000, + 2.785191e+000, + -5.705236e+000, + 2.645121e+001, + 1.768330e+001, + 2.191903e+001, + // albedo 1, turbidity 6 + 1.344052e+000, + 2.951807e+000, + -6.683851e+000, + 2.744271e+001, + 1.985706e+001, + 2.229452e+001, + // albedo 1, turbidity 7 + 1.245827e+000, + 3.182923e+000, + -7.822960e+000, + 2.791395e+001, + 2.327254e+001, + 2.315910e+001, + // albedo 1, turbidity 8 + 1.132305e+000, + 3.202593e+000, + -8.008429e+000, + 2.521093e+001, + 3.000014e+001, + 2.405306e+001, + // albedo 1, turbidity 9 + 1.020330e+000, + 2.820556e+000, + -6.238704e+000, + 1.709276e+001, + 4.077916e+001, + 2.509949e+001, + // albedo 1, turbidity 10 + 9.031570e-001, + 1.863917e+000, + -1.955738e+000, + 3.032665e+000, + 5.434290e+001, + 2.641780e+001, +}; + +double datasetXYZ3[] = +{ + // albedo 0, turbidity 1 + -1.310023e+000, + -4.407658e-001, + -3.640340e+001, + 3.683292e+001, + -8.124762e-003, + 5.297961e-001, + 1.188633e-002, + 3.138320e+000, + 5.134778e-001, + -1.424100e+000, + -5.501606e-001, + -1.753510e+001, + 1.822769e+001, + -1.539272e-002, + 6.366826e-001, + 2.661996e-003, + 2.659915e+000, + 4.071138e-001, + -1.103436e+000, + -1.884105e-001, + 6.425322e+000, + -6.910579e+000, + -2.019861e-002, + 3.553271e-001, + -1.589061e-002, + 5.345985e+000, + 8.790218e-001, + -1.186200e+000, + -4.307514e-001, + -3.957947e+000, + 5.979352e+000, + -5.348869e-002, + 1.736117e+000, + 3.491346e-002, + -2.692261e+000, + 5.610506e-001, + -1.006038e+000, + -1.305995e-001, + 4.473513e+000, + -3.806719e+000, + 1.419407e-001, + -2.148238e-002, + -5.081185e-002, + 3.735362e+000, + 5.358280e-001, + -1.078507e+000, + -1.633754e-001, + -3.812368e+000, + 4.381700e+000, + 2.988122e-002, + 1.754224e+000, + 1.472376e-001, + 3.722798e+000, + 4.999157e-001, + // albedo 0, turbidity 2 + -1.333582e+000, + -4.649908e-001, + -3.359528e+001, + 3.404375e+001, + -9.384242e-003, + 5.587511e-001, + 5.726310e-003, + 3.073145e+000, + 5.425529e-001, + -1.562624e+000, + -7.107068e-001, + -1.478170e+001, + 1.559839e+001, + -1.462375e-002, + 5.050133e-001, + 2.516017e-002, + 1.604696e+000, + 2.902403e-001, + -8.930158e-001, + 4.068077e-002, + 1.373481e+000, + -2.342752e+000, + -2.098058e-002, + 6.248686e-001, + -5.258363e-002, + 7.058214e+000, + 1.150373e+000, + -1.262823e+000, + -4.818353e-001, + 8.892610e-004, + 1.923120e+000, + -4.979718e-002, + 1.040693e+000, + 1.558103e-001, + -2.852480e+000, + 2.420691e-001, + -9.968383e-001, + -1.200648e-001, + 1.324342e+000, + -9.430889e-001, + 1.931098e-001, + 4.436916e-001, + -7.320456e-002, + 4.215931e+000, + 7.898019e-001, + -1.078185e+000, + -1.718192e-001, + -1.720191e+000, + 2.358918e+000, + 2.765637e-002, + 1.260245e+000, + 2.021941e-001, + 3.395483e+000, + 5.173628e-001, + // albedo 0, turbidity 3 + -1.353023e+000, + -4.813523e-001, + -3.104920e+001, + 3.140156e+001, + -9.510741e-003, + 5.542030e-001, + 8.135471e-003, + 3.136646e+000, + 5.215989e-001, + -1.624704e+000, + -7.990201e-001, + -2.167125e+001, + 2.246341e+001, + -1.163533e-002, + 5.415746e-001, + 2.618378e-002, + 1.139214e+000, + 3.444357e-001, + -7.983610e-001, + 1.417476e-001, + 9.914841e+000, + -1.081503e+001, + -1.218845e-002, + 3.411392e-001, + -6.137698e-002, + 7.445848e+000, + 1.180080e+000, + -1.266679e+000, + -4.288977e-001, + -5.818701e+000, + 6.986437e+000, + -8.180711e-002, + 1.397403e+000, + 2.016916e-001, + -1.275731e+000, + 2.592773e-001, + -1.009707e+000, + -1.537754e-001, + 3.496378e+000, + -3.013726e+000, + 2.421150e-001, + -2.831925e-001, + 3.003395e-002, + 3.702862e+000, + 7.746320e-001, + -1.075646e+000, + -1.768747e-001, + -1.347762e+000, + 1.989004e+000, + 1.375836e-002, + 1.764810e+000, + 1.330018e-001, + 3.230864e+000, + 6.626210e-001, + // albedo 0, turbidity 4 + -1.375269e+000, + -5.103569e-001, + -3.442661e+001, + 3.478703e+001, + -8.460009e-003, + 5.408643e-001, + 4.813323e-003, + 3.016078e+000, + 5.062069e-001, + -1.821679e+000, + -9.766461e-001, + -1.926488e+001, + 1.997912e+001, + -9.822567e-003, + 3.649556e-001, + 4.316092e-002, + 8.930190e-001, + 4.166527e-001, + -6.633542e-001, + 1.997841e-001, + 2.395592e+000, + -3.117175e+000, + -1.080884e-002, + 8.983814e-001, + -1.375825e-001, + 6.673463e+000, + 1.115663e+000, + -1.303240e+000, + -3.612712e-001, + 8.292959e-002, + 3.381364e-001, + -6.078648e-002, + 3.229247e-001, + 3.680987e-001, + 7.046755e-001, + 3.144924e-001, + -9.952598e-001, + -2.039076e-001, + 4.026851e-001, + 2.686684e-001, + 1.640712e-001, + 5.186341e-001, + -1.205520e-002, + 2.659613e+000, + 8.030394e-001, + -1.098579e+000, + -2.151992e-001, + 6.558198e-001, + -7.436900e-004, + -1.421817e-003, + 1.073701e+000, + 1.886875e-001, + 2.536857e+000, + 6.673923e-001, + // albedo 0, turbidity 5 + -1.457986e+000, + -5.906842e-001, + -3.812464e+001, + 3.838539e+001, + -6.024357e-003, + 4.741484e-001, + 1.209223e-002, + 2.818432e+000, + 5.012433e-001, + -1.835728e+000, + -1.003405e+000, + -6.848129e+000, + 7.601943e+000, + -1.277375e-002, + 4.785598e-001, + 3.366853e-002, + 1.097701e+000, + 4.636635e-001, + -8.491348e-001, + 9.466365e-003, + -2.685226e+000, + 2.004060e+000, + -1.168708e-002, + 6.752316e-001, + -1.543371e-001, + 5.674759e+000, + 1.039534e+000, + -1.083379e+000, + -1.506790e-001, + 7.328236e-001, + -5.095568e-001, + -8.609153e-002, + 4.448820e-001, + 4.174662e-001, + 1.481556e+000, + 3.942551e-001, + -1.117089e+000, + -3.337605e-001, + 2.502281e-001, + 4.036323e-001, + 2.673899e-001, + 2.829817e-001, + 2.242450e-002, + 2.043207e+000, + 7.706902e-001, + -1.071648e+000, + -2.126200e-001, + 6.069466e-001, + -1.456290e-003, + -5.515960e-001, + 1.046755e+000, + 1.985021e-001, + 2.290245e+000, + 6.876058e-001, + // albedo 0, turbidity 6 + -1.483903e+000, + -6.309647e-001, + -4.380213e+001, + 4.410537e+001, + -5.712161e-003, + 5.195992e-001, + 2.028428e-003, + 2.687114e+000, + 5.098321e-001, + -2.053976e+000, + -1.141473e+000, + 5.109183e-001, + 8.060391e-002, + -1.033983e-002, + 4.066532e-001, + 4.869627e-002, + 1.161722e+000, + 4.039525e-001, + -6.348185e-001, + 7.651292e-002, + -1.031327e+001, + 1.007598e+001, + -2.083688e-002, + 7.359516e-001, + -2.029459e-001, + 5.013257e+000, + 1.077649e+000, + -1.228630e+000, + -1.650496e-001, + 4.077157e-002, + -7.189167e-001, + -5.092220e-002, + 2.959814e-001, + 5.111496e-001, + 2.540433e+000, + 3.615330e-001, + -1.041883e+000, + -3.278413e-001, + -6.691911e-002, + 1.307364e+000, + 2.166663e-001, + 3.000595e-001, + -3.157136e-003, + 1.389208e+000, + 7.999026e-001, + -1.103556e+000, + -2.443602e-001, + 4.705347e-001, + -9.296482e-004, + -5.309920e-001, + 9.654511e-001, + 2.142587e-001, + 2.244723e+000, + 6.839976e-001, + // albedo 0, turbidity 7 + -1.555684e+000, + -6.962113e-001, + -4.647983e+001, + 4.674270e+001, + -5.034895e-003, + 4.755090e-001, + -9.502561e-007, + 2.626569e+000, + 5.056194e-001, + -1.998288e+000, + -1.124720e+000, + -1.629586e+000, + 2.187993e+000, + -8.284384e-003, + 3.845258e-001, + 5.726240e-002, + 1.185644e+000, + 4.255812e-001, + -1.032570e+000, + -2.513850e-001, + -3.721112e+000, + 3.506967e+000, + -2.186561e-002, + 9.436049e-001, + -2.451412e-001, + 4.725724e+000, + 1.039256e+000, + -8.597532e-001, + 9.073332e-002, + -2.553741e+000, + 1.993237e+000, + -4.390891e-002, + -2.046928e-001, + 5.515623e-001, + 1.909127e+000, + 3.948212e-001, + -1.210482e+000, + -4.477622e-001, + -2.267805e-001, + 1.219488e+000, + 1.336186e-001, + 6.866897e-001, + 2.808997e-002, + 1.600403e+000, + 7.816409e-001, + -1.078168e+000, + -2.699261e-001, + 2.537282e-001, + 3.820684e-001, + -4.425103e-001, + 5.298235e-001, + 2.185217e-001, + 1.728679e+000, + 6.882743e-001, + // albedo 0, turbidity 8 + -1.697968e+000, + -8.391488e-001, + -5.790105e+001, + 5.814120e+001, + -3.404760e-003, + 4.265140e-001, + -1.796301e-006, + 2.368442e+000, + 5.324429e-001, + -2.141552e+000, + -1.172230e+000, + 1.677872e+001, + -1.641470e+001, + -5.732425e-003, + 2.002199e-001, + 6.841834e-002, + 1.485338e+000, + 3.215763e-001, + -1.442946e+000, + -7.264245e-001, + -9.503706e+000, + 9.650462e+000, + -2.120995e-002, + 1.419263e+000, + -2.893098e-001, + 3.860731e+000, + 1.120857e+000, + -5.696752e-001, + 3.411279e-001, + -2.931035e-001, + -6.512552e-001, + -1.068437e-001, + -1.085661e+000, + 6.107549e-001, + 1.459503e+000, + 3.210336e-001, + -1.313839e+000, + -5.921371e-001, + -2.332222e-001, + 1.648196e+000, + 2.492787e-001, + 1.381033e+000, + -1.993392e-002, + 9.812560e-001, + 8.316329e-001, + -1.087464e+000, + -3.195534e-001, + 2.902095e-001, + 3.383709e-001, + -8.798482e-001, + 1.494668e-002, + 2.529703e-001, + 1.452644e+000, + 6.693870e-001, + // albedo 0, turbidity 9 + -2.068582e+000, + -1.118605e+000, + -5.081598e+001, + 5.097486e+001, + -3.280669e-003, + 4.067371e-001, + -2.544951e-006, + 2.179497e+000, + 5.778017e-001, + -1.744693e+000, + -8.537207e-001, + 2.234361e+001, + -2.208318e+001, + -5.932616e-003, + 1.035049e-001, + 5.742772e-002, + 1.977880e+000, + 2.124846e-001, + -3.287515e+000, + -2.140268e+000, + -1.249566e+001, + 1.240091e+001, + -2.409349e-002, + 1.397821e+000, + -2.371627e-001, + 2.771192e+000, + 1.170496e+000, + 5.502311e-001, + 1.046630e+000, + 2.193517e+000, + -2.220400e+000, + -1.064394e-001, + -1.017926e+000, + 4.795457e-001, + 1.030644e+000, + 3.177516e-001, + -1.719734e+000, + -9.536198e-001, + -6.586821e-001, + 1.386361e+000, + -2.513065e-002, + 1.187011e+000, + 6.542539e-002, + 5.296055e-001, + 8.082660e-001, + -1.005700e+000, + -3.028096e-001, + 4.470957e-002, + 1.007760e+000, + -8.119016e-001, + 3.153338e-002, + 2.311321e-001, + 1.182208e+000, + 6.824758e-001, + // albedo 0, turbidity 10 + -2.728867e+000, + -1.580388e+000, + -3.079627e+001, + 3.092586e+001, + -4.197673e-003, + 3.154759e-001, + -3.897675e-006, + 1.920567e+000, + 6.664791e-001, + -1.322495e+000, + -7.249275e-001, + 1.477660e+001, + -1.468154e+001, + -9.044857e-003, + 5.624314e-002, + 6.498392e-002, + 2.047389e+000, + 6.367540e-002, + -6.102376e+000, + -3.473018e+000, + -9.926071e+000, + 9.637797e+000, + -1.097909e-002, + 1.103498e+000, + -2.424521e-001, + 2.520748e+000, + 1.240260e+000, + 1.351796e+000, + 1.018588e+000, + 2.009081e+000, + -1.333394e+000, + -1.979125e-001, + -3.318292e-001, + 4.476624e-001, + 9.095235e-001, + 2.955611e-001, + -1.774467e+000, + -1.079880e+000, + -8.084680e-002, + 2.577697e-001, + -1.149295e-001, + 4.975303e-001, + 2.931611e-003, + -3.803171e-001, + 8.002794e-001, + -9.898401e-001, + -2.542513e-001, + -7.530911e-002, + 1.870355e+000, + -1.521918e+000, + 2.405164e-001, + 2.964615e-001, + 1.334800e+000, + 6.789053e-001, + // albedo 1, turbidity 1 + -1.279730e+000, + -4.290674e-001, + -4.277972e+001, + 4.343305e+001, + -6.541826e-003, + 4.945086e-001, + 1.425338e-002, + 2.685244e+000, + 5.011313e-001, + -1.449506e+000, + -5.766374e-001, + -1.688496e+001, + 1.781118e+001, + -1.121649e-002, + 3.545020e-001, + 2.287338e-002, + 1.904281e+000, + 4.936998e-001, + -1.021980e+000, + -1.897574e-001, + 2.482462e+000, + -2.941725e+000, + -1.570448e-002, + 7.532578e-001, + -4.256800e-002, + 5.239660e+000, + 4.983116e-001, + -1.162608e+000, + -3.428049e-001, + 3.974358e+000, + -1.527935e+000, + -3.919201e-002, + 8.758593e-001, + 7.291363e-002, + -3.455257e+000, + 8.007426e-001, + -9.929985e-001, + -8.712006e-002, + -7.397313e-001, + 1.348372e+000, + 9.511685e-002, + 3.233584e-001, + -7.549148e-002, + 5.806452e+000, + 4.990042e-001, + -1.084996e+000, + -1.739767e-001, + 1.580475e-001, + 9.088180e-001, + 6.871433e-002, + 5.933079e-001, + 1.188921e-001, + 3.074079e+000, + 4.999327e-001, + // albedo 1, turbidity 2 + -1.317009e+000, + -4.661946e-001, + -4.255347e+001, + 4.312782e+001, + -5.727235e-003, + 4.285447e-001, + 2.189854e-002, + 2.608310e+000, + 5.190700e-001, + -1.469236e+000, + -6.282139e-001, + -1.241404e+001, + 1.348765e+001, + -1.204770e-002, + 5.070285e-001, + -7.280216e-004, + 1.491533e+000, + 3.635064e-001, + -9.713808e-001, + -8.138038e-002, + 3.709854e-001, + -1.041174e+000, + -1.814075e-002, + 5.060860e-001, + -2.053756e-002, + 6.161431e+000, + 1.093736e+000, + -1.159057e+000, + -3.698074e-001, + 2.711209e+000, + -6.006479e-001, + -4.896926e-002, + 9.273957e-001, + 1.137712e-001, + -3.496828e+000, + 2.867109e-001, + -1.011601e+000, + -8.201890e-002, + 2.105725e-001, + 4.597520e-001, + 1.478925e-001, + 2.138940e-001, + -5.660670e-002, + 6.057755e+000, + 7.859121e-001, + -1.078020e+000, + -1.811580e-001, + 1.646622e-001, + 8.348426e-001, + 1.149064e-001, + 4.985738e-001, + 1.376605e-001, + 2.746607e+000, + 4.999626e-001, + // albedo 1, turbidity 3 + -1.325672e+000, + -4.769313e-001, + -4.111215e+001, + 4.168293e+001, + -6.274997e-003, + 4.649469e-001, + 1.119411e-002, + 2.631267e+000, + 5.234546e-001, + -1.619391e+000, + -8.000253e-001, + -1.534098e+001, + 1.632706e+001, + -1.012023e-002, + 4.242255e-001, + 2.931597e-002, + 8.925807e-001, + 3.314765e-001, + -7.356979e-001, + 1.368406e-001, + 2.972579e+000, + -3.535359e+000, + -1.318948e-002, + 4.607620e-001, + -7.182778e-002, + 6.254100e+000, + 1.236299e+000, + -1.316217e+000, + -4.194427e-001, + 3.489902e-002, + 1.289849e+000, + -4.755960e-002, + 1.138222e+000, + 1.975992e-001, + -8.991542e-001, + 2.290572e-001, + -9.502188e-001, + -1.172703e-001, + 1.405202e+000, + -3.061919e-001, + 1.058772e-001, + -3.760592e-001, + -1.983179e-002, + 3.562353e+000, + 7.895959e-001, + -1.100117e+000, + -1.900567e-001, + 4.925030e-001, + 5.250225e-001, + 1.576804e-001, + 1.042701e+000, + 7.330743e-002, + 2.796064e+000, + 6.749783e-001, + // albedo 1, turbidity 4 + -1.354183e+000, + -5.130625e-001, + -4.219268e+001, + 4.271772e+001, + -5.365373e-003, + 4.136743e-001, + 1.235172e-002, + 2.520122e+000, + 5.187269e-001, + -1.741434e+000, + -9.589761e-001, + -8.230339e+000, + 9.296799e+000, + -9.600162e-003, + 4.994969e-001, + 2.955452e-002, + 3.667099e-001, + 3.526999e-001, + -6.917347e-001, + 2.154887e-001, + -8.760264e-001, + 2.334121e-001, + -1.909621e-002, + 4.748033e-001, + -1.138514e-001, + 6.515360e+000, + 1.225097e+000, + -1.293189e+000, + -4.218700e-001, + 1.620952e+000, + -7.858597e-001, + -3.769410e-002, + 6.636786e-001, + 3.364945e-001, + -5.341017e-001, + 2.128347e-001, + -9.735521e-001, + -1.325495e-001, + 1.007517e+000, + 2.598258e-001, + 6.762169e-002, + 1.421018e-003, + -6.915987e-002, + 3.185897e+000, + 8.641956e-001, + -1.094800e+000, + -1.962062e-001, + 5.755591e-001, + 2.906259e-001, + 2.625748e-001, + 7.644049e-001, + 1.347492e-001, + 2.677126e+000, + 6.465460e-001, + // albedo 1, turbidity 5 + -1.393063e+000, + -5.578338e-001, + -4.185249e+001, + 4.233504e+001, + -5.435640e-003, + 4.743765e-001, + 7.422477e-003, + 2.442801e+000, + 5.211707e-001, + -1.939487e+000, + -1.128509e+000, + -8.974257e+000, + 9.978383e+000, + -7.965597e-003, + 2.948830e-001, + 4.436763e-002, + 2.839868e-001, + 3.440424e-001, + -6.011562e-001, + 2.354877e-001, + -3.079820e+000, + 2.585094e+000, + -2.002701e-002, + 7.793909e-001, + -1.598414e-001, + 5.834678e+000, + 1.202856e+000, + -1.315676e+000, + -3.903446e-001, + 1.701900e+000, + -1.304609e+000, + -1.045121e-002, + 2.747707e-001, + 4.143967e-001, + 3.197102e-001, + 2.637580e-001, + -9.618628e-001, + -1.625841e-001, + 1.187138e+000, + 1.497802e-001, + -5.590954e-006, + 3.178475e-002, + -4.153145e-002, + 2.496096e+000, + 8.195082e-001, + -1.111554e+000, + -2.365546e-001, + 7.831875e-001, + 2.018684e-001, + 2.074369e-001, + 7.395978e-001, + 1.225730e-001, + 1.876478e+000, + 6.821167e-001, + // albedo 1, turbidity 6 + -1.427879e+000, + -5.994879e-001, + -3.531016e+001, + 3.581581e+001, + -6.431497e-003, + 4.554192e-001, + 7.348731e-004, + 2.334619e+000, + 5.233377e-001, + -1.998177e+000, + -1.206633e+000, + -2.146510e+001, + 2.242237e+001, + -5.857596e-003, + 2.755663e-001, + 6.384795e-002, + 1.358244e-001, + 3.328437e-001, + -6.440630e-001, + 2.058571e-001, + 2.155499e+000, + -2.587968e+000, + -1.840023e-002, + 8.826555e-001, + -2.222452e-001, + 5.847073e+000, + 1.228387e+000, + -1.229071e+000, + -3.360441e-001, + -3.429599e-001, + 6.179469e-001, + 2.029610e-003, + 8.899319e-002, + 5.041624e-001, + 1.882964e-001, + 2.252040e-001, + -1.022905e+000, + -2.101621e-001, + 1.915689e+000, + -6.498794e-001, + -3.463651e-002, + 8.954605e-002, + -6.797854e-002, + 2.417705e+000, + 8.568618e-001, + -1.082538e+000, + -2.007723e-001, + 4.731009e-001, + 4.077267e-001, + 1.324289e-001, + 6.514880e-001, + 1.702912e-001, + 2.309383e+000, + 6.600895e-001, + // albedo 1, turbidity 7 + -1.472139e+000, + -6.499815e-001, + -3.428465e+001, + 3.469659e+001, + -5.747023e-003, + 4.174167e-001, + 1.688597e-003, + 2.323046e+000, + 5.395191e-001, + -2.161176e+000, + -1.353089e+000, + -2.226827e+001, + 2.329138e+001, + -5.583808e-003, + 2.364793e-001, + 6.096656e-002, + 1.944666e-003, + 2.861624e-001, + -6.593044e-001, + 1.393558e-001, + 4.698373e+000, + -5.193883e+000, + -1.998390e-002, + 1.095635e+000, + -2.391254e-001, + 5.598103e+000, + 1.236193e+000, + -1.195717e+000, + -2.972715e-001, + 4.648953e-002, + 3.024588e-001, + 5.003313e-003, + -3.754741e-001, + 5.247265e-001, + -1.381312e-001, + 2.493896e-001, + -1.020139e+000, + -2.253524e-001, + 3.548437e-001, + 7.030485e-001, + -2.107076e-002, + 4.581395e-001, + -3.243757e-002, + 2.453259e+000, + 8.323623e-001, + -1.098770e+000, + -2.435780e-001, + 8.761614e-001, + 1.941613e-001, + -1.990692e-001, + 3.761139e-001, + 1.657412e-001, + 1.590503e+000, + 6.741417e-001, + // albedo 1, turbidity 8 + -1.648007e+000, + -8.205121e-001, + -4.435106e+001, + 4.479801e+001, + -4.181353e-003, + 3.854830e-001, + -1.842385e-006, + 2.000281e+000, + 5.518363e-001, + -2.140986e+000, + -1.282239e+000, + -3.979213e+000, + 4.672459e+000, + -5.008582e-003, + 2.421920e-001, + 6.253602e-002, + 6.612713e-001, + 2.555851e-001, + -1.300502e+000, + -5.137898e-001, + 5.179821e-001, + -4.032341e-001, + -2.066785e-002, + 1.087929e+000, + -2.615309e-001, + 4.225887e+000, + 1.229237e+000, + -6.963340e-001, + 9.241060e-002, + 6.936356e-002, + -3.588571e-001, + -5.461843e-002, + -5.616643e-001, + 5.484166e-001, + -4.776267e-002, + 2.414935e-001, + -1.233179e+000, + -4.325498e-001, + 6.479813e-001, + 8.368356e-001, + 2.458875e-001, + 6.464752e-001, + -2.897097e-002, + 1.561773e+000, + 8.518598e-001, + -1.051023e+000, + -2.533690e-001, + 1.004294e+000, + 3.028083e-001, + -1.520108e+000, + 1.607013e-001, + 1.619975e-001, + 1.131094e+000, + 6.706655e-001, + // albedo 1, turbidity 9 + -1.948249e+000, + -1.097383e+000, + -4.453697e+001, + 4.494902e+001, + -3.579939e-003, + 3.491605e-001, + -2.500253e-006, + 1.740442e+000, + 6.188022e-001, + -2.154253e+000, + -1.209559e+000, + 4.144894e+000, + -3.562411e+000, + -5.638843e-003, + 1.067169e-001, + 7.594858e-002, + 1.005280e+000, + 1.072543e-001, + -2.513259e+000, + -1.507208e+000, + -1.602979e+000, + 1.404154e+000, + -5.560750e-003, + 1.240490e+000, + -2.852117e-001, + 3.485252e+000, + 1.349321e+000, + -7.832214e-002, + 3.655626e-001, + 3.856288e-001, + 6.867894e-001, + -1.609523e-001, + -6.704306e-001, + 5.357301e-001, + -6.457935e-001, + 1.479503e-001, + -1.354784e+000, + -5.454375e-001, + 8.797469e-001, + -1.466514e+000, + 7.134420e-001, + 5.934903e-001, + -2.911178e-002, + 8.643737e-001, + 9.030724e-001, + -1.048324e+000, + -2.738736e-001, + 8.783074e-001, + 3.246188e+000, + -4.435369e+000, + 1.251791e-001, + 1.783486e-001, + 1.064657e+000, + 6.522878e-001, + // albedo 1, turbidity 10 + -2.770408e+000, + -1.618911e+000, + -2.504031e+001, + 2.531674e+001, + -4.239279e-003, + 3.241013e-001, + -3.764484e-006, + 1.586843e+000, + 7.035906e-001, + -1.913500e+000, + -1.144014e+000, + -1.080587e+001, + 1.153677e+001, + -1.003197e-002, + 1.577515e-001, + 5.217789e-002, + 1.225278e+000, + 5.172771e-003, + -5.293208e+000, + -2.876463e+000, + 2.087053e+000, + -3.201552e+000, + 3.892964e-003, + 5.323930e-001, + -2.034512e-001, + 2.617760e+000, + 1.273597e+000, + 9.060340e-001, + 3.773409e-001, + -6.399945e-001, + 3.213979e+000, + -9.112172e-002, + 6.494055e-001, + 3.953280e-001, + 5.047796e-001, + 2.998695e-001, + -1.482179e+000, + -6.778310e-001, + 1.161775e+000, + -3.004872e+000, + 4.774797e-001, + -4.969248e-001, + -3.512074e-003, + -1.307190e+000, + 7.927378e-001, + -9.863181e-001, + -1.803364e-001, + 5.810824e-001, + 4.580570e+000, + -3.863454e+000, + 5.328174e-001, + 2.272821e-001, + 1.771114e+000, + 6.791814e-001, +}; + +double datasetXYZRad3[] = +{ + // albedo 0, turbidity 1 + 1.168084e+000, + 2.156455e+000, + -3.980314e+000, + 1.989302e+001, + 1.328335e+001, + 1.435621e+001, + // albedo 0, turbidity 2 + 1.135488e+000, + 2.294701e+000, + -4.585886e+000, + 2.090208e+001, + 1.347840e+001, + 1.467658e+001, + // albedo 0, turbidity 3 + 1.107408e+000, + 2.382765e+000, + -5.112357e+000, + 2.147823e+001, + 1.493128e+001, + 1.460882e+001, + // albedo 0, turbidity 4 + 1.054193e+000, + 2.592891e+000, + -6.115000e+000, + 2.268967e+001, + 1.635672e+001, + 1.518999e+001, + // albedo 0, turbidity 5 + 1.006946e+000, + 2.705420e+000, + -6.698930e+000, + 2.291830e+001, + 1.834324e+001, + 1.570651e+001, + // albedo 0, turbidity 6 + 9.794044e-001, + 2.742440e+000, + -6.805283e+000, + 2.225271e+001, + 2.050797e+001, + 1.563130e+001, + // albedo 0, turbidity 7 + 9.413577e-001, + 2.722009e+000, + -6.760707e+000, + 2.098242e+001, + 2.342588e+001, + 1.605011e+001, + // albedo 0, turbidity 8 + 8.917923e-001, + 2.592780e+000, + -6.152635e+000, + 1.774141e+001, + 2.858324e+001, + 1.657910e+001, + // albedo 0, turbidity 9 + 8.288391e-001, + 2.153434e+000, + -4.118327e+000, + 1.078118e+001, + 3.681710e+001, + 1.738139e+001, + // albedo 0, turbidity 10 + 7.623528e-001, + 1.418187e+000, + -8.845235e-001, + 7.590129e-001, + 4.629859e+001, + 1.921657e+001, + // albedo 1, turbidity 1 + 1.352858e+000, + 2.048862e+000, + -2.053393e+000, + 1.405874e+001, + 3.045344e+001, + 3.044430e+001, + // albedo 1, turbidity 2 + 1.330497e+000, + 2.126497e+000, + -2.466296e+000, + 1.467559e+001, + 3.090738e+001, + 3.069707e+001, + // albedo 1, turbidity 3 + 1.286344e+000, + 2.200436e+000, + -2.877228e+000, + 1.492701e+001, + 3.236288e+001, + 3.077223e+001, + // albedo 1, turbidity 4 + 1.234428e+000, + 2.289628e+000, + -3.404699e+000, + 1.499436e+001, + 3.468390e+001, + 3.084842e+001, + // albedo 1, turbidity 5 + 1.178660e+000, + 2.306071e+000, + -3.549159e+000, + 1.411006e+001, + 3.754188e+001, + 3.079730e+001, + // albedo 1, turbidity 6 + 1.151366e+000, + 2.333005e+000, + -3.728627e+000, + 1.363374e+001, + 3.905894e+001, + 3.092599e+001, + // albedo 1, turbidity 7 + 1.101593e+000, + 2.299422e+000, + -3.565787e+000, + 1.196745e+001, + 4.188472e+001, + 3.102755e+001, + // albedo 1, turbidity 8 + 1.038322e+000, + 2.083539e+000, + -2.649585e+000, + 8.037389e+000, + 4.700869e+001, + 3.065948e+001, + // albedo 1, turbidity 9 + 9.596146e-001, + 1.671470e+000, + -8.751538e-001, + 1.679772e+000, + 5.345784e+001, + 3.054520e+001, + // albedo 1, turbidity 10 + 8.640731e-001, + 9.858301e-001, + 1.854956e+000, + -6.798097e+000, + 5.936468e+001, + 3.110255e+001, +}; + + + +double* datasetsXYZ[] = +{ + datasetXYZ1, + datasetXYZ2, + datasetXYZ3 +}; + +double* datasetsXYZRad[] = +{ + datasetXYZRad1, + datasetXYZRad2, + datasetXYZRad3 +}; diff --git a/src/ext/skymodel/ArHosekSkyModelData_RGB.h b/src/ext/skymodel/ArHosekSkyModelData_RGB.h new file mode 100644 index 00000000..9276ddae --- /dev/null +++ b/src/ext/skymodel/ArHosekSkyModelData_RGB.h @@ -0,0 +1,3861 @@ +/* +This source is published under the following 3-clause BSD license. + +Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * None of the names of the contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +/* ============================================================================ + +This file is part of a sample implementation of the analytical skylight and +solar radiance models presented in the SIGGRAPH 2012 paper + + + "An Analytic Model for Full Spectral Sky-Dome Radiance" + +and the 2013 IEEE CG&A paper + + "Adding a Solar Radiance Function to the Hosek Skylight Model" + + both by + + Lukas Hosek and Alexander Wilkie + Charles University in Prague, Czech Republic + + + Version: 1.4a, February 22nd, 2013 + +Version history: + +1.4a February 22nd, 2013 + Removed unnecessary and counter-intuitive solar radius parameters + from the interface of the colourspace sky dome initialisation functions. + +1.4 February 11th, 2013 + Fixed a bug which caused the relative brightness of the solar disc + and the sky dome to be off by a factor of about 6. The sun was too + bright: this affected both normal and alien sun scenarios. The + coefficients of the solar radiance function were changed to fix this. + +1.3 January 21st, 2013 (not released to the public) + Added support for solar discs that are not exactly the same size as + the terrestrial sun. Also added support for suns with a different + emission spectrum ("Alien World" functionality). + +1.2a December 18th, 2012 + Fixed a mistake and some inaccuracies in the solar radiance function + explanations found in ArHosekSkyModel.h. The actual source code is + unchanged compared to version 1.2. + +1.2 December 17th, 2012 + Native RGB data and a solar radiance function that matches the turbidity + conditions were added. + +1.1 September 2012 + The coefficients of the spectral model are now scaled so that the output + is given in physical units: W / (m^-2 * sr * nm). Also, the output of the + XYZ model is now no longer scaled to the range [0...1]. Instead, it is + the result of a simple conversion from spectral data via the CIE 2 degree + standard observer matching functions. Therefore, after multiplication + with 683 lm / W, the Y channel now corresponds to luminance in lm. + +1.0 May 11th, 2012 + Initial release. + + +Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if +an updated version of this code has been published! + +============================================================================ */ + + +/* + +This file contains the coefficient data for the RGB colour space version of +the model. + +*/ + +// uses Aug 23 dataset + +double datasetRGB1[] = +{ + // albedo 0, turbidity 1 + -1.099459e+000, + -1.335146e-001, + -4.083223e+000, + 5.919603e+000, + -1.104166e-001, + 1.600158e+000, + -1.326538e-006, + 4.917807e+000, + 5.127716e-001, + -1.169858e+000, + -1.832793e-001, + 9.694744e-001, + 9.495762e-002, + -4.738918e-002, + 2.194171e-001, + 1.095749e-001, + 3.603604e+000, + 3.815119e-001, + -9.665225e-001, + -1.403888e-001, + 5.194457e+000, + -1.107607e+000, + -8.135181e-001, + 4.969661e+000, + -2.300508e-001, + -2.489350e+000, + 1.279158e+000, + -1.292508e+000, + -1.299552e-001, + -2.071404e+000, + -4.752482e-002, + 1.215598e+000, + -1.904179e+000, + 3.027985e-001, + 8.707768e+000, + 6.332446e-002, + -9.264666e-001, + -1.696780e-001, + 4.574070e+000, + -4.232936e-001, + -7.575833e+000, + 5.079755e+000, + -2.576343e-001, + -4.506805e+000, + 6.908129e-001, + -1.139072e+000, + -1.796056e-001, + 1.923311e+000, + 6.788529e+000, + -2.364389e+000, + -1.064041e+000, + 1.717010e-001, + 1.534681e+000, + 5.015810e-001, + // albedo 0, turbidity 2 + -1.107257e+000, + -1.384411e-001, + -4.285744e+000, + 5.713157e+000, + -1.015992e-001, + 1.372638e+000, + 6.555893e-002, + 5.127514e+000, + 6.550471e-001, + -1.187337e+000, + -1.969013e-001, + 8.551048e-001, + 5.289708e-002, + -7.626406e-002, + 1.733153e-002, + 1.779454e-001, + 3.801038e+000, + 4.742709e-001, + -9.685321e-001, + -1.553308e-001, + 4.732492e+000, + -1.178935e+000, + -7.852791e-001, + 4.604492e+000, + -2.666518e-001, + -2.367663e+000, + 1.177527e+000, + -1.252817e+000, + -5.129949e-002, + -2.800433e+000, + -1.295992e-002, + 1.308964e+000, + -2.204331e+000, + 7.276011e-001, + 8.699265e+000, + 1.188388e-001, + -9.459509e-001, + -2.322133e-001, + 4.375041e+000, + -1.712018e-001, + -7.451681e+000, + 5.078019e+000, + -4.223538e-001, + -4.595561e+000, + 1.074719e+000, + -1.125092e+000, + -1.796750e-001, + 1.626399e+000, + 6.989743e+000, + -2.406382e+000, + -9.060383e-001, + 2.961611e-001, + 1.337715e+000, + 5.438140e-001, + // albedo 0, turbidity 3 + -1.135338e+000, + -1.716160e-001, + -1.499253e+000, + 2.373491e+000, + -1.654023e-001, + 9.566404e-001, + 1.113453e-001, + 4.528473e+000, + 6.579439e-001, + -1.132780e+000, + -1.456214e-001, + -1.736672e+000, + 1.756589e+000, + -1.087003e-001, + 3.757927e-001, + 2.525070e-001, + 7.178513e+000, + 5.003814e-001, + -1.167176e+000, + -2.927225e-001, + 5.727667e+000, + -3.139244e+000, + -6.425204e-001, + 2.822634e+000, + -1.457812e-001, + -6.787080e+000, + 1.017072e+000, + -1.042529e+000, + 4.110823e-002, + -4.000629e+000, + 4.362364e+000, + 1.090540e+000, + -1.338674e+000, + 8.246964e-001, + 1.095249e+001, + 2.912211e-001, + -1.061598e+000, + -2.096143e-001, + 3.803155e+000, + -7.977069e+000, + -3.637880e+000, + 3.707671e+000, + -1.903128e-001, + -3.397953e+000, + 9.971500e-001, + -1.073560e+000, + -2.077964e-001, + 1.492052e+000, + 1.626322e+001, + -5.015304e+000, + -4.059889e-001, + 2.659782e-001, + 6.395380e-001, + 5.634436e-001, + // albedo 0, turbidity 4 + -1.172794e+000, + -2.111186e-001, + -1.360013e+000, + 1.604080e+000, + -8.473723e-002, + 7.217312e-001, + 1.548030e-001, + 4.257010e+000, + 6.328974e-001, + -1.238374e+000, + -2.670827e-001, + 3.247678e-001, + 5.466311e-001, + -7.425952e-001, + 5.276440e-001, + 2.678026e-002, + 5.484169e+000, + 6.814734e-001, + -1.176923e+000, + -2.574586e-001, + 2.304045e+000, + -2.797678e+000, + 1.464405e+000, + 1.998552e+000, + 2.550559e-001, + -4.199772e+000, + 7.544892e-001, + -1.003284e+000, + 1.943984e-002, + -2.145066e+000, + 1.030924e+001, + -1.525413e+001, + -2.023010e+000, + 5.448699e-001, + 8.159497e+000, + 5.539148e-001, + -1.060017e+000, + -2.037206e-001, + 2.483018e+000, + -4.595459e+000, + 6.526991e+000, + 4.031804e+000, + 1.206513e-001, + -2.586527e+000, + 7.875752e-001, + -1.081141e+000, + -2.123302e-001, + 1.092275e+000, + 2.683841e+000, + -4.166938e+000, + -1.396582e+000, + 4.371205e-001, + 1.030233e+000, + 6.664862e-001, + // albedo 0, turbidity 5 + -1.222392e+000, + -2.651924e-001, + -4.625037e-001, + 3.521964e-001, + 2.148855e-002, + 5.078494e-001, + 1.791590e-001, + 3.852516e+000, + 5.998216e-001, + -1.424610e+000, + -4.710155e-001, + -1.826815e-001, + 1.786277e+000, + -1.952442e+000, + 5.277612e-001, + -1.773629e-002, + 2.415874e+000, + 6.701272e-001, + -1.130655e+000, + -1.358609e-001, + 9.171203e-001, + -4.660394e+000, + 6.251162e+000, + 1.904529e+000, + 2.639668e-001, + 1.856130e+000, + 8.228440e-001, + -9.739015e-001, + -6.674749e-002, + -4.768897e-001, + 1.248589e+001, + -1.994688e+001, + -2.353043e+000, + 5.885575e-001, + 1.287251e+000, + 4.830135e-001, + -1.082178e+000, + -1.974495e-001, + 1.050245e+000, + -4.792855e+000, + 8.663406e+000, + 3.246969e+000, + 1.556731e-001, + 8.117442e-001, + 8.050376e-001, + -1.063354e+000, + -1.727108e-001, + 9.681592e-001, + 2.736077e+000, + -4.969269e+000, + -8.360570e-001, + 5.994612e-001, + 1.024039e+000, + 6.786935e-001, + // albedo 0, turbidity 6 + -1.261936e+000, + -3.053676e-001, + -4.262222e-001, + 4.000196e-001, + -2.059388e-002, + 4.721802e-001, + 1.480028e-001, + 3.505343e+000, + 6.121337e-001, + -1.681088e+000, + -6.971919e-001, + -1.105652e-001, + 7.437426e-001, + -6.594399e-001, + 2.254221e-001, + 8.710195e-002, + 1.263913e+000, + 5.681865e-001, + -9.453001e-001, + 3.460388e-002, + 6.067038e-001, + -1.985128e+000, + 3.457236e+000, + 2.655483e+000, + -1.162354e-002, + 3.304716e+000, + 1.001950e+000, + -1.086609e+000, + -2.029011e-001, + -6.399170e-001, + 6.926885e+000, + -1.512189e+001, + -3.793051e+000, + 9.456120e-001, + 2.222222e-001, + 2.893725e-001, + -1.041259e+000, + -1.388790e-001, + 1.147331e+000, + 6.282086e+000, + 3.679836e+000, + 4.398314e+000, + -1.355232e-001, + 1.031134e+000, + 9.273509e-001, + -1.063473e+000, + -1.916051e-001, + 6.556979e-001, + -3.371891e-003, + -3.699664e+000, + -1.926783e+000, + 7.371154e-001, + 1.179975e+000, + 6.367068e-001, + // albedo 0, turbidity 7 + -1.336390e+000, + -3.778927e-001, + -7.259477e-001, + 2.270247e-001, + 4.627513e-001, + 1.366459e-001, + 2.637347e-001, + 3.292059e+000, + 4.998211e-001, + -2.119878e+000, + -1.055472e+000, + 5.422052e-001, + 7.826648e-001, + -1.286065e+000, + 9.517905e-001, + -1.432358e-001, + -2.379816e-001, + 5.910513e-001, + -7.761432e-001, + 2.124336e-001, + -6.845184e-001, + -9.812342e-001, + 4.347257e+000, + 9.671980e-001, + 3.773150e-001, + 5.789529e+000, + 9.646598e-001, + -1.118734e+000, + -3.513815e-001, + 5.500918e-001, + 9.449627e-001, + -1.262070e+001, + -1.825280e+000, + 4.731260e-001, + -3.326892e+000, + 3.568768e-001, + -1.026437e+000, + -8.257946e-002, + 3.221701e-001, + 1.198372e+001, + 1.555130e+000, + 2.560304e+000, + 1.406465e-001, + 2.912858e+000, + 8.643181e-001, + -1.069949e+000, + -2.029607e-001, + 5.825042e-001, + -2.398595e-003, + -3.278335e+000, + -1.349882e+000, + 7.208433e-001, + 8.505164e-001, + 6.625391e-001, + // albedo 0, turbidity 8 + -1.392309e+000, + -4.454945e-001, + -5.664000e-001, + 6.283393e-001, + -3.761727e-001, + 6.949802e-001, + 7.748178e-002, + 3.192797e+000, + 5.968661e-001, + -2.713405e+000, + -1.395112e+000, + 2.029230e-001, + 1.877272e-001, + -3.715859e-001, + -1.652929e-001, + 2.385861e-001, + -4.150768e-001, + 1.375467e-001, + -9.588644e-001, + 2.433900e-002, + -1.527493e+000, + -9.632874e-001, + 5.496269e+000, + 1.094931e+000, + 2.004044e-001, + 6.084554e+000, + 1.369604e+000, + -8.028546e-001, + -2.473563e-001, + 1.617898e+000, + 2.073591e+000, + -1.149446e+001, + -8.394131e-001, + 2.726847e-001, + -4.634538e+000, + 1.367293e-001, + -1.198326e+000, + -1.804865e-001, + -3.565414e-001, + 4.073200e+000, + 1.662086e+000, + 1.239770e+000, + 3.367978e-001, + 2.997402e+000, + 9.360383e-001, + -1.013531e+000, + -1.859060e-001, + 5.799857e-001, + 1.331883e+001, + -4.346873e+000, + -1.113820e+000, + 5.275714e-001, + 8.045177e-001, + 6.496373e-001, + // albedo 0, turbidity 9 + -1.530103e+000, + -6.107468e-001, + -3.841771e-001, + 1.881508e+000, + -1.464807e+000, + 6.654690e-001, + -5.950797e-006, + 2.738912e+000, + 8.101012e-001, + -2.415469e+000, + -1.057499e+000, + -4.161968e-001, + -2.357548e+000, + 6.300296e-001, + 6.224915e-001, + 1.545048e-002, + 2.038561e+000, + -1.339415e-001, + -3.096796e+000, + -1.465688e+000, + -1.199232e+000, + 4.567061e+000, + 3.260980e+000, + -9.794907e-001, + 8.950491e-001, + 2.049235e+000, + 1.331015e+000, + 2.713904e-001, + 2.852852e-001, + 1.202090e+000, + -8.206784e+000, + -5.805762e+000, + 1.804431e+000, + -6.090648e-001, + -1.990902e+000, + 3.288858e-001, + -1.456580e+000, + -3.455960e-001, + -6.409257e-002, + 1.667697e+001, + -2.311094e+000, + -9.771104e-001, + 6.759863e-001, + 1.245136e+000, + 7.911932e-001, + -9.860389e-001, + -2.099564e-001, + 2.946650e-001, + -3.547800e-003, + -2.268313e+000, + -6.205647e-002, + 4.705185e-001, + 8.657995e-001, + 6.856284e-001, + // albedo 0, turbidity 10 + -1.971736e+000, + -9.414047e-001, + -3.400557e-001, + 1.468763e+000, + -1.474284e+000, + 5.501062e-001, + -1.109750e-005, + 2.356370e+000, + 9.001702e-001, + -1.589845e+000, + -7.797079e-001, + -5.582240e-001, + -8.137376e-001, + 5.846617e-001, + 1.129459e-001, + -2.658005e-002, + 2.707248e+000, + -2.112486e-001, + -6.940173e+000, + -2.823963e+000, + -1.620848e+000, + 1.090696e+000, + 2.391730e+000, + 1.370047e+000, + 5.890462e-001, + 1.728400e+000, + 1.331253e+000, + 1.293144e+000, + -1.919778e-003, + 1.644206e+000, + -8.666967e-001, + -7.161953e+000, + -1.385018e+000, + -1.505374e-001, + -1.388643e+000, + 2.530122e-001, + -1.488880e+000, + -2.495496e-001, + -2.377137e-001, + 1.167714e+001, + -8.617124e-001, + 1.053828e+000, + 1.992744e-001, + 3.633564e-001, + 8.553304e-001, + -1.060891e+000, + -4.035829e-001, + 2.823207e-001, + -2.369798e-003, + -1.876577e+000, + -5.950265e-001, + 4.241017e-001, + 3.140802e-001, + 6.631669e-001, + // albedo 1, turbidity 1 + -1.101204e+000, + -1.351353e-001, + -4.030882e+000, + 6.096353e+000, + -1.148599e-001, + 1.606507e+000, + -1.555474e-006, + 4.436084e+000, + 5.973715e-001, + -1.154597e+000, + -1.923378e-001, + 8.512132e-001, + 2.934895e-001, + -6.522777e-002, + 1.389077e-001, + 9.091469e-002, + 3.133307e+000, + 2.108541e-001, + -1.031588e+000, + -1.546804e-001, + 5.266214e+000, + -9.491390e-001, + -7.184867e-001, + 4.875626e+000, + -1.911907e-001, + -2.865642e+000, + 1.087895e+000, + -1.159454e+000, + -9.546699e-002, + -1.508146e+000, + -2.031411e-002, + 1.040653e+000, + -2.333508e+000, + 2.540592e-001, + 8.594981e+000, + 9.316770e-002, + -1.035940e+000, + -2.021151e-001, + 4.719343e+000, + -9.019318e-001, + -7.858046e+000, + 3.901234e+000, + -2.233137e-001, + -4.344739e+000, + 6.550733e-001, + -1.096669e+000, + -1.558196e-001, + 2.057553e+000, + 6.274495e+000, + -2.678352e+000, + -1.814927e+000, + 1.550676e-001, + 1.903276e+000, + 4.998989e-001, + // albedo 1, turbidity 2 + -1.114209e+000, + -1.473531e-001, + -7.602914e+000, + 8.973685e+000, + -4.980074e-002, + 1.289198e+000, + 8.366906e-002, + 4.557987e+000, + 6.118757e-001, + -1.149397e+000, + -1.981628e-001, + 4.914096e+000, + -3.498986e+000, + -6.257090e-002, + 1.667401e-001, + 1.048980e-001, + 2.284689e+000, + 5.935965e-001, + -1.056121e+000, + -1.456172e-001, + 4.272656e-001, + 2.912649e+000, + -5.501745e-001, + 4.406542e+000, + -1.387680e-001, + 1.245555e+000, + 9.733011e-001, + -1.125047e+000, + -4.003662e-002, + 1.058457e+000, + -3.462236e+000, + 4.395278e-001, + -2.395805e+000, + 5.177589e-001, + 4.866247e+000, + 4.253189e-001, + -1.051444e+000, + -2.804541e-001, + 3.364668e+000, + 3.293787e+000, + -1.015741e+001, + 3.807407e+000, + -3.592377e-001, + -3.367415e+000, + 7.900825e-001, + -1.093847e+000, + -1.436965e-001, + 2.384780e+000, + 5.787070e+000, + -2.445987e+000, + -1.311171e+000, + 2.326563e-001, + 1.158439e+000, + 5.555416e-001, + // albedo 1, turbidity 3 + -1.134824e+000, + -1.680468e-001, + -3.325620e+000, + 4.458596e+000, + -1.135063e-001, + 1.104500e+000, + 7.794544e-002, + 4.609952e+000, + 6.854854e-001, + -1.143017e+000, + -1.565926e-001, + 3.014687e-001, + -1.763027e-001, + -3.557925e-002, + -2.342406e-001, + 2.528705e-001, + 5.884085e+000, + 4.750602e-001, + -1.136801e+000, + -2.907502e-001, + 3.682423e+000, + -4.061202e-001, + -8.728159e-001, + 4.001510e+000, + -1.522202e-001, + -5.528713e+000, + 1.044847e+000, + -1.063652e+000, + 7.808107e-002, + -1.983678e+000, + 3.648078e-001, + 2.102276e+000, + -3.065050e+000, + 8.431951e-001, + 1.038830e+001, + 2.662834e-001, + -1.061015e+000, + -2.859814e-001, + 4.223615e+000, + -2.290138e+000, + -8.314010e+000, + 4.405718e+000, + -4.613627e-001, + -4.502910e+000, + 1.008383e+000, + -1.106302e+000, + -1.697123e-001, + 2.087196e+000, + 8.238929e+000, + -2.992416e+000, + -1.821776e+000, + 3.434859e-001, + 7.755179e-001, + 5.341190e-001, + // albedo 1, turbidity 4 + -1.171110e+000, + -2.106304e-001, + -1.614361e+000, + 2.378103e+000, + -1.625969e-001, + 8.504483e-001, + 1.059312e-001, + 4.046256e+000, + 6.618227e-001, + -1.200480e+000, + -2.235733e-001, + 1.014390e+000, + -1.174074e+000, + -4.440180e-001, + 2.262406e-001, + 1.665868e-001, + 5.461829e+000, + 5.676310e-001, + -1.223587e+000, + -3.502622e-001, + 1.699106e+000, + 6.724266e-001, + 1.268567e+000, + 2.135102e+000, + 8.039374e-004, + -5.221111e+000, + 9.445690e-001, + -9.452673e-001, + 1.468459e-001, + -1.335034e+000, + 4.346628e+000, + -1.285652e+001, + -1.807046e+000, + 8.175243e-001, + 9.301065e+000, + 3.656798e-001, + -1.134681e+000, + -3.310951e-001, + 3.571244e+000, + -2.208948e+000, + 6.041580e+000, + 3.107577e+000, + -3.112127e-001, + -4.186351e+000, + 9.188333e-001, + -1.083237e+000, + -1.831394e-001, + 2.062654e+000, + 1.385424e+000, + -5.004950e+000, + -1.332669e+000, + 3.627352e-001, + 3.323150e-001, + 6.191181e-001, + // albedo 1, turbidity 5 + -1.211527e+000, + -2.590617e-001, + -1.660874e-001, + 3.627905e-001, + -1.039258e-001, + 4.697924e-001, + 1.671653e-001, + 3.507497e+000, + 6.022506e-001, + -1.433017e+000, + -4.733592e-001, + 1.724445e-001, + 9.953236e-001, + -1.874457e+000, + 4.432099e-001, + 1.715810e-002, + 2.339272e+000, + 6.441470e-001, + -1.084920e+000, + -1.587903e-001, + 8.999585e-001, + -2.537516e+000, + 5.877859e+000, + 2.014554e+000, + 9.689141e-002, + 3.177242e-001, + 9.030399e-001, + -1.008242e+000, + 2.793030e-003, + -3.507469e-001, + 1.028300e+001, + -2.080454e+001, + -2.781026e+000, + 8.995090e-001, + 3.366951e+000, + 3.473867e-001, + -1.103151e+000, + -2.799598e-001, + 2.525791e+000, + -4.255704e+000, + 9.903388e+000, + 3.722668e+000, + -3.603941e-001, + -1.303292e+000, + 9.369454e-001, + -1.102235e+000, + -2.025061e-001, + 2.085660e+000, + 1.686787e+000, + -5.010957e+000, + -1.656458e+000, + 4.584029e-001, + -2.751759e-001, + 6.184162e-001, + // albedo 1, turbidity 6 + -1.256130e+000, + -3.104904e-001, + 1.639350e-001, + 1.315502e-001, + -7.297583e-001, + 4.778480e-001, + 1.259265e-001, + 3.012108e+000, + 6.202728e-001, + -1.620114e+000, + -6.552670e-001, + -2.877157e-001, + 1.094371e+000, + 2.818914e-001, + 3.696830e-001, + 9.428521e-002, + 1.450951e+000, + 5.681308e-001, + -9.686204e-001, + -3.755647e-002, + 1.469980e+000, + -3.103414e+000, + 2.856583e+000, + 1.883209e+000, + -5.746099e-002, + 1.286383e+000, + 1.001751e+000, + -1.089377e+000, + -1.023062e-001, + -1.498891e+000, + 1.066455e+001, + -1.720184e+001, + -2.759314e+000, + 1.061258e+000, + 2.910211e+000, + 2.624701e-001, + -1.044681e+000, + -2.156857e-001, + 3.230136e+000, + -5.863862e-001, + 6.096640e+000, + 3.550019e+000, + -4.255773e-001, + -1.500033e+000, + 9.687696e-001, + -1.133658e+000, + -2.505101e-001, + 1.717840e+000, + 8.480428e-003, + -5.011789e+000, + -1.740989e+000, + 4.983430e-001, + -2.081829e-001, + 6.088641e-001, + // albedo 1, turbidity 7 + -1.335366e+000, + -3.863319e-001, + -5.279971e-001, + 3.638324e-001, + 3.230699e-001, + 8.339707e-002, + 2.483293e-001, + 2.678646e+000, + 4.998346e-001, + -2.004511e+000, + -9.957121e-001, + 1.250807e+000, + 1.625025e-002, + -3.410754e-001, + 7.858244e-001, + -9.506757e-002, + 2.651876e-002, + 5.788643e-001, + -8.714157e-001, + 1.192051e-001, + -8.486879e-001, + -3.702497e-001, + 1.818277e+000, + 1.103427e+000, + 2.454866e-001, + 3.841575e+000, + 9.847350e-001, + -1.042618e+000, + -2.285793e-001, + 3.620175e-001, + 2.983368e+000, + -9.776844e+000, + -1.971587e+000, + 6.691674e-001, + -7.901947e-001, + 3.213200e-001, + -1.099112e+000, + -1.869868e-001, + 2.044065e+000, + 2.062964e+000, + 1.265668e+000, + 2.710130e+000, + -1.099443e-001, + 2.179353e-001, + 9.024108e-001, + -1.106985e+000, + -2.396881e-001, + 1.809807e+000, + 8.523319e+000, + -5.011788e+000, + -1.590086e+000, + 3.248449e-001, + -1.003187e-001, + 6.550606e-001, + // albedo 1, turbidity 8 + -1.421285e+000, + -4.767024e-001, + -3.885004e-001, + 8.274590e-001, + -3.644229e-001, + 6.999513e-001, + 5.196710e-002, + 2.578431e+000, + 6.246310e-001, + -2.611217e+000, + -1.398846e+000, + 4.527425e-001, + -5.932142e-001, + 2.224617e-001, + -5.593581e-001, + 3.389633e-001, + -7.767112e-001, + 6.536004e-002, + -9.881543e-001, + 4.684782e-002, + -8.616613e-001, + 8.799807e-001, + 4.003130e+000, + 1.739543e+000, + -8.098378e-002, + 5.524802e+000, + 1.499673e+000, + -7.544759e-001, + -2.314808e-001, + 8.125770e-001, + -7.724135e-001, + -9.577645e+000, + -1.629433e+000, + 6.790832e-001, + -4.193895e+000, + -2.526624e-002, + -1.273719e+000, + -2.187030e-001, + 1.401798e+000, + 5.231832e+000, + 7.405093e-001, + 1.775166e+000, + -7.269476e-002, + 1.996087e+000, + 1.057450e+000, + -1.046864e+000, + -2.247559e-001, + 1.679449e+000, + 1.140057e+001, + -4.948829e+000, + -1.182664e+000, + 3.241038e-001, + -2.470012e-001, + 6.115900e-001, + // albedo 1, turbidity 9 + -1.514607e+000, + -5.985430e-001, + -1.877610e-001, + 1.756930e+000, + -1.314206e+000, + 6.115810e-001, + -5.970460e-006, + 2.412975e+000, + 8.124304e-001, + -2.308414e+000, + -1.083797e+000, + -1.179959e-001, + -1.728246e+000, + 7.784742e-001, + 5.494505e-001, + 6.203168e-003, + 9.326251e-001, + -1.419518e-001, + -3.230837e+000, + -1.438670e+000, + -9.868286e-001, + 2.974393e+000, + 1.949339e+000, + -6.337857e-001, + 8.160271e-001, + 3.278606e+000, + 1.354373e+000, + 5.149378e-001, + 2.754789e-001, + 1.040965e+000, + -4.501186e+000, + -3.399057e+000, + 9.661861e-001, + -4.736173e-001, + -4.037574e+000, + 2.794847e-001, + -1.621870e+000, + -3.192763e-001, + 8.786242e-001, + 9.785565e+000, + -2.727652e+000, + 1.903691e-002, + 5.521261e-001, + 2.138764e+000, + 8.419871e-001, + -9.951701e-001, + -2.550607e-001, + 1.498952e+000, + -2.737197e-003, + -3.101832e+000, + -5.921329e-001, + 2.864422e-001, + -4.405218e-001, + 6.631410e-001, + // albedo 1, turbidity 10 + -1.902954e+000, + -9.056918e-001, + -2.069570e-001, + 1.191499e+000, + -1.092577e+000, + 5.849556e-001, + -9.649602e-006, + 2.048407e+000, + 9.001527e-001, + -1.271627e+000, + -7.193923e-001, + -1.136606e-002, + -1.167951e-001, + 3.286175e-003, + -5.262827e-002, + -2.473874e-002, + 1.716125e+000, + -2.187133e-001, + -7.647175e+000, + -3.114129e+000, + -1.490128e+000, + -5.266488e-001, + 3.063090e+000, + 1.474262e+000, + 5.481458e-001, + 2.052174e+000, + 1.353089e+000, + 2.191403e+000, + 3.421120e-001, + 1.446510e+000, + 2.170943e+000, + -7.768187e+000, + -1.471207e+000, + -1.456708e-001, + -1.753574e+000, + 2.310576e-001, + -1.932296e+000, + -3.814739e-001, + 6.245422e-001, + 6.748294e+000, + -3.060171e-001, + 1.067747e+000, + 2.500671e-001, + -1.252596e-001, + 8.614611e-001, + -9.471101e-001, + -4.052640e-001, + 1.300174e+000, + -3.951536e-003, + -1.908284e+000, + -5.385721e-001, + 2.133578e-001, + -6.250292e-001, + 6.658012e-001, +}; + +double datasetRGBRad1[] = +{ + // albedo 0, turbidity 1 + 1.962684e+000, + 1.159831e+000, + 4.450588e+000, + 5.079633e+000, + 4.437388e+000, + 4.324573e+000, + // albedo 0, turbidity 2 + 1.946487e+000, + 1.287515e+000, + 3.703696e+000, + 8.782833e+000, + 3.440437e+000, + 5.160333e+000, + // albedo 0, turbidity 3 + 1.882170e+000, + 1.335878e+000, + 2.648641e+000, + 1.358368e+001, + 3.105473e+000, + 5.907387e+000, + // albedo 0, turbidity 4 + 1.738159e+000, + 1.624289e+000, + -8.786695e-003, + 2.118253e+001, + 2.770255e+000, + 7.055672e+000, + // albedo 0, turbidity 5 + 1.571896e+000, + 2.301786e+000, + -4.028545e+000, + 2.966806e+001, + 1.630876e+000, + 8.711031e+000, + // albedo 0, turbidity 6 + 1.475048e+000, + 2.679086e+000, + -6.311315e+000, + 3.377896e+001, + 2.140975e+000, + 9.385283e+000, + // albedo 0, turbidity 7 + 1.326174e+000, + 3.378759e+000, + -9.831444e+000, + 3.942061e+001, + 2.852702e+000, + 1.082542e+001, + // albedo 0, turbidity 8 + 1.153344e+000, + 3.967771e+000, + -1.265181e+001, + 4.195016e+001, + 7.468239e+000, + 1.221350e+001, + // albedo 0, turbidity 9 + 9.746081e-001, + 4.051626e+000, + -1.298454e+001, + 3.754964e+001, + 1.749232e+001, + 1.420619e+001, + // albedo 0, turbidity 10 + 8.448016e-001, + 3.181809e+000, + -8.757338e+000, + 2.197962e+001, + 3.524033e+001, + 1.639549e+001, + // albedo 1, turbidity 1 + 2.029623e+000, + 1.364434e+000, + 4.201529e+000, + 5.415099e+000, + 9.825839e+000, + 1.063328e+001, + // albedo 1, turbidity 2 + 2.023126e+000, + 1.494728e+000, + 3.420413e+000, + 9.072178e+000, + 9.205157e+000, + 1.186639e+001, + // albedo 1, turbidity 3 + 1.956307e+000, + 1.648665e+000, + 2.039712e+000, + 1.430239e+001, + 9.039526e+000, + 1.330453e+001, + // albedo 1, turbidity 4 + 1.825053e+000, + 1.985022e+000, + -8.036307e-001, + 2.202493e+001, + 9.415361e+000, + 1.517659e+001, + // albedo 1, turbidity 5 + 1.650367e+000, + 2.593201e+000, + -4.469328e+000, + 2.969817e+001, + 9.410977e+000, + 1.744850e+001, + // albedo 1, turbidity 6 + 1.555202e+000, + 2.962925e+000, + -6.608170e+000, + 3.329887e+001, + 1.064559e+001, + 1.850816e+001, + // albedo 1, turbidity 7 + 1.412478e+000, + 3.439403e+000, + -9.196616e+000, + 3.685077e+001, + 1.345341e+001, + 2.003128e+001, + // albedo 1, turbidity 8 + 1.252990e+000, + 3.820805e+000, + -1.115338e+001, + 3.721593e+001, + 2.014916e+001, + 2.182320e+001, + // albedo 1, turbidity 9 + 1.091952e+000, + 3.663027e+000, + -1.031330e+001, + 2.978985e+001, + 3.296835e+001, + 2.375450e+001, + // albedo 1, turbidity 10 + 9.501691e-001, + 2.664579e+000, + -5.545167e+000, + 1.281159e+001, + 5.154768e+001, + 2.574284e+001, +}; + +double datasetRGB2[] = +{ + // albedo 0, turbidity 1 + -1.140530e+000, + -1.982747e-001, + -7.512730e+000, + 8.403899e+000, + -5.699038e-002, + 9.015907e-001, + 3.392161e-002, + 4.772522e+000, + 5.111184e-001, + -1.165117e+000, + -1.852955e-001, + 2.963684e+000, + -2.262274e+000, + -1.571683e-001, + 6.339974e-001, + 4.977879e-002, + 7.243307e+000, + 4.220053e-001, + -1.169936e+000, + -3.357429e-001, + 1.911291e+000, + -2.391074e-001, + -4.791643e-001, + 1.446113e+000, + -9.178108e-002, + -4.700239e+000, + 8.096219e-001, + -1.060246e+000, + -1.051633e-001, + 5.013829e-001, + 2.832309e+000, + -3.707855e-001, + 1.523131e+000, + 9.163749e-002, + 5.604183e+000, + 7.208566e-001, + -1.089753e+000, + -2.382167e-001, + 2.360312e+000, + -5.902562e+000, + -8.799894e+000, + 1.377692e+000, + -6.131633e-002, + -1.415472e+000, + 6.124057e-001, + -1.075481e+000, + -1.242391e-001, + 1.425781e+000, + 8.810319e+000, + -2.922646e+000, + 1.486520e+000, + 3.270580e-002, + 3.889783e+000, + 4.999482e-001, + // albedo 0, turbidity 2 + -1.149342e+000, + -2.076337e-001, + -7.446587e+000, + 8.014559e+000, + -4.866227e-002, + 8.203043e-001, + 6.386483e-002, + 4.894198e+000, + 5.452051e-001, + -1.120531e+000, + -1.513311e-001, + 2.735504e+000, + -2.417591e+000, + -1.361114e-001, + 4.296342e-001, + 9.427488e-002, + 8.171403e+000, + 4.102448e-001, + -1.226964e+000, + -3.516378e-001, + 1.308298e+000, + -5.097487e-002, + -4.846783e-001, + 1.654619e+000, + -1.134940e-001, + -3.347854e+000, + 1.131147e+000, + -9.664377e-001, + 2.767589e-002, + 1.658235e-001, + 2.407439e+000, + -1.300304e-001, + 9.170958e-001, + 2.742895e-001, + 6.642633e+000, + 2.550064e-001, + -1.153358e+000, + -3.126223e-001, + 2.078934e+000, + -5.857733e+000, + -8.659848e+000, + 1.758505e+000, + -9.616094e-002, + -1.230863e+000, + 9.663832e-001, + -1.053850e+000, + -1.330743e-001, + 1.481738e+000, + 1.049485e+001, + -3.528854e+000, + 9.142363e-001, + 1.244880e-001, + 2.644615e+000, + 5.001048e-001, + // albedo 0, turbidity 3 + -1.173687e+000, + -2.360362e-001, + -3.741454e+000, + 4.088507e+000, + -7.528205e-002, + 6.645237e-001, + 7.718265e-002, + 4.651220e+000, + 5.586318e-001, + -1.213757e+000, + -2.589561e-001, + 7.132551e-001, + -4.259327e-001, + -1.980821e-001, + 3.627815e-001, + 4.666560e-002, + 5.807984e+000, + 5.847377e-001, + -1.108794e+000, + -2.259870e-001, + 1.574179e+000, + -3.753731e-001, + -5.984743e-001, + 1.659414e+000, + -1.681021e-002, + 6.785219e-001, + 8.647325e-001, + -1.060896e+000, + -1.346690e-002, + -7.529656e-001, + 1.711319e+000, + -9.792435e-001, + 2.022433e-001, + 3.826487e-001, + 5.725157e+000, + 5.290714e-001, + -1.085145e+000, + -2.840715e-001, + 2.088029e+000, + -4.935097e+000, + -9.056542e+000, + 1.976149e+000, + -3.912485e-002, + -8.636064e-001, + 7.452125e-001, + -1.077983e+000, + -1.416633e-001, + 1.100848e+000, + 1.015875e+001, + -2.943712e+000, + 5.255135e-001, + 2.164224e-001, + 2.941143e+000, + 6.699937e-001, + // albedo 0, turbidity 4 + -1.223293e+000, + -2.867444e-001, + -1.624136e+000, + 1.668299e+000, + -9.537589e-002, + 5.015947e-001, + 1.130741e-001, + 4.244812e+000, + 5.082152e-001, + -1.325342e+000, + -4.280991e-001, + 4.705490e-001, + 6.926592e-002, + -4.572587e-001, + 5.344144e-001, + -2.554192e-002, + 3.093939e+000, + 6.639401e-001, + -1.113581e+000, + -1.192133e-001, + 4.011536e-001, + 7.011889e-001, + 2.052842e-001, + 9.880724e-001, + 1.807533e-002, + 4.690160e+000, + 8.576240e-001, + -1.016063e+000, + -1.038138e-001, + -2.280391e-001, + 7.898918e-001, + -1.127333e+001, + 2.074545e-001, + 5.388182e-001, + 1.364263e+000, + 4.660455e-001, + -1.099582e+000, + -2.228607e-001, + 1.332648e+000, + 5.135188e+000, + 1.653152e+000, + 1.417020e+000, + -1.087532e-001, + 1.809275e+000, + 8.080874e-001, + -1.064357e+000, + -1.520775e-001, + 8.207368e-001, + -1.323565e-003, + -5.009523e+000, + 3.946298e-001, + 4.337902e-001, + 2.593198e+000, + 6.719172e-001, + // albedo 0, turbidity 5 + -1.278702e+000, + -3.512866e-001, + -4.511055e-001, + 3.895760e-001, + -2.429672e-001, + 4.270577e-001, + 1.135348e-001, + 3.719130e+000, + 4.998867e-001, + -1.580069e+000, + -7.095475e-001, + -3.198904e-001, + 1.715748e+000, + -1.185915e+000, + 4.523161e-001, + -1.026159e-002, + 7.927188e-001, + 5.538350e-001, + -9.474023e-001, + 1.173703e-001, + 4.881381e-001, + -2.618684e+000, + 3.251661e+000, + 1.213931e+000, + -1.736274e-002, + 8.000768e+000, + 1.025998e+000, + -1.129091e+000, + -3.287694e-001, + -3.524077e-001, + 3.352892e+000, + -1.416073e+001, + -8.485617e-001, + 6.560766e-001, + -2.820937e+000, + 3.111303e-001, + -1.030884e+000, + -1.137581e-001, + 1.109855e+000, + 8.082276e+000, + 1.519214e+000, + 2.112433e+000, + -1.592299e-001, + 3.675905e+000, + 8.703367e-001, + -1.075192e+000, + -1.627166e-001, + 3.514910e-001, + 1.168164e+000, + -4.255822e+000, + -6.015348e-001, + 6.265776e-001, + 2.884818e+000, + 6.548384e-001, + // albedo 0, turbidity 6 + -1.316017e+000, + -3.889652e-001, + -5.030854e-001, + 4.488704e-001, + -3.186800e-001, + 4.570763e-001, + 8.909201e-002, + 3.659274e+000, + 5.011746e-001, + -1.731876e+000, + -8.493806e-001, + 1.194871e-001, + 2.002781e+000, + -2.006547e+000, + 4.872233e-001, + -2.854606e-002, + 2.662137e-001, + 4.611629e-001, + -9.273680e-001, + 1.380954e-001, + -3.302179e-001, + -3.553265e+000, + 4.633345e+000, + 9.696729e-001, + 8.799775e-002, + 8.291129e+000, + 1.094451e+000, + -1.099377e+000, + -3.325392e-001, + 2.501063e-001, + 2.613712e+000, + -1.328142e+001, + -5.579527e-001, + 4.992081e-001, + -3.504402e+000, + 3.022924e-001, + -1.048420e+000, + -1.227773e-001, + 5.845373e-001, + 1.105869e+001, + 3.813151e-002, + 1.330409e+000, + 1.978131e-002, + 3.959430e+000, + 8.396439e-001, + -1.063233e+000, + -1.560639e-001, + 2.840033e-001, + 8.751565e-001, + -3.411820e+000, + -1.436564e-001, + 5.846580e-001, + 2.899292e+000, + 6.799095e-001, + // albedo 0, turbidity 7 + -1.376715e+000, + -4.541567e-001, + -1.445491e+000, + 1.569898e+000, + -1.390627e-001, + 5.558270e-001, + 4.109877e-002, + 3.349451e+000, + 5.516123e-001, + -1.953391e+000, + -1.035869e+000, + 1.690563e+000, + -1.964690e-001, + -7.787096e-001, + 5.799605e-001, + 2.945626e-002, + 4.217906e-002, + 2.451373e-001, + -1.012422e+000, + 7.136451e-002, + -1.862534e+000, + -7.228653e-001, + 1.947997e-001, + 2.091805e-001, + 6.399233e-002, + 7.928994e+000, + 1.290733e+000, + -9.706708e-001, + -2.880950e-001, + 1.107797e+000, + -2.731734e+000, + -8.445995e+000, + 4.296774e-001, + 5.117648e-001, + -3.824277e+000, + 1.761207e-001, + -1.110611e+000, + -1.789409e-001, + 2.108488e-001, + 2.071430e+001, + -1.763174e+000, + 9.554695e-002, + -2.943103e-002, + 3.422079e+000, + 8.815496e-001, + -1.048334e+000, + -1.614087e-001, + 2.475184e-001, + 2.146938e-002, + -2.983901e+000, + 2.538224e-001, + 5.601370e-001, + 2.461925e+000, + 6.777394e-001, + // albedo 0, turbidity 8 + -1.393719e+000, + -5.002724e-001, + -2.408940e+000, + 2.680983e+000, + -1.362825e-001, + 7.395067e-001, + -3.300343e-006, + 3.260889e+000, + 8.132057e-001, + -2.128663e+000, + -1.151182e+000, + 2.923026e+000, + -1.931838e+000, + -4.426170e-001, + 2.309983e-001, + -5.485890e-003, + 3.279529e-001, + -2.229467e-001, + -1.618022e+000, + -3.766490e-001, + -3.163544e+000, + 1.611608e+000, + -3.967476e-001, + 3.933680e-001, + 3.006742e-001, + 6.835177e+000, + 1.613765e+000, + -5.669064e-001, + -1.481749e-001, + 2.071817e+000, + -8.157422e+000, + -5.988088e+000, + 2.387202e-001, + 1.447191e-001, + -4.296385e+000, + 5.011258e-002, + -1.241724e+000, + -2.519348e-001, + -1.908609e-001, + 2.952235e+001, + -3.333660e+000, + -1.837651e-002, + 1.022249e-001, + 2.929320e+000, + 8.867262e-001, + -1.021670e+000, + -1.667327e-001, + 1.789771e-001, + -2.178108e-003, + -2.641572e+000, + -5.641484e-002, + 5.303758e-001, + 2.138196e+000, + 6.780350e-001, + // albedo 0, turbidity 9 + -1.669332e+000, + -7.588708e-001, + -2.993557e+000, + 3.178760e+000, + -8.066442e-002, + 6.544672e-001, + -8.089880e-006, + 2.628924e+000, + 9.001272e-001, + -1.755806e+000, + -8.735348e-001, + 3.258881e+000, + -2.504785e+000, + -3.300791e-001, + 1.180565e-001, + -9.315982e-003, + 1.785154e+000, + -3.205824e-001, + -3.720277e+000, + -1.733350e+000, + -3.332272e+000, + 1.515869e+000, + 1.734218e-001, + 8.011956e-001, + 1.995440e-001, + 3.817666e+000, + 1.638502e+000, + 4.724641e-001, + 3.209828e-001, + 2.051443e+000, + -5.105574e+000, + -6.509139e+000, + -4.232041e-001, + 2.598931e-001, + -2.151756e+000, + -3.493910e-003, + -1.525600e+000, + -4.897606e-001, + -9.891121e-002, + 2.346818e+001, + -2.278152e+000, + 1.681219e-001, + -4.469389e-002, + 1.051000e+000, + 9.294666e-001, + -9.908649e-001, + -2.008182e-001, + 1.605143e-001, + -2.463113e-003, + -2.477349e+000, + -1.218647e-001, + 4.750121e-001, + 1.460813e+000, + 6.661364e-001, + // albedo 0, turbidity 10 + -2.122119e+000, + -1.125475e+000, + -3.066599e+000, + 3.145078e+000, + -5.411593e-002, + 5.133628e-001, + -7.823408e-006, + 2.268448e+000, + 9.001416e-001, + -1.528158e+000, + -9.370249e-001, + 2.567559e+000, + -1.591439e+000, + -3.634460e-001, + 1.763256e-001, + 1.119624e-003, + 1.811848e+000, + -2.637929e-001, + -6.524387e+000, + -2.673507e+000, + -2.940472e+000, + -6.025609e-001, + 7.852067e-001, + 1.073499e+000, + -3.540435e-002, + 3.517416e+000, + 1.490466e+000, + 8.886026e-001, + -9.681828e-002, + 1.430554e+000, + 4.993717e+000, + -6.071355e+000, + -6.053986e-001, + 5.092997e-001, + -1.273010e+000, + 7.491329e-002, + -1.481997e+000, + -5.897282e-001, + 2.659264e-001, + 1.267239e+000, + -5.741291e-001, + 5.983011e-002, + -2.217312e-001, + -3.016452e-001, + 9.260830e-001, + -1.010943e+000, + -2.075134e-001, + 5.066749e-002, + 1.470708e+001, + -3.780501e+000, + 7.253223e-002, + 4.045458e-001, + 1.320164e+000, + 6.559925e-001, + // albedo 1, turbidity 1 + -1.129907e+000, + -1.884011e-001, + -8.047670e+000, + 9.035776e+000, + -5.539419e-002, + 8.823349e-001, + 3.197135e-002, + 4.839388e+000, + 5.042822e-001, + -1.133821e+000, + -1.510781e-001, + 3.362822e+000, + -2.453381e+000, + -1.463925e-001, + 4.728708e-001, + 5.958140e-002, + 7.636300e+000, + 4.805162e-001, + -1.176518e+000, + -3.549902e-001, + 1.729044e+000, + -2.160966e-001, + -5.075865e-001, + 1.675584e+000, + -8.906902e-002, + -5.386842e+000, + 5.452218e-001, + -1.043563e+000, + -7.520975e-002, + 8.750644e-001, + 2.510518e+000, + 7.584882e-003, + 9.361250e-001, + 7.889083e-002, + 6.066644e+000, + 5.813108e-001, + -1.081304e+000, + -2.222253e-001, + 2.517638e+000, + -4.453820e+000, + -8.663691e+000, + 8.662558e-001, + -4.802657e-002, + -8.965449e-001, + 4.886656e-001, + -1.083774e+000, + -1.375469e-001, + 1.685818e+000, + 5.631120e+000, + -3.100752e+000, + 4.045941e-001, + 2.346895e-002, + 3.390321e+000, + 5.008309e-001, + // albedo 1, turbidity 2 + -1.143158e+000, + -2.058334e-001, + -9.660198e+000, + 1.062394e+001, + -4.434119e-002, + 8.607615e-001, + 3.177325e-002, + 4.416481e+000, + 5.918162e-001, + -1.146773e+000, + -1.727385e-001, + 4.626048e+000, + -4.684602e+000, + -8.307137e-002, + 1.619616e-001, + 1.484866e-001, + 7.572868e+000, + 2.681126e-001, + -1.151324e+000, + -3.099303e-001, + 4.125596e-001, + 2.340752e+000, + -4.214444e-001, + 1.987375e+000, + -1.913410e-001, + -3.845978e+000, + 1.337311e+000, + -1.034258e+000, + -7.778759e-003, + 7.050094e-001, + -8.036369e-001, + 3.138570e-001, + 2.469452e-001, + 3.559970e-001, + 7.485917e+000, + 4.790329e-002, + -1.096568e+000, + -2.673169e-001, + 2.575654e+000, + -8.057121e-001, + -8.884928e+000, + 1.416170e+000, + -2.091315e-001, + -1.543494e+000, + 1.065445e+000, + -1.083304e+000, + -1.528265e-001, + 1.697727e+000, + 2.503702e+000, + -2.885296e+000, + -1.298500e-001, + 1.548870e-001, + 2.479652e+000, + 5.066496e-001, + // albedo 1, turbidity 3 + -1.165736e+000, + -2.329945e-001, + -5.967964e+000, + 6.705959e+000, + -5.931355e-002, + 7.485638e-001, + 3.913878e-002, + 4.221591e+000, + 6.183926e-001, + -1.212422e+000, + -2.545910e-001, + 2.418626e+000, + -2.266104e+000, + -1.102014e-001, + 1.363887e-002, + 1.055411e-001, + 5.648062e+000, + 4.557412e-001, + -1.070436e+000, + -2.163341e-001, + 7.098718e-001, + 7.843075e-001, + -4.323930e-001, + 2.109823e+000, + -9.589700e-002, + -1.985193e-001, + 1.060428e+000, + -1.104879e+000, + -3.013622e-002, + 2.976276e-002, + 1.069707e+000, + 1.410000e-001, + -4.880020e-001, + 4.452288e-001, + 6.418590e+000, + 3.195986e-001, + -1.048969e+000, + -2.655317e-001, + 2.689426e+000, + -3.941038e+000, + -9.506461e+000, + 1.837119e+000, + -1.892124e-001, + -1.562146e+000, + 9.043414e-001, + -1.106145e+000, + -1.601642e-001, + 1.544544e+000, + 7.388492e+000, + -2.924600e+000, + -4.328453e-001, + 1.763161e-001, + 2.523111e+000, + 5.851902e-001, + // albedo 1, turbidity 4 + -1.203666e+000, + -2.776587e-001, + -2.084286e+000, + 2.450840e+000, + -8.746613e-002, + 5.258507e-001, + 7.983316e-002, + 3.860055e+000, + 5.486167e-001, + -1.340448e+000, + -4.230590e-001, + 3.462849e-001, + 4.707607e-001, + -2.512626e-001, + 1.530746e-001, + 2.724218e-002, + 3.035216e+000, + 5.876133e-001, + -1.014554e+000, + -1.168790e-001, + 9.477794e-001, + -1.061218e+000, + -4.196730e-001, + 2.058832e+000, + -5.989624e-002, + 3.058168e+000, + 9.763861e-001, + -1.137388e+000, + -9.854030e-002, + -2.984893e-001, + 3.647820e+000, + -6.585571e-001, + -1.479180e+000, + 6.102932e-001, + 3.265914e+000, + 3.480333e-001, + -1.021816e+000, + -2.344957e-001, + 2.463671e+000, + -7.240685e+000, + -8.862697e+000, + 2.514058e+000, + -2.122768e-001, + -3.313968e-002, + 9.028136e-001, + -1.126581e+000, + -1.874347e-001, + 1.454154e+000, + 1.034398e+001, + -3.237393e+000, + -8.654927e-001, + 2.457248e-001, + 1.845769e+000, + 6.002482e-001, + // albedo 1, turbidity 5 + -1.263727e+000, + -3.439354e-001, + -1.786388e-001, + 3.980166e-001, + -3.349517e-001, + 3.825166e-001, + 1.029225e-001, + 3.331096e+000, + 4.998955e-001, + -1.530010e+000, + -6.879698e-001, + 2.380415e-001, + 1.608216e+000, + -1.682679e+000, + 3.546360e-001, + -3.915220e-003, + 4.517655e-001, + 5.128605e-001, + -9.685659e-001, + 9.480403e-002, + 6.076844e-002, + -3.217561e+000, + 4.568074e+000, + 1.069299e+000, + 2.083638e-002, + 7.301088e+000, + 1.072165e+000, + -1.113925e+000, + -3.112382e-001, + 3.954133e-001, + 5.105907e+000, + -1.456866e+001, + -4.917378e-001, + 5.289909e-001, + -2.678374e+000, + 3.014709e-001, + -1.046864e+000, + -1.215754e-001, + 1.778308e+000, + 4.661489e+000, + 2.565583e-001, + 1.353680e+000, + -1.175767e-001, + 3.415972e+000, + 8.457746e-001, + -1.104480e+000, + -1.940913e-001, + 1.343668e+000, + -1.759206e-003, + -5.009204e+000, + -4.186951e-001, + 3.125710e-001, + 1.628183e+000, + 6.720408e-001, + // albedo 1, turbidity 6 + -1.286902e+000, + -3.781238e-001, + -8.977253e-002, + 3.545393e-001, + -4.866515e-001, + 3.843664e-001, + 8.281675e-002, + 3.122231e+000, + 5.046991e-001, + -1.712597e+000, + -8.549112e-001, + 4.809286e-001, + 1.515398e+000, + -2.212211e+000, + 2.539029e-001, + 2.335997e-002, + -6.089466e-002, + 4.268444e-001, + -8.807283e-001, + 1.646097e-001, + -4.437898e-001, + -3.188247e+000, + 5.984417e+000, + 1.334779e+000, + -4.026975e-002, + 7.546431e+000, + 1.175751e+000, + -1.147253e+000, + -3.538199e-001, + 6.101836e-001, + 4.437780e+000, + -1.559813e+001, + -1.103222e+000, + 6.242039e-001, + -3.091472e+000, + 2.174290e-001, + -1.038230e+000, + -1.213475e-001, + 1.547505e+000, + 5.893176e+000, + 1.368738e+000, + 1.663127e+000, + -1.377130e-001, + 3.185279e+000, + 8.736453e-001, + -1.101026e+000, + -1.874907e-001, + 1.272667e+000, + 3.596524e+000, + -5.007243e+000, + -6.352483e-001, + 3.048985e-001, + 1.931613e+000, + 6.788844e-001, + // albedo 1, turbidity 7 + -1.342753e+000, + -4.384971e-001, + -1.213491e+000, + 1.621399e+000, + -1.551441e-001, + 5.614218e-001, + 2.591739e-002, + 2.958967e+000, + 5.782132e-001, + -1.937684e+000, + -1.066019e+000, + 1.913336e+000, + -7.347719e-001, + -5.916167e-001, + 1.587590e-001, + 1.092568e-001, + -6.275002e-001, + 1.599071e-001, + -9.302391e-001, + 1.486187e-001, + -1.603835e+000, + 1.783713e-001, + 1.100461e+000, + 1.174181e+000, + -1.602361e-001, + 7.868331e+000, + 1.468971e+000, + -1.053631e+000, + -3.727050e-001, + 1.114117e+000, + -9.603286e-001, + -1.062469e+001, + -1.162140e+000, + 7.952797e-001, + -4.478765e+000, + -4.440862e-002, + -1.083629e+000, + -1.261405e-001, + 1.229344e+000, + 1.127825e+001, + 1.319010e-001, + 1.624729e+000, + -2.825898e-001, + 3.661082e+000, + 1.036911e+000, + -1.093950e+000, + -2.067455e-001, + 1.258035e+000, + 7.548645e+000, + -4.598387e+000, + -8.944932e-001, + 3.292634e-001, + 1.311304e+000, + 6.291871e-001, + // albedo 1, turbidity 8 + -1.385867e+000, + -5.068139e-001, + -1.486490e+000, + 1.969049e+000, + -1.698025e-001, + 6.629167e-001, + -5.289365e-006, + 2.760315e+000, + 8.644368e-001, + -2.107367e+000, + -1.175639e+000, + 2.313241e+000, + -1.001653e+000, + -4.843139e-001, + 1.124485e-001, + 3.901494e-005, + -3.502469e-001, + -3.204780e-001, + -1.475244e+000, + -2.833055e-001, + -2.085824e+000, + 1.192563e+000, + -7.645200e-001, + 8.380081e-001, + 2.203580e-001, + 7.157885e+000, + 1.753702e+000, + -6.644372e-001, + -2.549735e-001, + 1.600273e+000, + -8.589034e+000, + -6.144718e+000, + -7.599731e-001, + 2.898370e-001, + -5.770923e+000, + -9.656242e-002, + -1.211687e+000, + -1.653494e-001, + 8.393400e-001, + 2.792988e+001, + -3.395461e+000, + 9.933752e-001, + -3.976877e-002, + 3.776659e+000, + 9.546526e-001, + -1.063757e+000, + -2.037563e-001, + 1.117207e+000, + -1.252806e-003, + -3.332330e+000, + -6.971409e-001, + 3.388719e-001, + 1.311398e+000, + 6.635171e-001, + // albedo 1, turbidity 9 + -1.678889e+000, + -7.992295e-001, + -2.421687e+000, + 2.871029e+000, + -7.662842e-002, + 6.046208e-001, + -7.598099e-006, + 2.002314e+000, + 9.001307e-001, + -1.692144e+000, + -8.804250e-001, + 3.060895e+000, + -2.000009e+000, + -3.183563e-001, + 8.385862e-002, + -6.326713e-003, + 1.206639e+000, + -3.369967e-001, + -3.676795e+000, + -1.719207e+000, + -2.534697e+000, + 1.005285e+000, + 1.550407e-001, + 1.072910e+000, + 1.318094e-001, + 3.717018e+000, + 1.689191e+000, + 5.424542e-001, + 3.263528e-001, + 1.551055e+000, + -3.841058e+000, + -6.598996e+000, + -1.201779e+000, + 3.530669e-001, + -2.542945e+000, + -6.482523e-002, + -1.553849e+000, + -4.576860e-001, + 9.324676e-001, + 1.950982e+001, + -2.344516e+000, + 1.121020e+000, + -1.221537e-001, + 7.285496e-001, + 9.582816e-001, + -1.020650e+000, + -2.215797e-001, + 1.009774e+000, + -2.056855e-003, + -2.740338e+000, + -8.122355e-001, + 3.328967e-001, + 8.982766e-001, + 6.594676e-001, + // albedo 1, turbidity 10 + -2.247360e+000, + -1.221267e+000, + -3.072346e+000, + 3.385139e+000, + -4.387559e-002, + 5.084887e-001, + -7.418833e-006, + 1.750107e+000, + 9.001401e-001, + -1.248499e+000, + -8.442718e-001, + 3.062611e+000, + -2.020314e+000, + -2.815341e-001, + 5.254745e-002, + 3.345008e-003, + 1.433225e+000, + -2.835911e-001, + -7.004119e+000, + -2.927978e+000, + -2.649852e+000, + 7.971894e-001, + 5.466893e-001, + 1.442667e+000, + -6.063912e-002, + 2.806194e+000, + 1.547429e+000, + 1.434882e+000, + 9.114639e-002, + 1.170089e+000, + 3.512808e-002, + -5.861915e+000, + -1.411843e+000, + 5.400486e-001, + -7.746522e-001, + 2.386984e-002, + -1.559053e+000, + -5.502302e-001, + 1.200396e+000, + 1.347741e+001, + -2.344397e+000, + 8.868907e-001, + -3.292661e-001, + -1.362105e+000, + 9.217826e-001, + -1.044436e+000, + -2.360719e-001, + 7.054471e-001, + -2.904518e-003, + -2.092829e+000, + -5.119668e-001, + 4.174861e-001, + 9.687435e-001, + 6.588427e-001, +}; + +double datasetRGBRad2[] = +{ + // albedo 0, turbidity 1 + 1.590330e+000, + 1.355401e+000, + 1.151412e+000, + 1.359116e+001, + 5.857714e+000, + 8.090833e+000, + // albedo 0, turbidity 2 + 1.552540e+000, + 1.510040e+000, + 1.276413e-001, + 1.604643e+001, + 5.912162e+000, + 8.350009e+000, + // albedo 0, turbidity 3 + 1.470871e+000, + 1.880464e+000, + -1.865398e+000, + 2.030808e+001, + 5.471461e+000, + 9.109834e+000, + // albedo 0, turbidity 4 + 1.356563e+000, + 2.373866e+000, + -4.653245e+000, + 2.570922e+001, + 5.686009e+000, + 1.009480e+001, + // albedo 0, turbidity 5 + 1.244232e+000, + 2.851519e+000, + -7.130942e+000, + 2.993449e+001, + 6.382120e+000, + 1.114578e+001, + // albedo 0, turbidity 6 + 1.173693e+000, + 3.120604e+000, + -8.491886e+000, + 3.187393e+001, + 7.290615e+000, + 1.180066e+001, + // albedo 0, turbidity 7 + 1.091845e+000, + 3.368888e+000, + -9.722083e+000, + 3.268508e+001, + 1.032424e+001, + 1.236508e+001, + // albedo 0, turbidity 8 + 9.858985e-001, + 3.500541e+000, + -1.026328e+001, + 3.092956e+001, + 1.610881e+001, + 1.331222e+001, + // albedo 0, turbidity 9 + 8.864993e-001, + 3.172888e+000, + -8.687550e+000, + 2.362161e+001, + 2.621851e+001, + 1.474967e+001, + // albedo 0, turbidity 10 + 7.946973e-001, + 2.189355e+000, + -4.207953e+000, + 9.399091e+000, + 4.062849e+001, + 1.681753e+001, + // albedo 1, turbidity 1 + 1.711696e+000, + 1.657311e+000, + 9.328021e-001, + 1.317880e+001, + 1.506751e+001, + 1.863556e+001, + // albedo 1, turbidity 2 + 1.666968e+000, + 1.849993e+000, + -2.088601e-001, + 1.586653e+001, + 1.486880e+001, + 1.940719e+001, + // albedo 1, turbidity 3 + 1.584846e+000, + 2.170022e+000, + -2.019597e+000, + 1.970826e+001, + 1.490684e+001, + 2.045055e+001, + // albedo 1, turbidity 4 + 1.469412e+000, + 2.524017e+000, + -4.197267e+000, + 2.365249e+001, + 1.664588e+001, + 2.134477e+001, + // albedo 1, turbidity 5 + 1.369714e+000, + 2.843548e+000, + -6.059031e+000, + 2.634993e+001, + 1.881361e+001, + 2.232186e+001, + // albedo 1, turbidity 6 + 1.310477e+000, + 2.984444e+000, + -6.831686e+000, + 2.682340e+001, + 2.123267e+001, + 2.259755e+001, + // albedo 1, turbidity 7 + 1.222552e+000, + 3.176523e+000, + -7.731496e+000, + 2.671760e+001, + 2.484358e+001, + 2.336863e+001, + // albedo 1, turbidity 8 + 1.115781e+000, + 3.130635e+000, + -7.581744e+000, + 2.336531e+001, + 3.171048e+001, + 2.413859e+001, + // albedo 1, turbidity 9 + 1.013181e+000, + 2.699342e+000, + -5.602709e+000, + 1.500158e+001, + 4.217613e+001, + 2.515957e+001, + // albedo 1, turbidity 10 + 8.976323e-001, + 1.726948e+000, + -1.296120e+000, + 1.183675e+000, + 5.503215e+001, + 2.643066e+001, +}; + +double datasetRGB3[] = +{ + // albedo 0, turbidity 1 + -1.372629e+000, + -4.905585e-001, + -4.100789e+001, + 4.122169e+001, + -7.389360e-003, + 4.839359e-001, + 6.474757e-003, + 3.471755e+000, + 5.092936e-001, + -1.523025e+000, + -6.497084e-001, + 6.249857e+000, + -5.662543e+000, + -1.908402e-002, + 5.512810e-001, + -2.181049e-005, + 2.507663e+000, + 4.339598e-001, + -1.035567e+000, + -7.478740e-002, + 9.221030e-001, + -2.140047e+000, + -2.374146e-002, + 3.795517e-001, + -1.769134e-002, + 7.479831e+000, + 7.729303e-001, + -1.271086e+000, + -5.588190e-001, + 6.908023e-001, + 2.096832e+000, + -2.453967e-001, + 1.410648e+000, + 4.475036e-002, + -4.719115e+000, + 5.741186e-001, + -9.712598e-001, + -7.033926e-002, + 9.167274e-001, + -9.502097e-001, + 3.004684e-001, + 4.547054e-001, + -5.929017e-002, + 5.266196e+000, + 7.204135e-001, + -1.087457e+000, + -1.888896e-001, + 8.156686e-001, + 3.101712e-001, + -2.155419e+000, + 1.422205e+000, + 9.692261e-002, + 3.122404e+000, + 4.999430e-001, + // albedo 0, turbidity 2 + -1.425280e+000, + -5.413508e-001, + -3.454883e+001, + 3.481142e+001, + -8.686975e-003, + 4.914268e-001, + -2.479243e-006, + 3.239879e+000, + 6.094201e-001, + -1.688557e+000, + -8.070865e-001, + 7.018459e+000, + -6.244574e+000, + -2.149341e-002, + 3.993971e-001, + 1.252502e-002, + 1.630662e+000, + 1.097860e-001, + -8.664152e-001, + 7.869125e-002, + -5.236535e-001, + -1.218960e+000, + -2.059093e-002, + 6.684898e-001, + -5.584112e-002, + 8.602299e+000, + 1.410496e+000, + -1.319763e+000, + -5.985323e-001, + 1.253918e+000, + 1.914706e+000, + -3.216739e-001, + 9.011213e-001, + 1.324845e-001, + -5.252749e+000, + 6.231252e-002, + -9.706008e-001, + -5.914059e-002, + 5.693150e-001, + -1.175362e+000, + 5.221644e-001, + 7.518213e-001, + -8.247655e-002, + 5.875635e+000, + 9.850863e-001, + -1.085330e+000, + -1.956105e-001, + 8.019605e-001, + 5.338101e-001, + -3.423464e+000, + 1.110444e+000, + 1.507923e-001, + 2.864942e+000, + 4.999481e-001, + // albedo 0, turbidity 3 + -1.431967e+000, + -5.478935e-001, + -3.286288e+001, + 3.305288e+001, + -8.380797e-003, + 4.772050e-001, + -3.044274e-006, + 3.289973e+000, + 5.976303e-001, + -1.801361e+000, + -9.315889e-001, + 5.391756e+000, + -4.588592e+000, + -2.040076e-002, + 4.144684e-001, + 1.814534e-002, + 1.051795e+000, + 1.145651e-001, + -7.905357e-001, + 1.451332e-001, + -1.605661e-001, + -1.592174e+000, + 4.561348e-004, + 3.380323e-001, + -7.770275e-002, + 8.775384e+000, + 1.489512e+000, + -1.308575e+000, + -5.539232e-001, + 9.184133e-001, + 2.011479e+000, + -3.842472e-001, + 1.432274e+000, + 1.637153e-001, + -4.408856e+000, + 5.272957e-002, + -9.829872e-001, + -8.183048e-002, + 4.464556e-001, + -1.442716e+000, + 1.029641e+000, + -6.991617e-002, + 8.702356e-003, + 5.706417e+000, + 9.116452e-001, + -1.087130e+000, + -2.038013e-001, + 7.260801e-001, + 9.164376e-001, + -5.006183e+000, + 1.511271e+000, + 1.257134e-001, + 2.715439e+000, + 6.201652e-001, + // albedo 0, turbidity 4 + -1.448662e+000, + -5.799075e-001, + -2.833268e+001, + 2.858023e+001, + -9.134061e-003, + 4.404783e-001, + -2.709026e-006, + 3.029357e+000, + 5.540071e-001, + -2.061772e+000, + -1.145190e+000, + 7.918478e+000, + -7.212525e+000, + -2.020760e-002, + 2.962715e-001, + 4.689670e-002, + 8.517209e-001, + 2.334587e-001, + -6.413755e-001, + 1.780425e-001, + -2.412919e+000, + 1.064484e+000, + -1.949986e-002, + 6.769741e-001, + -1.752760e-001, + 7.262714e+000, + 1.325869e+000, + -1.304871e+000, + -3.975581e-001, + 1.219002e+000, + 7.285178e-001, + -2.710105e-001, + 7.779727e-001, + 3.247139e-001, + -8.818168e-001, + 1.839517e-001, + -1.001104e+000, + -1.994801e-001, + 3.676742e-001, + -1.409737e+000, + 2.901555e-001, + 2.506940e-001, + 2.468899e-003, + 3.398923e+000, + 8.584645e-001, + -1.111552e+000, + -2.487204e-001, + 7.410842e-001, + 1.703749e+000, + -5.007855e+000, + 1.057763e+000, + 1.354511e-001, + 2.088715e+000, + 6.600013e-001, + // albedo 0, turbidity 5 + -1.547227e+000, + -6.679466e-001, + -1.861465e+001, + 1.884045e+001, + -1.242210e-002, + 4.157339e-001, + -2.432805e-006, + 2.812423e+000, + 5.446957e-001, + -2.043890e+000, + -1.149081e+000, + 2.304118e+000, + -1.715757e+000, + -2.433628e-002, + 2.816836e-001, + 7.185458e-002, + 1.064860e+000, + 2.706789e-001, + -9.040720e-001, + -8.274472e-002, + -2.555676e-001, + -6.326215e-001, + -2.770880e-002, + 6.676024e-001, + -2.513532e-001, + 5.903839e+000, + 1.241452e+000, + -1.000013e+000, + -1.010774e-001, + 3.699166e-001, + 8.774526e-001, + -3.042007e-001, + 6.951053e-001, + 4.361813e-001, + 6.793421e-001, + 2.573892e-001, + -1.171332e+000, + -3.768188e-001, + 3.701377e-001, + -1.470757e+000, + 5.525942e-001, + 2.991456e-002, + 1.581823e-002, + 2.365233e+000, + 8.214514e-001, + -1.068667e+000, + -2.326330e-001, + 6.725059e-001, + 2.243733e+000, + -4.614370e+000, + 1.033677e+000, + 1.376291e-001, + 2.013334e+000, + 6.865304e-001, + // albedo 0, turbidity 6 + -1.592991e+000, + -7.246948e-001, + -2.598204e+001, + 2.621960e+001, + -8.365176e-003, + 4.207571e-001, + -2.742772e-006, + 2.623735e+000, + 5.873190e-001, + -2.271349e+000, + -1.280884e+000, + 6.308739e+000, + -5.758350e+000, + -1.977049e-002, + 3.671835e-001, + 6.698038e-002, + 1.150597e+000, + 1.759218e-001, + -6.368620e-001, + -7.436052e-003, + -2.230026e+000, + 1.640997e+000, + -1.548497e-002, + 3.145331e-001, + -2.492644e-001, + 5.083843e+000, + 1.260215e+000, + -1.177925e+000, + -9.628114e-002, + 3.051152e-001, + -3.749544e-002, + -2.713209e-001, + 1.164226e+000, + 4.559969e-001, + 2.175429e+000, + 2.874284e-001, + -1.078500e+000, + -3.801779e-001, + 4.788906e-001, + -4.795969e-001, + 5.977621e-001, + -4.488535e-001, + 3.386874e-002, + 1.538143e+000, + 8.062054e-001, + -1.108028e+000, + -2.596892e-001, + 5.162202e-001, + 1.557081e+000, + -4.265039e+000, + 1.182535e+000, + 1.563762e-001, + 2.095084e+000, + 6.883383e-001, + // albedo 0, turbidity 7 + -1.668427e+000, + -7.908511e-001, + -2.779690e+001, + 2.799746e+001, + -7.186935e-003, + 3.757766e-001, + -3.326858e-006, + 2.563421e+000, + 5.439687e-001, + -2.156175e+000, + -1.220004e+000, + 3.585732e+000, + -3.235988e+000, + -1.086239e-002, + 1.846143e-001, + 1.046017e-001, + 1.234427e+000, + 2.842191e-001, + -1.117051e+000, + -4.101627e-001, + -8.463730e-001, + 7.671472e-001, + -2.226609e-002, + 8.574943e-001, + -3.434124e-001, + 4.475715e+000, + 1.154824e+000, + -7.444840e-001, + 2.312078e-001, + -5.393724e-001, + 1.574213e-001, + -1.763914e-001, + 2.751692e-001, + 5.564200e-001, + 2.217672e+000, + 3.483932e-001, + -1.273036e+000, + -5.275562e-001, + 4.902512e-001, + -4.498436e-002, + 4.339366e-001, + 2.386682e-001, + 2.380879e-002, + 1.413444e+000, + 7.855923e-001, + -1.084192e+000, + -2.936753e-001, + 4.719432e-001, + 1.384436e+000, + -3.257789e+000, + 6.119543e-001, + 1.681884e-001, + 1.650441e+000, + 6.936631e-001, + // albedo 0, turbidity 8 + -1.848490e+000, + -9.512670e-001, + -3.005251e+001, + 3.024315e+001, + -5.635304e-003, + 3.447780e-001, + -2.782999e-006, + 2.309422e+000, + 5.643559e-001, + -2.300008e+000, + -1.252335e+000, + -1.218876e+000, + 1.493730e+000, + -6.107100e-003, + 7.974860e-002, + 1.023449e-001, + 1.505934e+000, + 2.360948e-001, + -1.483705e+000, + -8.547575e-001, + -7.797146e-001, + 6.447971e-001, + -2.678052e-002, + 1.091263e+000, + -3.344889e-001, + 3.830416e+000, + 1.189425e+000, + -5.348005e-001, + 3.982733e-001, + -4.071573e-001, + 3.265569e-001, + -8.658789e-002, + -2.370892e-001, + 5.369097e-001, + 1.478279e+000, + 3.143303e-001, + -1.320401e+000, + -6.043247e-001, + 3.019196e-001, + -7.732911e-002, + 4.768381e-001, + 6.745764e-001, + 3.694098e-002, + 1.158234e+000, + 8.169056e-001, + -1.101040e+000, + -3.420019e-001, + 3.775661e-001, + 1.769338e+000, + -2.990515e+000, + 1.649529e-001, + 1.970125e-001, + 1.453355e+000, + 6.759757e-001, + // albedo 0, turbidity 9 + -2.251946e+000, + -1.229349e+000, + -3.271808e+001, + 3.283114e+001, + -4.252027e-003, + 3.372289e-001, + -3.001937e-006, + 2.154046e+000, + 5.842674e-001, + -1.867834e+000, + -9.531252e-001, + -1.229365e+001, + 1.269149e+001, + -6.844772e-003, + 1.185107e-001, + 7.539587e-002, + 1.846381e+000, + 1.899412e-001, + -3.398629e+000, + -2.180862e+000, + 2.335213e+000, + -3.382823e+000, + -8.613985e-003, + 8.431602e-001, + -2.393567e-001, + 3.112460e+000, + 1.218556e+000, + 5.708381e-001, + 9.406030e-001, + -6.890113e-001, + 2.746233e+000, + -5.772068e-002, + 1.096005e-001, + 3.491978e-001, + 7.281453e-001, + 3.212049e-001, + -1.705909e+000, + -8.517224e-001, + 1.131160e-001, + -2.141434e+000, + 4.274043e-001, + 3.397600e-001, + 1.786490e-001, + 9.026101e-001, + 7.882800e-001, + -1.012865e+000, + -3.495551e-001, + 3.369038e-001, + 3.724205e+000, + -3.089586e+000, + 1.266964e-001, + 1.461790e-001, + 1.170199e+000, + 6.931052e-001, + // albedo 0, turbidity 10 + -2.890318e+000, + -1.665573e+000, + -3.493756e+001, + 3.500369e+001, + -2.984251e-003, + 2.622419e-001, + -4.259360e-006, + 1.947681e+000, + 6.905752e-001, + -1.956022e+000, + -1.062900e+000, + -1.919714e+001, + 1.975164e+001, + -8.865396e-003, + 2.165540e-001, + 5.475637e-002, + 1.761134e+000, + 3.164249e-003, + -5.612198e+000, + -3.101371e+000, + 4.098034e+000, + -6.144001e+000, + 9.944958e-003, + 2.905472e-001, + -1.707110e-001, + 3.199107e+000, + 1.337660e+000, + 8.353756e-001, + 4.855943e-001, + -1.243589e+000, + 5.147385e+000, + -7.013963e-002, + 9.380410e-001, + 2.335714e-001, + 1.727744e-001, + 2.802696e-001, + -1.524329e+000, + -7.388547e-001, + 3.259025e-001, + -4.050634e+000, + 4.058549e-001, + -2.591384e-001, + 1.898299e-001, + 3.556071e-001, + 7.884126e-001, + -1.070371e+000, + -4.207858e-001, + 1.739862e-001, + 5.293410e+000, + -3.136757e+000, + 2.323856e-001, + 1.673706e-001, + 1.007227e+000, + 6.844287e-001, + // albedo 1, turbidity 1 + -1.341720e+000, + -4.834889e-001, + -4.633447e+001, + 4.682148e+001, + -6.137296e-003, + 4.599216e-001, + 7.047323e-003, + 2.895798e+000, + 4.999398e-001, + -1.529104e+000, + -6.498631e-001, + 1.534103e+001, + -1.450675e+001, + -1.531439e-002, + 3.280082e-001, + 1.682926e-002, + 1.901587e+000, + 5.013227e-001, + -1.014776e+000, + -1.454495e-001, + -4.071085e+000, + 2.954982e+000, + -2.630348e-002, + 5.681531e-001, + -3.016505e-002, + 6.773854e+000, + 5.003504e-001, + -1.172413e+000, + -4.026320e-001, + 2.960428e+000, + 2.020710e-001, + -2.004947e-001, + 9.375572e-001, + 5.998168e-002, + -4.945934e+000, + 4.502898e-001, + -9.898161e-001, + -5.772814e-002, + 4.470024e-001, + -5.786656e-001, + 1.158168e-001, + 3.468040e-001, + -5.043360e-002, + 6.867947e+000, + 8.012363e-001, + -1.085111e+000, + -1.882675e-001, + 1.223748e+000, + 3.565495e-001, + -3.688357e+000, + 5.653723e-001, + 6.727646e-002, + 2.690130e+000, + 4.999400e-001, + // albedo 1, turbidity 2 + -1.389119e+000, + -5.290250e-001, + -4.055774e+001, + 4.105972e+001, + -7.062577e-003, + 4.560060e-001, + -1.736334e-006, + 2.775512e+000, + 6.671455e-001, + -1.584641e+000, + -7.200619e-001, + 1.248067e+001, + -1.156028e+001, + -1.659568e-002, + 3.050029e-001, + 1.099895e-002, + 1.438927e+000, + -2.138015e-002, + -9.826068e-001, + -8.887254e-002, + -2.960031e+000, + 1.808816e+000, + -2.478159e-002, + 6.035733e-001, + -4.868441e-002, + 7.347705e+000, + 1.584739e+000, + -1.150423e+000, + -4.073793e-001, + 2.412991e+000, + 4.870840e-001, + -2.337902e-001, + 8.295114e-001, + 1.129914e-001, + -5.150045e+000, + -9.016643e-002, + -1.016933e+000, + -6.311501e-002, + 5.218937e-001, + -5.716430e-001, + 1.250993e-001, + 3.601524e-001, + -5.497586e-002, + 7.060139e+000, + 1.018333e+000, + -1.073151e+000, + -1.845444e-001, + 1.155394e+000, + 3.004486e-001, + -3.431711e+000, + 4.657031e-001, + 9.401223e-002, + 2.688620e+000, + 4.999544e-001, + // albedo 1, turbidity 3 + -1.391257e+000, + -5.365815e-001, + -4.255881e+001, + 4.299132e+001, + -5.838466e-003, + 4.229134e-001, + -2.760038e-006, + 2.775531e+000, + 6.234597e-001, + -1.780062e+000, + -9.228880e-001, + 1.376172e+001, + -1.260946e+001, + -1.507526e-002, + 3.117435e-001, + 2.205045e-002, + 6.093731e-001, + 3.463446e-002, + -7.388169e-001, + 1.275670e-001, + -3.999528e+000, + 2.223993e+000, + -1.856853e-002, + 5.439310e-001, + -8.834054e-002, + 8.037139e+000, + 1.645951e+000, + -1.322387e+000, + -5.320143e-001, + 2.659359e+000, + 1.086712e+000, + -2.129712e-001, + 8.704649e-001, + 1.800315e-001, + -4.967241e+000, + -1.383720e-001, + -9.378288e-001, + -1.599895e-002, + 3.607555e-001, + -1.980561e+000, + 3.791456e-001, + 1.212268e-001, + -2.845992e-002, + 6.825542e+000, + 1.059139e+000, + -1.100832e+000, + -2.172313e-001, + 1.211561e+000, + 2.002721e+000, + -5.010011e+000, + 5.717583e-001, + 6.777702e-002, + 2.160006e+000, + 5.676392e-001, + // albedo 1, turbidity 4 + -1.409373e+000, + -5.708751e-001, + -3.034974e+001, + 3.079809e+001, + -7.280715e-003, + 3.723304e-001, + -2.436279e-006, + 2.577348e+000, + 5.913377e-001, + -1.954312e+000, + -1.116510e+000, + 5.399148e+000, + -4.299553e+000, + -1.724739e-002, + 3.742824e-001, + 4.187077e-002, + 1.044883e-001, + 1.232727e-001, + -6.772215e-001, + 2.001396e-001, + -3.670523e-001, + -1.014628e+000, + -3.497152e-003, + 4.099858e-001, + -1.584633e-001, + 7.750400e+000, + 1.514559e+000, + -1.291600e+000, + -4.977437e-001, + 9.641914e-001, + 1.562420e+000, + -3.227782e-001, + 9.055427e-001, + 3.046444e-001, + -3.385619e+000, + 9.546291e-003, + -9.750857e-001, + -8.770560e-002, + 9.054256e-001, + -1.429236e+000, + 8.974777e-001, + -1.217961e-001, + -5.194608e-002, + 4.909409e+000, + 9.589153e-001, + -1.088007e+000, + -1.959301e-001, + 9.745799e-001, + 1.260761e+000, + -5.008864e+000, + 7.271248e-001, + 1.096661e-001, + 2.717295e+000, + 6.340731e-001, + // albedo 1, turbidity 5 + -1.456050e+000, + -6.223072e-001, + -2.228088e+001, + 2.269604e+001, + -9.340812e-003, + 4.118308e-001, + -2.418083e-006, + 2.442117e+000, + 5.589638e-001, + -2.176449e+000, + -1.302416e+000, + 2.222836e+000, + -1.222730e+000, + -1.728051e-002, + 1.323513e-001, + 7.027731e-002, + 4.835745e-002, + 2.093351e-001, + -5.789641e-001, + 2.215407e-001, + 2.142291e-001, + -1.201725e+000, + -1.185728e-002, + 8.122982e-001, + -2.380420e-001, + 6.706841e+000, + 1.404146e+000, + -1.307463e+000, + -4.515174e-001, + 6.447827e-001, + 1.223841e+000, + -2.902391e-001, + 4.986588e-001, + 4.073652e-001, + -1.706696e+000, + 1.060885e-001, + -9.698678e-001, + -1.307094e-001, + 9.389347e-001, + -1.522852e+000, + 7.768797e-001, + -1.368595e-001, + -3.857426e-002, + 3.676935e+000, + 8.980966e-001, + -1.104349e+000, + -2.380323e-001, + 1.047043e+000, + 1.865421e+000, + -5.011664e+000, + 7.014954e-001, + 9.622701e-002, + 1.891360e+000, + 6.687354e-001, + // albedo 1, turbidity 6 + -1.502249e+000, + -6.724523e-001, + -2.888092e+001, + 2.930360e+001, + -6.685766e-003, + 3.685464e-001, + -2.469442e-006, + 2.310797e+000, + 5.566754e-001, + -2.217125e+000, + -1.364924e+000, + 4.048243e+000, + -3.111333e+000, + -1.317747e-002, + 1.921948e-001, + 8.627702e-002, + 1.981769e-003, + 2.213689e-001, + -6.215757e-001, + 1.687995e-001, + -5.949131e-001, + -1.551293e-001, + 3.356129e-004, + 6.897657e-001, + -2.855053e-001, + 6.271042e+000, + 1.363084e+000, + -1.216317e+000, + -3.489429e-001, + 7.566226e-001, + 5.409809e-001, + -2.830843e-001, + 6.191825e-001, + 4.755163e-001, + -9.131387e-001, + 1.383909e-001, + -1.030437e+000, + -2.034064e-001, + 8.335995e-001, + -1.050947e+000, + 8.689093e-001, + -3.672310e-001, + -4.056183e-002, + 3.111269e+000, + 8.856842e-001, + -1.078984e+000, + -2.070549e-001, + 9.683145e-001, + 1.497022e+000, + -5.007653e+000, + 7.702541e-001, + 1.285822e-001, + 2.225188e+000, + 6.587911e-001, + // albedo 1, turbidity 7 + -1.559291e+000, + -7.374039e-001, + -3.596311e+001, + 3.634470e+001, + -4.667132e-003, + 3.277964e-001, + -2.487945e-006, + 2.215652e+000, + 5.764681e-001, + -2.356929e+000, + -1.444755e+000, + 6.244526e+000, + -5.540162e+000, + -8.794510e-003, + 1.792100e-001, + 9.578517e-002, + 3.737676e-001, + 1.922194e-001, + -6.589752e-001, + -2.926910e-002, + -1.831779e+000, + 1.869962e+000, + -2.030095e-003, + 7.552089e-001, + -3.168157e-001, + 4.632196e+000, + 1.294054e+000, + -1.161046e+000, + -1.472506e-001, + 6.494138e-001, + -8.327174e-001, + -2.320724e-001, + 3.391212e-001, + 5.269637e-001, + 9.376341e-001, + 2.458573e-001, + -1.034427e+000, + -3.062504e-001, + 8.975634e-001, + 3.203531e-001, + 8.565142e-001, + -1.250162e-001, + -4.094017e-002, + 1.861304e+000, + 8.223468e-001, + -1.109954e+000, + -2.740277e-001, + 1.063811e+000, + 7.077398e-001, + -4.695734e+000, + 5.621696e-001, + 1.248956e-001, + 1.297723e+000, + 6.789720e-001, + // albedo 1, turbidity 8 + -1.788293e+000, + -9.368751e-001, + -4.382980e+001, + 4.424963e+001, + -3.652530e-003, + 3.094331e-001, + -2.810503e-006, + 1.904402e+000, + 5.861599e-001, + -2.268206e+000, + -1.312676e+000, + 2.863082e+000, + -2.373727e+000, + -5.144980e-003, + 1.711072e-001, + 9.316041e-002, + 9.309598e-001, + 1.791683e-001, + -1.376966e+000, + -7.418582e-001, + -1.349589e+000, + 1.563419e+000, + -3.124219e-003, + 6.967139e-001, + -3.061887e-001, + 3.602731e+000, + 1.255669e+000, + -6.017540e-001, + 2.815928e-001, + 5.424052e-001, + -6.885450e-001, + -1.620001e-001, + 2.980046e-001, + 4.995571e-001, + 7.371203e-001, + 2.812466e-001, + -1.278853e+000, + -5.245326e-001, + 7.870520e-001, + 3.125067e-001, + 7.748105e-001, + -7.788581e-002, + 3.490956e-003, + 1.283748e+000, + 8.130190e-001, + -1.050930e+000, + -2.786331e-001, + 1.056344e+000, + 1.053002e+000, + -4.047789e+000, + 4.432174e-001, + 1.169077e-001, + 9.532621e-001, + 6.806764e-001, + // albedo 1, turbidity 9 + -2.084927e+000, + -1.203954e+000, + -4.881638e+001, + 4.920160e+001, + -2.896045e-003, + 2.882977e-001, + -3.073517e-006, + 1.702211e+000, + 6.374180e-001, + -2.328567e+000, + -1.238023e+000, + -1.891019e+000, + 2.451520e+000, + -5.847581e-003, + 2.084702e-001, + 7.848130e-002, + 1.211048e+000, + 8.095008e-002, + -2.634632e+000, + -1.789460e+000, + -1.370558e-001, + -3.326435e-001, + 2.783737e-003, + 5.239451e-001, + -2.548881e-001, + 2.896327e+000, + 1.324116e+000, + 6.882616e-002, + 5.997821e-001, + 1.535398e-001, + 1.375209e+000, + -1.267285e-001, + 4.239743e-001, + 4.013122e-001, + 1.794675e-001, + 2.395382e-001, + -1.430918e+000, + -6.439041e-001, + 8.325980e-001, + -1.705612e+000, + 7.236426e-001, + -5.567593e-002, + 6.408718e-002, + 6.836524e-001, + 8.388887e-001, + -1.037956e+000, + -3.215402e-001, + 9.457349e-001, + 3.178114e+000, + -4.152156e+000, + 2.230992e-001, + 1.156198e-001, + 7.606223e-001, + 6.656923e-001, + // albedo 1, turbidity 10 + -2.967314e+000, + -1.728778e+000, + -3.730988e+001, + 3.755578e+001, + -2.588835e-003, + 2.927966e-001, + -3.935038e-006, + 1.592161e+000, + 6.868694e-001, + -2.123311e+000, + -1.175148e+000, + -1.314988e+001, + 1.386882e+001, + -7.828537e-003, + 1.852026e-001, + 5.481038e-002, + 1.294309e+000, + 2.428177e-002, + -5.443597e+000, + -3.156344e+000, + 2.110838e+000, + -3.421556e+000, + 1.181890e-002, + 1.196951e-001, + -1.742902e-001, + 2.404353e+000, + 1.272805e+000, + 1.029898e+000, + 5.912521e-001, + -3.983531e-001, + 3.286069e+000, + -9.252065e-002, + 1.331381e+000, + 2.560642e-001, + 8.001754e-001, + 3.624178e-001, + -1.547574e+000, + -7.881604e-001, + 1.020902e+000, + -2.897069e+000, + 5.213470e-001, + -9.242315e-001, + 1.185594e-001, + -1.150721e+000, + 7.317211e-001, + -9.621043e-001, + -1.991406e-001, + 6.531287e-001, + 3.925839e+000, + -3.596904e+000, + 6.317332e-001, + 1.531334e-001, + 1.457846e+000, + 6.966285e-001, +}; + +double datasetRGBRad3[] = +{ + // albedo 0, turbidity 1 + 9.926518e-001, + 1.999494e+000, + -4.136109e+000, + 1.856270e+001, + 1.351028e+001, + 1.390238e+001, + // albedo 0, turbidity 2 + 9.634366e-001, + 2.119694e+000, + -4.614523e+000, + 1.919701e+001, + 1.376644e+001, + 1.418731e+001, + // albedo 0, turbidity 3 + 9.446537e-001, + 2.171610e+000, + -4.915556e+000, + 1.918240e+001, + 1.537135e+001, + 1.400530e+001, + // albedo 0, turbidity 4 + 9.073074e-001, + 2.330536e+000, + -5.577596e+000, + 1.961615e+001, + 1.688365e+001, + 1.446955e+001, + // albedo 0, turbidity 5 + 8.739124e-001, + 2.388682e+000, + -5.842995e+000, + 1.923265e+001, + 1.887735e+001, + 1.485698e+001, + // albedo 0, turbidity 6 + 8.563688e-001, + 2.391534e+000, + -5.769133e+000, + 1.828709e+001, + 2.097209e+001, + 1.469587e+001, + // albedo 0, turbidity 7 + 8.270533e-001, + 2.342790e+000, + -5.558071e+000, + 1.684993e+001, + 2.356498e+001, + 1.505975e+001, + // albedo 0, turbidity 8 + 7.908339e-001, + 2.190341e+000, + -4.852571e+000, + 1.374862e+001, + 2.806846e+001, + 1.548444e+001, + // albedo 0, turbidity 9 + 7.403619e-001, + 1.783998e+000, + -2.983854e+000, + 7.622563e+000, + 3.507610e+001, + 1.615805e+001, + // albedo 0, turbidity 10 + 6.840111e-001, + 1.154457e+000, + -2.393830e-001, + -7.896893e-001, + 4.282765e+001, + 1.779469e+001, + // albedo 1, turbidity 1 + 1.168300e+000, + 1.860993e+000, + -2.129074e+000, + 1.251952e+001, + 3.032499e+001, + 2.938716e+001, + // albedo 1, turbidity 2 + 1.150338e+000, + 1.918813e+000, + -2.413527e+000, + 1.274862e+001, + 3.087134e+001, + 2.951432e+001, + // albedo 1, turbidity 3 + 1.114719e+000, + 1.964689e+000, + -2.625423e+000, + 1.247837e+001, + 3.237949e+001, + 2.943596e+001, + // albedo 1, turbidity 4 + 1.077948e+000, + 2.006292e+000, + -2.846934e+000, + 1.190195e+001, + 3.459293e+001, + 2.937492e+001, + // albedo 1, turbidity 5 + 1.035143e+000, + 1.986681e+000, + -2.752584e+000, + 1.060972e+001, + 3.722185e+001, + 2.918594e+001, + // albedo 1, turbidity 6 + 1.015992e+000, + 1.992054e+000, + -2.812626e+000, + 1.001416e+001, + 3.847300e+001, + 2.924624e+001, + // albedo 1, turbidity 7 + 9.756887e-001, + 1.939897e+000, + -2.533281e+000, + 8.319176e+000, + 4.083907e+001, + 2.925586e+001, + // albedo 1, turbidity 8 + 9.264164e-001, + 1.716454e+000, + -1.597044e+000, + 4.739725e+000, + 4.507683e+001, + 2.878915e+001, + // albedo 1, turbidity 9 + 8.595191e-001, + 1.346034e+000, + -2.801895e-002, + -6.582906e-001, + 5.017523e+001, + 2.852953e+001, + // albedo 1, turbidity 10 + 7.754116e-001, + 7.709245e-001, + 2.200201e+000, + -7.487661e+000, + 5.436622e+001, + 2.893432e+001, +}; + +double* datasetsRGB[] = +{ + datasetRGB1, + datasetRGB2, + datasetRGB3 +}; + +double* datasetsRGBRad[] = +{ + datasetRGBRad1, + datasetRGBRad2, + datasetRGBRad3 +}; diff --git a/src/ext/skymodel/ArHosekSkyModelData_Spectral.h b/src/ext/skymodel/ArHosekSkyModelData_Spectral.h new file mode 100644 index 00000000..2e095a43 --- /dev/null +++ b/src/ext/skymodel/ArHosekSkyModelData_Spectral.h @@ -0,0 +1,33770 @@ +/* +This source is published under the following 3-clause BSD license. + +Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * None of the names of the contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +/* ============================================================================ + +This file is part of a sample implementation of the analytical skylight and +solar radiance models presented in the SIGGRAPH 2012 paper + + + "An Analytic Model for Full Spectral Sky-Dome Radiance" + +and the 2013 IEEE CG&A paper + + "Adding a Solar Radiance Function to the Hosek Skylight Model" + + both by + + Lukas Hosek and Alexander Wilkie + Charles University in Prague, Czech Republic + + + Version: 1.4a, February 22nd, 2013 + +Version history: + +1.4a February 22nd, 2013 + Removed unnecessary and counter-intuitive solar radius parameters + from the interface of the colourspace sky dome initialisation functions. + +1.4 February 11th, 2013 + Fixed a bug which caused the relative brightness of the solar disc + and the sky dome to be off by a factor of about 6. The sun was too + bright: this affected both normal and alien sun scenarios. The + coefficients of the solar radiance function were changed to fix this. + +1.3 January 21st, 2013 (not released to the public) + Added support for solar discs that are not exactly the same size as + the terrestrial sun. Also added support for suns with a different + emission spectrum ("Alien World" functionality). + +1.2a December 18th, 2012 + Fixed a mistake and some inaccuracies in the solar radiance function + explanations found in ArHosekSkyModel.h. The actual source code is + unchanged compared to version 1.2. + +1.2 December 17th, 2012 + Native RGB data and a solar radiance function that matches the turbidity + conditions were added. + +1.1 September 2012 + The coefficients of the spectral model are now scaled so that the output + is given in physical units: W / (m^-2 * sr * nm). Also, the output of the + XYZ model is now no longer scaled to the range [0...1]. Instead, it is + the result of a simple conversion from spectral data via the CIE 2 degree + standard observer matching functions. Therefore, after multiplication + with 683 lm / W, the Y channel now corresponds to luminance in lm. + +1.0 May 11th, 2012 + Initial release. + + +Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if +an updated version of this code has been published! + +============================================================================ */ + + +/* + +This file contains the coefficient data for the spectral version of the model. + +*/ + +// uses Apr 26 dataset + +double dataset320[] = +{ + // albedo 0, turbidity 1 + -1.341049e+001, + -3.742293e+000, + -5.229614e+000, + 5.307180e+000, + -2.182658e-002, + 1.497676e-001, + -8.561730e-006, + 1.733480e+000, + 8.826913e-001, + -1.426825e+001, + -3.550926e+000, + 5.719350e-002, + 3.165753e-001, + -5.870693e-002, + 1.333896e-001, + 1.779338e-005, + 1.504276e+000, + 9.750357e-001, + -2.239068e+000, + -4.290407e+000, + -7.494879e-001, + 2.864989e-001, + -6.017855e-002, + 1.325901e-001, + -1.661674e-004, + 1.732120e+000, + 6.513374e-001, + -1.336194e+000, + -2.467808e-001, + 3.961139e-001, + -6.723820e-002, + -1.817268e-001, + 1.017581e-002, + 6.096079e-004, + 1.986859e+000, + 1.415296e+000, + -1.554271e+000, + -1.811527e+000, + 7.309756e-001, + 1.766793e-003, + 5.779090e-001, + 6.186216e-001, + -1.755338e-003, + -2.701090e-002, + 2.699530e-001, + -8.449639e-001, + -5.665198e-001, + 5.525823e-001, + -2.838870e-003, + -4.555228e+000, + 2.824945e-001, + 4.002014e-003, + 1.114208e+000, + 6.637074e-001, + // albedo 0, turbidity 2 + -1.298333e+001, + -3.775577e+000, + -5.173531e+000, + 5.316518e+000, + -2.572615e-002, + 1.516601e-001, + -8.297168e-006, + 1.669649e+000, + 9.000495e-001, + -1.402639e+001, + -3.787558e+000, + 7.611941e-002, + 2.521881e-001, + -5.859973e-002, + 1.753711e-001, + 4.670097e-005, + 1.459275e+000, + 8.998629e-001, + -2.190256e+000, + -3.575495e+000, + -4.930996e-001, + 4.826321e-002, + -6.797145e-002, + 3.425922e-002, + -3.512550e-004, + 1.978419e+000, + 8.866517e-001, + -2.415991e+000, + -1.453294e+000, + 2.170671e-001, + 1.341284e-001, + -1.926330e-001, + 1.059103e-001, + 1.360739e-003, + 1.587725e+000, + 9.821154e-001, + -5.254592e-001, + -8.181026e-001, + 7.535702e-001, + -3.323364e-002, + 4.503149e-001, + 5.778285e-001, + -4.089673e-003, + 3.335089e-001, + 6.827164e-001, + -1.280108e+000, + -1.013716e+000, + 5.577676e-001, + 9.539205e-004, + -4.934956e+000, + 2.642883e-001, + 1.005169e-002, + 9.265844e-001, + 4.999698e-001, + // albedo 0, turbidity 3 + -1.292247e+001, + -3.819777e+000, + -4.478733e+000, + 4.582924e+000, + -2.364370e-002, + 1.619828e-001, + -3.053548e-006, + 1.646629e+000, + 5.103371e-001, + -1.433099e+001, + -3.766213e+000, + 4.930150e-001, + -3.081235e-002, + -6.522199e-002, + 1.564198e-001, + 3.455657e-004, + 1.428507e+000, + 4.312273e-001, + -2.539220e+000, + -3.459074e+000, + -3.774393e-001, + -3.628419e-001, + -2.124451e-001, + -1.358132e-002, + -1.812805e-003, + 2.245152e+000, + 7.247429e-001, + -2.393246e+000, + -1.937898e+000, + 1.005834e-001, + 5.867890e-001, + 2.645044e-001, + 1.413695e-001, + 6.378716e-003, + 1.140715e+000, + 1.263014e+000, + -1.185583e-001, + -1.960943e-001, + 7.212723e-001, + -1.763978e-001, + -1.000190e+000, + 6.259726e-001, + -1.783726e-002, + 7.790644e-001, + 3.244710e-001, + -1.550325e+000, + -1.333575e+000, + 5.618137e-001, + 2.563595e-002, + -5.007716e+000, + 6.522985e-002, + 4.262830e-002, + 7.371930e-001, + 5.239972e-001, + // albedo 0, turbidity 4 + -1.234358e+001, + -3.851875e+000, + -3.911206e+000, + 4.011324e+000, + -2.734425e-002, + 1.272306e-001, + -7.628210e-006, + 1.661843e+000, + 8.993903e-001, + -1.349727e+001, + -3.592681e+000, + 1.335192e+000, + -9.426446e-001, + -5.741127e-002, + 9.765267e-002, + 5.518099e-005, + 1.428554e+000, + -4.278471e-001, + -3.399618e+000, + -3.818725e+000, + -8.698171e-001, + 2.723930e-001, + -3.644369e-001, + 1.238759e-001, + -5.189179e-004, + 2.279175e+000, + 1.841076e+000, + -1.925152e+000, + -1.539333e+000, + 2.757771e-001, + -6.435980e-002, + 6.466700e-001, + 3.084382e-002, + 3.114730e-003, + 1.259818e+000, + 5.121617e-001, + -5.706832e-001, + -6.696186e-001, + 6.798158e-001, + 6.920162e-001, + -3.898854e+000, + 5.954021e-001, + -1.196667e-002, + 5.714991e-001, + 6.528481e-001, + -1.371907e+000, + -1.142330e+000, + 5.207805e-001, + -4.480298e-003, + -5.008950e+000, + 1.251549e-001, + 3.531514e-002, + 8.776759e-001, + 4.999465e-001, + // albedo 0, turbidity 5 + -1.459738e+001, + -3.833562e+000, + -4.148717e+000, + 4.203270e+000, + -2.484405e-002, + 1.189704e-001, + 4.166397e-004, + 1.748850e+000, + 4.999721e-001, + -1.223022e+001, + -3.942049e+000, + 1.183072e+000, + -9.018678e-001, + -4.644071e-002, + 1.237476e-001, + -2.359994e-003, + 1.471013e+000, + 5.298845e-001, + -4.078262e+000, + -3.261096e+000, + -5.520001e-001, + 2.174261e-001, + -3.582576e-001, + 2.000597e-002, + 9.890182e-003, + 2.199274e+000, + 2.756320e-001, + -2.499065e+000, + -2.408391e+000, + 3.391663e-002, + -6.167543e-002, + 7.555424e-001, + 2.349252e-001, + -2.443140e-002, + 1.328540e+000, + 1.348906e+000, + 5.456648e-002, + -9.221401e-002, + 7.403428e-001, + 5.565324e-001, + -5.134970e+000, + 3.021763e-001, + 3.638500e-002, + 5.560149e-001, + 1.818210e-001, + -1.590269e+000, + -1.344330e+000, + 4.805789e-001, + 5.038509e-001, + -3.370644e+000, + 3.040357e-001, + 2.418483e-003, + 8.979818e-001, + 7.477974e-001, + // albedo 0, turbidity 6 + -6.775680e+000, + -3.436745e+000, + -2.696730e+000, + 2.740681e+000, + -4.032382e-002, + 1.036486e-001, + 8.133034e-005, + 1.767160e+000, + 5.401354e-001, + -7.800595e+000, + -2.867058e+000, + 1.478909e+000, + -1.380160e+000, + -1.658909e-001, + 1.962673e-001, + -6.512798e-004, + 1.634359e+000, + 4.300704e-001, + -4.392403e+000, + -3.857979e+000, + -1.022020e+000, + 1.449394e+000, + 2.769695e-001, + -3.331834e-001, + 3.513950e-003, + 1.942113e+000, + 3.970742e-001, + -2.469701e+000, + -1.357319e+000, + 2.132600e-001, + -1.918729e+000, + -4.193060e+000, + 8.101579e-001, + -9.605279e-003, + 1.844443e+000, + 1.582310e+000, + -7.759612e-001, + -1.298076e+000, + 7.162377e-001, + 2.906682e+000, + -8.261148e-001, + -2.892123e-001, + 1.491449e-002, + 6.529387e-002, + -4.180287e-002, + -9.962340e-001, + -6.488730e-001, + 3.933344e-001, + -4.752111e-003, + -4.721793e+000, + 6.053196e-001, + 3.453563e-003, + 1.247655e+000, + 8.673379e-001, + // albedo 0, turbidity 7 + -7.552689e+000, + -3.219112e+000, + -2.730242e+000, + 2.755929e+000, + -3.925138e-002, + 8.394617e-002, + 1.514980e-004, + 1.844410e+000, + 5.389194e-001, + -8.494732e+000, + -3.138528e+000, + 1.424739e+000, + -1.269326e+000, + -1.561580e-001, + 1.767060e-001, + -1.175921e-003, + 1.659123e+000, + 3.746132e-001, + -4.672972e+000, + -4.049529e+000, + -1.027600e+000, + 1.072252e+000, + 7.908165e-002, + -2.243835e-001, + 6.190595e-003, + 1.988822e+000, + 6.684758e-001, + -2.256117e+000, + -1.258356e+000, + 2.198377e-001, + -1.296239e+000, + -3.200970e+000, + 6.407291e-001, + -1.527762e-002, + 1.735209e+000, + 1.170530e+000, + -7.790059e-001, + -1.269213e+000, + 6.315194e-001, + 2.368850e+000, + -1.199163e+000, + -1.504024e-001, + 1.733299e-002, + 2.544016e-001, + 2.756763e-001, + -1.046916e+000, + -6.991719e-001, + 3.620624e-001, + 7.364236e-002, + -5.012491e+000, + 4.240417e-001, + 3.580425e-002, + 1.202329e+000, + 6.255804e-001, + // albedo 0, turbidity 8 + -1.886851e+001, + -4.491136e+000, + -3.660440e+000, + 3.704226e+000, + -3.158478e-002, + 1.229909e-001, + 9.233613e-004, + 1.745459e+000, + 5.011929e-001, + -1.986322e+001, + -3.528401e+000, + 1.401749e+000, + -1.191377e+000, + -7.474944e-002, + -2.193835e-002, + -5.138968e-003, + 1.710181e+000, + 5.473672e-001, + 5.355660e-001, + -5.459304e+000, + -8.809226e-001, + 5.959028e-001, + -3.311339e-001, + 3.876731e-001, + 2.126070e-002, + 1.929868e+000, + 1.883429e-001, + -3.136053e+000, + -2.856938e-001, + 1.048390e-001, + -7.708877e-001, + 2.106630e-001, + -1.488471e-001, + -5.172733e-002, + 1.769302e+000, + 1.526253e+000, + 1.496752e-001, + -9.170428e-001, + 5.628226e-001, + 1.733601e+000, + -4.784033e+000, + 3.570330e-001, + 7.396580e-002, + 3.954993e-001, + 1.397727e-003, + -1.839740e+000, + -1.279260e+000, + 3.173503e-001, + 1.096266e+000, + -4.168649e+000, + 2.121881e-001, + 2.150917e-002, + 1.151497e+000, + 7.233585e-001, + // albedo 0, turbidity 9 + -1.841090e+001, + -4.803089e+000, + -4.883823e+000, + 4.962235e+000, + -2.693216e-002, + 1.089917e-001, + -6.338015e-006, + 1.725865e+000, + 8.890717e-001, + -1.947081e+001, + -2.961260e+000, + 1.963002e+000, + -1.942423e+000, + -5.550118e-002, + 7.036456e-002, + -5.990592e-004, + 1.807097e+000, + -8.871814e-003, + 9.588307e-001, + -6.379803e+000, + -1.021090e+000, + 9.560589e-001, + -2.175500e-001, + 8.613517e-002, + 1.362268e-002, + 1.953529e+000, + 7.422482e-001, + -3.609766e+000, + -1.823498e-003, + 2.516424e-002, + -8.909855e-001, + 2.207805e-001, + 1.783064e-001, + -4.293958e-002, + 1.607901e+000, + 1.131559e+000, + 6.087707e-001, + -6.744295e-001, + 4.236310e-001, + 1.505925e+000, + -4.197126e+000, + 2.046561e-001, + 6.445824e-002, + 7.793118e-001, + 3.262213e-001, + -2.148492e+000, + -1.597890e+000, + 3.166858e-001, + 2.414329e+000, + -4.201339e+000, + 1.005902e-001, + 4.687865e-002, + 9.335376e-001, + 5.289661e-001, + // albedo 0, turbidity 10 + -1.787767e+001, + -4.873485e+000, + -5.861224e+000, + 5.866336e+000, + -1.564202e-002, + 6.967640e-002, + 7.574926e-004, + 1.768065e+000, + 5.856596e-001, + -1.932995e+001, + -4.092647e+000, + 2.679531e+000, + -2.555671e+000, + -4.181418e-002, + 1.023654e-001, + -5.964172e-003, + 1.625691e+000, + 4.036808e-001, + 1.788482e+000, + -5.652582e+000, + -1.517519e+000, + 1.251535e+000, + -2.225912e-001, + -1.084716e-001, + 3.272584e-002, + 2.139078e+000, + 3.876645e-001, + -3.363801e+000, + -3.266475e-001, + 1.313912e-001, + -6.889075e-001, + 4.356523e-001, + 3.120297e-001, + -8.700131e-002, + 1.750122e+000, + 1.223546e+000, + 4.668756e-004, + -9.612337e-001, + 3.082344e-001, + 1.298938e+000, + -4.371395e+000, + 8.845524e-002, + 1.303481e-001, + 5.843720e-001, + 2.718863e-001, + -1.759172e+000, + -1.386072e+000, + 2.349661e-001, + 1.592185e+000, + -3.063267e+000, + 1.529736e-001, + 3.429185e-002, + 1.030294e+000, + 6.917018e-001, + // albedo 1, turbidity 1 + -1.341051e+001, + -3.742047e+000, + -5.229556e+000, + 5.307222e+000, + -2.094796e-002, + 1.499787e-001, + -7.023116e-006, + 1.732898e+000, + 8.826861e-001, + -1.426829e+001, + -3.550660e+000, + 5.731266e-002, + 3.166575e-001, + -5.821080e-002, + 1.335860e-001, + 2.003178e-004, + 1.503788e+000, + 9.750310e-001, + -2.239143e+000, + -4.290084e+000, + -7.493158e-001, + 2.865753e-001, + -5.993923e-002, + 1.327393e-001, + -5.399344e-004, + 1.731677e+000, + 6.513329e-001, + -1.336350e+000, + -2.463606e-001, + 3.963632e-001, + -6.721398e-002, + -1.816244e-001, + 1.021503e-002, + 8.081470e-004, + 1.986453e+000, + 1.415292e+000, + -1.554584e+000, + -1.810948e+000, + 7.313475e-001, + 1.703307e-003, + 5.779436e-001, + 6.184790e-001, + -6.832621e-004, + -2.739619e-002, + 2.699443e-001, + -8.456234e-001, + -5.656772e-001, + 5.531782e-001, + -2.975361e-003, + -4.555221e+000, + 2.821035e-001, + 4.007713e-004, + 1.113850e+000, + 6.636719e-001, + // albedo 1, turbidity 2 + -1.263311e+001, + -4.099112e+000, + -5.130792e+000, + 5.526406e+000, + -2.122841e-002, + 1.202556e-001, + -8.060670e-006, + 1.209196e+000, + 8.997967e-001, + -1.361400e+001, + -3.538236e+000, + 1.570583e-001, + 3.445259e-001, + -5.306874e-002, + 2.322893e-001, + 1.572516e-005, + 1.152750e+000, + 9.026902e-001, + -1.477014e+000, + -3.664310e+000, + -1.442116e-001, + -4.293554e-002, + -3.768326e-002, + -1.388530e-001, + -1.687893e-004, + 1.592625e+000, + 8.804841e-001, + -2.050884e+000, + -1.470536e+000, + 3.327590e-001, + 1.976143e-001, + -1.930369e-001, + 2.831960e-001, + 6.940849e-004, + 1.271203e+000, + 9.790242e-001, + -3.704793e-001, + -5.829841e-001, + 1.168589e+000, + -1.387973e-001, + 5.998426e-001, + 3.825096e-001, + -2.188637e-003, + -2.273264e-001, + 7.393514e-001, + -9.877542e-001, + -7.646946e-001, + 8.859003e-001, + 5.263145e-002, + -4.849410e+000, + 1.301905e-001, + 5.464872e-003, + 5.270984e-001, + 5.001226e-001, + // albedo 1, turbidity 3 + -1.294452e+001, + -3.858933e+000, + -4.362969e+000, + 4.657159e+000, + -2.281956e-002, + 1.371565e-001, + 3.552610e-006, + 1.354369e+000, + 5.222053e-001, + -1.425646e+001, + -3.745266e+000, + 6.901454e-001, + -5.345642e-002, + -5.238708e-002, + 1.157055e-001, + -1.961110e-005, + 1.030408e+000, + 4.036292e-001, + -2.236186e+000, + -3.560196e+000, + -1.053059e-001, + -3.002269e-001, + -1.702750e-001, + 3.290753e-002, + -7.253274e-005, + 1.846963e+000, + 6.828000e-001, + -1.991088e+000, + -2.028027e+000, + 2.747056e-001, + 5.076456e-001, + 2.056096e-001, + 1.537040e-001, + 1.010611e-003, + 8.439763e-001, + 1.286657e+000, + -2.733597e-001, + -1.938590e-001, + 1.108079e+000, + -1.668080e-001, + -8.136300e-001, + 3.962292e-001, + -4.757393e-003, + 1.536882e-001, + 4.595467e-001, + -9.782447e-001, + -8.452104e-001, + 9.149995e-001, + 2.750126e-002, + -4.996263e+000, + 1.226836e-001, + 1.533731e-002, + 3.686265e-001, + 5.004484e-001, + // albedo 1, turbidity 4 + -1.234416e+001, + -3.818503e+000, + -3.804408e+000, + 4.093838e+000, + -2.505623e-002, + 1.149315e-001, + -7.610563e-006, + 1.361584e+000, + 8.981571e-001, + -1.349621e+001, + -3.551853e+000, + 1.469377e+000, + -8.971164e-001, + -5.623731e-002, + 1.078524e-001, + 1.491378e-003, + 1.113040e+000, + -4.279059e-001, + -3.391950e+000, + -3.791028e+000, + -6.935352e-001, + 2.998175e-001, + -3.155309e-001, + 1.196041e-001, + -4.708048e-003, + 2.001973e+000, + 1.840166e+000, + -1.915114e+000, + -1.493080e+000, + 4.567342e-001, + -7.334296e-002, + 6.767060e-001, + -4.562689e-003, + 1.016838e-002, + 1.003272e+000, + 5.102018e-001, + -5.674128e-001, + -5.568719e-001, + 9.084369e-001, + 6.684870e-001, + -3.892720e+000, + 5.312866e-001, + -1.768715e-002, + 3.252051e-001, + 6.541029e-001, + -1.343751e+000, + -9.647458e-001, + 7.945561e-001, + 5.127485e-004, + -5.009873e+000, + 6.165389e-002, + 2.642926e-002, + 6.213595e-001, + 5.327376e-001, + // albedo 1, turbidity 5 + -1.450562e+001, + -4.021778e+000, + -4.181517e+000, + 4.509518e+000, + -2.369519e-002, + 6.955582e-002, + 1.149882e-004, + 1.329583e+000, + 5.260857e-001, + -1.297772e+001, + -3.655039e+000, + 2.030636e+000, + -1.537436e+000, + -4.915490e-002, + 1.511047e-001, + -9.053517e-004, + 1.156980e+000, + 4.831690e-001, + -1.991837e+000, + -3.919397e+000, + -8.466357e-001, + 5.319508e-001, + -3.165811e-001, + 1.056172e-001, + 4.836036e-003, + 1.843574e+000, + 3.084513e-001, + -2.052725e+000, + -1.606839e+000, + 5.876624e-001, + -7.464148e-002, + 7.525473e-001, + 1.590947e-003, + -1.261084e-002, + 8.587516e-001, + 1.404076e+000, + -3.737447e-001, + -4.061843e-001, + 8.985804e-001, + 5.700187e-001, + -5.422882e+000, + 4.334301e-001, + 1.759754e-002, + 2.613056e-001, + 2.062463e-001, + -1.002263e+000, + -1.006484e+000, + 9.629219e-001, + 8.528366e-002, + -4.220831e+000, + 7.848806e-002, + 1.254937e-002, + 2.140208e-001, + 6.187813e-001, + // albedo 1, turbidity 6 + -7.175451e+000, + -3.313094e+000, + -2.396914e+000, + 2.657177e+000, + -3.936959e-002, + 1.123476e-001, + 7.315860e-005, + 1.431209e+000, + 5.107145e-001, + -8.058121e+000, + -3.119458e+000, + 1.729776e+000, + -1.435370e+000, + -1.414745e-001, + 2.338787e-001, + -5.865288e-004, + 1.247225e+000, + 5.037743e-001, + -4.387785e+000, + -3.851081e+000, + -7.774273e-001, + 1.405520e+000, + 1.743075e-001, + -4.108912e-001, + 3.058571e-003, + 1.519803e+000, + 2.636805e-001, + -1.807473e+000, + -1.498491e+000, + 3.237723e-001, + -1.626737e+000, + -3.741656e+000, + 8.444519e-001, + -8.297013e-003, + 1.624861e+000, + 1.753817e+000, + -6.242455e-001, + -1.063850e+000, + 1.166897e+000, + 2.283807e+000, + -1.150947e+000, + -3.242997e-001, + 1.279340e-002, + -5.448139e-001, + -8.653106e-002, + -8.143405e-001, + -5.251732e-001, + 7.822692e-001, + -3.764280e-003, + -5.011112e+000, + 3.985065e-001, + 3.652394e-003, + 7.140115e-001, + 7.004910e-001, + // albedo 1, turbidity 7 + -7.579673e+000, + -3.495594e+000, + -2.498830e+000, + 2.771470e+000, + -3.451351e-002, + 8.186886e-002, + 1.272079e-004, + 1.390420e+000, + 5.545117e-001, + -8.524117e+000, + -3.121778e+000, + 1.680395e+000, + -1.329455e+000, + -1.395912e-001, + 1.911589e-001, + -1.027988e-003, + 1.259267e+000, + 3.356989e-001, + -4.579718e+000, + -4.086739e+000, + -8.030175e-001, + 1.103390e+000, + 1.429699e-001, + -2.211841e-001, + 5.620349e-003, + 1.693702e+000, + 7.084432e-001, + -1.946704e+000, + -1.512415e+000, + 3.559506e-001, + -1.318829e+000, + -3.063409e+000, + 6.250046e-001, + -1.490672e-002, + 1.414520e+000, + 1.317647e+000, + -7.123367e-001, + -1.133848e+000, + 1.064800e+000, + 2.217543e+000, + -1.247373e+000, + -2.105594e-001, + 2.261048e-002, + -3.648618e-001, + 1.147223e-001, + -7.979833e-001, + -5.546030e-001, + 7.765850e-001, + -4.676928e-003, + -5.014372e+000, + 3.694816e-001, + 2.373221e-003, + 6.783145e-001, + 7.862971e-001, + // albedo 1, turbidity 8 + -1.886599e+001, + -4.523457e+000, + -3.559445e+000, + 3.748747e+000, + -2.082711e-002, + 1.120505e-001, + 4.908827e-005, + 1.430333e+000, + 4.999603e-001, + -1.985552e+001, + -3.530040e+000, + 1.578922e+000, + -1.170838e+000, + -6.347814e-002, + 2.032158e-003, + -7.291357e-004, + 1.399338e+000, + 5.515394e-001, + 5.631541e-001, + -5.483754e+000, + -6.832337e-001, + 6.170499e-001, + -2.824393e-001, + 3.546810e-001, + 6.248420e-003, + 1.638520e+000, + 2.300717e-001, + -3.083195e+000, + -3.071409e-001, + 2.822360e-001, + -7.871125e-001, + 2.420642e-001, + -1.716096e-001, + -1.936307e-002, + 1.450902e+000, + 1.590291e+000, + 2.003824e-001, + -8.374106e-001, + 8.800366e-001, + 1.702679e+000, + -4.785357e+000, + 3.194078e-001, + 3.028099e-002, + 6.649245e-002, + -4.459174e-003, + -1.738851e+000, + -1.144728e+000, + 6.950894e-001, + 1.073870e+000, + -4.176611e+000, + 9.901497e-002, + 2.719362e-002, + 6.579628e-001, + 6.542088e-001, + // albedo 1, turbidity 9 + -1.842858e+001, + -4.464894e+000, + -4.876181e+000, + 4.999894e+000, + -1.680473e-002, + 9.284371e-002, + 8.631599e-005, + 1.551671e+000, + 8.637202e-001, + -1.946220e+001, + -2.928492e+000, + 1.932796e+000, + -2.009963e+000, + -2.067172e-002, + 2.760643e-001, + -1.316034e-003, + 1.910005e+000, + -2.057018e-002, + 1.012726e+000, + -6.397245e+000, + -8.570688e-001, + 9.466942e-001, + -2.428074e-001, + 4.505376e-002, + 1.159119e-002, + 1.686356e+000, + 7.885028e-001, + -3.502022e+000, + -9.795202e-002, + 3.286657e-001, + -8.318684e-001, + 1.254695e-001, + 9.600123e-002, + -3.501772e-002, + 1.161309e+000, + 1.205342e+000, + 7.024550e-001, + -6.903001e-001, + 7.519618e-001, + 1.501909e+000, + -4.224528e+000, + 1.253867e-001, + 5.829515e-002, + 2.671626e-001, + 3.030079e-001, + -2.056576e+000, + -1.583471e+000, + 7.947031e-001, + 2.224097e+000, + -4.127138e+000, + 1.885249e-001, + 1.729132e-005, + 3.336881e-001, + 5.332061e-001, + // albedo 1, turbidity 10 + -1.825745e+001, + -5.122861e+000, + -5.876715e+000, + 5.970876e+000, + -1.788919e-002, + 1.063934e-001, + 4.770037e-004, + 1.612403e+000, + 5.156506e-001, + -1.981828e+001, + -3.746331e+000, + 2.729783e+000, + -2.477317e+000, + -2.797536e-002, + -5.281985e-002, + -3.739083e-003, + 1.378246e+000, + 5.904024e-001, + 1.346751e+000, + -6.486837e+000, + -1.082622e+000, + 1.125524e+000, + -2.228944e-001, + 3.975587e-001, + 2.035973e-002, + 1.884664e+000, + 1.086023e-003, + -3.996320e+000, + -4.646476e-001, + 3.008639e-002, + -1.193861e+000, + 4.443960e-001, + -2.593178e-001, + -5.378377e-002, + 1.528777e+000, + 1.734923e+000, + 4.789259e-001, + -8.952042e-001, + 8.595191e-001, + 2.353988e+000, + -4.885398e+000, + 4.438339e-001, + 7.931163e-002, + -8.144393e-002, + 1.663921e-002, + -1.772626e+000, + -1.783205e+000, + 7.322534e-001, + 1.529827e+000, + -2.789303e+000, + -1.817210e-001, + 2.737502e-002, + 2.620216e-001, + 6.227585e-001, +}; + +double datasetRad320[] = +{ + // albedo 0, turbidity 1 + 9.282016e-004, + 3.169257e-004, + 5.255138e-003, + -1.465200e-002, + 7.187172e-002, + 5.400860e-002, + // albedo 0, turbidity 2 + 9.160628e-004, + 2.599956e-004, + 5.466998e-003, + -1.503537e-002, + 7.200167e-002, + 5.387713e-002, + // albedo 0, turbidity 3 + 9.148749e-004, + 2.164768e-004, + 5.576667e-003, + -1.537254e-002, + 7.215609e-002, + 5.380753e-002, + // albedo 0, turbidity 4 + 9.090685e-004, + 1.467840e-004, + 5.775870e-003, + -1.598491e-002, + 7.252530e-002, + 5.329870e-002, + // albedo 0, turbidity 5 + 8.902830e-004, + 1.126529e-004, + 5.945913e-003, + -1.648173e-002, + 7.220217e-002, + 5.391054e-002, + // albedo 0, turbidity 6 + 8.885423e-004, + 1.142350e-004, + 5.938903e-003, + -1.668800e-002, + 7.231405e-002, + 5.331532e-002, + // albedo 0, turbidity 7 + 8.674766e-004, + 3.506619e-005, + 6.176212e-003, + -1.732036e-002, + 7.223472e-002, + 5.318228e-002, + // albedo 0, turbidity 8 + 8.525095e-004, + -1.752028e-005, + 6.286417e-003, + -1.779286e-002, + 7.150222e-002, + 5.334072e-002, + // albedo 0, turbidity 9 + 8.232652e-004, + -1.292152e-004, + 6.645270e-003, + -1.886566e-002, + 7.052974e-002, + 5.331726e-002, + // albedo 0, turbidity 10 + 7.670001e-004, + -1.885989e-004, + 6.484739e-003, + -1.852036e-002, + 6.610758e-002, + 5.484068e-002, + // albedo 1, turbidity 1 + 1.105405e-003, + 2.555979e-005, + 7.984713e-003, + -2.152422e-002, + 8.452836e-002, + 9.622688e-002, + // albedo 1, turbidity 2 + 1.111427e-003, + -6.046059e-005, + 8.035207e-003, + -2.134768e-002, + 8.363698e-002, + 9.641842e-002, + // albedo 1, turbidity 3 + 1.103552e-003, + -8.229160e-005, + 8.170699e-003, + -2.189940e-002, + 8.404871e-002, + 9.504912e-002, + // albedo 1, turbidity 4 + 1.075129e-003, + -1.473970e-004, + 8.391094e-003, + -2.255482e-002, + 8.415497e-002, + 9.338994e-002, + // albedo 1, turbidity 5 + 1.036467e-003, + -1.328992e-004, + 8.348236e-003, + -2.256138e-002, + 8.304671e-002, + 9.263679e-002, + // albedo 1, turbidity 6 + 1.042383e-003, + -2.016636e-004, + 8.479624e-003, + -2.296524e-002, + 8.303746e-002, + 9.082494e-002, + // albedo 1, turbidity 7 + 1.014293e-003, + -2.355927e-004, + 8.551010e-003, + -2.333261e-002, + 8.258160e-002, + 8.873588e-002, + // albedo 1, turbidity 8 + 9.683336e-004, + -2.120256e-004, + 8.172046e-003, + -2.223973e-002, + 7.852279e-002, + 8.864017e-002, + // albedo 1, turbidity 9 + 9.139571e-004, + -2.688667e-004, + 8.068793e-003, + -2.224390e-002, + 7.590320e-002, + 8.464876e-002, + // albedo 1, turbidity 10 + 8.457855e-004, + -3.459869e-004, + 7.626953e-003, + -2.067614e-002, + 6.841363e-002, + 8.244103e-002, +}; + +double dataset360[] = +{ + // albedo 0, turbidity 1 + -2.974290e+000, + -1.670904e+000, + -5.183199e+000, + 5.377376e+000, + -2.904124e-002, + 2.486720e-001, + 8.045624e-005, + 1.889212e+000, + 5.188203e-001, + -2.638402e+000, + -1.651876e+000, + -1.229939e+000, + 1.776358e+000, + -6.372414e-002, + 3.767834e-001, + -6.475530e-004, + 1.373589e+000, + 4.349252e-001, + -2.449142e+000, + -1.541788e+000, + 4.629358e-001, + -1.149742e+000, + -7.317185e-002, + -2.422158e-001, + 3.667113e-003, + 3.146429e+000, + 6.725657e-001, + -8.559357e-001, + -5.054959e-001, + 4.334205e-001, + 4.254155e-001, + -2.920605e-001, + 9.303230e-001, + -1.212609e-002, + 4.498482e-001, + 2.117838e-001, + -1.098145e+000, + -5.123514e-001, + 7.773196e-001, + -1.325175e-001, + 4.648396e-001, + 1.386648e-001, + 2.427679e-002, + 1.199386e+000, + 7.988611e-001, + -1.124849e+000, + -5.693597e-001, + 7.315125e-001, + 2.986435e-002, + -4.536788e+000, + 6.650081e-001, + -9.004215e-007, + 1.006380e+000, + 4.999682e-001, + // albedo 0, turbidity 2 + -2.709497e+000, + -1.635812e+000, + -4.594177e+000, + 4.809336e+000, + -3.672907e-002, + 2.383111e-001, + 3.241989e-005, + 1.885505e+000, + 6.619619e-001, + -2.590279e+000, + -1.525236e+000, + -6.846073e-001, + 1.216080e+000, + -8.022814e-002, + 3.040074e-001, + -4.984576e-004, + 1.521429e+000, + 1.746040e-001, + -2.988403e+000, + -1.938687e+000, + 4.954649e-002, + -8.992325e-001, + -7.157111e-002, + -4.370068e-002, + 4.336645e-003, + 2.849496e+000, + 8.892788e-001, + -2.932084e-001, + -1.323910e-001, + 5.535910e-001, + 7.456284e-001, + -2.713400e-001, + 6.989175e-001, + -1.513162e-002, + 6.926848e-001, + 5.719944e-001, + -1.379400e+000, + -6.876864e-001, + 7.224534e-001, + -6.172704e-001, + 1.217500e-001, + 3.074795e-001, + 2.905167e-002, + 1.123563e+000, + 6.837510e-001, + -1.042446e+000, + -5.201193e-001, + 7.107656e-001, + 4.182566e-001, + -4.956238e+000, + 5.315425e-001, + 6.232999e-003, + 1.059015e+000, + 5.116427e-001, + // albedo 0, turbidity 3 + -2.686687e+000, + -1.615137e+000, + -3.811956e+000, + 4.018597e+000, + -3.953418e-002, + 2.171778e-001, + -7.374887e-006, + 1.875745e+000, + 8.996180e-001, + -3.049670e+000, + -1.775802e+000, + 2.577719e-002, + 5.331200e-001, + -9.424429e-002, + 3.852753e-001, + -8.678326e-005, + 1.347053e+000, + -1.078327e-001, + -2.414334e+000, + -1.637863e+000, + -3.948523e-001, + -4.867989e-001, + -1.545516e-001, + -2.045592e-001, + 2.308206e-003, + 3.257409e+000, + 1.029606e+000, + -6.821703e-001, + -3.665215e-001, + 7.496076e-001, + 5.391760e-001, + -2.903450e-001, + 8.498544e-001, + -1.388990e-002, + 2.126622e-001, + 6.857005e-001, + -1.227285e+000, + -5.958479e-001, + 5.828611e-001, + -4.050489e-001, + -2.935835e-001, + 1.410603e-001, + 4.352812e-002, + 1.406076e+000, + 4.955059e-001, + -1.080553e+000, + -5.308084e-001, + 6.980027e-001, + 2.193524e-001, + -5.007206e+000, + 5.895807e-001, + 1.122391e-002, + 1.052433e+000, + 6.643198e-001, + // albedo 0, turbidity 4 + -2.983088e+000, + -1.746025e+000, + -4.564198e+000, + 4.776145e+000, + -3.208607e-002, + 2.008358e-001, + -6.578048e-006, + 1.829880e+000, + 9.001069e-001, + -2.858023e+000, + -1.624623e+000, + 1.859497e+000, + -1.348577e+000, + -7.427284e-002, + 2.943068e-001, + -1.961205e-004, + 1.502334e+000, + -3.183648e-001, + -2.858102e+000, + -2.072804e+000, + -1.205584e+000, + 5.674135e-001, + -3.934144e-001, + -3.736288e-002, + 4.780332e-003, + 2.831298e+000, + 1.553942e+000, + -3.305766e-001, + -8.277591e-003, + 8.561917e-001, + -2.239172e-001, + 5.896697e-001, + 6.229823e-001, + -2.242577e-002, + 7.216263e-001, + 4.295956e-001, + -1.322728e+000, + -7.101315e-001, + 5.645563e-001, + 9.897384e-001, + -6.756374e+000, + 2.491515e-001, + 5.308124e-002, + 1.166258e+000, + 5.472501e-001, + -1.117086e+000, + -5.760006e-001, + 6.388217e-001, + 1.659290e-001, + -4.687099e+000, + 4.544540e-001, + 2.672063e-002, + 1.067777e+000, + 6.419825e-001, + // albedo 0, turbidity 5 + -2.943340e+000, + -1.779161e+000, + -3.715839e+000, + 3.949049e+000, + -4.499824e-002, + 2.234466e-001, + -8.091518e-006, + 1.825217e+000, + 9.000118e-001, + -3.717358e+000, + -1.850324e+000, + 2.277659e+000, + -2.027790e+000, + -1.240730e-001, + 3.029522e-001, + -2.176255e-004, + 1.585933e+000, + -2.794001e-001, + -2.439542e+000, + -2.277701e+000, + -1.702329e+000, + 2.025885e+000, + -1.142291e-001, + -2.011641e-001, + 5.563891e-003, + 2.424957e+000, + 1.399542e+000, + -1.562453e-001, + 5.099893e-001, + 1.026847e+000, + -2.516874e+000, + -2.212969e+000, + 9.252660e-001, + -2.696795e-002, + 1.443711e+000, + 7.450372e-001, + -1.579698e+000, + -1.110703e+000, + 4.743061e-001, + 4.160187e+000, + -4.597085e+000, + -2.112156e-001, + 6.791770e-002, + 6.131169e-001, + 2.291635e-001, + -9.959610e-001, + -4.119588e-001, + 5.707529e-001, + -3.505536e-003, + -4.253949e+000, + 7.498003e-001, + 8.246945e-003, + 1.397857e+000, + 8.021253e-001, + // albedo 0, turbidity 6 + -2.304734e+000, + -1.483605e+000, + -1.531059e+000, + 1.707306e+000, + -1.150367e-001, + 2.153063e-001, + -3.351533e-006, + 2.021261e+000, + 5.742842e-001, + -3.130477e+000, + -1.966839e+000, + 6.058600e-001, + -9.209976e-001, + -1.932901e-001, + 3.242645e-001, + 3.361262e-002, + 1.529938e+000, + 2.851152e-001, + -1.110129e+000, + -1.306323e+000, + -3.235833e-001, + 2.998748e+000, + -1.535927e-002, + -4.001906e-001, + -9.430492e-002, + 2.211086e+000, + 8.632200e-001, + -1.174540e+000, + 7.550161e-002, + -1.849588e-001, + -6.281432e+000, + -6.186665e+000, + 1.173048e+000, + 1.481656e-001, + 2.668578e+000, + 6.145923e-001, + -1.104583e+000, + -8.430389e-001, + 8.668416e-001, + 9.153752e+000, + -7.289540e-001, + -4.346537e-001, + -9.065784e-002, + 2.866983e-001, + 6.920973e-001, + -1.105893e+000, + -4.500399e-001, + 4.286451e-001, + 1.207864e+000, + -5.018291e+000, + 6.988292e-001, + 3.891745e-002, + 1.602324e+000, + 6.269169e-001, + // albedo 0, turbidity 7 + -3.709341e+000, + -2.038242e+000, + -3.127214e+000, + 3.287030e+000, + -4.565671e-002, + 2.427627e-001, + -7.503980e-006, + 1.817881e+000, + 9.000389e-001, + -3.393374e+000, + -1.710497e+000, + 1.661275e+000, + -1.388896e+000, + -1.012293e-001, + 1.676172e-001, + -5.719846e-004, + 1.694199e+000, + -3.140071e-001, + -2.812820e+000, + -2.678401e+000, + -1.170428e+000, + 1.560988e+000, + -4.488218e-001, + 1.088693e-001, + 1.391966e-002, + 2.144426e+000, + 1.525731e+000, + 2.547360e-001, + 8.840167e-001, + 5.469168e-001, + -2.615530e+000, + -1.048663e+000, + 4.823171e-001, + -5.958515e-002, + 1.842479e+000, + 5.322138e-001, + -1.612173e+000, + -1.055541e+000, + 4.733463e-001, + 5.083504e+000, + -5.558403e+000, + 8.029584e-002, + 1.294180e-001, + 7.807964e-001, + 3.949822e-001, + -1.098367e+000, + -5.550631e-001, + 4.221569e-001, + -1.661587e-003, + -4.970027e+000, + 3.479325e-001, + 4.503648e-002, + 1.369224e+000, + 6.753984e-001, + // albedo 0, turbidity 8 + -4.292777e+000, + -2.231300e+000, + -4.359252e+000, + 4.562131e+000, + -3.759725e-002, + 2.170783e-001, + -6.945269e-006, + 1.791630e+000, + 8.996451e-001, + -4.016595e+000, + -1.761175e+000, + 2.616213e+000, + -2.658657e+000, + -8.209207e-002, + 2.736152e-001, + -6.864170e-004, + 1.820262e+000, + -2.712707e-001, + -2.942646e+000, + -3.350329e+000, + -1.645817e+000, + 2.957424e+000, + -1.073783e-001, + -1.920050e-001, + 1.665992e-002, + 1.723144e+000, + 1.394962e+000, + 9.793627e-001, + 1.743715e+000, + 5.396545e-001, + -4.618273e+000, + -2.186669e+000, + 1.012973e+000, + -7.213786e-002, + 2.388103e+000, + 6.712519e-001, + -2.085434e+000, + -1.445755e+000, + 3.384806e-001, + 7.702938e+000, + -3.897179e+000, + -5.947697e-001, + 1.614194e-001, + 7.854754e-001, + 3.291034e-001, + -9.660466e-001, + -5.247410e-001, + 4.199048e-001, + -3.304707e-003, + -5.014144e+000, + 6.733599e-001, + 2.345161e-002, + 1.225739e+000, + 7.256834e-001, + // albedo 0, turbidity 9 + -3.950771e+000, + -2.192673e+000, + -7.263653e+000, + 7.343312e+000, + -1.840332e-002, + 1.893809e-001, + -3.583629e-006, + 1.901172e+000, + 5.902387e-001, + -6.384690e+000, + -2.515788e+000, + 3.874778e+000, + -3.776079e+000, + -3.484710e-002, + 3.311078e-001, + 8.248395e-003, + 1.612712e+000, + 3.123684e-001, + -6.207616e-001, + -2.681061e+000, + -2.005212e+000, + 2.445498e+000, + -1.935675e-001, + -1.988856e-001, + -1.553754e-002, + 2.210740e+000, + 6.507040e-001, + -1.241493e+000, + 5.908170e-001, + 3.899777e-001, + -2.344038e+000, + -1.820327e-001, + 7.889592e-001, + -1.468064e-002, + 1.586758e+000, + 1.007885e+000, + -4.395130e-001, + -3.700611e-001, + 2.452754e-001, + 3.602006e+000, + -4.692896e+000, + -8.620746e-002, + 1.418548e-001, + 1.521301e+000, + 3.989756e-001, + -1.794977e+000, + -1.190586e+000, + 3.928989e-001, + 1.946953e+000, + -1.874118e+000, + -3.292602e-002, + 2.983309e-002, + 6.737092e-001, + 7.322706e-001, + // albedo 0, turbidity 10 + -8.896186e+000, + -3.278330e+000, + -7.998349e+000, + 8.023312e+000, + -1.357555e-002, + 1.947910e-001, + -5.390226e-006, + 1.798414e+000, + 7.881395e-001, + -8.040403e+000, + -2.528514e+000, + 3.774303e+000, + -3.590457e+000, + -3.551313e-002, + 3.650761e-001, + -4.401382e-004, + 1.701545e+000, + -6.992899e-003, + -4.150010e-001, + -3.539507e+000, + -1.527733e+000, + 1.415242e+000, + -1.831476e-001, + -3.009746e-001, + 1.211955e-002, + 2.365976e+000, + 9.928240e-001, + -2.090923e+000, + 1.673638e-001, + -2.183495e-001, + -8.374584e-001, + 2.774184e-002, + 7.912769e-001, + -6.650609e-002, + 1.154446e+000, + 7.863979e-001, + 5.115239e-001, + 2.415831e-001, + 4.022318e-001, + 2.292950e+000, + -4.061496e+000, + 7.453182e-002, + 1.902451e-001, + 1.587339e+000, + 5.207620e-001, + -2.334879e+000, + -1.642495e+000, + 2.384458e-001, + 3.068363e+000, + -1.699588e+000, + -3.936924e-001, + 3.028660e-002, + 4.715374e-001, + 7.091893e-001, + // albedo 1, turbidity 1 + -2.375941e+000, + -1.508643e+000, + -5.070151e+000, + 5.509378e+000, + -2.915769e-002, + 2.122471e-001, + 8.584007e-005, + 1.517285e+000, + 5.163253e-001, + -2.605398e+000, + -1.589160e+000, + -1.137560e+000, + 1.827729e+000, + -4.939637e-002, + 3.243952e-001, + -6.464612e-004, + 1.008816e+000, + 4.568463e-001, + -2.176260e+000, + -1.601522e+000, + 7.060324e-001, + -1.060717e+000, + -5.144614e-002, + -1.938031e-001, + 3.449257e-003, + 2.641594e+000, + 5.976852e-001, + -7.365744e-001, + -3.720296e-001, + 7.315328e-001, + 3.156067e-001, + -2.739385e-001, + 8.252942e-001, + -1.055013e-002, + 7.327610e-002, + 3.218251e-001, + -1.017537e+000, + -4.631811e-001, + 1.093174e+000, + -7.215941e-002, + 5.408457e-001, + -1.848322e-002, + 1.942990e-002, + 6.882763e-001, + 7.268524e-001, + -1.025215e+000, + -3.712574e-001, + 9.661278e-001, + 7.791398e-003, + -4.508617e+000, + 4.371074e-001, + -1.241898e-006, + 1.152655e+000, + 5.008240e-001, + // albedo 1, turbidity 2 + -2.621793e+000, + -1.611544e+000, + -4.494730e+000, + 4.902741e+000, + -2.935751e-002, + 1.930048e-001, + 1.821579e-005, + 1.522018e+000, + 6.563013e-001, + -2.473330e+000, + -1.495083e+000, + -5.536781e-001, + 1.305457e+000, + -7.261347e-002, + 2.967738e-001, + -2.858526e-004, + 1.132650e+000, + 1.737068e-001, + -2.843519e+000, + -1.913751e+000, + 2.006296e-001, + -8.580922e-001, + -5.273753e-002, + -7.800250e-002, + 2.395781e-003, + 2.505017e+000, + 9.023934e-001, + -1.805184e-001, + -3.670063e-002, + 7.583717e-001, + 7.594739e-001, + -2.092951e-001, + 6.278666e-001, + -8.086828e-003, + 4.136002e-001, + 6.026937e-001, + -1.274753e+000, + -5.831501e-001, + 9.711756e-001, + -6.209175e-001, + 1.488633e-001, + 2.117108e-001, + 1.531499e-002, + 9.306008e-001, + 7.201852e-001, + -9.224434e-001, + -3.344822e-001, + 9.964647e-001, + 3.991735e-001, + -4.951439e+000, + 4.332347e-001, + -1.082832e-005, + 9.570977e-001, + 5.221054e-001, + // albedo 1, turbidity 3 + -2.648100e+000, + -1.587720e+000, + -3.738681e+000, + 4.084015e+000, + -3.301163e-002, + 1.736140e-001, + -5.598265e-006, + 1.628176e+000, + 8.967917e-001, + -3.004556e+000, + -1.702983e+000, + 1.060112e-001, + 5.816666e-001, + -8.140777e-002, + 3.584557e-001, + -7.793874e-005, + 1.090228e+000, + -1.079451e-001, + -2.337937e+000, + -1.584523e+000, + -2.912486e-001, + -4.467895e-001, + -9.195281e-002, + -2.355753e-001, + 1.887118e-003, + 3.053238e+000, + 1.043382e+000, + -5.985994e-001, + -2.846782e-001, + 8.903642e-001, + 5.578845e-001, + -2.510042e-001, + 8.033778e-001, + -9.920460e-003, + 7.388584e-002, + 7.097127e-001, + -1.155357e+000, + -4.638306e-001, + 8.041892e-001, + -4.051351e-001, + -2.819435e-001, + 8.505708e-002, + 2.749222e-002, + 1.334820e+000, + 5.216620e-001, + -1.010658e+000, + -3.816787e-001, + 9.644918e-001, + 2.144477e-001, + -5.005667e+000, + 5.475125e-001, + 3.758162e-005, + 1.033427e+000, + 6.866266e-001, + // albedo 1, turbidity 4 + -2.686681e+000, + -1.694114e+000, + -4.346908e+000, + 4.745876e+000, + -2.879846e-002, + 2.237339e-001, + -6.438656e-006, + 1.456353e+000, + 9.000340e-001, + -2.684912e+000, + -1.616888e+000, + 2.447798e+000, + -1.626883e+000, + -7.346183e-002, + 2.641722e-001, + -1.001518e-004, + 1.045501e+000, + -2.314856e-001, + -2.587652e+000, + -1.999748e+000, + -1.325810e+000, + 7.561102e-001, + -4.182131e-001, + -4.285017e-002, + 2.719759e-003, + 2.420598e+000, + 1.281981e+000, + -2.679506e-001, + 5.139740e-002, + 1.276587e+000, + -2.286956e-001, + 7.388924e-001, + 5.606395e-001, + -1.472508e-002, + 5.105614e-001, + 7.670396e-001, + -1.267160e+000, + -7.441021e-001, + 9.154665e-001, + 8.190436e-001, + -6.805266e+000, + 1.013064e-001, + 4.140297e-002, + 3.378301e-001, + 3.128860e-001, + -9.570978e-001, + -3.478847e-001, + 9.709923e-001, + -3.444499e-003, + -4.677921e+000, + 3.551546e-001, + 6.241534e-003, + 1.052060e+000, + 7.543152e-001, + // albedo 1, turbidity 5 + -3.093830e+000, + -1.859478e+000, + -4.003711e+000, + 4.391665e+000, + -3.051581e-002, + 2.180265e-001, + -7.401285e-006, + 1.448366e+000, + 9.000549e-001, + -3.121106e+000, + -1.664385e+000, + 2.868256e+000, + -2.280292e+000, + -8.456847e-002, + 2.227469e-001, + -1.681252e-004, + 1.176332e+000, + -2.605895e-001, + -2.166025e+000, + -2.172663e+000, + -1.705862e+000, + 1.960864e+000, + -2.185020e-001, + 1.891067e-002, + 4.423413e-003, + 2.071931e+000, + 1.297661e+000, + -5.263078e-001, + 2.296403e-001, + 1.342025e+000, + -2.034590e+000, + -1.024013e+000, + 4.873264e-001, + -1.982506e-002, + 9.818474e-001, + 1.040041e+000, + -1.138361e+000, + -8.186096e-001, + 8.845700e-001, + 3.291911e+000, + -5.915866e+000, + 1.125846e-001, + 4.477952e-002, + 9.195132e-002, + -1.138939e-002, + -1.013651e+000, + -3.811416e-001, + 9.420266e-001, + -3.599378e-003, + -4.895655e+000, + 2.864445e-001, + 1.940262e-002, + 1.026648e+000, + 7.421204e-001, + // albedo 1, turbidity 6 + -2.379373e+000, + -1.540348e+000, + -1.318467e+000, + 1.724703e+000, + -1.017147e-001, + 1.811106e-001, + -3.047951e-006, + 1.598808e+000, + 5.796580e-001, + -3.200327e+000, + -2.016985e+000, + 9.935187e-001, + -9.970906e-001, + -2.159523e-001, + 3.183812e-001, + 1.575987e-002, + 1.180131e+000, + 2.839510e-001, + -1.107956e+000, + -1.330969e+000, + -1.627216e-001, + 2.985435e+000, + -2.198633e-002, + -4.401148e-001, + -5.433064e-002, + 1.701087e+000, + 8.289746e-001, + -9.423359e-001, + 4.619106e-002, + 3.116348e-002, + -6.353122e+000, + -6.192769e+000, + 1.175886e+000, + 1.020452e-001, + 2.180417e+000, + 7.076018e-001, + -1.037343e+000, + -5.711080e-001, + 1.282899e+000, + 8.808032e+000, + -8.741903e-001, + -6.097972e-001, + -5.996612e-002, + 1.533313e-001, + 5.842877e-001, + -1.002208e+000, + -3.271512e-001, + 7.288675e-001, + 7.950560e-001, + -5.029931e+000, + 4.493639e-001, + 2.389923e-002, + 1.568465e+000, + 5.653910e-001, + // albedo 1, turbidity 7 + -3.584221e+000, + -2.140498e+000, + -5.324613e+000, + 5.753381e+000, + -2.662581e-002, + 2.099272e-001, + -6.879519e-006, + 1.362229e+000, + 9.000467e-001, + -3.579609e+000, + -1.804420e+000, + 3.448490e+000, + -2.929179e+000, + -6.009529e-002, + 2.821561e-001, + -6.203809e-004, + 1.312035e+000, + -3.013934e-001, + -2.053811e+000, + -2.420850e+000, + -1.795999e+000, + 1.835004e+000, + -3.451800e-001, + -1.042135e-001, + 1.511574e-002, + 1.751304e+000, + 1.491704e+000, + -2.602659e-001, + 5.963320e-001, + 1.059632e+000, + -1.214076e+000, + 6.424455e-001, + 6.890202e-001, + -6.544341e-002, + 1.457883e+000, + 5.321707e-001, + -1.266632e+000, + -8.504227e-001, + 8.680693e-001, + 1.899473e+000, + -8.680238e+000, + -1.798563e-001, + 1.477665e-001, + 2.430031e-001, + 4.229871e-001, + -1.021321e+000, + -5.129049e-001, + 9.006232e-001, + 1.534018e+000, + -3.672948e+000, + 2.301115e-001, + 5.151145e-003, + 7.460819e-001, + 5.418252e-001, + // albedo 1, turbidity 8 + -4.095186e+000, + -2.274183e+000, + -4.115160e+000, + 4.514741e+000, + -3.131440e-002, + 1.475658e-001, + -5.329133e-006, + 1.411833e+000, + 8.893477e-001, + -3.691554e+000, + -1.654418e+000, + 3.158573e+000, + -2.961366e+000, + -7.834161e-002, + 3.035141e-001, + -4.241191e-004, + 1.485200e+000, + -1.689443e-001, + -2.697067e+000, + -3.473351e+000, + -1.707297e+000, + 3.138823e+000, + -8.323430e-002, + -1.605972e-001, + 1.025052e-002, + 1.132282e+000, + 1.093318e+000, + 7.049827e-001, + 1.769870e+000, + 8.659868e-001, + -4.445404e+000, + -2.256134e+000, + 7.768538e-001, + -4.741793e-002, + 2.212406e+000, + 1.109562e+000, + -1.771411e+000, + -1.358270e+000, + 7.604506e-001, + 7.191590e+000, + -4.358366e+000, + -3.375251e-001, + 1.136852e-001, + 1.844576e-001, + -1.208189e-003, + -9.623648e-001, + -5.518470e-001, + 9.623684e-001, + -5.697517e-003, + -5.015884e+000, + 2.811964e-001, + 2.100168e-002, + 4.434131e-001, + 7.212648e-001, + // albedo 1, turbidity 9 + -5.131552e+000, + -2.558716e+000, + -8.066753e+000, + 8.403192e+000, + -1.450692e-002, + 1.494495e-001, + -2.898774e-006, + 1.427512e+000, + 5.020826e-001, + -6.192910e+000, + -2.261479e+000, + 5.059205e+000, + -4.892079e+000, + -2.703716e-002, + 3.381259e-001, + 2.231257e-002, + 1.490697e+000, + 5.441761e-001, + -6.741018e-001, + -3.356237e+000, + -2.207329e+000, + 3.300094e+000, + -1.801120e-001, + -2.560242e-001, + -6.216731e-002, + 1.180699e+000, + 2.241782e-001, + -8.312435e-001, + 1.325391e+000, + 5.324159e-001, + -2.912438e+000, + -8.384977e-002, + 7.600872e-001, + 7.749519e-002, + 2.129188e+000, + 1.328287e+000, + -7.455272e-001, + -8.504579e-001, + 9.021474e-001, + 3.426594e+000, + -4.607412e+000, + -1.706127e-001, + 4.792024e-002, + 2.354077e-001, + 2.718195e-001, + -1.448374e+000, + -9.739004e-001, + 8.801628e-001, + 1.705262e+000, + -2.420298e+000, + -1.077392e-002, + 2.691713e-002, + 1.854876e-001, + 7.097466e-001, + // albedo 1, turbidity 10 + -8.672396e+000, + -3.339107e+000, + -7.666257e+000, + 7.916291e+000, + -1.396976e-002, + 1.676538e-001, + -5.816416e-006, + 1.448247e+000, + 8.178892e-001, + -7.852799e+000, + -2.606120e+000, + 4.231840e+000, + -3.774406e+000, + -3.540722e-002, + 2.178494e-001, + 6.198617e-005, + 1.295236e+000, + 1.130678e-001, + -1.374103e-001, + -3.570476e+000, + -1.588768e+000, + 1.538806e+000, + -1.923629e-001, + -1.793545e-002, + 3.373950e-003, + 2.008581e+000, + 6.041668e-001, + -2.211224e+000, + 1.190704e-001, + 6.700025e-002, + -8.972445e-001, + 2.133056e-001, + 4.471730e-001, + -3.148150e-002, + 9.759721e-001, + 1.166537e+000, + 5.932825e-001, + 2.482606e-001, + 9.239617e-001, + 2.382787e+000, + -4.611846e+000, + 1.608983e-001, + 1.385590e-001, + 7.641781e-001, + 3.076032e-001, + -2.098394e+000, + -1.561705e+000, + 7.602298e-001, + 1.783879e+000, + -1.486238e+000, + -4.025919e-001, + 2.965074e-002, + -8.717180e-002, + 7.279518e-001, +}; + +double datasetRad360[] = +{ + // albedo 0, turbidity 1 + 2.494129e-003, + 3.556297e-003, + 2.965923e-004, + 2.713084e-003, + 1.335823e-001, + 8.293879e-002, + // albedo 0, turbidity 2 + 2.473622e-003, + 3.518055e-003, + 4.432438e-004, + 1.754027e-003, + 1.352516e-001, + 8.253805e-002, + // albedo 0, turbidity 3 + 2.485307e-003, + 3.507686e-003, + 4.235269e-004, + 1.120748e-003, + 1.360769e-001, + 8.328522e-002, + // albedo 0, turbidity 4 + 2.421491e-003, + 3.278595e-003, + 1.395344e-003, + -1.953245e-003, + 1.392978e-001, + 8.376885e-002, + // albedo 0, turbidity 5 + 2.403587e-003, + 3.114517e-003, + 2.224702e-003, + -5.305220e-003, + 1.435766e-001, + 8.315234e-002, + // albedo 0, turbidity 6 + 2.351950e-003, + 2.915308e-003, + 3.179213e-003, + -8.297787e-003, + 1.471589e-001, + 8.200387e-002, + // albedo 0, turbidity 7 + 2.347797e-003, + 2.761449e-003, + 3.671854e-003, + -1.012039e-002, + 1.480091e-001, + 8.399335e-002, + // albedo 0, turbidity 8 + 2.296250e-003, + 2.420416e-003, + 5.106803e-003, + -1.515460e-002, + 1.526421e-001, + 8.454641e-002, + // albedo 0, turbidity 9 + 2.193368e-003, + 1.826966e-003, + 7.606333e-003, + -2.312584e-002, + 1.588488e-001, + 8.547295e-002, + // albedo 0, turbidity 10 + 2.037533e-003, + 9.415569e-004, + 1.104382e-002, + -3.348390e-002, + 1.637893e-001, + 8.792408e-002, + // albedo 1, turbidity 1 + 3.061048e-003, + 2.126839e-003, + 1.132767e-002, + -2.788848e-002, + 1.948610e-001, + 1.618476e-001, + // albedo 1, turbidity 2 + 3.047180e-003, + 2.153513e-003, + 1.116935e-002, + -2.810228e-002, + 1.949994e-001, + 1.614103e-001, + // albedo 1, turbidity 3 + 3.038920e-003, + 2.051613e-003, + 1.130934e-002, + -2.861029e-002, + 1.941964e-001, + 1.617911e-001, + // albedo 1, turbidity 4 + 2.963024e-003, + 1.869150e-003, + 1.189063e-002, + -3.088695e-002, + 1.962576e-001, + 1.593205e-001, + // albedo 1, turbidity 5 + 2.918936e-003, + 1.726267e-003, + 1.250792e-002, + -3.337994e-002, + 1.973927e-001, + 1.577752e-001, + // albedo 1, turbidity 6 + 2.855489e-003, + 1.647214e-003, + 1.256484e-002, + -3.387525e-002, + 1.965371e-001, + 1.571482e-001, + // albedo 1, turbidity 7 + 2.825443e-003, + 1.406555e-003, + 1.336433e-002, + -3.675617e-002, + 1.982073e-001, + 1.535780e-001, + // albedo 1, turbidity 8 + 2.678428e-003, + 1.109106e-003, + 1.431453e-002, + -4.011878e-002, + 1.979278e-001, + 1.510186e-001, + // albedo 1, turbidity 9 + 2.555750e-003, + 6.244779e-004, + 1.562522e-002, + -4.466841e-002, + 1.968517e-001, + 1.462399e-001, + // albedo 1, turbidity 10 + 2.323920e-003, + 1.300657e-004, + 1.663828e-002, + -4.826021e-002, + 1.889056e-001, + 1.427310e-001, +}; + +double dataset400[] = +{ + // albedo 0, turbidity 1 + -1.869600e+000, + -9.575785e-001, + -6.993871e+000, + 7.306207e+000, + -3.240320e-002, + 3.834949e-001, + 4.369976e-005, + 2.254773e+000, + 5.025988e-001, + -1.746138e+000, + -1.001117e+000, + -1.758295e+000, + 2.492931e+000, + -6.202861e-002, + 4.442043e-001, + -3.779550e-004, + 1.411622e+000, + 4.890101e-001, + -1.536453e+000, + -5.330479e-001, + 1.126830e+000, + -2.452367e+000, + -6.694842e-002, + -2.983825e-002, + 2.320196e-003, + 5.488905e+000, + 5.403856e-001, + -1.069780e+000, + -5.815078e-001, + 8.612956e-001, + 1.301347e+000, + -4.089489e-001, + 1.269432e+000, + -9.018004e-003, + -2.283572e+000, + 3.760374e-001, + -1.060384e+000, + -2.207518e-001, + 6.362691e-001, + -5.757237e-001, + 4.275177e-001, + 8.443714e-002, + 2.082596e-002, + 3.125040e+000, + 7.891611e-001, + -1.077246e+000, + -2.993040e-001, + 8.167430e-001, + 2.203982e-001, + -3.984213e+000, + 1.123699e+000, + 1.313138e-002, + 1.750491e+000, + 4.999653e-001, + // albedo 0, turbidity 2 + -1.752499e+000, + -9.053927e-001, + -1.080943e+001, + 1.110516e+001, + -2.092090e-002, + 3.348109e-001, + -8.432141e-006, + 2.326824e+000, + 9.000500e-001, + -1.888565e+000, + -1.067725e+000, + 1.491851e+000, + -7.934014e-001, + -4.853718e-002, + 5.346693e-001, + 9.170370e-005, + 1.397595e+000, + -3.635730e-001, + -1.471013e+000, + -5.497976e-001, + -4.310423e-001, + -8.787275e-001, + -9.206447e-002, + -1.490862e-001, + -4.078054e-005, + 5.442983e+000, + 1.757010e+000, + -1.061905e+000, + -5.429222e-001, + 1.412232e+000, + 8.460977e-001, + -2.973654e-001, + 1.357299e+000, + -5.347332e-003, + -2.444304e+000, + -3.363016e-002, + -1.071200e+000, + -2.263246e-001, + 3.639469e-001, + -6.109244e-001, + -2.484665e-001, + -7.097027e-002, + 4.735641e-002, + 3.445733e+000, + 8.486491e-001, + -1.081645e+000, + -3.128264e-001, + 8.436471e-001, + 3.884148e-001, + -5.004662e+000, + 1.137000e+000, + 1.500838e-002, + 1.585647e+000, + 5.832608e-001, + // albedo 0, turbidity 3 + -1.774187e+000, + -9.327599e-001, + -9.130103e+000, + 9.413272e+000, + -2.448089e-002, + 3.487996e-001, + -3.033497e-006, + 2.291071e+000, + 6.408360e-001, + -1.849342e+000, + -1.038735e+000, + 2.863013e+000, + -2.260302e+000, + -5.040252e-002, + 4.583723e-001, + 1.008690e-002, + 1.502617e+000, + 7.223351e-002, + -1.624679e+000, + -7.257060e-001, + -1.493033e+000, + 5.658415e-001, + -2.079847e-001, + -4.651180e-002, + -3.701743e-002, + 4.858534e+000, + 1.342775e+000, + -8.692395e-001, + -3.025565e-001, + 1.630221e+000, + -4.624355e-002, + 8.408669e-002, + 1.091981e+000, + 6.506253e-002, + -1.403006e+000, + 2.076066e-001, + -1.169258e+000, + -3.711802e-001, + 3.440155e-001, + -1.044556e-001, + -3.304858e+000, + 1.185883e-001, + 1.489352e-002, + 2.642598e+000, + 8.151882e-001, + -1.058391e+000, + -2.657785e-001, + 6.984363e-001, + 9.737578e-002, + -1.903943e+000, + 8.963329e-001, + 6.480860e-002, + 2.034024e+000, + 5.870424e-001, + // albedo 0, turbidity 4 + -1.898858e+000, + -1.031814e+000, + -9.726056e+000, + 1.000989e+001, + -2.125268e-002, + 3.569897e-001, + -2.706653e-006, + 2.147646e+000, + 5.982401e-001, + -2.136007e+000, + -1.206456e+000, + 3.801172e+000, + -3.254852e+000, + -4.516490e-002, + 4.001123e-001, + 2.151890e-002, + 1.481457e+000, + 1.444904e-001, + -1.355343e+000, + -6.736369e-001, + -2.052620e+000, + 1.298239e+000, + -1.986869e-001, + 6.321488e-002, + -6.792635e-002, + 4.482593e+000, + 1.322565e+000, + -9.063816e-001, + -1.873797e-001, + 1.559544e+000, + -2.631298e-001, + 5.988684e-002, + 9.375378e-001, + 9.681349e-002, + -6.480890e-001, + 2.362949e-001, + -1.170470e+000, + -3.968082e-001, + 2.266604e-001, + -2.018118e-001, + -3.768512e+000, + 9.706445e-002, + 6.046660e-002, + 2.723200e+000, + 7.968878e-001, + -1.085813e+000, + -3.519543e-001, + 7.537557e-001, + 3.003522e-001, + -1.811803e+000, + 7.945754e-001, + 5.293207e-002, + 1.335214e+000, + 6.385980e-001, + // albedo 0, turbidity 5 + -1.743240e+000, + -9.391727e-001, + -8.905876e+000, + 9.139326e+000, + -2.333803e-002, + 3.093783e-001, + -2.051734e-006, + 2.320564e+000, + 5.474845e-001, + -2.624196e+000, + -1.516703e+000, + 5.053093e+000, + -4.599198e+000, + -4.248730e-002, + 4.820250e-001, + 1.829762e-002, + 1.216991e+000, + 2.739806e-001, + -1.040612e+000, + -6.103044e-001, + -3.190021e+000, + 3.216574e+000, + -3.285978e-001, + -1.982489e-001, + -5.367025e-002, + 3.984414e+000, + 1.158312e+000, + -9.537244e-001, + -6.895800e-003, + 1.788307e+000, + -2.659655e+000, + 6.473584e-001, + 1.333544e+000, + 5.529579e-002, + 8.049825e-001, + 4.930209e-001, + -1.163791e+000, + -5.095388e-001, + 1.215079e-001, + 3.427998e+000, + -9.243257e+000, + -5.059496e-001, + 1.412681e-001, + 1.829389e+000, + 5.544610e-001, + -1.118058e+000, + -3.706501e-001, + 6.885180e-001, + -1.596776e-003, + -3.279613e+000, + 1.068229e+000, + 3.010797e-002, + 1.479756e+000, + 7.483765e-001, + // albedo 0, turbidity 6 + -1.811701e+000, + -1.002650e+000, + -9.194183e+000, + 9.469966e+000, + -2.224886e-002, + 3.237441e-001, + -2.632967e-006, + 2.168879e+000, + 5.952956e-001, + -2.746180e+000, + -1.592055e+000, + 4.225172e+000, + -3.929912e+000, + -3.866297e-002, + 3.982440e-001, + 3.812089e-002, + 1.390284e+000, + 1.922369e-001, + -9.558770e-001, + -6.401790e-001, + -2.117905e+000, + 2.293799e+000, + -2.226591e-001, + 6.151477e-002, + -1.223358e-001, + 3.475975e+000, + 1.124575e+000, + -9.065351e-001, + 1.443765e-001, + 7.871576e-001, + -1.631026e+000, + 1.537369e-001, + 8.353048e-001, + 1.849704e-001, + 1.650615e+000, + 4.473559e-001, + -1.180081e+000, + -5.441674e-001, + 3.963103e-001, + 1.375519e+000, + -4.882926e+000, + -9.391794e-004, + 6.455569e-002, + 1.774670e+000, + 6.989373e-001, + -1.128755e+000, + -3.892532e-001, + 5.327884e-001, + 1.825253e+000, + -2.335719e+000, + 5.863162e-001, + 5.535626e-002, + 1.452293e+000, + 6.920090e-001, + // albedo 0, turbidity 7 + -2.042064e+000, + -1.144943e+000, + -5.152625e+000, + 5.384535e+000, + -3.519943e-002, + 3.025845e-001, + -2.994849e-006, + 2.113418e+000, + 6.000255e-001, + -2.700541e+000, + -1.485611e+000, + 2.159154e+000, + -2.188608e+000, + -5.879735e-002, + 3.921779e-001, + 5.020849e-002, + 1.869923e+000, + 2.118398e-001, + -1.187417e+000, + -1.102630e+000, + -9.404690e-001, + 2.427532e+000, + -2.948903e-001, + -3.437257e-002, + -1.636446e-001, + 1.894926e+000, + 1.001327e+000, + -5.639857e-001, + 7.170770e-001, + -1.146502e-001, + -3.487513e+000, + -7.711076e-001, + 1.046031e+000, + 2.606854e-001, + 3.873520e+000, + 5.637980e-001, + -1.363103e+000, + -8.396317e-001, + 5.750351e-001, + 4.317766e+000, + -2.364722e+000, + -4.135433e-001, + 2.669162e-002, + 5.768700e-001, + 6.649078e-001, + -1.102449e+000, + -3.685043e-001, + 4.622549e-001, + -2.018634e-003, + -3.947538e+000, + 8.449276e-001, + 8.837036e-002, + 1.601304e+000, + 7.026980e-001, + // albedo 0, turbidity 8 + -2.314053e+000, + -1.314766e+000, + -7.125646e+000, + 7.357344e+000, + -2.585710e-002, + 2.863908e-001, + -2.425744e-006, + 2.039404e+000, + 5.594003e-001, + -2.630411e+000, + -1.404258e+000, + 3.675058e+000, + -3.804226e+000, + -4.249037e-002, + 3.486414e-001, + 5.675141e-002, + 1.944935e+000, + 2.880711e-001, + -1.884599e+000, + -1.657069e+000, + -1.731916e+000, + 3.034605e+000, + -1.746846e-001, + -1.559184e-002, + -1.600465e-001, + 1.915108e+000, + 9.460232e-001, + 6.351036e-002, + 1.061776e+000, + 1.195544e-002, + -3.018584e+000, + -5.618808e-001, + 1.008146e+000, + 2.013783e-001, + 3.212273e+000, + 6.523624e-001, + -1.672505e+000, + -9.752710e-001, + 5.282860e-001, + 3.776331e+000, + -4.325128e+000, + -4.384279e-001, + 1.352387e-001, + 8.847662e-001, + 5.717158e-001, + -1.007695e+000, + -3.840375e-001, + 3.463543e-001, + 2.848366e+000, + -2.105699e+000, + 4.636429e-001, + 2.800131e-002, + 1.306056e+000, + 7.618236e-001, + // albedo 0, turbidity 9 + -2.865406e+000, + -1.637174e+000, + -7.429613e+000, + 7.592861e+000, + -2.196505e-002, + 2.800873e-001, + -3.908530e-006, + 1.962505e+000, + 5.891464e-001, + -3.196334e+000, + -1.512711e+000, + 3.947880e+000, + -4.029796e+000, + -3.699620e-002, + 1.461452e-001, + 5.921432e-002, + 1.806132e+000, + 2.331816e-001, + -2.335492e+000, + -2.353032e+000, + -1.764665e+000, + 2.841986e+000, + -7.331326e-002, + 4.537047e-001, + -1.668000e-001, + 2.156269e+000, + 9.812486e-001, + 3.278911e-001, + 1.315177e+000, + -1.438189e-001, + -2.859630e+000, + -8.436262e-001, + 2.645711e-001, + 2.154409e-001, + 2.264493e+000, + 5.975203e-001, + -1.738015e+000, + -1.091057e+000, + 5.425696e-001, + 4.650166e+000, + -3.975190e+000, + 2.066035e-001, + 1.017332e-001, + 9.321625e-001, + 6.517783e-001, + -1.006457e+000, + -4.243112e-001, + 1.934952e-001, + 2.795030e+000, + -1.680697e+000, + -9.428375e-002, + 7.158314e-002, + 1.082383e+000, + 7.234775e-001, + // albedo 0, turbidity 10 + -4.195701e+000, + -2.171135e+000, + -5.278016e+000, + 5.393085e+000, + -2.419182e-002, + 2.050075e-001, + -3.797795e-006, + 1.853402e+000, + 6.912927e-001, + -4.119053e+000, + -1.648023e+000, + 2.332552e+000, + -2.173813e+000, + -6.442977e-002, + 2.188945e-001, + 3.548565e-002, + 1.792598e+000, + 4.162082e-002, + -4.016823e+000, + -3.599323e+000, + -6.179057e-001, + 6.454998e-001, + -9.913704e-002, + 2.770986e-001, + -9.265471e-002, + 2.227501e+000, + 1.179216e+000, + 1.066227e+000, + 1.392783e+000, + -9.653695e-001, + -5.471637e-001, + -8.500569e-001, + 4.678476e-001, + 8.760324e-002, + 1.564314e+000, + 4.885251e-001, + -1.855594e+000, + -1.029300e+000, + 8.521013e-001, + 3.975027e+000, + -3.806819e+000, + -2.044703e-002, + 1.757298e-001, + 7.790123e-001, + 6.918921e-001, + -1.014961e+000, + -6.014045e-001, + 1.926619e-002, + 2.357335e+000, + -1.312911e+000, + -8.783609e-002, + 7.739369e-002, + 7.356770e-001, + 7.042591e-001, + // albedo 1, turbidity 1 + -1.467874e+000, + -7.636581e-001, + -7.251111e+000, + 7.726558e+000, + -2.759341e-002, + 3.527534e-001, + 5.340629e-005, + 2.007747e+000, + 5.447487e-001, + -1.863242e+000, + -1.048209e+000, + -1.580541e+000, + 2.558030e+000, + -5.622126e-002, + 3.053960e-001, + -4.657733e-004, + 9.956390e-001, + 3.409087e-001, + -1.384101e+000, + -5.553588e-001, + 1.191974e+000, + -2.157512e+000, + -3.567589e-002, + 1.020018e-001, + 2.940191e-003, + 4.555372e+000, + 8.736043e-001, + -9.828878e-001, + -4.220161e-001, + 1.184916e+000, + 9.230716e-001, + -4.062756e-001, + 1.064980e+000, + -1.060088e-002, + -1.764815e+000, + 2.932808e-001, + -1.057001e+000, + -2.727017e-001, + 1.000018e+000, + -3.108668e-001, + 6.848382e-001, + -1.682596e-001, + 2.301218e-002, + 2.075821e+000, + 7.647327e-001, + -1.058165e+000, + -2.436130e-001, + 1.074414e+000, + 8.554434e-002, + -3.846431e+000, + 7.595465e-001, + 9.729528e-006, + 1.915942e+000, + 4.999612e-001, + // albedo 1, turbidity 2 + -1.610179e+000, + -8.336019e-001, + -1.443356e+001, + 1.492556e+001, + -1.381931e-002, + 2.902743e-001, + -7.665717e-006, + 1.981513e+000, + 9.000423e-001, + -2.004083e+000, + -1.148388e+000, + 3.747156e+000, + -2.808560e+000, + -3.298677e-002, + 4.224754e-001, + 4.166438e-004, + 8.792110e-001, + -2.321793e-001, + -1.178554e+000, + -5.064839e-001, + -1.117126e+000, + 2.815740e-001, + -7.068438e-002, + -3.031589e-002, + -3.468069e-003, + 4.539093e+000, + 1.385612e+000, + -1.091191e+000, + -4.200919e-001, + 1.826508e+000, + 7.131992e-002, + -1.883417e-001, + 1.061437e+000, + 1.311913e-002, + -1.972550e+000, + 2.511246e-001, + -9.987232e-001, + -2.073656e-001, + 7.443384e-001, + -7.245157e-002, + -5.588818e-001, + -1.364188e-001, + 2.023795e-002, + 2.829822e+000, + 7.230021e-001, + -1.075477e+000, + -2.556973e-001, + 1.051690e+000, + 3.075960e-002, + -1.895492e+000, + 6.408333e-001, + 2.109454e-002, + 1.891240e+000, + 5.652527e-001, + // albedo 1, turbidity 3 + -1.531711e+000, + -8.266123e-001, + -9.324763e+000, + 9.811491e+000, + -1.988560e-002, + 3.404598e-001, + -2.068369e-006, + 1.869307e+000, + 5.860842e-001, + -2.113444e+000, + -1.209106e+000, + 3.526508e+000, + -2.628730e+000, + -4.634065e-002, + 3.182739e-001, + 9.500212e-003, + 1.004871e+000, + 2.109968e-001, + -1.196720e+000, + -5.485073e-001, + -1.667136e+000, + 9.920197e-001, + -1.622954e-001, + 6.951315e-002, + -3.482877e-002, + 4.214632e+000, + 1.108967e+000, + -1.003096e+000, + -3.200944e-001, + 2.042427e+000, + -4.417822e-001, + -1.404599e-001, + 9.288535e-001, + 6.077264e-002, + -1.386737e+000, + 4.557129e-001, + -1.061048e+000, + -2.908451e-001, + 6.390633e-001, + 1.406786e-001, + -1.834706e+000, + -1.432145e-001, + 1.914080e-002, + 2.284516e+000, + 5.965839e-001, + -1.054623e+000, + -2.267971e-001, + 1.028491e+000, + -3.197518e-003, + -1.705329e+000, + 6.747358e-001, + 2.072713e-002, + 2.140509e+000, + 7.205824e-001, + // albedo 1, turbidity 4 + -1.610001e+000, + -8.622601e-001, + -1.060181e+001, + 1.106133e+001, + -1.648296e-002, + 2.590559e-001, + -1.904522e-006, + 1.930415e+000, + 6.006964e-001, + -2.308577e+000, + -1.440194e+000, + 2.937335e+000, + -2.093599e+000, + -3.430217e-002, + 3.427774e-001, + 2.590705e-002, + 5.673750e-001, + 1.250422e-001, + -9.441254e-001, + -3.064812e-001, + -8.895068e-001, + 2.815271e-001, + -8.036228e-002, + 1.867017e-001, + -7.809247e-002, + 4.774631e+000, + 1.391904e+000, + -1.214397e+000, + -5.423074e-001, + 1.361001e+000, + 1.782273e-001, + -3.648675e-001, + 7.181838e-001, + 1.135547e-001, + -1.935982e+000, + 1.820361e-001, + -9.377631e-001, + -1.533211e-001, + 8.439993e-001, + -3.893771e-001, + -2.564779e-001, + -6.742272e-002, + 2.255856e-002, + 2.780601e+000, + 7.972008e-001, + -1.101428e+000, + -3.069552e-001, + 9.687591e-001, + 4.500576e-001, + -4.912444e+000, + 5.398387e-001, + 3.638172e-002, + 1.582999e+000, + 6.425950e-001, + // albedo 1, turbidity 5 + -1.687541e+000, + -9.378170e-001, + -8.475686e+000, + 8.929279e+000, + -2.132746e-002, + 2.917650e-001, + -2.177239e-006, + 1.863407e+000, + 5.908179e-001, + -2.278432e+000, + -1.387936e+000, + 5.425292e+000, + -4.725025e+000, + -3.892912e-002, + 4.084727e-001, + 1.842665e-002, + 8.461986e-001, + 1.673366e-001, + -1.302702e+000, + -7.200083e-001, + -3.084331e+000, + 3.191487e+000, + -3.222828e-001, + -1.493849e-001, + -5.641672e-002, + 3.624218e+000, + 1.256086e+000, + -7.886965e-001, + -3.966453e-002, + 2.110076e+000, + -2.232935e+000, + 7.269719e-001, + 1.163410e+000, + 7.133744e-002, + -1.660119e-001, + 4.329084e-001, + -1.157760e+000, + -4.084596e-001, + 5.689088e-001, + 2.379590e+000, + -9.687743e+000, + -5.598487e-001, + 9.191895e-002, + 1.923047e+000, + 5.802927e-001, + -1.047250e+000, + -2.873072e-001, + 1.046858e+000, + 6.890046e-001, + -2.947892e+000, + 7.245997e-001, + 1.125227e-002, + 1.352625e+000, + 7.193979e-001, + // albedo 1, turbidity 6 + -1.643764e+000, + -9.086683e-001, + -8.750078e+000, + 9.165653e+000, + -2.025728e-002, + 2.737848e-001, + -2.240987e-006, + 1.943471e+000, + 5.731722e-001, + -2.473069e+000, + -1.505194e+000, + 5.448737e+000, + -4.863726e+000, + -3.662439e-002, + 1.938729e-001, + 4.741355e-002, + 8.586572e-001, + 2.284408e-001, + -1.232599e+000, + -7.896777e-001, + -3.056911e+000, + 3.546334e+000, + -1.948820e-001, + 3.344216e-001, + -1.376967e-001, + 3.029469e+000, + 1.120573e+000, + -6.095289e-001, + 2.745468e-001, + 1.809782e+000, + -2.593032e+000, + -1.710009e-002, + 5.537278e-001, + 1.935506e-001, + 1.259882e+000, + 4.970103e-001, + -1.324655e+000, + -6.255071e-001, + 6.240868e-001, + 2.021182e+000, + -5.876050e+000, + -1.507819e-001, + 3.301250e-002, + 1.142019e+000, + 5.986671e-001, + -9.888131e-001, + -2.584852e-001, + 1.052160e+000, + 7.264224e-001, + -2.563426e+000, + 5.494058e-001, + 1.821983e-002, + 1.277896e+000, + 7.557967e-001, + // albedo 1, turbidity 7 + -2.100689e+000, + -1.204431e+000, + -7.573121e+000, + 8.039632e+000, + -2.300526e-002, + 2.839214e-001, + -2.346958e-006, + 1.678847e+000, + 5.536303e-001, + -2.610610e+000, + -1.587799e+000, + 5.460928e+000, + -5.158708e+000, + -4.505650e-002, + 3.876929e-001, + 3.852459e-002, + 1.172854e+000, + 3.104745e-001, + -8.340903e-001, + -7.487965e-001, + -3.154774e+000, + 4.600448e+000, + -1.818975e-001, + -1.871764e-001, + -1.222094e-001, + 2.067197e+000, + 8.802127e-001, + -9.180308e-001, + 3.752197e-001, + 1.471125e+000, + -4.691789e+000, + -5.128294e-001, + 1.164707e+000, + 1.831224e-001, + 2.900937e+000, + 7.718397e-001, + -1.126819e+000, + -6.652330e-001, + 7.386065e-001, + 5.362044e+000, + -6.196453e+000, + -7.280092e-001, + 6.312604e-002, + 2.874666e-001, + 4.225580e-001, + -1.091610e+000, + -3.433417e-001, + 1.042206e+000, + 1.075776e-001, + -4.443940e+000, + 7.469895e-001, + 3.166247e-002, + 1.019495e+000, + 7.523771e-001, + // albedo 1, turbidity 8 + -2.234623e+000, + -1.310221e+000, + -8.525764e+000, + 8.932373e+000, + -1.814945e-002, + 2.615153e-001, + -2.992344e-006, + 1.672403e+000, + 5.897681e-001, + -2.566352e+000, + -1.472664e+000, + 5.894182e+000, + -5.619094e+000, + -3.204346e-002, + 2.993298e-001, + 4.281047e-002, + 1.303481e+000, + 2.453403e-001, + -1.577477e+000, + -1.491725e+000, + -3.065840e+000, + 4.446634e+000, + -1.689128e-001, + 9.559287e-002, + -1.384724e-001, + 1.778589e+000, + 9.159045e-001, + -2.747774e-001, + 8.787060e-001, + 1.071723e+000, + -4.169230e+000, + -3.029966e-001, + 6.326611e-001, + 2.145395e-001, + 2.611218e+000, + 7.082708e-001, + -1.433045e+000, + -8.939972e-001, + 8.538090e-001, + 4.481475e+000, + -5.978961e+000, + -1.608369e-001, + 5.335732e-002, + 3.510751e-001, + 5.421327e-001, + -9.961738e-001, + -3.023960e-001, + 9.152994e-001, + 2.936173e+000, + -2.311060e+000, + 1.216642e-001, + 2.844950e-002, + 9.492671e-001, + 6.929460e-001, + // albedo 1, turbidity 9 + -2.428587e+000, + -1.538689e+000, + -9.076712e+000, + 9.464050e+000, + -1.503392e-002, + 2.373401e-001, + -2.770103e-006, + 1.537508e+000, + 5.959289e-001, + -3.240872e+000, + -1.646067e+000, + 6.091797e+000, + -5.738481e+000, + -3.098072e-002, + 2.698026e-001, + 3.864212e-002, + 1.286514e+000, + 2.461153e-001, + -1.970987e+000, + -2.124015e+000, + -2.894000e+000, + 3.858260e+000, + -1.449222e-001, + 1.903898e-001, + -1.194017e-001, + 1.882566e+000, + 8.764452e-001, + 3.562238e-002, + 1.092427e+000, + 6.291668e-001, + -3.337396e+000, + -2.817141e-001, + 4.799828e-001, + 1.674350e-001, + 1.943489e+000, + 7.728749e-001, + -1.501790e+000, + -9.408520e-001, + 1.000954e+000, + 4.599103e+000, + -5.295662e+000, + -1.111397e-001, + 1.040124e-001, + 3.185557e-001, + 4.959400e-001, + -9.859417e-001, + -3.827367e-001, + 8.040930e-001, + 2.980678e+000, + -2.015582e+000, + -8.947514e-003, + 1.696367e-002, + 6.489501e-001, + 7.555598e-001, + // albedo 1, turbidity 10 + -3.758956e+000, + -2.159015e+000, + -7.207163e+000, + 7.516659e+000, + -1.643521e-002, + 2.465725e-001, + -4.045068e-006, + 1.471688e+000, + 6.687943e-001, + -4.635664e+000, + -1.766046e+000, + 4.282669e+000, + -4.058908e+000, + -2.908998e-002, + 1.202684e-001, + 3.167305e-002, + 1.450927e+000, + 8.171815e-002, + -3.458011e+000, + -3.657280e+000, + -1.484743e+000, + 2.264533e+000, + -1.033120e-001, + 4.282323e-001, + -8.387881e-002, + 1.687334e+000, + 1.130604e+000, + 9.673527e-001, + 1.500425e+000, + -3.604932e-001, + -2.050346e+000, + -3.778381e-001, + 2.416298e-001, + 8.439313e-002, + 1.458583e+000, + 5.816071e-001, + -1.808078e+000, + -1.089975e+000, + 1.291838e+000, + 5.144631e+000, + -5.047822e+000, + 4.301183e-002, + 1.426941e-001, + 1.187472e-001, + 6.145551e-001, + -8.399253e-001, + -3.832885e-001, + 6.306417e-001, + 2.179775e+000, + -1.492762e+000, + -1.682763e-001, + 4.109851e-002, + 4.221724e-001, + 7.086504e-001, +}; + +double datasetRad400[] = +{ + // albedo 0, turbidity 1 + 5.767645e-003, + 1.219302e-002, + -2.188467e-002, + 8.262275e-002, + 1.719839e-001, + 1.233791e-001, + // albedo 0, turbidity 2 + 5.661981e-003, + 1.258489e-002, + -2.324339e-002, + 8.372421e-002, + 1.730981e-001, + 1.255797e-001, + // albedo 0, turbidity 3 + 5.644031e-003, + 1.248986e-002, + -2.287316e-002, + 7.999388e-002, + 1.815345e-001, + 1.252983e-001, + // albedo 0, turbidity 4 + 5.479152e-003, + 1.215496e-002, + -2.122586e-002, + 7.189527e-002, + 1.962517e-001, + 1.245648e-001, + // albedo 0, turbidity 5 + 5.385972e-003, + 1.187505e-002, + -2.025911e-002, + 6.602510e-002, + 2.067312e-001, + 1.264910e-001, + // albedo 0, turbidity 6 + 5.319970e-003, + 1.160513e-002, + -1.904232e-002, + 6.030292e-002, + 2.158311e-001, + 1.261204e-001, + // albedo 0, turbidity 7 + 5.179289e-003, + 1.125842e-002, + -1.708641e-002, + 5.111365e-002, + 2.285030e-001, + 1.278260e-001, + // albedo 0, turbidity 8 + 4.994685e-003, + 1.025385e-002, + -1.254777e-002, + 3.429945e-002, + 2.490310e-001, + 1.302691e-001, + // albedo 0, turbidity 9 + 4.759538e-003, + 8.205142e-003, + -3.246300e-003, + 3.909938e-003, + 2.819549e-001, + 1.322430e-001, + // albedo 0, turbidity 10 + 4.412341e-003, + 4.910210e-003, + 1.040886e-002, + -3.627125e-002, + 3.147182e-001, + 1.409331e-001, + // albedo 1, turbidity 1 + 7.016633e-003, + 9.796846e-003, + -9.823849e-004, + 2.324224e-002, + 3.035010e-001, + 2.573850e-001, + // albedo 1, turbidity 2 + 6.984411e-003, + 9.584282e-003, + -5.945671e-004, + 2.061312e-002, + 3.090019e-001, + 2.547364e-001, + // albedo 1, turbidity 3 + 6.865141e-003, + 9.540856e-003, + -3.311701e-004, + 1.726495e-002, + 3.147099e-001, + 2.539552e-001, + // albedo 1, turbidity 4 + 6.701191e-003, + 9.352606e-003, + 3.392916e-004, + 1.159886e-002, + 3.228446e-001, + 2.530111e-001, + // albedo 1, turbidity 5 + 6.513679e-003, + 8.873317e-003, + 2.339520e-003, + 2.817964e-003, + 3.341256e-001, + 2.496316e-001, + // albedo 1, turbidity 6 + 6.405833e-003, + 8.466409e-003, + 3.661909e-003, + -3.045984e-003, + 3.414328e-001, + 2.464327e-001, + // albedo 1, turbidity 7 + 6.220899e-003, + 7.997469e-003, + 5.957591e-003, + -1.302863e-002, + 3.523355e-001, + 2.418785e-001, + // albedo 1, turbidity 8 + 5.912801e-003, + 6.826679e-003, + 1.008544e-002, + -2.771812e-002, + 3.640405e-001, + 2.386599e-001, + // albedo 1, turbidity 9 + 5.550967e-003, + 5.157051e-003, + 1.661696e-002, + -5.072656e-002, + 3.807009e-001, + 2.315489e-001, + // albedo 1, turbidity 10 + 5.011118e-003, + 2.636752e-003, + 2.499879e-002, + -7.576617e-002, + 3.828189e-001, + 2.328116e-001, +}; + +double dataset440[] = +{ + // albedo 0, turbidity 1 + -1.397312e+000, + -5.327311e-001, + -5.456059e+000, + 5.777674e+000, + -5.111575e-002, + 4.730804e-001, + 7.375500e-003, + 3.032806e+000, + 5.181890e-001, + -1.561639e+000, + -7.024946e-001, + -2.140322e+000, + 2.841761e+000, + -8.846023e-002, + 5.529005e-001, + 6.219344e-003, + 2.004212e+000, + 3.701256e-001, + -1.047473e+000, + -1.152734e-001, + 2.275873e+000, + -3.020347e+000, + -1.739218e-001, + 2.250142e-001, + -2.731776e-002, + 6.659723e+000, + 1.067495e+000, + -1.298483e+000, + -5.788209e-001, + 4.906412e-001, + 1.522576e+000, + -5.650061e-001, + 1.544707e+000, + 4.638003e-002, + -3.742019e+000, + 2.485397e-001, + -9.485899e-001, + -7.383610e-002, + 1.039247e+000, + -4.744931e-001, + -1.822357e-001, + 2.284415e-001, + -4.796962e-002, + 4.363935e+000, + 8.217971e-001, + -1.099082e+000, + -2.001688e-001, + 7.365077e-001, + 1.068489e-001, + -5.005434e+000, + 1.508145e+000, + 8.181497e-002, + 3.226865e+000, + 4.999418e-001, + // albedo 0, turbidity 2 + -1.416143e+000, + -5.515006e-001, + -7.045898e+000, + 7.448161e+000, + -4.504075e-002, + 5.055437e-001, + -1.378949e-006, + 2.955475e+000, + 6.184716e-001, + -1.698183e+000, + -8.272914e-001, + 9.984388e-001, + -2.511235e-001, + -9.262675e-002, + 5.681534e-001, + 5.377123e-003, + 1.631048e+000, + 1.137691e-001, + -9.234085e-001, + -2.165404e-002, + 6.483039e-002, + -8.535145e-001, + -2.497457e-001, + 1.695057e-001, + -3.410225e-002, + 6.726925e+000, + 1.331197e+000, + -1.265077e+000, + -5.034231e-001, + 1.196547e+000, + 3.666463e-001, + -3.960044e-001, + 1.404008e+000, + 1.129300e-001, + -2.644439e+000, + 1.103356e-001, + -1.008210e+000, + -1.455232e-001, + 7.347739e-001, + 2.462433e-002, + -2.534587e+000, + 3.088590e-001, + -6.687136e-002, + 3.786007e+000, + 9.578369e-001, + -1.076840e+000, + -1.851501e-001, + 7.341818e-001, + -2.658571e-003, + -5.001762e+000, + 1.275390e+000, + 1.277410e-001, + 3.223315e+000, + 5.147659e-001, + // albedo 0, turbidity 3 + -1.449526e+000, + -5.738159e-001, + -8.976383e+000, + 9.275142e+000, + -3.157845e-002, + 5.011970e-001, + -1.218363e-006, + 3.001006e+000, + 5.662190e-001, + -1.748840e+000, + -9.338946e-001, + 5.557460e-002, + 9.451626e-001, + -6.929558e-002, + 5.458365e-001, + 5.505399e-003, + 8.818793e-001, + 2.135274e-001, + -8.369988e-001, + 1.127967e-001, + 8.846958e-001, + -2.467908e+000, + -8.394011e-002, + 1.684067e-001, + -3.352743e-002, + 7.957386e+000, + 1.297777e+000, + -1.284515e+000, + -5.332365e-001, + 5.511261e-001, + 1.702784e+000, + -6.616281e-001, + 1.349449e+000, + 1.269152e-001, + -3.247373e+000, + 2.115827e-001, + -9.889637e-001, + -9.962819e-002, + 6.096776e-001, + -8.472749e-001, + 7.672924e-001, + 7.425160e-002, + 2.113714e-002, + 4.990637e+000, + 8.274585e-001, + -1.093910e+000, + -2.211349e-001, + 6.959659e-001, + 3.423174e-001, + -5.004213e+000, + 1.347201e+000, + 1.198192e-001, + 2.547517e+000, + 6.329489e-001, + // albedo 0, turbidity 4 + -1.394462e+000, + -5.287733e-001, + -8.095187e+000, + 8.076613e+000, + -1.275227e-002, + 1.916790e-001, + 4.741296e-002, + 3.145140e+000, + 5.071760e-001, + -2.234192e+000, + -1.437079e+000, + -5.734544e-001, + 1.248687e+000, + -4.136344e-002, + 7.671749e-001, + -1.273584e-002, + 4.751894e-001, + 4.116995e-001, + -4.063889e-001, + 4.920785e-001, + 3.865520e-001, + 2.254008e-001, + -1.618861e-001, + 1.950875e-001, + -8.622479e-002, + 3.836900e+000, + 1.108189e+000, + -1.366924e+000, + -4.557853e-001, + -6.731417e-001, + -3.011452e-001, + 2.413069e-001, + 1.404821e+000, + 1.920278e-001, + 6.394529e+000, + 4.219713e-001, + -9.128947e-001, + 1.980978e-002, + 5.119874e-001, + 8.027541e-002, + -3.680159e+000, + 6.597416e-001, + 3.853339e-002, + 3.969131e+000, + 8.351942e-001, + -1.162856e+000, + -3.606511e-001, + 7.055795e-001, + -2.702137e-003, + 4.777294e-001, + -7.722331e-001, + 3.446509e-001, + 1.186834e+000, + 5.118539e-001, + // albedo 0, turbidity 5 + -1.563353e+000, + -6.916347e-001, + -4.154766e+001, + 4.181703e+001, + -5.673370e-003, + 4.344900e-001, + 1.839829e-003, + 2.669278e+000, + 5.021266e-001, + -1.948172e+000, + -1.080669e+000, + 1.082552e+001, + -1.034262e+001, + -1.196421e-002, + 3.895739e-001, + 5.621831e-002, + 1.347130e+000, + 4.561106e-001, + -9.155219e-001, + -1.456265e-001, + -2.177275e+000, + 2.079788e+000, + -2.154465e-002, + 7.743816e-001, + -2.181642e-001, + 4.897704e+000, + 1.035464e+000, + -1.010898e+000, + -4.425431e-002, + 3.067880e-001, + -6.899235e-001, + -1.891895e-001, + 3.015686e-001, + 4.236422e-001, + 1.901582e+000, + 3.916662e-001, + -1.159005e+000, + -4.048136e-001, + 5.385745e-001, + 3.423651e-001, + 1.474365e-001, + 3.516065e-001, + 2.564260e-003, + 1.815518e+000, + 7.634079e-001, + -1.081675e+000, + -2.556981e-001, + 6.544471e-001, + 4.093649e-001, + -3.215201e+000, + 9.116400e-001, + 1.406660e-001, + 1.869407e+000, + 6.968119e-001, + // albedo 0, turbidity 6 + -1.561484e+000, + -7.153039e-001, + -1.623772e+001, + 1.650713e+001, + -1.394913e-002, + 4.467465e-001, + 9.613464e-004, + 2.564429e+000, + 5.363746e-001, + -2.308050e+000, + -1.314851e+000, + -1.484346e+000, + 1.928705e+000, + -2.164130e-002, + 2.817711e-001, + 7.177671e-002, + 1.146387e+000, + 3.025595e-001, + -4.886429e-001, + 8.279799e-002, + 2.432876e+000, + -2.276257e+000, + -4.799742e-002, + 9.362010e-001, + -2.753669e-001, + 4.784291e+000, + 1.180593e+000, + -1.306115e+000, + -1.759650e-001, + -1.392008e+000, + 3.119302e-001, + -2.268673e-001, + 8.336951e-002, + 5.250725e-001, + 2.534962e+000, + 2.800244e-001, + -1.016608e+000, + -3.429911e-001, + 5.659470e-001, + 9.044333e-001, + 7.387499e-002, + 4.267609e-001, + -4.165623e-002, + 1.452779e+000, + 8.409560e-001, + -1.127637e+000, + -2.854231e-001, + 4.933964e-001, + -3.379287e-003, + -1.181893e+000, + 8.164171e-001, + 1.910509e-001, + 1.979338e+000, + 6.658885e-001, + // albedo 0, turbidity 7 + -1.675310e+000, + -8.020443e-001, + -1.136130e+001, + 1.159861e+001, + -1.871156e-002, + 4.151400e-001, + -1.940992e-006, + 2.486322e+000, + 5.256426e-001, + -2.071301e+000, + -1.175325e+000, + 1.789426e+000, + -1.455233e+000, + -2.855906e-002, + 3.218745e-001, + 7.776969e-002, + 1.431615e+000, + 3.478887e-001, + -1.093503e+000, + -4.120496e-001, + -8.598647e-002, + 4.564844e-001, + -1.231980e-001, + 7.992132e-001, + -2.910745e-001, + 3.881502e+000, + 1.064658e+000, + -7.736128e-001, + 2.385498e-001, + -7.867818e-001, + -6.009723e-001, + -1.808566e-001, + -8.796429e-003, + 5.412620e-001, + 2.991552e+000, + 4.008143e-001, + -1.259083e+000, + -5.300975e-001, + 5.418031e-001, + 1.150966e+000, + -7.553821e-001, + 5.991000e-001, + -2.344718e-003, + 1.097939e+000, + 7.756612e-001, + -1.094148e+000, + -3.178958e-001, + 4.126954e-001, + 3.591106e-001, + -1.415744e+000, + 3.908399e-001, + 1.806147e-001, + 1.584959e+000, + 6.862009e-001, + // albedo 0, turbidity 8 + -1.815485e+000, + -9.306778e-001, + -1.249527e+001, + 1.271288e+001, + -1.497209e-002, + 3.576353e-001, + -2.464284e-006, + 2.326460e+000, + 5.655414e-001, + -2.225570e+000, + -1.213627e+000, + 6.082472e+000, + -5.907562e+000, + -2.446452e-002, + 2.113558e-001, + 7.708802e-002, + 1.647556e+000, + 2.416155e-001, + -1.439532e+000, + -8.666475e-001, + -2.734807e+000, + 3.355265e+000, + -1.311068e-001, + 1.048703e+000, + -2.887025e-001, + 3.419973e+000, + 1.146322e+000, + -5.599890e-001, + 4.437236e-001, + 1.582320e-001, + -2.000110e+000, + -2.859304e-001, + -5.600631e-001, + 5.382793e-001, + 1.986387e+000, + 3.455121e-001, + -1.319304e+000, + -6.466246e-001, + 5.684685e-001, + 2.050330e+000, + -2.796053e+000, + 1.001659e+000, + -1.161356e-002, + 9.737235e-001, + 8.101246e-001, + -1.097281e+000, + -3.336023e-001, + 1.781708e-001, + 1.733079e+000, + -1.378806e+000, + -1.870394e-001, + 1.997578e-001, + 1.456148e+000, + 6.791796e-001, + // albedo 0, turbidity 9 + -2.208666e+000, + -1.219745e+000, + -7.548669e+000, + 7.680830e+000, + -2.012473e-002, + 3.627866e-001, + -2.906182e-006, + 2.147138e+000, + 6.340095e-001, + -1.967348e+000, + -9.528057e-001, + 4.171590e+000, + -4.002838e+000, + -5.074552e-002, + 1.581866e-001, + 5.920106e-002, + 1.981564e+000, + 1.023257e-001, + -3.150304e+000, + -2.193706e+000, + -2.016165e+000, + 2.374337e+000, + -6.793058e-002, + 9.623811e-001, + -2.195022e-001, + 2.736885e+000, + 1.252161e+000, + 4.737094e-001, + 1.067875e+000, + -1.003861e-001, + -1.566752e+000, + -1.217264e+000, + -4.270598e-001, + 3.968055e-001, + 1.234108e+000, + 3.105789e-001, + -1.706975e+000, + -9.607442e-001, + 7.140098e-001, + 3.981202e+000, + -3.521433e+000, + 6.308820e-001, + 5.140937e-002, + 7.435120e-001, + 8.074305e-001, + -1.012042e+000, + -3.372525e-001, + 2.589450e-002, + 1.768224e+000, + -1.059990e+000, + -1.299077e-001, + 1.790337e-001, + 1.091012e+000, + 6.873854e-001, + // albedo 0, turbidity 10 + -2.912541e+000, + -1.677524e+000, + -3.843452e+000, + 3.954207e+000, + -3.414327e-002, + 2.945890e-001, + -4.245832e-006, + 1.934337e+000, + 7.258748e-001, + -1.567383e+000, + -8.279686e-001, + 1.690940e+000, + -1.413268e+000, + -1.216792e-001, + 7.332798e-002, + 4.862765e-002, + 2.034766e+000, + -5.041561e-002, + -6.058613e+000, + -3.509207e+000, + -6.312870e-001, + -4.558316e-002, + 6.168891e-002, + 8.153413e-001, + -1.686845e-001, + 2.670227e+000, + 1.362906e+000, + 1.347177e+000, + 9.821888e-001, + -9.242155e-001, + 5.851576e-001, + -1.897421e+000, + -2.729487e-002, + 2.866724e-001, + 7.306238e-001, + 2.792136e-001, + -1.810783e+000, + -1.027512e+000, + 1.216071e+000, + 5.270108e+000, + -3.887149e+000, + 6.193256e-002, + 2.774610e-002, + 1.484756e-001, + 8.033249e-001, + -9.801965e-001, + -3.375841e-001, + -3.004804e-001, + 1.385754e+000, + -6.834540e-001, + 5.827734e-002, + 2.268309e-001, + 1.028696e+000, + 6.797371e-001, + // albedo 1, turbidity 1 + -1.345260e+000, + -5.085528e-001, + -6.052009e+000, + 6.604590e+000, + -4.300752e-002, + 4.745234e-001, + 6.591457e-003, + 2.595142e+000, + 5.013653e-001, + -1.573525e+000, + -7.133524e-001, + -1.671346e+000, + 2.693205e+000, + -7.828763e-002, + 2.915699e-001, + 1.795879e-002, + 1.469445e+000, + 4.927472e-001, + -1.013665e+000, + -1.731419e-001, + 2.043423e+000, + -2.919634e+000, + -1.020807e-001, + 5.467619e-001, + -4.041481e-002, + 5.853992e+000, + 5.272064e-001, + -1.173191e+000, + -3.964683e-001, + 1.097258e+000, + 1.509973e+000, + -5.675641e-001, + 9.815927e-001, + 6.962319e-002, + -3.358210e+000, + 4.263117e-001, + -1.003507e+000, + -1.124908e-001, + 1.030642e+000, + -5.357088e-001, + 6.114201e-001, + 1.628414e-001, + -5.701497e-002, + 4.541126e+000, + 8.084996e-001, + -1.071959e+000, + -1.567262e-001, + 9.923029e-001, + 1.457160e-001, + -4.742907e+000, + 7.280970e-001, + 6.770360e-002, + 3.919300e+000, + 4.999529e-001, + // albedo 1, turbidity 2 + -1.399982e+000, + -5.538549e-001, + -6.983148e+000, + 7.513966e+000, + -3.358417e-002, + 3.667027e-001, + 1.158837e-002, + 2.499680e+000, + 5.598537e-001, + -1.602839e+000, + -7.835806e-001, + 1.200264e+000, + -1.454290e-001, + -7.431927e-002, + 5.374263e-001, + 9.505505e-004, + 1.096167e+000, + 2.185838e-001, + -9.587294e-001, + -6.134134e-002, + 2.234030e-001, + -8.115395e-001, + -2.344054e-001, + 2.018782e-001, + -4.192332e-002, + 6.331499e+000, + 1.353587e+000, + -1.166832e+000, + -4.057833e-001, + 1.461335e+000, + 3.165401e-001, + -3.245858e-001, + 1.199323e+000, + 1.100274e-001, + -2.727373e+000, + 5.329788e-002, + -1.023178e+000, + -1.351631e-001, + 9.944251e-001, + 2.103341e-002, + -2.460318e+000, + 5.136074e-003, + -5.267951e-002, + 4.097235e+000, + 9.388837e-001, + -1.071426e+000, + -1.726491e-001, + 1.048949e+000, + -2.624840e-003, + -4.993124e+000, + 6.621513e-001, + 7.801931e-002, + 3.227750e+000, + 5.363265e-001, + // albedo 1, turbidity 3 + -1.362723e+000, + -5.257224e-001, + -1.325130e+001, + 1.374641e+001, + -1.971887e-002, + 4.480379e-001, + -9.588735e-007, + 2.679516e+000, + 5.628531e-001, + -1.824466e+000, + -9.877790e-001, + 4.631069e+000, + -3.630521e+000, + -4.340325e-002, + 3.913450e-001, + 3.415899e-002, + 4.746800e-001, + 2.022772e-001, + -6.435267e-001, + 1.629762e-001, + -1.452097e+000, + 8.028761e-001, + -9.611017e-002, + 4.267105e-001, + -1.023573e-001, + 6.652106e+000, + 1.406057e+000, + -1.400277e+000, + -5.150235e-001, + 1.752017e+000, + -1.699743e-001, + -3.411643e-001, + 8.465596e-001, + 2.127075e-001, + -2.235971e+000, + 4.728189e-002, + -9.044866e-001, + -7.979493e-002, + 8.298122e-001, + -5.604698e-002, + -1.433761e+000, + 1.011757e-001, + -7.175544e-002, + 4.243075e+000, + 9.588179e-001, + -1.115618e+000, + -2.148000e-001, + 1.109081e+000, + 2.661209e-001, + -5.008111e+000, + 6.333048e-001, + 9.274718e-002, + 2.494529e+000, + 5.890657e-001, + // albedo 1, turbidity 4 + -1.389611e+000, + -5.579886e-001, + -1.045229e+001, + 1.092342e+001, + -2.282772e-002, + 4.054079e-001, + 2.781558e-003, + 2.578484e+000, + 5.372706e-001, + -1.893851e+000, + -1.116122e+000, + 2.111553e+000, + -8.775468e-001, + -5.640158e-002, + 5.399894e-001, + 1.929352e-002, + -5.585557e-002, + 2.870402e-001, + -7.015617e-001, + 1.884526e-001, + -1.660273e-001, + -8.785899e-001, + -5.471987e-002, + 1.787856e-001, + -9.958870e-002, + 7.207213e+000, + 1.277933e+000, + -1.279075e+000, + -4.794032e-001, + 9.037342e-001, + 6.225399e-001, + -6.592270e-001, + 9.474313e-001, + 2.524811e-001, + -2.485658e+000, + 2.050401e-001, + -9.744212e-001, + -9.899254e-002, + 9.474600e-001, + -2.536639e-001, + 5.390432e-001, + -8.465488e-002, + -3.140532e-002, + 4.512343e+000, + 8.530654e-001, + -1.093264e+000, + -2.115594e-001, + 9.876876e-001, + 7.531309e-002, + -5.003648e+000, + 6.719560e-001, + 1.111699e-001, + 2.412349e+000, + 6.482966e-001, + // albedo 1, turbidity 5 + -1.410458e+000, + -5.905263e-001, + -4.146328e+001, + 4.190254e+001, + -5.607421e-003, + 4.437719e-001, + -1.948391e-006, + 2.496743e+000, + 5.031933e-001, + -1.817258e+000, + -9.848495e-001, + 1.089217e+001, + -1.028029e+001, + -1.221684e-002, + 3.317008e-001, + 5.060062e-002, + 1.198443e+000, + 4.449482e-001, + -8.920534e-001, + -8.835804e-002, + -2.111594e+000, + 2.083599e+000, + -1.507800e-002, + 6.993567e-001, + -1.987686e-001, + 4.793539e+000, + 1.072586e+000, + -1.048633e+000, + -1.110825e-001, + 5.438710e-001, + -6.707296e-001, + -1.825365e-001, + 2.307221e-001, + 4.056218e-001, + 1.886912e+000, + 3.579576e-001, + -1.094223e+000, + -3.084727e-001, + 9.739595e-001, + 3.972140e-001, + 1.511647e-001, + 2.788218e-001, + -6.279180e-002, + 1.866444e+000, + 7.995203e-001, + -1.078162e+000, + -2.176197e-001, + 1.088756e+000, + 4.329413e-001, + -3.209490e+000, + 8.364785e-001, + 7.689785e-002, + 1.943182e+000, + 7.150615e-001, + // albedo 1, turbidity 6 + -1.455846e+000, + -6.322333e-001, + -1.618289e+001, + 1.656258e+001, + -1.280603e-002, + 4.130359e-001, + -9.061644e-007, + 2.461391e+000, + 5.315915e-001, + -2.222251e+000, + -1.233356e+000, + -1.454954e+000, + 1.957432e+000, + -1.730555e-002, + 2.418496e-001, + 7.240262e-002, + 1.061939e+000, + 3.148474e-001, + -4.536196e-001, + 1.457295e-001, + 2.483934e+000, + -2.244550e+000, + -4.593767e-002, + 8.967621e-001, + -2.712877e-001, + 4.732142e+000, + 1.188839e+000, + -1.277343e+000, + -2.046024e-001, + -1.229720e+000, + 3.977256e-001, + -2.209195e-001, + 6.033235e-002, + 5.267707e-001, + 2.536445e+000, + 2.759606e-001, + -1.029833e+000, + -2.979843e-001, + 8.742883e-001, + 1.037710e+000, + 1.350257e-001, + 4.066094e-001, + -1.376375e-001, + 1.500753e+000, + 8.676699e-001, + -1.095935e+000, + -2.211775e-001, + 9.320585e-001, + 8.955212e-002, + -1.113388e+000, + 7.909911e-001, + 1.393848e-001, + 2.057146e+000, + 6.699739e-001, + // albedo 1, turbidity 7 + -1.571831e+000, + -7.466353e-001, + -1.226063e+001, + 1.265995e+001, + -1.514083e-002, + 3.639653e-001, + -2.504287e-006, + 2.204454e+000, + 5.468861e-001, + -2.235398e+000, + -1.371434e+000, + 1.787996e+000, + -1.073965e+000, + -2.503530e-002, + 2.143584e-001, + 7.703453e-002, + 5.207181e-001, + 2.714312e-001, + -6.944677e-001, + -7.243136e-002, + -6.193104e-001, + 9.567440e-001, + -6.317194e-002, + 8.881508e-001, + -2.783301e-001, + 4.224532e+000, + 1.192802e+000, + -1.133391e+000, + -9.811942e-002, + 2.312721e-001, + -1.100585e+000, + -3.655097e-001, + 2.268787e-003, + 5.074358e-001, + 1.512457e+000, + 3.165593e-001, + -1.057051e+000, + -3.424797e-001, + 9.536822e-001, + 1.034064e+000, + 6.413292e-001, + 1.165363e-001, + -4.248128e-002, + 1.592803e+000, + 7.875911e-001, + -1.096695e+000, + -2.745143e-001, + 1.077920e+000, + -8.435082e-004, + -3.715956e+000, + 5.197900e-001, + 1.171467e-001, + 1.236912e+000, + 6.915287e-001, + // albedo 1, turbidity 8 + -1.711623e+000, + -9.023881e-001, + -9.799257e+000, + 1.022040e+001, + -1.708447e-002, + 3.309925e-001, + -3.241111e-006, + 1.932295e+000, + 5.844205e-001, + -2.351937e+000, + -1.340391e+000, + 6.329976e+000, + -6.054139e+000, + -2.843868e-002, + 2.298301e-001, + 7.698142e-002, + 1.109800e+000, + 1.863187e-001, + -1.141314e+000, + -6.670322e-001, + -3.262632e+000, + 4.551521e+000, + -8.614941e-002, + 8.058038e-001, + -2.791051e-001, + 3.084281e+000, + 1.236638e+000, + -7.950557e-001, + 2.489854e-001, + 9.966347e-001, + -3.391737e+000, + -7.235716e-001, + -2.155609e-001, + 5.126659e-001, + 1.452322e+000, + 2.882812e-001, + -1.182289e+000, + -5.192524e-001, + 9.672941e-001, + 3.091448e+000, + -4.193043e+000, + 4.051469e-001, + -5.708309e-002, + 9.386723e-001, + 8.208828e-001, + -1.080579e+000, + -2.918654e-001, + 9.499317e-001, + 2.856082e+000, + -2.256007e+000, + 1.377750e-002, + 1.012914e-001, + 9.716489e-001, + 6.832750e-001, + // albedo 1, turbidity 9 + -1.964781e+000, + -1.162652e+000, + -6.074737e+000, + 6.497797e+000, + -2.595660e-002, + 3.222936e-001, + -3.220871e-006, + 1.685891e+000, + 6.501551e-001, + -2.352213e+000, + -1.199539e+000, + 4.248376e+000, + -3.876965e+000, + -6.837923e-002, + 1.764412e-001, + 5.514810e-002, + 1.442736e+000, + 6.979575e-002, + -2.560247e+000, + -1.883591e+000, + -1.916723e+000, + 2.598994e+000, + -2.372381e-002, + 8.442578e-001, + -2.063113e-001, + 2.359942e+000, + 1.287838e+000, + 7.281064e-002, + 7.835433e-001, + 1.380748e-001, + -2.065580e+000, + -1.696648e+000, + -4.575316e-001, + 3.840004e-001, + 9.397056e-001, + 3.103904e-001, + -1.444446e+000, + -7.662151e-001, + 1.364103e+000, + 4.930232e+000, + -4.455564e+000, + 6.735458e-001, + -4.052978e-003, + 3.194173e-001, + 7.842959e-001, + -1.039666e+000, + -3.171617e-001, + 7.295920e-001, + 2.813846e+000, + -1.561230e+000, + -4.128303e-001, + 1.004149e-001, + 6.653613e-001, + 6.980277e-001, + // albedo 1, turbidity 10 + -2.999915e+000, + -1.721740e+000, + -4.796494e+000, + 5.021888e+000, + -2.163250e-002, + 3.309183e-001, + -4.051804e-006, + 1.645464e+000, + 7.145890e-001, + -1.673162e+000, + -1.056666e+000, + 3.209766e+000, + -2.559187e+000, + -7.456364e-002, + 6.215063e-002, + 4.469425e-002, + 1.242757e+000, + -1.580590e-002, + -5.775475e+000, + -3.239700e+000, + -1.356432e+000, + 1.099950e+000, + -9.497509e-002, + 7.121875e-001, + -1.656838e-001, + 2.553396e+000, + 1.286227e+000, + 1.241869e+000, + 6.671222e-001, + -4.156007e-001, + -8.167921e-001, + -1.037816e+000, + 5.950065e-002, + 3.114868e-001, + 6.414114e-001, + 3.677503e-001, + -1.580126e+000, + -7.852349e-001, + 1.749569e+000, + 5.987990e+000, + -5.075133e+000, + -4.693815e-002, + -5.106759e-002, + -9.755925e-001, + 7.440092e-001, + -9.732917e-001, + -1.939297e-001, + 2.709367e-001, + 1.352990e+000, + -9.040352e-001, + 5.181217e-003, + 2.302437e-001, + 1.506500e+000, + 6.840186e-001, +}; + +double datasetRad440[] = +{ + // albedo 0, turbidity 1 + 9.406889e-003, + 1.954373e-002, + -4.018205e-002, + 1.740051e-001, + 1.351020e-001, + 1.365376e-001, + // albedo 0, turbidity 2 + 9.206049e-003, + 2.042313e-002, + -4.377380e-002, + 1.787089e-001, + 1.388614e-001, + 1.384128e-001, + // albedo 0, turbidity 3 + 9.050889e-003, + 2.086396e-002, + -4.652916e-002, + 1.794829e-001, + 1.524222e-001, + 1.376563e-001, + // albedo 0, turbidity 4 + 8.656343e-003, + 2.210653e-002, + -5.212791e-002, + 1.836315e-001, + 1.663040e-001, + 1.419649e-001, + // albedo 0, turbidity 5 + 8.355466e-003, + 2.244975e-002, + -5.393078e-002, + 1.788056e-001, + 1.868417e-001, + 1.445069e-001, + // albedo 0, turbidity 6 + 8.187585e-003, + 2.235434e-002, + -5.291187e-002, + 1.693688e-001, + 2.073941e-001, + 1.424517e-001, + // albedo 0, turbidity 7 + 7.909229e-003, + 2.199365e-002, + -5.165975e-002, + 1.577725e-001, + 2.297489e-001, + 1.468516e-001, + // albedo 0, turbidity 8 + 7.580566e-003, + 2.048421e-002, + -4.471863e-002, + 1.277026e-001, + 2.737620e-001, + 1.497600e-001, + // albedo 0, turbidity 9 + 7.101943e-003, + 1.675094e-002, + -2.761544e-002, + 7.078506e-002, + 3.397147e-001, + 1.557184e-001, + // albedo 0, turbidity 10 + 6.525444e-003, + 1.090411e-002, + -1.995302e-003, + -8.176097e-003, + 4.124321e-001, + 1.714881e-001, + // albedo 1, turbidity 1 + 1.111702e-002, + 1.783998e-002, + -1.949635e-002, + 1.124970e-001, + 2.993330e-001, + 2.864943e-001, + // albedo 1, turbidity 2 + 1.099681e-002, + 1.809609e-002, + -2.099087e-002, + 1.131858e-001, + 3.057413e-001, + 2.866962e-001, + // albedo 1, turbidity 3 + 1.070017e-002, + 1.818573e-002, + -2.159895e-002, + 1.084494e-001, + 3.229180e-001, + 2.835407e-001, + // albedo 1, turbidity 4 + 1.032234e-002, + 1.871074e-002, + -2.469404e-002, + 1.069731e-001, + 3.380450e-001, + 2.864479e-001, + // albedo 1, turbidity 5 + 9.893912e-003, + 1.844953e-002, + -2.358500e-002, + 9.439551e-002, + 3.642566e-001, + 2.829554e-001, + // albedo 1, turbidity 6 + 9.650400e-003, + 1.877062e-002, + -2.542361e-002, + 9.189004e-002, + 3.720610e-001, + 2.856265e-001, + // albedo 1, turbidity 7 + 9.322628e-003, + 1.810055e-002, + -2.246559e-002, + 7.543314e-002, + 3.958251e-001, + 2.842134e-001, + // albedo 1, turbidity 8 + 8.842659e-003, + 1.604245e-002, + -1.397353e-002, + 4.233011e-002, + 4.358270e-001, + 2.789888e-001, + // albedo 1, turbidity 9 + 8.169168e-003, + 1.265551e-002, + 4.076399e-004, + -7.877623e-003, + 4.830048e-001, + 2.768485e-001, + // albedo 1, turbidity 10 + 7.383449e-003, + 7.340131e-003, + 2.094279e-002, + -7.138907e-002, + 5.217098e-001, + 2.803810e-001, +}; + +double dataset480[] = +{ + // albedo 0, turbidity 1 + -1.255072e+000, + -3.501170e-001, + -5.952795e+000, + 6.529723e+000, + -6.362962e-002, + 6.436422e-001, + 7.745270e-003, + 3.657426e+000, + 5.329375e-001, + -1.344988e+000, + -4.365880e-001, + -1.750961e+000, + 2.262943e+000, + -1.049983e-001, + 3.754288e-001, + 5.298712e-002, + 3.402851e+000, + 3.874229e-001, + -1.073402e+000, + -1.395260e-001, + 2.839003e+000, + -2.827315e+000, + -1.882090e-001, + 1.054349e+000, + -8.976330e-002, + 5.604794e+000, + 6.740510e-001, + -1.183711e+000, + -4.011868e-001, + 7.358740e-001, + 1.479436e+000, + -7.268596e-001, + 1.133998e+000, + 1.205942e-001, + -4.232970e+000, + 1.060586e+000, + -1.018668e+000, + -8.561816e-002, + 1.030241e+000, + -4.461392e-001, + 3.940284e-001, + 1.220382e+000, + -1.391238e-001, + 5.771847e+000, + 5.627180e-001, + -1.080081e+000, + -1.746769e-001, + 1.174843e+000, + 9.389450e-002, + -4.893194e+000, + 1.162505e+000, + 1.563406e-001, + 2.606800e+000, + 4.999990e-001, + // albedo 0, turbidity 2 + -1.268430e+000, + -3.752425e-001, + -8.504068e+000, + 9.021017e+000, + -4.092613e-002, + 6.553965e-001, + 8.607147e-003, + 3.444138e+000, + 5.600385e-001, + -1.459780e+000, + -5.882818e-001, + 1.800729e+000, + -9.674514e-001, + -8.308819e-002, + 4.453337e-001, + 4.086836e-002, + 1.853978e+000, + 2.818975e-001, + -8.680288e-001, + 1.148721e-001, + 3.161508e-001, + -1.524870e+000, + -1.921031e-001, + 6.496299e-001, + 4.422347e-004, + 8.241268e+000, + 9.821338e-001, + -1.277439e+000, + -4.550135e-001, + 1.088681e+000, + 1.552370e+000, + -6.184442e-001, + 1.386667e+000, + 1.035135e-001, + -3.331179e+000, + 5.236122e-001, + -9.964896e-001, + -9.832891e-002, + 9.746026e-001, + -9.125638e-001, + -7.457170e-001, + 9.111352e-001, + -7.027011e-002, + 4.669829e+000, + 7.455938e-001, + -1.083449e+000, + -1.686372e-001, + 1.003727e+000, + 4.085513e-001, + -4.725304e+000, + 1.112591e+000, + 1.855240e-001, + 3.038195e+000, + 5.969305e-001, + // albedo 0, turbidity 3 + -1.290677e+000, + -3.901158e-001, + -9.520695e+000, + 9.828711e+000, + -3.154131e-002, + 5.939314e-001, + 2.686840e-002, + 3.612397e+000, + 5.140176e-001, + -1.535002e+000, + -6.667464e-001, + 2.735758e-002, + 9.423936e-001, + -8.287240e-002, + 6.775029e-001, + 4.575744e-003, + 1.432097e+000, + 3.872415e-001, + -7.903104e-001, + 1.563438e-001, + -2.022567e-001, + -1.026670e+000, + 9.063977e-003, + 3.942033e-001, + -1.241980e-002, + 7.980026e+000, + 1.066191e+000, + -1.278947e+000, + -3.694875e-001, + 8.111792e-001, + 4.993027e-001, + -1.096772e+000, + 1.008837e+000, + 2.920972e-001, + -7.314209e-001, + 3.179440e-001, + -1.006667e+000, + -1.519095e-001, + 8.774664e-001, + -1.909283e-001, + 3.756189e+000, + 9.311862e-001, + -9.327427e-002, + 3.499747e+000, + 8.574583e-001, + -1.086931e+000, + -1.774734e-001, + 8.989024e-001, + 5.536469e-002, + -3.474034e+000, + 9.736834e-001, + 2.325787e-001, + 2.809427e+000, + 6.246481e-001, + // albedo 0, turbidity 4 + -1.346571e+000, + -4.451276e-001, + -2.373159e+001, + 2.408962e+001, + -1.225268e-002, + 5.720568e-001, + 1.636363e-002, + 3.288957e+000, + 5.104502e-001, + -1.607315e+000, + -7.416360e-001, + -5.233286e-001, + 1.169215e+000, + -2.350907e-002, + 4.942922e-001, + 3.544231e-002, + 1.659598e+000, + 3.959771e-001, + -8.259129e-001, + 9.305732e-002, + 4.864320e+000, + -5.585537e+000, + -4.428624e-002, + 7.540493e-001, + -1.060506e-001, + 6.548781e+000, + 1.138009e+000, + -1.204471e+000, + -2.620580e-001, + -2.637261e+000, + 3.057335e+000, + -1.226916e-001, + 5.657925e-001, + 4.446409e-001, + 1.136957e+000, + 2.881385e-001, + -1.035718e+000, + -2.116415e-001, + 1.288642e+000, + -3.834162e-001, + -9.488050e-002, + 7.404996e-001, + -6.538922e-002, + 2.336877e+000, + 8.612030e-001, + -1.087946e+000, + -1.841898e-001, + 4.491757e-001, + 1.691479e-001, + 1.022577e-001, + 9.202996e-001, + 2.926112e-001, + 2.844475e+000, + 6.452620e-001, + // albedo 0, turbidity 5 + -1.381782e+000, + -4.914069e-001, + -4.813999e+001, + 4.837634e+001, + -5.296025e-003, + 5.571609e-001, + 1.649034e-002, + 3.203385e+000, + 5.048069e-001, + -1.776157e+000, + -9.226583e-001, + 1.389662e+001, + -1.292490e+001, + -1.480095e-002, + 5.073308e-001, + 4.585849e-002, + 7.385206e-001, + 4.280887e-001, + -8.381948e-001, + 1.229315e-001, + -3.370527e+000, + 1.825510e+000, + -9.728251e-003, + 8.572929e-001, + -1.855299e-001, + 7.471741e+000, + 1.133190e+000, + -1.125194e+000, + -2.647028e-001, + 6.942391e-001, + 1.389102e+000, + -2.216447e-001, + 1.356485e-001, + 5.812792e-001, + -5.073865e-001, + 2.675490e-001, + -1.095144e+000, + -2.442208e-001, + 4.787687e-001, + -2.707940e+000, + 6.129627e-001, + 7.213058e-001, + -6.034254e-002, + 2.798703e+000, + 8.787214e-001, + -1.062019e+000, + -1.765309e-001, + 5.423897e-001, + 3.783099e+000, + -5.007038e+000, + 7.376299e-001, + 3.034085e-001, + 2.733411e+000, + 6.555070e-001, + // albedo 0, turbidity 6 + -1.390263e+000, + -5.185474e-001, + -1.630741e+001, + 1.654109e+001, + -1.499201e-002, + 5.661787e-001, + 1.452544e-002, + 3.046179e+000, + 5.026700e-001, + -1.935801e+000, + -9.953289e-001, + -1.483271e+000, + 1.913745e+000, + -2.518160e-002, + 4.593343e-001, + 4.285617e-002, + 1.448437e+000, + 4.509310e-001, + -7.547378e-001, + 2.590987e-002, + 2.480507e+000, + -2.271835e+000, + -5.259620e-002, + 9.001709e-001, + -2.024986e-001, + 4.958191e+000, + 1.036940e+000, + -1.157324e+000, + -1.198742e-001, + -1.440574e+000, + 3.070751e-001, + -1.807577e-001, + 4.059237e-002, + 6.210184e-001, + 2.425946e+000, + 3.828327e-001, + -1.065566e+000, + -3.139616e-001, + 5.715306e-001, + 8.053761e-001, + 1.396364e-001, + 4.009778e-001, + 5.681033e-003, + 1.354013e+000, + 7.861375e-001, + -1.095972e+000, + -2.178745e-001, + 4.681537e-001, + 1.235458e-001, + -1.084613e+000, + 1.006455e+000, + 2.754677e-001, + 2.239616e+000, + 6.954839e-001, + // albedo 0, turbidity 7 + -1.453150e+000, + -5.790574e-001, + -1.243832e+001, + 1.263425e+001, + -1.892784e-002, + 4.979177e-001, + 1.035899e-002, + 2.982682e+000, + 5.056256e-001, + -1.925518e+000, + -1.010928e+000, + 1.513827e+000, + -9.219873e-001, + -3.776925e-002, + 4.692652e-001, + 4.083023e-002, + 1.303495e+000, + 4.245150e-001, + -1.134311e+000, + -2.754710e-001, + -2.443212e-001, + 3.845396e-002, + -1.074645e-001, + 1.066657e+000, + -2.324557e-001, + 4.996897e+000, + 1.052268e+000, + -8.094396e-001, + 1.096826e-001, + -5.117072e-001, + -1.915992e-001, + -1.991693e-001, + -5.943341e-001, + 6.791986e-001, + 1.332014e+000, + 3.606306e-001, + -1.227889e+000, + -4.522793e-001, + 5.338266e-002, + 1.074118e+000, + 8.733709e-002, + 1.005448e+000, + -1.725176e-002, + 1.326110e+000, + 8.063751e-001, + -1.065450e+000, + -2.160134e-001, + 3.413994e-001, + 4.950303e-001, + -1.077199e+000, + 3.654185e-001, + 3.125819e-001, + 1.998536e+000, + 6.865917e-001, + // albedo 0, turbidity 8 + -1.594869e+000, + -7.366760e-001, + -1.252117e+001, + 1.275030e+001, + -1.697659e-002, + 4.892543e-001, + 2.831848e-003, + 2.542039e+000, + 5.457358e-001, + -1.980952e+000, + -9.910920e-001, + 6.178699e+000, + -5.888582e+000, + -3.099336e-002, + 3.859266e-001, + 4.511764e-002, + 1.839601e+000, + 2.791527e-001, + -1.766081e+000, + -8.995150e-001, + -2.712687e+000, + 3.263201e+000, + -1.840688e-001, + 1.305410e+000, + -2.675879e-001, + 3.647246e+000, + 1.168203e+000, + -3.742071e-001, + 4.678023e-001, + 6.371403e-002, + -2.016941e+000, + -2.723239e-001, + -1.446876e+000, + 7.533604e-001, + 1.131760e+000, + 2.537537e-001, + -1.380378e+000, + -6.406403e-001, + 7.018678e-001, + 2.032023e+000, + -2.393487e+000, + 1.930827e+000, + -1.260608e-001, + 7.634327e-001, + 8.870918e-001, + -1.088465e+000, + -2.971190e-001, + 1.411657e-001, + 1.879601e+000, + -1.310304e+000, + -7.045740e-001, + 3.313185e-001, + 1.264266e+000, + 6.534482e-001, + // albedo 0, turbidity 9 + -2.229949e+000, + -1.153733e+000, + -7.505783e+000, + 7.718722e+000, + -2.407129e-002, + 4.175820e-001, + 4.559186e-005, + 2.157318e+000, + 6.337774e-001, + -1.995509e+000, + -8.778717e-001, + 4.191031e+000, + -3.968507e+000, + -5.176872e-002, + 1.960357e-001, + 3.755797e-002, + 1.975436e+000, + 1.077053e-001, + -3.174785e+000, + -2.105130e+000, + -2.062230e+000, + 2.391786e+000, + -4.217147e-002, + 9.727297e-001, + -1.540078e-001, + 2.691773e+000, + 1.235189e+000, + 4.882832e-001, + 1.097365e+000, + -1.866214e-001, + -1.567231e+000, + -1.216396e+000, + -4.391280e-001, + 4.541998e-001, + 1.167636e+000, + 3.003642e-001, + -1.709118e+000, + -9.374505e-001, + 6.559000e-001, + 3.977860e+000, + -3.525762e+000, + 6.202828e-001, + 7.863257e-002, + 6.882512e-001, + 8.161696e-001, + -9.999977e-001, + -2.777886e-001, + 9.586687e-003, + 1.766813e+000, + -1.065121e+000, + -1.325963e-001, + 2.512239e-001, + 1.055043e+000, + 6.874661e-001, + // albedo 0, turbidity 10 + -2.932652e+000, + -1.609416e+000, + -3.825171e+000, + 3.969752e+000, + -3.638195e-002, + 3.557402e-001, + -4.379735e-006, + 1.927804e+000, + 7.278380e-001, + -1.591732e+000, + -7.579896e-001, + 1.711976e+000, + -1.369988e+000, + -1.107557e-001, + 1.237841e-001, + 1.548121e-002, + 2.024749e+000, + -4.315379e-002, + -6.085760e+000, + -3.429651e+000, + -6.780006e-001, + -1.902709e-002, + 6.566034e-002, + 8.329946e-001, + -1.012845e-001, + 2.617589e+000, + 1.342663e+000, + 1.335204e+000, + 1.035931e+000, + -1.008915e+000, + 5.915758e-001, + -1.907371e+000, + -3.568938e-002, + 3.295382e-001, + 6.546480e-001, + 2.435447e-001, + -1.800155e+000, + -1.010684e+000, + 1.160290e+000, + 5.269190e+000, + -3.895543e+000, + 5.274946e-002, + 3.971324e-002, + 8.769492e-002, + 8.252336e-001, + -9.843476e-001, + -3.014031e-001, + -3.167912e-001, + 1.384556e+000, + -6.881572e-001, + 5.617519e-002, + 2.805263e-001, + 9.930291e-001, + 6.783964e-001, + // albedo 1, turbidity 1 + -1.257325e+000, + -3.441598e-001, + -5.951667e+000, + 6.530618e+000, + -5.773033e-002, + 6.437990e-001, + 8.453838e-003, + 3.657343e+000, + 5.329715e-001, + -1.346061e+000, + -4.331978e-001, + -1.749638e+000, + 2.263845e+000, + -1.013807e-001, + 3.755084e-001, + 5.287214e-002, + 3.402954e+000, + 3.874047e-001, + -1.073983e+000, + -1.372222e-001, + 2.840388e+000, + -2.826616e+000, + -1.866609e-001, + 1.054193e+000, + -8.989038e-002, + 5.604984e+000, + 6.739811e-001, + -1.184707e+000, + -3.992543e-001, + 7.374377e-001, + 1.479838e+000, + -7.263903e-001, + 1.133619e+000, + 1.199206e-001, + -4.232702e+000, + 1.060412e+000, + -1.021623e+000, + -8.422241e-002, + 1.032293e+000, + -4.460168e-001, + 3.941239e-001, + 1.219939e+000, + -1.420884e-001, + 5.772239e+000, + 5.623142e-001, + -1.087791e+000, + -1.754873e-001, + 1.178006e+000, + 9.386850e-002, + -4.893184e+000, + 1.162164e+000, + 1.535543e-001, + 2.607460e+000, + 4.997706e-001, + // albedo 1, turbidity 2 + -1.251295e+000, + -3.651612e-001, + -9.950987e+000, + 1.058444e+001, + -3.065334e-002, + 5.979560e-001, + 1.817303e-002, + 3.132460e+000, + 5.458738e-001, + -1.374134e+000, + -5.079738e-001, + 2.333109e+000, + -1.251359e+000, + -7.802080e-002, + 3.182768e-001, + 3.746599e-002, + 1.963940e+000, + 2.733180e-001, + -9.862389e-001, + -2.441831e-002, + 2.657376e-001, + -1.054016e+000, + -8.576871e-002, + 7.356127e-001, + -4.711349e-002, + 6.677884e+000, + 1.206629e+000, + -1.140461e+000, + -3.212487e-001, + 1.547332e+000, + 9.031281e-001, + -8.421239e-001, + 1.166595e+000, + 1.643076e-001, + -2.534096e+000, + 1.884034e-001, + -1.049493e+000, + -1.256523e-001, + 1.205849e+000, + -3.649526e-001, + 8.075413e-001, + 3.421308e-001, + -1.173508e-001, + 4.535809e+000, + 9.497555e-001, + -1.063961e+000, + -1.336751e-001, + 1.173271e+000, + 1.016777e-001, + -4.093576e+000, + 4.559998e-001, + 1.519017e-001, + 4.153208e+000, + 5.324846e-001, + // albedo 1, turbidity 3 + -1.271751e+000, + -3.837936e-001, + -1.052025e+001, + 1.102826e+001, + -2.411879e-002, + 5.019991e-001, + 3.094786e-002, + 3.138107e+000, + 5.059631e-001, + -1.472034e+000, + -6.259760e-001, + -5.356154e-001, + 1.713500e+000, + -6.089970e-002, + 4.750716e-001, + 6.622428e-003, + 1.224931e+000, + 4.198087e-001, + -8.587401e-001, + 1.099859e-001, + 3.258521e-001, + -1.301658e+000, + -4.452458e-002, + 6.461336e-001, + -2.947489e-002, + 7.603712e+000, + 1.091511e+000, + -1.221875e+000, + -3.659269e-001, + 9.953072e-001, + 8.481237e-001, + -5.952235e-001, + 1.016442e+000, + 2.259940e-001, + -1.925411e+000, + 3.654292e-001, + -1.008105e+000, + -1.136472e-001, + 1.248935e+000, + -3.865165e-001, + 1.714619e+000, + -1.216223e-001, + -2.436842e-002, + 4.227455e+000, + 7.030495e-001, + -1.082262e+000, + -1.513279e-001, + 1.052383e+000, + 2.125686e-001, + -5.028093e-001, + 8.694047e-001, + 1.099128e-001, + 3.634467e+000, + 7.206727e-001, + // albedo 1, turbidity 4 + -1.310438e+000, + -4.332417e-001, + -2.812457e+001, + 2.859054e+001, + -7.241887e-003, + 4.123186e-001, + 2.839263e-002, + 2.866138e+000, + 5.063521e-001, + -1.598864e+000, + -7.787419e-001, + 4.189377e+000, + -3.122921e+000, + -1.896105e-002, + 6.071985e-001, + 1.999660e-002, + 7.039076e-001, + 4.125456e-001, + -7.834866e-001, + 1.890740e-001, + 1.102853e+000, + -1.842558e+000, + -3.985000e-002, + 6.423282e-001, + -1.131231e-001, + 7.222493e+000, + 1.177285e+000, + -1.244910e+000, + -3.668018e-001, + -2.083168e-001, + 1.051092e+000, + -1.483362e-001, + 4.066210e-001, + 4.623360e-001, + -1.971682e-001, + 2.178890e-001, + -1.010078e+000, + -1.593623e-001, + 1.747411e+000, + -6.961852e-002, + -1.503091e-001, + 5.439839e-001, + -1.874287e-001, + 2.074758e+000, + 9.133302e-001, + -1.086611e+000, + -1.529597e-001, + 4.548984e-001, + 2.836062e-001, + 4.168066e-001, + 3.953841e-001, + 2.451427e-001, + 3.799065e+000, + 6.288711e-001, + // albedo 1, turbidity 5 + -1.338369e+000, + -4.683873e-001, + -3.858110e+001, + 3.898823e+001, + -5.111812e-003, + 4.638476e-001, + 2.389163e-002, + 2.774207e+000, + 5.242274e-001, + -1.785780e+000, + -9.773633e-001, + 6.470331e+000, + -5.147348e+000, + -1.593592e-002, + 4.175720e-001, + 2.497956e-002, + 7.090702e-002, + 3.252744e-001, + -6.972735e-001, + 2.786524e-001, + 4.011350e-003, + -1.686706e+000, + -4.966516e-003, + 8.368703e-001, + -1.225606e-001, + 7.731542e+000, + 1.267577e+000, + -1.307129e+000, + -4.728119e-001, + 2.639424e-002, + 2.633155e+000, + -2.357439e-001, + 1.263362e-001, + 4.765765e-001, + -2.025027e+000, + 1.705113e-001, + -9.583414e-001, + -7.928834e-002, + 1.447497e+000, + -2.797571e+000, + 8.553597e-001, + 4.842942e-001, + -7.727878e-002, + 3.765006e+000, + 9.191738e-001, + -1.114040e+000, + -2.132678e-001, + 1.030931e+000, + 2.871507e+000, + -5.013319e+000, + 2.699945e-001, + 1.819978e-001, + 2.239642e+000, + 6.539653e-001, + // albedo 1, turbidity 6 + -1.393024e+000, + -5.200008e-001, + -1.941271e+001, + 1.986171e+001, + -1.212818e-002, + 5.019138e-001, + 7.897163e-003, + 2.696459e+000, + 5.258316e-001, + -1.831466e+000, + -1.018106e+000, + 3.204932e+000, + -2.139369e+000, + -2.441969e-002, + 3.191029e-001, + 5.563321e-002, + 1.320760e-001, + 3.265220e-001, + -7.994553e-001, + 1.337239e-001, + -1.563712e+000, + 7.392042e-001, + -3.136373e-002, + 1.008208e+000, + -1.988762e-001, + 6.626579e+000, + 1.223213e+000, + -1.159543e+000, + -2.836180e-001, + 1.057464e+000, + -3.647533e-001, + -2.513115e-001, + -1.995636e-001, + 5.943224e-001, + -4.865436e-001, + 2.279895e-001, + -1.044528e+000, + -2.152538e-001, + 1.023157e+000, + 5.599579e-002, + 6.321805e-001, + 5.155639e-001, + -1.111252e-001, + 2.282270e+000, + 8.647371e-001, + -1.092518e+000, + -1.865821e-001, + 1.057856e+000, + 3.491427e-001, + -2.631526e+000, + 3.584288e-001, + 2.191649e-001, + 2.389704e+000, + 6.765946e-001, + // albedo 1, turbidity 7 + -1.384989e+000, + -5.305700e-001, + -1.459855e+001, + 1.497673e+001, + -1.471976e-002, + 4.569028e-001, + 5.419006e-003, + 2.735360e+000, + 5.389891e-001, + -2.086660e+000, + -1.234696e+000, + 2.053196e+000, + -1.257012e+000, + -2.129117e-002, + 1.990309e-001, + 8.511032e-002, + -1.312659e-001, + 2.800139e-001, + -7.309069e-001, + 1.413931e-001, + -1.773938e-001, + 2.938820e-001, + -4.933601e-002, + 1.496853e+000, + -3.213358e-001, + 6.305852e+000, + 1.298086e+000, + -1.203529e+000, + -3.216432e-001, + -1.458970e-001, + -5.598789e-001, + -2.934068e-001, + -1.206192e+000, + 7.793654e-001, + -9.223710e-001, + 1.229360e-001, + -1.002538e+000, + -1.984480e-001, + 1.233954e+000, + 8.779171e-001, + 3.133737e-001, + 1.311239e+000, + -2.132532e-001, + 2.223702e+000, + 9.461065e-001, + -1.123572e+000, + -2.342682e-001, + 9.679089e-001, + -1.017991e-003, + -1.960819e+000, + -1.153680e-001, + 2.843114e-001, + 1.779831e+000, + 6.400916e-001, + // albedo 1, turbidity 8 + -1.537393e+000, + -6.924151e-001, + -1.239252e+001, + 1.285585e+001, + -1.666284e-002, + 4.429862e-001, + 2.398230e-003, + 2.210714e+000, + 5.509453e-001, + -1.817841e+000, + -9.662082e-001, + 6.281905e+000, + -5.778709e+000, + -3.131226e-002, + 3.074609e-001, + 4.530074e-002, + 1.409838e+000, + 2.538213e-001, + -1.790530e+000, + -8.332867e-001, + -2.605975e+000, + 3.383959e+000, + -1.685493e-001, + 1.307568e+000, + -2.569465e-001, + 3.272862e+000, + 1.247743e+000, + -3.808658e-001, + 3.525732e-001, + 3.897535e-001, + -2.085715e+000, + -1.845614e-001, + -1.470598e+000, + 7.033938e-001, + 8.475130e-001, + 1.758974e-001, + -1.374360e+000, + -5.517879e-001, + 1.276626e+000, + 1.821209e+000, + -2.480880e+000, + 1.866494e+000, + -1.649246e-001, + 6.333864e-001, + 9.339444e-001, + -1.024167e+000, + -2.097189e-001, + 8.424991e-001, + 1.767689e+000, + -1.312031e+000, + -8.191386e-001, + 2.156968e-001, + 1.201032e+000, + 6.593457e-001, + // albedo 1, turbidity 9 + -2.190652e+000, + -1.106580e+000, + -7.466636e+000, + 7.752518e+000, + -2.263662e-002, + 4.154878e-001, + -1.646586e-006, + 2.076563e+000, + 6.322611e-001, + -1.972368e+000, + -8.108244e-001, + 4.233742e+000, + -3.927321e+000, + -5.152609e-002, + 2.005285e-001, + 2.985984e-002, + 1.903602e+000, + 1.099985e-001, + -3.148093e+000, + -2.033135e+000, + -2.019650e+000, + 2.409779e+000, + -1.255187e-002, + 9.697956e-001, + -1.538080e-001, + 2.617071e+000, + 1.234755e+000, + 5.592882e-001, + 1.073057e+000, + -2.763735e-002, + -1.563728e+000, + -1.191791e+000, + -4.331798e-001, + 4.622361e-001, + 1.142664e+000, + 2.988891e-001, + -1.706427e+000, + -8.516236e-001, + 1.014996e+000, + 3.980336e+000, + -3.487485e+000, + 6.331985e-001, + -1.818380e-002, + 7.352340e-001, + 8.452629e-001, + -1.006197e+000, + -1.932306e-001, + 5.337019e-001, + 1.797637e+000, + -9.474717e-001, + -1.353274e-001, + 2.049954e-001, + 1.156100e+000, + 6.894153e-001, + // albedo 1, turbidity 10 + -2.473813e+000, + -1.478132e+000, + -3.492210e+000, + 3.805303e+000, + -3.251673e-002, + 3.621052e-001, + -6.447770e-006, + 1.596383e+000, + 8.551930e-001, + -1.494464e+000, + -7.635918e-001, + 2.071212e+000, + -1.536108e+000, + -1.369345e-001, + 1.287259e-001, + 2.147844e-002, + 1.753080e+000, + -2.246103e-001, + -6.305007e+000, + -3.323156e+000, + -7.099379e-001, + 1.686111e-001, + 1.080881e-001, + 8.729732e-001, + -1.291207e-001, + 2.282989e+000, + 1.475588e+000, + 1.325532e+000, + 5.765517e-001, + -7.011257e-001, + 7.720216e-001, + -2.013560e+000, + -1.990572e-001, + 3.922685e-001, + 9.898769e-003, + 1.789360e-001, + -1.590406e+000, + -7.529646e-001, + 1.930414e+000, + 5.169169e+000, + -4.221403e+000, + 4.614858e-002, + -9.527005e-002, + -7.894472e-001, + 8.458063e-001, + -1.005785e+000, + -2.286223e-001, + 3.330253e-001, + 1.438452e+000, + -7.701349e-001, + 2.780764e-002, + 2.630698e-001, + 8.329894e-001, + 6.747408e-001, +}; + +double datasetRad480[] = +{ + // albedo 0, turbidity 1 + 1.367487e-002, + 1.998477e-002, + -2.747378e-002, + 2.012913e-001, + 1.065803e-001, + 1.249226e-001, + // albedo 0, turbidity 2 + 1.319623e-002, + 2.233282e-002, + -3.838862e-002, + 2.216885e-001, + 1.032539e-001, + 1.308019e-001, + // albedo 0, turbidity 3 + 1.265118e-002, + 2.391819e-002, + -4.721677e-002, + 2.352182e-001, + 1.174476e-001, + 1.303906e-001, + // albedo 0, turbidity 4 + 1.204726e-002, + 2.745130e-002, + -6.437791e-002, + 2.605947e-001, + 1.298129e-001, + 1.378516e-001, + // albedo 0, turbidity 5 + 1.125691e-002, + 3.031033e-002, + -7.856070e-002, + 2.797308e-001, + 1.411425e-001, + 1.486601e-001, + // albedo 0, turbidity 6 + 1.087451e-002, + 3.134174e-002, + -8.308676e-002, + 2.793109e-001, + 1.610134e-001, + 1.502290e-001, + // albedo 0, turbidity 7 + 1.035757e-002, + 3.176437e-002, + -8.486370e-002, + 2.674373e-001, + 1.974534e-001, + 1.533206e-001, + // albedo 0, turbidity 8 + 9.649434e-003, + 3.087937e-002, + -8.067259e-002, + 2.353243e-001, + 2.553337e-001, + 1.608814e-001, + // albedo 0, turbidity 9 + 8.869346e-003, + 2.627497e-002, + -5.891488e-002, + 1.570602e-001, + 3.504762e-001, + 1.724148e-001, + // albedo 0, turbidity 10 + 8.105360e-003, + 1.756907e-002, + -2.001928e-002, + 3.536541e-002, + 4.692392e-001, + 1.926373e-001, + // albedo 1, turbidity 1 + 1.531497e-002, + 2.090118e-002, + -1.665041e-002, + 1.626765e-001, + 2.602854e-001, + 2.739350e-001, + // albedo 1, turbidity 2 + 1.500055e-002, + 2.258405e-002, + -2.517423e-002, + 1.780058e-001, + 2.604774e-001, + 2.803331e-001, + // albedo 1, turbidity 3 + 1.435727e-002, + 2.473634e-002, + -3.651251e-002, + 1.966627e-001, + 2.645889e-001, + 2.894029e-001, + // albedo 1, turbidity 4 + 1.368791e-002, + 2.602874e-002, + -4.462666e-002, + 2.008996e-001, + 2.978971e-001, + 2.872899e-001, + // albedo 1, turbidity 5 + 1.298035e-002, + 2.709110e-002, + -5.084570e-002, + 2.010066e-001, + 3.257828e-001, + 2.917322e-001, + // albedo 1, turbidity 6 + 1.267531e-002, + 2.752851e-002, + -5.364450e-002, + 1.962715e-001, + 3.472458e-001, + 2.928354e-001, + // albedo 1, turbidity 7 + 1.200196e-002, + 2.782022e-002, + -5.449978e-002, + 1.818445e-001, + 3.795420e-001, + 2.974612e-001, + // albedo 1, turbidity 8 + 1.115769e-002, + 2.603247e-002, + -4.606362e-002, + 1.383509e-001, + 4.427481e-001, + 2.969281e-001, + // albedo 1, turbidity 9 + 1.034375e-002, + 2.111036e-002, + -2.502615e-002, + 6.215948e-002, + 5.253192e-001, + 2.999927e-001, + // albedo 1, turbidity 10 + 9.270257e-003, + 1.252950e-002, + 1.085115e-002, + -5.004679e-002, + 6.169243e-001, + 3.053035e-001, +}; + +double dataset520[] = +{ + // albedo 0, turbidity 1 + -1.171338e+000, + -2.379456e-001, + -6.515446e+000, + 7.133235e+000, + -5.382867e-002, + 6.889982e-001, + 4.250983e-002, + 4.471437e+000, + 5.087463e-001, + -1.193029e+000, + -2.445141e-001, + -4.311723e-001, + 1.019354e+000, + -1.281643e-001, + 7.837279e-001, + 2.609613e-002, + 5.965800e+000, + 4.381607e-001, + -1.165299e+000, + -2.503239e-001, + 3.829843e+000, + -2.234083e+000, + -4.693988e-001, + 1.045109e+000, + -6.241707e-002, + 2.623310e-001, + 7.500398e-001, + -1.077288e+000, + -2.659342e-001, + -7.565678e-002, + 1.145086e+000, + -2.316655e-002, + 1.564941e+000, + 9.375322e-002, + -7.476929e-001, + 6.076913e-001, + -1.075530e+000, + -1.232648e-001, + 1.877081e+000, + -1.186427e-001, + -2.748628e+000, + 1.249377e+000, + -1.085780e-001, + 3.838331e+000, + 8.601227e-001, + -1.067002e+000, + -1.572453e-001, + 1.350156e+000, + 3.140948e-003, + -3.277283e+000, + 1.488404e+000, + 1.127058e-001, + 2.655730e+000, + 4.999138e-001, + // albedo 0, turbidity 2 + -1.175145e+000, + -2.454528e-001, + -8.173280e+000, + 8.622722e+000, + -3.895019e-002, + 6.739096e-001, + 6.622835e-002, + 4.450872e+000, + 5.061382e-001, + -1.226543e+000, + -2.979950e-001, + 3.102814e+000, + -2.662701e+000, + -1.012309e-001, + 5.142095e-001, + 4.939276e-002, + 5.007851e+000, + 4.179865e-001, + -1.075743e+000, + -1.267529e-001, + 1.017884e-001, + 4.839556e-001, + -4.025119e-001, + 1.120466e+000, + -5.059103e-002, + 3.601070e+000, + 1.104232e+000, + -1.104008e+000, + -2.079352e-001, + 1.094572e+000, + 1.147058e+000, + -1.516726e-001, + 1.526097e+000, + 1.922554e-001, + 4.060614e-001, + 2.975787e-001, + -1.080135e+000, + -1.942481e-001, + 1.409056e+000, + -3.800384e+000, + -7.125701e+000, + 9.731220e-001, + -7.312793e-002, + 2.377810e+000, + 9.223131e-001, + -1.066280e+000, + -1.421591e-001, + 1.272936e+000, + 7.891881e+000, + -3.626975e+000, + 1.294678e+000, + 1.331475e-001, + 2.986127e+000, + 5.316962e-001, + // albedo 0, turbidity 3 + -1.210057e+000, + -2.827640e-001, + -5.179186e+000, + 5.514430e+000, + -5.638504e-002, + 6.656727e-001, + 5.417868e-002, + 4.216550e+000, + 5.495231e-001, + -1.311087e+000, + -3.921139e-001, + 1.436554e+000, + -7.051260e-001, + -1.462714e-001, + 2.604620e-001, + 5.771570e-002, + 3.493766e+000, + 5.041164e-001, + -9.705912e-001, + -4.316197e-002, + 5.357225e-001, + -1.399982e+000, + -3.407923e-001, + 1.585242e+000, + -6.423039e-002, + 5.338193e+000, + 9.835385e-001, + -1.177697e+000, + -1.893604e-001, + -5.207247e-002, + 4.572666e+000, + -5.523178e-001, + 2.677765e-001, + 3.872768e-001, + 1.978123e+000, + 4.095974e-001, + -1.029420e+000, + -2.105096e-001, + 1.657176e+000, + -1.028655e+001, + -7.725428e+000, + 1.707122e+000, + -7.681108e-002, + 1.074660e+000, + 8.312794e-001, + -1.082084e+000, + -1.321893e-001, + 8.487219e-001, + 1.858290e+001, + -3.172656e+000, + 6.915801e-001, + 1.905927e-001, + 3.901473e+000, + 6.144141e-001, + // albedo 0, turbidity 4 + -1.259854e+000, + -3.329630e-001, + -2.270176e+000, + 2.357599e+000, + -9.019414e-002, + 5.779792e-001, + 7.706039e-002, + 3.971905e+000, + 4.999172e-001, + -1.413220e+000, + -5.430979e-001, + -1.715627e-001, + 1.151561e+000, + -2.318489e-001, + 2.791441e-001, + 1.306646e-002, + 1.794583e+000, + 6.167457e-001, + -9.926840e-001, + 2.303697e-002, + 7.306051e-001, + -2.124879e+000, + -2.221853e-001, + 1.635982e+000, + -8.684297e-002, + 7.621636e+000, + 9.443863e-001, + -1.113409e+000, + -2.409045e-001, + -1.979662e-001, + 5.089736e+000, + -2.071840e+000, + -6.954891e-001, + 5.966469e-001, + -1.346819e+000, + 3.752080e-001, + -1.055595e+000, + -1.703680e-001, + 1.089771e+000, + -1.041463e+001, + -4.687545e+000, + 2.149733e+000, + -1.118987e-001, + 3.558810e+000, + 8.741214e-001, + -1.070779e+000, + -1.445161e-001, + 6.385947e-001, + 1.695445e+001, + -3.724275e+000, + -3.465499e-002, + 3.645376e-001, + 3.232410e+000, + 6.285788e-001, + // albedo 0, turbidity 5 + -1.297812e+000, + -3.805039e-001, + -1.474455e+000, + 1.558382e+000, + -1.292485e-001, + 5.206238e-001, + 7.166147e-002, + 3.651150e+000, + 4.998781e-001, + -1.680599e+000, + -8.036751e-001, + 8.267015e-001, + -2.109200e-001, + -4.326451e-001, + 3.843930e-001, + 5.207142e-002, + 6.938520e-001, + 4.752346e-001, + -8.467684e-001, + 1.620743e-001, + -5.520307e-001, + 8.293798e-001, + 8.728132e-001, + 9.075147e-001, + -1.734859e-001, + 7.815672e+000, + 1.126843e+000, + -1.182658e+000, + -3.290773e-001, + 1.442907e-001, + -1.705529e+000, + -1.186174e+001, + -1.903040e-001, + 7.826049e-001, + -1.497409e+000, + 2.238945e-001, + -1.032316e+000, + -1.590425e-001, + 9.289968e-001, + 1.217091e+001, + 1.274690e+000, + 1.400296e+000, + -3.047612e-001, + 2.805729e+000, + 9.198989e-001, + -1.073060e+000, + -1.623303e-001, + 3.798836e-001, + 2.223272e+000, + -4.660805e+000, + -1.172357e-001, + 5.306455e-001, + 3.105520e+000, + 6.420864e-001, + // albedo 0, turbidity 6 + -1.374072e+000, + -4.453408e-001, + -1.081601e+000, + 1.104314e+000, + -1.730612e-001, + 5.074812e-001, + 5.784588e-002, + 3.488150e+000, + 5.037112e-001, + -1.704606e+000, + -8.629255e-001, + -3.905040e-001, + 2.152742e+000, + -6.716606e-001, + 5.638527e-001, + -5.967161e-003, + 4.886292e-001, + 4.385432e-001, + -9.651511e-001, + 1.186522e-001, + 3.421397e-001, + -4.626814e+000, + 9.716770e-001, + 7.579588e-001, + -1.064476e-002, + 8.154392e+000, + 1.103676e+000, + -1.067172e+000, + -3.214506e-001, + -3.934660e-001, + 9.254630e+000, + -3.599603e+000, + -1.624031e-001, + 5.478446e-001, + -2.781628e+000, + 2.905848e-001, + -1.063218e+000, + -1.412572e-001, + 8.153795e-001, + -1.467486e+001, + -2.020170e+000, + 1.094685e+000, + 7.786265e-002, + 3.719129e+000, + 8.826899e-001, + -1.070058e+000, + -1.684172e-001, + 2.225147e-001, + 2.345795e+001, + -4.342429e+000, + -4.661816e-002, + 3.545794e-001, + 3.051769e+000, + 6.567686e-001, + // albedo 0, turbidity 7 + -1.397244e+000, + -4.874379e-001, + -2.217129e+000, + 2.415780e+000, + -1.039290e-001, + 5.444596e-001, + 2.296795e-002, + 3.242776e+000, + 5.575920e-001, + -1.943117e+000, + -1.042293e+000, + 1.936194e+000, + -7.807718e-001, + -4.753317e-001, + 6.351817e-001, + 3.357824e-002, + 3.221570e-001, + 2.277390e-001, + -1.007469e+000, + 4.283560e-002, + -1.830583e+000, + -1.613949e-001, + 5.103059e-001, + 1.830881e-001, + -6.111472e-002, + 7.698471e+000, + 1.322151e+000, + -9.885823e-001, + -2.796329e-001, + 9.017585e-001, + 9.500529e-001, + -8.751757e+000, + 5.198673e-001, + 6.111910e-001, + -3.165369e+000, + 1.193651e-001, + -1.105054e+000, + -1.835801e-001, + 2.099263e-001, + 3.626436e+000, + 4.241807e-001, + 2.861915e-002, + -3.245808e-002, + 3.560209e+000, + 9.581069e-001, + -1.061783e+000, + -1.955111e-001, + 3.405765e-001, + 1.682185e+001, + -4.868111e+000, + 3.591669e-001, + 3.518670e-001, + 2.163473e+000, + 6.425305e-001, + // albedo 0, turbidity 8 + -1.452178e+000, + -5.662818e-001, + -1.492883e+000, + 1.742373e+000, + -1.894966e-001, + 6.129524e-001, + 2.370115e-006, + 3.042560e+000, + 7.988979e-001, + -2.146318e+000, + -1.176122e+000, + 1.480664e+000, + 1.846814e-001, + -9.003192e-001, + 2.819986e-001, + -6.858291e-003, + 5.447940e-001, + -2.109028e-001, + -1.465359e+000, + -3.055025e-001, + -1.747423e+000, + -2.538335e+000, + 6.082904e-001, + 6.523133e-001, + 1.426957e-001, + 6.921276e+000, + 1.637843e+000, + -7.135462e-001, + -2.351046e-001, + 1.111445e+000, + 2.259275e+000, + -7.853810e+000, + -3.006083e-001, + 3.100486e-001, + -4.047366e+000, + -3.732308e-002, + -1.188030e+000, + -2.177467e-001, + 8.022451e-002, + 8.746107e+000, + -6.824017e-001, + 5.968181e-001, + 7.024883e-002, + 3.164998e+000, + 9.909158e-001, + -1.038065e+000, + -1.989059e-001, + 1.630845e-001, + 1.261969e+001, + -4.006594e+000, + -3.213161e-001, + 3.948313e-001, + 2.040063e+000, + 6.364874e-001, + // albedo 0, turbidity 9 + -1.789980e+000, + -8.450140e-001, + -2.591234e+000, + 2.769295e+000, + -8.338896e-002, + 5.620741e-001, + -8.271253e-006, + 2.531602e+000, + 9.001159e-001, + -1.468080e+000, + -7.426812e-001, + 2.369441e+000, + -1.635443e+000, + -3.560365e-001, + 2.130482e-001, + -2.124886e-003, + 1.863478e+000, + -3.426455e-001, + -3.911974e+000, + -1.873182e+000, + -2.428294e+000, + 1.019786e+000, + 2.178584e-001, + 9.599962e-001, + 3.763471e-002, + 4.121844e+000, + 1.708236e+000, + 5.986629e-001, + 4.160930e-001, + 1.499968e+000, + -4.234635e+000, + -7.153272e+000, + -8.777277e-001, + 4.276508e-001, + -2.268730e+000, + -9.278595e-002, + -1.581111e+000, + -5.414559e-001, + 3.449756e-002, + 2.095624e+001, + -1.717086e+000, + 6.913385e-001, + -1.227380e-001, + 1.401315e+000, + 9.723511e-001, + -9.931334e-001, + -2.191364e-001, + 1.647201e-001, + 2.954460e+000, + -2.889774e+000, + -4.261816e-001, + 4.166838e-001, + 1.370273e+000, + 6.561021e-001, + // albedo 0, turbidity 10 + -2.368520e+000, + -1.245557e+000, + -3.473878e+000, + 3.511922e+000, + -4.076311e-002, + 4.228576e-001, + -8.136079e-006, + 2.268992e+000, + 9.001266e-001, + -1.498984e+000, + -9.483364e-001, + 2.970418e+000, + -2.003511e+000, + -3.005171e-001, + 3.242320e-001, + 6.724107e-003, + 1.693927e+000, + -2.648941e-001, + -6.258071e+000, + -2.616781e+000, + -3.186408e+000, + -3.570416e-002, + 5.972101e-001, + 5.638927e-001, + -8.227073e-002, + 3.805214e+000, + 1.486701e+000, + 7.183470e-001, + -1.332710e-001, + 1.495243e+000, + 3.859652e+000, + -5.605361e+000, + 3.808435e-001, + 4.998100e-001, + -1.207866e+000, + 1.082917e-001, + -1.422091e+000, + -5.984032e-001, + 2.297508e-001, + 1.726780e+000, + -6.684454e-001, + -1.024912e+000, + -1.967199e-001, + -3.214571e-001, + 8.922300e-001, + -1.018798e+000, + -2.003211e-001, + 5.344788e-002, + 1.474717e+001, + -4.025558e+000, + 9.010150e-001, + 3.605184e-001, + 1.504726e+000, + 6.720300e-001, + // albedo 1, turbidity 1 + -1.150179e+000, + -2.233430e-001, + -6.725138e+000, + 7.601675e+000, + -6.176639e-002, + 7.963802e-001, + 2.476816e-002, + 4.311811e+000, + 5.070506e-001, + -1.184017e+000, + -2.330060e-001, + 1.903877e-001, + 4.425206e-001, + -1.173330e-001, + 2.459899e-001, + 6.799957e-002, + 5.710763e+000, + 4.639162e-001, + -1.129855e+000, + -2.313999e-001, + 3.299978e+000, + -1.861830e+000, + -3.626476e-001, + 1.858194e+000, + -9.845844e-002, + 6.523143e-001, + 6.278178e-001, + -1.090030e+000, + -2.445577e-001, + 4.546659e-001, + 9.848860e-001, + -4.044981e-001, + 3.532740e-001, + 1.409977e-001, + -7.724273e-001, + 2.901711e-001, + -1.048192e+000, + -1.048720e-001, + 2.079951e+000, + -7.519850e-002, + -1.451911e+000, + 1.354243e+000, + -1.508252e-001, + 4.159135e+000, + 8.685415e-001, + -1.081709e+000, + -1.496534e-001, + 1.433416e+000, + -8.415186e-005, + -3.147387e+000, + 6.964893e-002, + 1.345400e-001, + 3.372381e+000, + 5.369835e-001, + // albedo 1, turbidity 2 + -1.163329e+000, + -2.341078e-001, + -8.084459e+000, + 8.765664e+000, + -4.227908e-002, + 6.476384e-001, + 5.575993e-002, + 4.291594e+000, + 5.023286e-001, + -1.234281e+000, + -3.038288e-001, + 3.304120e+000, + -2.565467e+000, + -1.080261e-001, + 5.183037e-001, + 2.633070e-002, + 4.459108e+000, + 4.526356e-001, + -1.015235e+000, + -1.003890e-001, + 2.834337e-001, + 4.230399e-001, + -4.060874e-001, + 1.119918e+000, + -2.357803e-002, + 3.215664e+000, + 1.089777e+000, + -1.171497e+000, + -2.465867e-001, + 1.219344e+000, + 1.184120e+000, + -6.451707e-002, + 1.087554e+000, + 1.687897e-001, + 4.111776e-001, + 2.471485e-001, + -1.010262e+000, + -1.337460e-001, + 1.953577e+000, + -3.761183e+000, + -7.089300e+000, + 5.963565e-001, + -8.297304e-002, + 2.741114e+000, + 9.771003e-001, + -1.102719e+000, + -1.647974e-001, + 1.510508e+000, + 7.573412e+000, + -3.431528e+000, + 3.953995e-001, + 6.793657e-002, + 2.744717e+000, + 5.018037e-001, + // albedo 1, turbidity 3 + -1.186728e+000, + -2.648685e-001, + -7.540497e+000, + 8.152868e+000, + -4.363040e-002, + 6.836829e-001, + 3.221451e-002, + 4.013046e+000, + 6.004295e-001, + -1.302626e+000, + -3.904258e-001, + 3.431819e+000, + -2.975541e+000, + -7.666020e-002, + 2.464561e-002, + 1.054528e-001, + 3.161765e+000, + 3.544185e-001, + -9.615438e-001, + -4.842098e-002, + -4.756207e-001, + 9.408081e-001, + -3.108222e-001, + 1.708814e+000, + -1.241215e-001, + 4.416567e+000, + 1.207369e+000, + -1.178731e+000, + -1.824314e-001, + 8.266664e-001, + 1.001614e+000, + 3.024332e-001, + 3.291998e-002, + 4.178949e-001, + 2.532397e+000, + 2.014902e-001, + -1.018913e+000, + -2.016682e-001, + 2.132865e+000, + -3.323938e+000, + -8.751654e+000, + 1.240780e+000, + -1.801214e-001, + 6.145479e-001, + 9.457932e-001, + -1.101603e+000, + -1.521834e-001, + 1.348807e+000, + 5.640453e+000, + -2.695953e+000, + -7.496627e-002, + 1.719606e-001, + 3.175091e+000, + 5.968939e-001, + // albedo 1, turbidity 4 + -1.229694e+000, + -3.167126e-001, + -3.548352e+000, + 3.846155e+000, + -5.028022e-002, + 5.061677e-001, + 7.498335e-002, + 3.626295e+000, + 4.999424e-001, + -1.436439e+000, + -5.562909e-001, + 8.010070e-001, + 3.290243e-001, + -1.385772e-001, + 4.556269e-002, + 2.571935e-002, + 1.623385e+000, + 5.222220e-001, + -8.876360e-001, + 5.717281e-002, + 4.713905e-001, + -1.668970e+000, + -3.199243e-001, + 2.050582e+000, + -7.783980e-002, + 6.117601e+000, + 1.070445e+000, + -1.235363e+000, + -2.778190e-001, + 1.577638e-001, + 3.982457e+000, + -2.266885e-002, + -1.411004e+000, + 5.570462e-001, + 1.740426e-001, + 2.747952e-001, + -9.785264e-001, + -1.458813e-001, + 1.996989e+000, + -7.517409e+000, + -6.602487e+000, + 2.387711e+000, + -1.996484e-001, + 2.112759e+000, + 9.289256e-001, + -1.117781e+000, + -1.699302e-001, + 1.214480e+000, + 1.141083e+001, + -3.253445e+000, + -8.156284e-001, + 2.248021e-001, + 2.860500e+000, + 6.151694e-001, + // albedo 1, turbidity 5 + -1.290523e+000, + -3.813116e-001, + -6.728796e-001, + 1.007366e+000, + -2.068030e-001, + 4.422499e-001, + 6.016254e-002, + 3.218056e+000, + 5.068822e-001, + -1.614452e+000, + -7.953309e-001, + 5.977485e-001, + 1.056365e+000, + -8.402403e-001, + 3.713919e-001, + 3.164720e-002, + -2.526630e-001, + 4.072481e-001, + -8.377211e-001, + 2.276878e-001, + -3.232539e-001, + -2.390300e+000, + 2.127070e+000, + 7.169058e-001, + -4.032313e-002, + 9.072383e+000, + 1.188019e+000, + -1.226600e+000, + -4.426177e-001, + 6.370202e-001, + 3.846913e+000, + -1.128719e+001, + 3.667721e-002, + 5.000027e-001, + -4.192432e+000, + 2.376054e-001, + -9.852235e-001, + -5.890324e-002, + 1.529937e+000, + 4.301220e+000, + -1.839775e+000, + 8.993504e-001, + -1.040866e-001, + 4.636528e+000, + 8.466710e-001, + -1.118112e+000, + -2.040213e-001, + 1.203227e+000, + 7.252102e+000, + -4.515955e+000, + -2.398231e-001, + 2.375855e-001, + 1.923160e+000, + 6.645269e-001, + // albedo 1, turbidity 6 + -1.330626e+000, + -4.272516e-001, + -1.317682e+000, + 1.650847e+000, + -1.192771e-001, + 4.904191e-001, + 4.074827e-002, + 3.015846e+000, + 5.271835e-001, + -1.711989e+000, + -8.644776e-001, + 4.057135e-001, + 9.037139e-001, + -3.100084e-001, + 6.317697e-002, + 1.065625e-001, + 9.226240e-002, + 3.022474e-001, + -8.465894e-001, + 1.652715e-001, + -2.532361e-001, + -2.422693e+000, + 3.144841e-001, + 1.839347e+000, + -2.818162e-001, + 7.856667e+000, + 1.387977e+000, + -1.192114e+000, + -3.830569e-001, + 5.124751e-001, + 7.280034e+000, + -2.610477e+000, + -1.832768e+000, + 9.101904e-001, + -3.349116e+000, + -7.313079e-002, + -1.011026e+000, + -1.061217e-001, + 1.357854e+000, + -1.496195e+001, + -2.180975e+000, + 2.484329e+000, + -3.239225e-001, + 3.899425e+000, + 1.179264e+000, + -1.106228e+000, + -1.927917e-001, + 1.179701e+000, + 2.379834e+001, + -4.870211e+000, + -1.290713e+000, + 2.854422e-001, + 2.078973e+000, + 5.128625e-001, + // albedo 1, turbidity 7 + -1.342815e+000, + -4.571984e-001, + -1.803521e+000, + 2.229578e+000, + -1.196587e-001, + 5.694038e-001, + 1.194687e-002, + 2.950110e+000, + 5.961719e-001, + -1.937297e+000, + -1.078823e+000, + 2.178495e+000, + -1.251900e+000, + -3.577875e-001, + 2.553915e-001, + 8.081142e-002, + -4.723152e-001, + 1.174551e-001, + -9.292675e-001, + 1.125551e-001, + -1.708569e+000, + 1.832840e+000, + 5.150525e-001, + 9.287322e-001, + -1.746780e-001, + 7.793815e+000, + 1.498832e+000, + -1.058850e+000, + -3.495292e-001, + 1.135259e+000, + -4.069374e+000, + -9.727412e+000, + -7.670653e-001, + 7.550431e-001, + -4.105064e+000, + -5.149354e-002, + -1.079472e+000, + -1.399984e-001, + 1.058148e+000, + 1.392667e+001, + -6.245343e-001, + 1.192083e+000, + -2.578858e-001, + 4.030723e+000, + 1.025069e+000, + -1.093159e+000, + -2.150433e-001, + 1.210946e+000, + 3.349246e+000, + -4.030345e+000, + -5.362971e-001, + 2.886842e-001, + 1.192375e+000, + 6.363049e-001, + // albedo 1, turbidity 8 + -1.408172e+000, + -5.491538e-001, + -1.360219e+000, + 1.738150e+000, + -1.505117e-001, + 6.030014e-001, + -6.866289e-006, + 2.656101e+000, + 9.001849e-001, + -2.171702e+000, + -1.231851e+000, + 1.860400e+000, + 3.613146e-002, + -7.300078e-001, + 1.974371e-001, + -5.351202e-003, + -1.443434e-001, + -3.779605e-001, + -1.284657e+000, + -1.935945e-001, + -1.494185e+000, + -2.070689e+000, + 2.974020e-001, + 8.048383e-001, + 1.097715e-001, + 6.907960e+000, + 1.819367e+000, + -8.288598e-001, + -3.374917e-001, + 1.029011e+000, + 1.347088e+000, + -7.655126e+000, + -8.232335e-001, + 3.722934e-001, + -4.847675e+000, + -1.864913e-001, + -1.146031e+000, + -1.480097e-001, + 1.051391e+000, + 8.396865e+000, + -1.407010e+000, + 1.240651e+000, + -3.942068e-002, + 3.291458e+000, + 1.060212e+000, + -1.069599e+000, + -2.047532e-001, + 9.437765e-001, + 1.189879e+001, + -4.026750e+000, + -9.372092e-001, + 2.463501e-001, + 1.782902e+000, + 6.235027e-001, + // albedo 1, turbidity 9 + -1.793508e+000, + -8.986075e-001, + -2.346395e+000, + 2.775625e+000, + -7.052213e-002, + 5.349215e-001, + -7.457456e-006, + 1.901248e+000, + 9.001358e-001, + -1.629402e+000, + -8.273410e-001, + 2.270930e+000, + -1.125114e+000, + -3.562854e-001, + 1.948044e-001, + 1.703882e-003, + 1.426305e+000, + -3.737234e-001, + -3.443431e+000, + -1.686429e+000, + -1.515036e+000, + -6.941862e-001, + 4.976814e-001, + 1.144483e+000, + -4.277285e-002, + 3.662107e+000, + 1.819972e+000, + 3.138150e-001, + 2.426714e-001, + 7.717995e-001, + 2.759520e+000, + -7.216077e+000, + -1.389093e+000, + 5.332838e-001, + -2.316313e+000, + -2.636593e-001, + -1.449802e+000, + -4.017798e-001, + 1.133688e+000, + 2.114337e+000, + 6.227965e-002, + 1.378688e+000, + -1.759313e-001, + 9.446579e-001, + 1.165017e+000, + -1.049420e+000, + -2.614006e-001, + 9.473363e-001, + 1.531288e+001, + -4.714989e+000, + -8.992715e-001, + 2.423509e-001, + 9.148027e-001, + 5.650972e-001, + // albedo 1, turbidity 10 + -2.382332e+000, + -1.290760e+000, + -3.316114e+000, + 3.587059e+000, + -3.748522e-002, + 4.468493e-001, + -7.212198e-006, + 1.789208e+000, + 9.001267e-001, + -1.333339e+000, + -9.355999e-001, + 3.281313e+000, + -2.263103e+000, + -2.499164e-001, + 1.591742e-001, + 8.117981e-003, + 1.345396e+000, + -2.689053e-001, + -6.612658e+000, + -2.809230e+000, + -2.744061e+000, + 1.005261e+000, + 4.216309e-001, + 1.055067e+000, + -9.021558e-002, + 2.940833e+000, + 1.495270e+000, + 1.251113e+000, + 5.915517e-002, + 1.142846e+000, + -2.807371e-001, + -5.335452e+000, + -6.967012e-001, + 5.129558e-001, + -5.264483e-001, + 1.137786e-001, + -1.517768e+000, + -5.807447e-001, + 1.179477e+000, + 1.252252e+001, + -2.305973e+000, + 2.184822e-001, + -3.092917e-001, + -1.524373e+000, + 8.724218e-001, + -1.037889e+000, + -2.065780e-001, + 6.479897e-001, + 4.786848e-002, + -2.348244e+000, + -3.053490e-002, + 4.059549e-001, + 1.313102e+000, + 6.713422e-001, +}; + +double datasetRad520[] = +{ + // albedo 0, turbidity 1 + 1.459826e-002, + 1.539451e-002, + -1.848659e-003, + 1.563602e-001, + 6.773320e-002, + 9.272923e-002, + // albedo 0, turbidity 2 + 1.433599e-002, + 1.641988e-002, + -1.010719e-002, + 1.752844e-001, + 7.101618e-002, + 9.423920e-002, + // albedo 0, turbidity 3 + 1.361165e-002, + 2.045058e-002, + -3.003054e-002, + 2.142268e-001, + 6.624853e-002, + 1.021088e-001, + // albedo 0, turbidity 4 + 1.263245e-002, + 2.450953e-002, + -5.278634e-002, + 2.554090e-001, + 7.442617e-002, + 1.093243e-001, + // albedo 0, turbidity 5 + 1.161553e-002, + 2.837614e-002, + -7.218472e-002, + 2.860706e-001, + 8.559036e-002, + 1.183292e-001, + // albedo 0, turbidity 6 + 1.106384e-002, + 3.079241e-002, + -8.377247e-002, + 3.007502e-001, + 9.584072e-002, + 1.242989e-001, + // albedo 0, turbidity 7 + 1.036501e-002, + 3.253539e-002, + -9.274680e-002, + 3.036297e-001, + 1.249370e-001, + 1.307019e-001, + // albedo 0, turbidity 8 + 9.469294e-003, + 3.287197e-002, + -9.329500e-002, + 2.773078e-001, + 1.866053e-001, + 1.366498e-001, + // albedo 0, turbidity 9 + 8.599754e-003, + 2.901873e-002, + -7.532574e-002, + 2.032418e-001, + 2.837623e-001, + 1.499765e-001, + // albedo 0, turbidity 10 + 7.760808e-003, + 1.977285e-002, + -3.328752e-002, + 7.084295e-002, + 4.155148e-001, + 1.708600e-001, + // albedo 1, turbidity 1 + 1.597952e-002, + 1.790201e-002, + -1.839686e-003, + 1.470389e-001, + 1.698205e-001, + 2.119268e-001, + // albedo 1, turbidity 2 + 1.553599e-002, + 1.969270e-002, + -1.173079e-002, + 1.677871e-001, + 1.714108e-001, + 2.173300e-001, + // albedo 1, turbidity 3 + 1.489601e-002, + 2.206336e-002, + -2.576017e-002, + 1.949160e-001, + 1.781909e-001, + 2.236776e-001, + // albedo 1, turbidity 4 + 1.384558e-002, + 2.528945e-002, + -4.419483e-002, + 2.249469e-001, + 1.968802e-001, + 2.312108e-001, + // albedo 1, turbidity 5 + 1.299228e-002, + 2.767429e-002, + -5.793193e-002, + 2.409692e-001, + 2.215448e-001, + 2.384850e-001, + // albedo 1, turbidity 6 + 1.245635e-002, + 2.874175e-002, + -6.384005e-002, + 2.429023e-001, + 2.428387e-001, + 2.418906e-001, + // albedo 1, turbidity 7 + 1.170787e-002, + 3.001101e-002, + -6.977107e-002, + 2.368382e-001, + 2.775809e-001, + 2.482129e-001, + // albedo 1, turbidity 8 + 1.081211e-002, + 2.854760e-002, + -6.360294e-002, + 1.948047e-001, + 3.501631e-001, + 2.490269e-001, + // albedo 1, turbidity 9 + 9.903541e-003, + 2.416012e-002, + -4.342521e-002, + 1.140965e-001, + 4.468771e-001, + 2.561579e-001, + // albedo 1, turbidity 10 + 8.793464e-003, + 1.518177e-002, + -4.699154e-003, + -9.107614e-003, + 5.554550e-001, + 2.692918e-001, +}; + +double dataset560[] = +{ + // albedo 0, turbidity 1 + -1.121223e+000, + -1.710187e-001, + -1.383038e+001, + 1.475343e+001, + -3.137953e-002, + 1.035662e+000, + 4.060064e-002, + 5.222551e+000, + 5.001051e-001, + -1.172565e+000, + -1.880874e-001, + 7.283594e+000, + -5.774643e+000, + -9.051333e-002, + 9.108126e-001, + -1.565410e-002, + 6.194404e+000, + 4.688599e-001, + -1.124108e+000, + -3.082835e-001, + -2.179926e-001, + 1.330167e+000, + -4.502254e-001, + 1.470140e+000, + 4.202392e-004, + -4.724308e+000, + 1.134678e+000, + -1.079809e+000, + -9.226814e-002, + 1.465364e+000, + 1.348856e+000, + 4.357794e-001, + 1.771543e+000, + 8.121383e-003, + 6.057395e+000, + 2.462141e-001, + -1.086667e+000, + -2.709889e-001, + 2.249152e+000, + -3.177505e+000, + -7.138130e+000, + 1.112553e+000, + -9.718434e-003, + -2.392239e+000, + 9.352768e-001, + -1.071154e+000, + -1.272150e-001, + 1.644374e+000, + 4.326598e+000, + -2.244682e+000, + 1.611051e+000, + 7.835546e-003, + 3.213282e+000, + 6.580432e-001, + // albedo 0, turbidity 2 + -1.133883e+000, + -1.835049e-001, + -1.232301e+001, + 1.307796e+001, + -3.760123e-002, + 1.051162e+000, + 3.392954e-002, + 5.319376e+000, + 6.501601e-001, + -1.116119e+000, + -1.457114e-001, + 5.436576e+000, + -5.114276e+000, + -7.178414e-002, + 2.658168e-001, + 1.603756e-001, + 7.619379e+000, + 3.112698e-001, + -1.215552e+000, + -3.391607e-001, + 4.502377e-001, + 1.281602e+000, + -4.095778e-001, + 2.374058e+000, + -1.988430e-001, + -3.809377e+000, + 1.254846e+000, + -9.657094e-001, + 3.858547e-002, + 3.324554e-001, + 1.541740e+000, + 6.029572e-001, + 2.346414e-001, + 3.902458e-001, + 7.263050e+000, + 1.353991e-001, + -1.152042e+000, + -3.155103e-001, + 2.163244e+000, + -5.230832e+000, + -7.443608e+000, + 2.247834e+000, + -1.632216e-001, + -1.725315e+000, + 1.034709e+000, + -1.051862e+000, + -1.310458e-001, + 1.554942e+000, + 1.063510e+001, + -3.558989e+000, + 6.764257e-001, + 1.428912e-001, + 2.541641e+000, + 5.000389e-001, + // albedo 0, turbidity 3 + -1.156925e+000, + -2.104634e-001, + -1.793090e+001, + 1.817524e+001, + -1.225514e-002, + 6.518753e-001, + 1.085708e-001, + 4.947239e+000, + 5.635117e-001, + -1.183783e+000, + -2.187288e-001, + 5.860654e+000, + -5.643960e+000, + -4.453459e-002, + 6.724995e-001, + 1.698133e-002, + 6.742131e+000, + 6.353553e-001, + -1.143101e+000, + -2.644541e-001, + 9.354577e-001, + 9.256854e-001, + -1.074845e-001, + 1.663131e+000, + 4.998918e-002, + -2.049721e+000, + 8.150826e-001, + -1.021102e+000, + 2.478746e-002, + -1.367363e+000, + -9.011684e-002, + -5.001730e-001, + 4.316685e-002, + 3.952231e-001, + 8.084754e+000, + 5.380131e-001, + -1.101145e+000, + -2.731481e-001, + 2.483816e+000, + 3.581780e-001, + 4.249615e-001, + 2.284087e+000, + -5.836688e-002, + -1.651434e+000, + 7.685430e-001, + -1.073863e+000, + -1.705854e-001, + 1.169673e+000, + -2.183705e-003, + -5.007439e+000, + 2.318154e-001, + 2.738714e-001, + 2.187327e+000, + 6.676882e-001, + // albedo 0, turbidity 4 + -1.207581e+000, + -2.653224e-001, + -9.004497e+000, + 8.985720e+000, + -9.024461e-003, + 4.273132e-001, + 1.378091e-001, + 4.307648e+000, + 5.309421e-001, + -1.278614e+000, + -3.516334e-001, + 2.489304e+000, + -1.840089e+000, + -6.293646e-002, + 8.426903e-001, + -7.266949e-002, + 4.434869e+000, + 7.077739e-001, + -1.150333e+000, + -2.033123e-001, + 8.150312e-001, + -7.926382e-001, + -3.230951e-001, + 1.291679e+000, + 1.822329e-001, + 1.619133e+000, + 7.522432e-001, + -1.002248e+000, + -3.092969e-002, + -1.092273e+000, + 2.820671e+000, + 4.504455e-001, + -5.121048e-001, + 4.229688e-001, + 4.037073e+000, + 5.843543e-001, + -1.087962e+000, + -2.434172e-001, + 1.817322e+000, + -6.031774e+000, + -4.873903e+000, + 2.094606e+000, + 1.184743e-001, + 2.293346e-001, + 7.283940e-001, + -1.072272e+000, + -1.614715e-001, + 8.337136e-001, + 1.086866e+001, + -3.373042e+000, + 2.260332e-002, + 2.622468e-001, + 2.470766e+000, + 7.078601e-001, + // albedo 0, turbidity 5 + -1.263850e+000, + -3.278851e-001, + -5.336400e+000, + 5.102832e+000, + 2.070020e-003, + 3.605369e-001, + 1.633426e-001, + 3.790121e+000, + 4.999503e-001, + -1.507623e+000, + -6.465694e-001, + -2.983753e+000, + 4.212027e+000, + -5.868795e-002, + 3.852488e-001, + -7.222995e-002, + 1.042808e+000, + 6.632120e-001, + -1.041397e+000, + 6.326589e-002, + 3.860471e+000, + -5.579882e+000, + -1.730201e-001, + 2.303753e+000, + 6.102393e-002, + 7.287763e+000, + 8.916057e-001, + -1.049861e+000, + -2.836044e-001, + -2.302537e+000, + 6.724969e+000, + 4.373598e-001, + -2.422514e+000, + 6.952438e-001, + -2.633600e+000, + 4.070954e-001, + -1.054117e+000, + -1.206625e-001, + 1.764625e+000, + -9.467716e+000, + -3.436987e+000, + 3.394707e+000, + -8.149683e-002, + 3.485918e+000, + 8.515716e-001, + -1.072517e+000, + -1.574135e-001, + 2.214599e-001, + 1.331766e+001, + -3.915381e+000, + -1.229973e+000, + 6.267275e-001, + 2.923262e+000, + 6.516824e-001, + // albedo 0, turbidity 6 + -1.293503e+000, + -3.676147e-001, + -1.323095e+001, + 1.301713e+001, + -3.471894e-004, + 3.957986e-001, + 1.317480e-001, + 3.616827e+000, + 4.998510e-001, + -1.757697e+000, + -8.202513e-001, + 2.560133e+000, + -1.337734e+000, + -3.413795e-002, + 5.633043e-001, + -4.355758e-002, + 7.324869e-001, + 5.728008e-001, + -8.814599e-001, + 9.828960e-002, + -2.701428e-001, + -1.298657e+000, + -6.721423e-002, + 1.581675e+000, + 4.095024e-002, + 6.548913e+000, + 9.726866e-001, + -1.125663e+000, + -2.625873e-001, + -2.797592e-001, + 2.848739e+000, + -3.363778e-002, + -1.672768e+000, + 7.349952e-001, + -1.708628e+000, + 3.557813e-001, + -1.044841e+000, + -1.712889e-001, + 7.091708e-001, + -4.275119e+000, + -7.565130e-001, + 2.483873e+000, + -7.781321e-002, + 2.667776e+000, + 8.709126e-001, + -1.067360e+000, + -1.543712e-001, + 3.884866e-001, + 6.915851e+000, + -4.250734e+000, + -6.525729e-001, + 6.368377e-001, + 2.671865e+000, + 6.566986e-001, + // albedo 0, turbidity 7 + -1.360356e+000, + -4.336026e-001, + -1.442967e+001, + 1.428579e+001, + -3.990325e-003, + 4.600126e-001, + 1.023159e-001, + 3.367805e+000, + 4.999150e-001, + -2.054147e+000, + -1.064745e+000, + -7.857491e-001, + 2.214734e+000, + -3.764113e-002, + 8.504761e-001, + -4.222958e-002, + 1.091377e-001, + 4.732161e-001, + -8.953952e-001, + 1.048085e-001, + 1.481293e+000, + -4.223012e+000, + -4.164160e-002, + 5.999023e-001, + 6.310005e-002, + 7.156883e+000, + 1.066682e+000, + -1.030251e+000, + -2.777709e-001, + -8.361086e-001, + 5.611154e+000, + 1.861240e-001, + -5.823197e-001, + 6.716210e-001, + -3.269717e+000, + 2.922029e-001, + -1.095631e+000, + -1.966849e-001, + 6.300566e-001, + -7.129591e+000, + -7.351951e-001, + 1.400340e+000, + -6.997516e-003, + 2.879018e+000, + 8.879337e-001, + -1.052935e+000, + -1.551958e-001, + 2.334578e-001, + 1.040948e+001, + -4.426381e+000, + -3.477323e-001, + 6.257070e-001, + 2.451148e+000, + 6.570737e-001, + // albedo 0, turbidity 8 + -1.382656e+000, + -4.830539e-001, + -1.107403e+001, + 1.127854e+001, + -2.723641e-002, + 8.478005e-001, + 2.907652e-003, + 3.290364e+000, + 7.398950e-001, + -2.230895e+000, + -1.163446e+000, + -1.001991e+001, + 1.125340e+001, + -3.233871e-002, + 3.041577e-001, + 3.870458e-003, + 3.463879e-001, + -8.829082e-002, + -1.489234e+000, + -3.402035e-001, + 2.948409e+000, + -8.098077e+000, + 9.078299e-002, + -3.179835e-001, + 4.730321e-001, + 6.765707e+000, + 1.440217e+000, + -6.206234e-001, + -1.701007e-001, + -7.346357e-002, + 9.350033e+000, + 1.548964e-001, + 1.313206e+000, + -1.479143e-001, + -5.119165e+000, + 1.854277e-001, + -1.226372e+000, + -2.128299e-001, + -1.643093e-001, + -9.382334e+000, + -4.857784e-001, + -1.374948e-001, + 5.877245e-001, + 3.862307e+000, + 8.700125e-001, + -1.030598e+000, + -1.931668e-001, + 3.691403e-001, + 1.066393e+001, + -4.244968e+000, + -5.872571e-002, + 4.193140e-001, + 1.461878e+000, + 6.699478e-001, + // albedo 0, turbidity 9 + -1.606656e+000, + -7.140209e-001, + -1.149565e+001, + 1.168427e+001, + -2.245577e-002, + 7.718953e-001, + -8.349882e-006, + 2.654449e+000, + 9.001224e-001, + -2.100494e+000, + -1.013602e+000, + -1.638934e+001, + 1.729185e+001, + -1.580924e-002, + 5.038208e-002, + -1.628735e-002, + 1.762584e+000, + -3.121794e-001, + -3.228292e+000, + -1.459508e+000, + 7.424519e+000, + -1.194272e+001, + 4.931054e-002, + 6.493074e-001, + 3.590561e-001, + 4.068321e+000, + 1.613039e+000, + 1.278814e-001, + 4.010913e-002, + -2.185675e+000, + 1.164548e+001, + 2.706306e-002, + 1.632886e-001, + -1.090111e-002, + -3.342580e+000, + 1.916992e-002, + -1.400278e+000, + -2.825658e-001, + 4.168149e-001, + -1.195909e+001, + -1.122968e-002, + 1.863328e-001, + 4.263033e-001, + 2.270053e+000, + 9.748449e-001, + -1.017511e+000, + -2.884028e-001, + 3.544996e-001, + 1.535118e+001, + -5.009184e+000, + 1.511064e-001, + 2.916578e-001, + 7.889658e-001, + 6.294910e-001, + // albedo 0, turbidity 10 + -2.031136e+000, + -1.076357e+000, + -8.660773e+000, + 8.800317e+000, + -2.370842e-002, + 5.736027e-001, + -8.441313e-006, + 2.248669e+000, + 9.001280e-001, + -1.270967e+000, + -7.828844e-001, + -1.198232e+001, + 1.262753e+001, + -1.509989e-002, + 1.663438e-001, + 2.440939e-004, + 2.068640e+000, + -2.521574e-001, + -6.600872e+000, + -2.689874e+000, + 6.453928e+000, + -9.592747e+000, + -3.551170e-002, + 1.325662e+000, + -1.894375e-002, + 3.506163e+000, + 1.469724e+000, + 7.961323e-001, + -1.989144e-001, + -2.685238e+000, + 1.034230e+001, + 2.076702e-001, + -7.692350e-001, + 6.184894e-001, + -1.969413e+000, + 3.842922e-002, + -1.459073e+000, + -4.964034e-001, + 1.060127e+000, + -1.277712e+001, + -9.634553e-001, + 5.610879e-001, + -2.034286e-001, + 3.525910e-001, + 1.003048e+000, + -1.021565e+000, + -2.553022e-001, + 6.367571e-002, + 2.028825e+001, + -4.623219e+000, + -2.400428e-002, + 4.251423e-001, + 9.640897e-001, + 6.080298e-001, + // albedo 1, turbidity 1 + -1.121224e+000, + -1.710171e-001, + -1.383038e+001, + 1.475343e+001, + -3.137812e-002, + 1.035662e+000, + 4.060006e-002, + 5.222551e+000, + 5.001051e-001, + -1.172565e+000, + -1.880857e-001, + 7.283595e+000, + -5.774643e+000, + -9.051285e-002, + 9.108124e-001, + -1.565627e-002, + 6.194404e+000, + 4.688599e-001, + -1.124109e+000, + -3.082816e-001, + -2.179926e-001, + 1.330167e+000, + -4.502252e-001, + 1.470140e+000, + 4.158616e-004, + -4.724308e+000, + 1.134678e+000, + -1.079810e+000, + -9.226583e-002, + 1.465364e+000, + 1.348856e+000, + 4.357794e-001, + 1.771543e+000, + 8.115381e-003, + 6.057395e+000, + 2.462140e-001, + -1.086668e+000, + -2.709863e-001, + 2.249153e+000, + -3.177505e+000, + -7.138130e+000, + 1.112553e+000, + -9.724210e-003, + -2.392239e+000, + 9.352768e-001, + -1.071158e+000, + -1.272123e-001, + 1.644374e+000, + 4.326598e+000, + -2.244682e+000, + 1.611051e+000, + 7.831866e-003, + 3.213282e+000, + 6.580432e-001, + // albedo 1, turbidity 2 + -1.125449e+000, + -1.733403e-001, + -1.228038e+001, + 1.311695e+001, + -3.541409e-002, + 1.005494e+000, + 4.147852e-002, + 5.316886e+000, + 6.051699e-001, + -1.101273e+000, + -1.422106e-001, + 5.484715e+000, + -5.089835e+000, + -6.655928e-002, + 2.076815e-001, + 1.633101e-001, + 7.624535e+000, + 3.044941e-001, + -1.213425e+000, + -3.085010e-001, + 5.550585e-001, + 1.302798e+000, + -3.946488e-001, + 2.285152e+000, + -1.925101e-001, + -3.790065e+000, + 1.263207e+000, + -9.610579e-001, + 9.458093e-003, + 5.293256e-001, + 1.553214e+000, + 6.053752e-001, + 1.172267e-001, + 3.674690e-001, + 7.305350e+000, + 1.509544e-001, + -1.119731e+000, + -2.765693e-001, + 2.433951e+000, + -5.229810e+000, + -7.449777e+000, + 2.123304e+000, + -2.242917e-001, + -1.669115e+000, + 1.041008e+000, + -1.094324e+000, + -1.418743e-001, + 1.836224e+000, + 1.063054e+001, + -3.561209e+000, + 5.916534e-001, + 9.296571e-002, + 2.600060e+000, + 4.999316e-001, + // albedo 1, turbidity 3 + -1.155818e+000, + -2.162981e-001, + -2.560068e+001, + 2.636088e+001, + -1.382944e-002, + 8.101983e-001, + 4.709210e-002, + 4.301909e+000, + 6.416958e-001, + -1.171460e+000, + -1.866443e-001, + 8.497645e+000, + -8.396229e+000, + -3.345417e-002, + 2.960022e-001, + 7.985279e-002, + 7.420544e+000, + 5.552152e-001, + -1.114385e+000, + -2.963805e-001, + 5.955009e-002, + 2.320529e+000, + -7.649266e-002, + 2.277940e+000, + -5.942479e-002, + -4.040964e+000, + 9.588558e-001, + -1.070647e+000, + 4.194546e-002, + -5.701942e-001, + -1.001278e+000, + -3.389615e-001, + -8.559533e-001, + 5.070784e-001, + 9.805560e+000, + 3.529747e-001, + -1.057912e+000, + -2.733753e-001, + 3.080618e+000, + 7.477366e-001, + 3.484876e-001, + 2.214994e+000, + -2.597625e-001, + -2.842961e+000, + 9.178917e-001, + -1.105636e+000, + -1.815423e-001, + 1.651373e+000, + -2.553941e-003, + -5.008441e+000, + -6.378055e-001, + 2.370503e-001, + 1.890656e+000, + 6.018255e-001, + // albedo 1, turbidity 4 + -1.194221e+000, + -2.570801e-001, + -8.919095e+000, + 9.380192e+000, + -2.650470e-002, + 6.233645e-001, + 6.663964e-002, + 4.027438e+000, + 6.125383e-001, + -1.308216e+000, + -3.781794e-001, + 2.369107e+000, + -1.977066e+000, + -4.079773e-002, + 1.443960e-001, + 8.206719e-002, + 3.465933e+000, + 5.442867e-001, + -1.048459e+000, + -1.617720e-001, + 1.015136e+000, + -2.989579e-001, + -2.764989e-001, + 2.427990e+000, + -1.147612e-001, + 1.522921e+000, + 1.041410e+000, + -1.105796e+000, + -4.826962e-002, + -8.419705e-001, + 3.285981e+000, + 7.975109e-001, + -1.954456e+000, + 7.424696e-001, + 4.604902e+000, + 2.602059e-001, + -1.033856e+000, + -2.507382e-001, + 2.882633e+000, + -8.250912e+000, + -6.878129e+000, + 2.948966e+000, + -2.850302e-001, + -8.253849e-001, + 9.844934e-001, + -1.125219e+000, + -1.879003e-001, + 1.474838e+000, + 1.453266e+001, + -3.271910e+000, + -1.231579e+000, + 2.397524e-001, + 1.654932e+000, + 5.625696e-001, + // albedo 1, turbidity 5 + -1.246640e+000, + -3.202274e-001, + -6.355032e+000, + 6.364143e+000, + 9.028376e-004, + 3.146975e-001, + 1.550718e-001, + 3.413749e+000, + 4.999065e-001, + -1.477471e+000, + -5.819223e-001, + 1.329471e+000, + -2.694229e-001, + -4.575905e-002, + 5.087866e-001, + -6.857139e-002, + 1.810092e+000, + 6.318693e-001, + -1.046136e+000, + -6.763679e-002, + 6.725076e-001, + -1.036786e+000, + -3.192799e-001, + 1.724205e+000, + 6.468388e-002, + 3.953855e+000, + 9.417528e-001, + -1.033910e+000, + -1.295544e-001, + -4.551294e-001, + 2.659205e+000, + 8.887235e-001, + -1.733153e+000, + 6.540117e-001, + 8.046523e-001, + 3.597443e-001, + -1.094530e+000, + -2.282012e-001, + 2.298267e+000, + -5.184881e+000, + -6.122309e+000, + 2.590799e+000, + -1.618707e-001, + 1.116033e+000, + 8.867666e-001, + -1.095556e+000, + -1.807112e-001, + 1.406193e+000, + 8.120385e+000, + -3.058239e+000, + -1.121150e+000, + 2.933606e-001, + 1.488339e+000, + 6.374827e-001, + // albedo 1, turbidity 6 + -1.270123e+000, + -3.552595e-001, + -8.975893e+000, + 9.110080e+000, + -3.388207e-003, + 3.559109e-001, + 1.201097e-001, + 3.109904e+000, + 4.998957e-001, + -1.663376e+000, + -7.846840e-001, + 6.951405e-001, + 3.139107e-001, + -2.448004e-002, + 3.572505e-001, + 1.453572e-002, + 6.307761e-001, + 5.142914e-001, + -9.518772e-001, + 7.764573e-002, + 1.247094e+000, + -2.224855e+000, + -1.195310e-001, + 1.709581e+000, + -8.836329e-002, + 5.688916e+000, + 1.113629e+000, + -1.087154e+000, + -2.665646e-001, + -8.624251e-001, + 4.536060e+000, + 4.180650e-001, + -1.629798e+000, + 8.479560e-001, + -1.293696e+000, + 1.869693e-001, + -1.064826e+000, + -1.599892e-001, + 2.285337e+000, + -8.584887e+000, + -3.074560e+000, + 2.139459e+000, + -2.592372e-001, + 1.937577e+000, + 9.957954e-001, + -1.099622e+000, + -1.849797e-001, + 1.193609e+000, + 1.416481e+001, + -5.009527e+000, + -8.592493e-001, + 3.485606e-001, + 1.884203e+000, + 6.097274e-001, + // albedo 1, turbidity 7 + -1.344841e+000, + -4.339942e-001, + -9.193112e+000, + 9.385864e+000, + -9.742818e-003, + 4.812040e-001, + 7.690647e-002, + 2.843801e+000, + 5.228047e-001, + -1.975928e+000, + -1.042040e+000, + 9.695714e-001, + 3.718000e-001, + -3.334078e-002, + 1.333620e-001, + 8.180282e-002, + -1.652429e-001, + 3.267010e-001, + -8.651864e-001, + 1.288722e-001, + 6.811456e-001, + -3.282787e+000, + -9.074685e-002, + 1.894059e+000, + -1.849744e-001, + 6.610614e+000, + 1.322978e+000, + -1.103780e+000, + -3.279618e-001, + -4.193802e-001, + 7.331165e+000, + 6.529659e-001, + -2.227297e+000, + 9.625482e-001, + -3.348971e+000, + -7.261722e-003, + -1.055963e+000, + -1.527328e-001, + 1.786114e+000, + -1.367578e+001, + -3.450729e+000, + 2.641691e+000, + -3.229222e-001, + 2.800131e+000, + 1.129409e+000, + -1.111541e+000, + -2.123518e-001, + 1.286159e+000, + 2.297563e+001, + -4.591526e+000, + -1.374672e+000, + 3.462811e-001, + 1.071127e+000, + 5.498514e-001, + // albedo 1, turbidity 8 + -1.387544e+000, + -4.964558e-001, + -9.744778e+000, + 1.014533e+001, + -2.463089e-002, + 7.188705e-001, + 3.919951e-003, + 2.760792e+000, + 7.369418e-001, + -2.206536e+000, + -1.191342e+000, + -2.244384e+000, + 3.629413e+000, + -3.601610e-002, + 7.725349e-002, + 5.357588e-002, + -2.692147e-001, + -1.142476e-001, + -1.358286e+000, + -2.268740e-001, + 9.805731e-001, + -5.163195e+000, + -8.589000e-003, + 7.697565e-001, + 2.198750e-001, + 7.029301e+000, + 1.567170e+000, + -7.167767e-001, + -2.969978e-001, + 2.300987e-001, + 7.956088e+000, + 6.339728e-001, + -6.195374e-001, + 2.502844e-001, + -6.307569e+000, + -2.208822e-002, + -1.210525e+000, + -1.245541e-001, + 9.742409e-001, + -9.705683e+000, + -1.658899e+000, + 1.365829e+000, + 2.003500e-001, + 4.400174e+000, + 1.042345e+000, + -1.061524e+000, + -2.323500e-001, + 1.284880e+000, + 1.294836e+001, + -5.011732e+000, + -9.141086e-001, + 2.723804e-001, + 6.225528e-001, + 6.030977e-001, + // albedo 1, turbidity 9 + -1.548946e+000, + -6.802676e-001, + -1.274231e+001, + 1.312954e+001, + -1.834225e-002, + 7.051580e-001, + -8.330446e-006, + 2.320435e+000, + 9.001244e-001, + -1.867128e+000, + -9.670210e-001, + -6.847422e+000, + 7.952765e+000, + -1.985986e-002, + 1.690548e-002, + -1.176902e-002, + 8.988469e-001, + -3.242269e-001, + -3.470633e+000, + -1.555121e+000, + 2.684966e+000, + -5.964736e+000, + -5.524158e-003, + 1.187089e+000, + 2.552534e-001, + 4.394076e+000, + 1.656399e+000, + 4.095837e-001, + 1.440005e-001, + -5.602190e-001, + 7.110869e+000, + 2.313366e-001, + -1.373206e+000, + 1.973962e-001, + -4.112998e+000, + -5.877027e-002, + -1.540633e+000, + -3.264234e-001, + 1.072405e+000, + -7.205546e+000, + -5.125251e-001, + 2.009905e+000, + 1.531985e-001, + 2.113439e+000, + 1.042547e+000, + -1.013330e+000, + -2.663837e-001, + 1.168934e+000, + 9.315778e+000, + -4.320502e+000, + -1.303393e+000, + 2.825872e-001, + 2.365015e-001, + 5.993344e-001, + // albedo 1, turbidity 10 + -2.055426e+000, + -1.093229e+000, + -3.487182e+000, + 3.753855e+000, + -4.639837e-002, + 5.797714e-001, + -8.056992e-006, + 1.916262e+000, + 9.001298e-001, + -1.643864e+000, + -9.676934e-001, + -1.147133e+001, + 1.253880e+001, + 2.347351e-002, + -1.602964e-002, + 4.481579e-003, + 1.373645e+000, + -2.884929e-001, + -6.156336e+000, + -2.568735e+000, + 6.499533e+000, + -9.136753e+000, + -1.751599e-001, + 1.876960e+000, + -7.959051e-002, + 3.074951e+000, + 1.579874e+000, + 7.378485e-001, + -2.614544e-001, + -2.861777e+000, + 9.518947e+000, + 5.033808e-001, + -1.844722e+000, + 6.855962e-001, + -1.497263e+000, + -9.081643e-002, + -1.341940e+000, + -3.847183e-001, + 2.045437e+000, + -1.179073e+001, + -1.532773e+000, + 1.639939e+000, + -2.668175e-001, + -8.401827e-001, + 1.083722e+000, + -1.086126e+000, + -2.811402e-001, + 7.554239e-001, + 1.862181e+001, + -4.343385e+000, + -8.611011e-001, + 3.146558e-001, + 7.022438e-001, + 5.872694e-001, +}; + +double datasetRad560[] = +{ + // albedo 0, turbidity 1 + 1.518543e-002, + 1.176421e-002, + 1.736355e-002, + 1.085640e-001, + 4.928107e-002, + 6.789277e-002, + // albedo 0, turbidity 2 + 1.482072e-002, + 1.335627e-002, + 7.685462e-003, + 1.336625e-001, + 4.842644e-002, + 7.083679e-002, + // albedo 0, turbidity 3 + 1.406436e-002, + 1.604888e-002, + -9.000273e-003, + 1.735923e-001, + 4.526955e-002, + 7.742648e-002, + // albedo 0, turbidity 4 + 1.296165e-002, + 2.074811e-002, + -3.672731e-002, + 2.310227e-001, + 4.272776e-002, + 8.807197e-002, + // albedo 0, turbidity 5 + 1.185836e-002, + 2.557920e-002, + -6.240734e-002, + 2.766326e-001, + 4.714655e-002, + 9.809189e-002, + // albedo 0, turbidity 6 + 1.107469e-002, + 2.825097e-002, + -7.618392e-002, + 2.978619e-001, + 5.429803e-002, + 1.044545e-001, + // albedo 0, turbidity 7 + 1.030435e-002, + 3.060206e-002, + -8.858708e-002, + 3.072427e-001, + 8.473378e-002, + 1.077059e-001, + // albedo 0, turbidity 8 + 9.197751e-003, + 3.269422e-002, + -9.785581e-002, + 2.997964e-001, + 1.328366e-001, + 1.192367e-001, + // albedo 0, turbidity 9 + 8.191103e-003, + 3.038883e-002, + -8.623921e-002, + 2.362785e-001, + 2.259917e-001, + 1.331360e-001, + // albedo 0, turbidity 10 + 7.275920e-003, + 2.128876e-002, + -4.464890e-002, + 1.022425e-001, + 3.640615e-001, + 1.521652e-001, + // albedo 1, turbidity 1 + 1.623600e-002, + 1.386631e-002, + 1.790676e-002, + 9.999420e-002, + 1.334051e-001, + 1.524062e-001, + // albedo 1, turbidity 2 + 1.580346e-002, + 1.594123e-002, + 5.795411e-003, + 1.311774e-001, + 1.256680e-001, + 1.627637e-001, + // albedo 1, turbidity 3 + 1.508292e-002, + 1.888592e-002, + -1.186753e-002, + 1.719109e-001, + 1.235706e-001, + 1.739866e-001, + // albedo 1, turbidity 4 + 1.385430e-002, + 2.238574e-002, + -3.390048e-002, + 2.155912e-001, + 1.366535e-001, + 1.840316e-001, + // albedo 1, turbidity 5 + 1.289448e-002, + 2.572803e-002, + -5.406854e-002, + 2.481650e-001, + 1.539663e-001, + 1.943329e-001, + // albedo 1, turbidity 6 + 1.229427e-002, + 2.715903e-002, + -6.212273e-002, + 2.543339e-001, + 1.780617e-001, + 1.961306e-001, + // albedo 1, turbidity 7 + 1.142362e-002, + 2.928317e-002, + -7.246911e-002, + 2.573202e-001, + 2.123595e-001, + 2.030761e-001, + // albedo 1, turbidity 8 + 1.030850e-002, + 2.979460e-002, + -7.568370e-002, + 2.359473e-001, + 2.693691e-001, + 2.158786e-001, + // albedo 1, turbidity 9 + 9.256414e-003, + 2.622384e-002, + -5.910990e-002, + 1.602850e-001, + 3.679614e-001, + 2.281095e-001, + // albedo 1, turbidity 10 + 8.220083e-003, + 1.701079e-002, + -1.768254e-002, + 2.593519e-002, + 4.977242e-001, + 2.394514e-001, +}; + +double dataset600[] = +{ + // albedo 0, turbidity 1 + -1.120756e+000, + -1.756050e-001, + -3.557732e+000, + 5.117996e+000, + -1.042966e-001, + 1.269364e+000, + 1.318863e-002, + 3.718263e+000, + 5.393663e-001, + -1.170564e+000, + -1.845108e-001, + 1.081952e+000, + 1.330153e+000, + -2.486698e-001, + 7.864551e-001, + 3.710973e-003, + 4.567181e+000, + 4.998408e-001, + -1.036563e+000, + -2.605284e-001, + 3.803752e+000, + -3.585400e+000, + -9.070196e-001, + 2.380958e+000, + -1.320680e-002, + -4.210738e+000, + 1.085121e+000, + -1.193752e+000, + -1.236757e-001, + -2.036484e-001, + 4.137855e+000, + 1.566414e+000, + 8.510547e-001, + 1.653213e-002, + 5.488784e+000, + 2.335910e-001, + -9.950781e-001, + -2.103974e-001, + 2.992004e+000, + -4.050491e+000, + -6.354208e+000, + 2.250652e+000, + -1.548511e-002, + -1.876535e+000, + 9.733518e-001, + -1.106820e+000, + -1.804412e-001, + 1.960315e+000, + 3.667064e+000, + -2.460232e+000, + 9.553453e-001, + 1.238019e-002, + 1.307691e+000, + 5.564710e-001, + // albedo 0, turbidity 2 + -1.112834e+000, + -1.534956e-001, + -4.968015e+000, + 6.079068e+000, + -8.917942e-002, + 1.167545e+000, + 5.945633e-002, + 5.295468e+000, + 6.272123e-001, + -1.160910e+000, + -1.640745e-001, + 7.416807e-001, + -2.894668e-001, + -8.983936e-002, + 3.778575e-002, + 2.133300e-001, + 6.390765e+000, + 3.592393e-001, + -1.054872e+000, + -2.642844e-001, + 4.375802e+000, + -1.434824e+000, + -7.521504e-001, + 3.669027e+000, + -2.992879e-001, + -5.159653e+000, + 1.284643e+000, + -1.147542e+000, + 1.011446e-002, + -2.308529e+000, + 1.587994e+000, + 1.226957e+000, + -1.328837e+000, + 5.996235e-001, + 1.004278e+001, + 5.212352e-002, + -1.023945e+000, + -2.867193e-001, + 3.733660e+000, + -2.572157e+000, + -7.749675e+000, + 3.927326e+000, + -3.230666e-001, + -4.260418e+000, + 1.091761e+000, + -1.100815e+000, + -1.590204e-001, + 1.413330e+000, + 6.546557e+000, + -2.407235e+000, + -2.678587e-001, + 2.367155e-001, + 2.242596e+000, + 5.273419e-001, + // albedo 0, turbidity 3 + -1.137271e+000, + -1.838447e-001, + -2.268731e+000, + 3.013967e+000, + -1.471213e-001, + 9.047947e-001, + 8.086373e-002, + 4.834215e+000, + 6.545047e-001, + -1.136415e+000, + -1.536696e-001, + -1.821062e+000, + 1.756804e+000, + -9.313635e-002, + 2.208938e-001, + 2.021774e-001, + 7.289664e+000, + 4.997813e-001, + -1.173214e+000, + -3.202233e-001, + 4.868221e+000, + -2.485467e+000, + -7.693969e-001, + 3.027854e+000, + -1.745243e-001, + -4.896365e+000, + 1.014186e+000, + -1.021346e+000, + 7.262425e-002, + -2.940205e+000, + 3.357462e+000, + 1.150486e+000, + -1.710207e+000, + 7.381637e-001, + 9.857427e+000, + 3.036725e-001, + -1.082107e+000, + -2.721172e-001, + 3.071962e+000, + -7.058088e+000, + -5.103538e+000, + 3.852302e+000, + -2.281911e-001, + -2.565665e+000, + 9.669584e-001, + -1.076296e+000, + -1.655466e-001, + 1.323765e+000, + 1.496892e+001, + -3.773928e+000, + -5.211752e-001, + 2.583009e-001, + 1.797906e+000, + 5.888323e-001, + // albedo 0, turbidity 4 + -1.180432e+000, + -2.327942e-001, + -7.152650e-001, + 1.078120e+000, + -2.935788e-001, + 6.977295e-001, + 1.118530e-001, + 4.270574e+000, + 6.241267e-001, + -1.260549e+000, + -2.865438e-001, + -2.736770e+000, + 2.720969e+000, + 1.291231e-001, + 4.072562e-001, + 4.510932e-002, + 5.412464e+000, + 6.781695e-001, + -1.119712e+000, + -2.521160e-001, + 4.860527e+000, + -1.950603e+000, + -1.598805e+000, + 2.556718e+000, + 2.462723e-002, + -2.059404e+000, + 8.000995e-001, + -1.056386e+000, + 2.018258e-002, + -3.728955e+000, + 1.022270e+000, + 1.722210e+000, + -2.691554e+000, + 8.329883e-001, + 6.982450e+000, + 4.746778e-001, + -1.044811e+000, + -2.531291e-001, + 3.102204e+000, + -3.662632e+000, + -5.609358e+000, + 4.574385e+000, + -2.173600e-001, + -1.646110e+000, + 8.593305e-001, + -1.090027e+000, + -1.699462e-001, + 7.118896e-001, + 1.287572e+001, + -2.747429e+000, + -1.706223e+000, + 4.483382e-001, + 2.029605e+000, + 6.366599e-001, + // albedo 0, turbidity 5 + -1.232266e+000, + -2.905676e-001, + -4.158347e-001, + 5.285264e-001, + -3.064312e-001, + 5.569478e-001, + 1.195289e-001, + 3.788091e+000, + 5.970680e-001, + -1.451205e+000, + -5.169964e-001, + -2.018331e-001, + 1.499655e+000, + -1.575963e+000, + 2.761459e-001, + 5.184923e-002, + 2.301119e+000, + 6.177771e-001, + -1.059832e+000, + -7.658003e-002, + 6.456894e-001, + -4.398594e+000, + 5.369604e+000, + 2.121235e+000, + 3.210869e-002, + 3.542794e+000, + 9.114953e-001, + -1.040966e+000, + -1.269405e-001, + -3.751056e-001, + 1.229395e+001, + -1.977090e+001, + -2.458488e+000, + 7.711932e-001, + 8.079227e-001, + 3.865305e-001, + -1.061923e+000, + -1.981907e-001, + 1.089854e+000, + -3.414507e+000, + 8.032592e+000, + 3.459965e+000, + -1.253984e-001, + 1.188198e+000, + 8.639277e-001, + -1.070607e+000, + -1.627049e-001, + 7.012071e-001, + 2.138780e+000, + -5.006595e+000, + -1.096698e+000, + 6.658771e-001, + 1.999430e+000, + 6.557122e-001, + // albedo 0, turbidity 6 + -1.280090e+000, + -3.357179e-001, + -9.337154e-002, + -5.075553e-003, + -3.096112e+000, + 4.001499e-001, + 1.489818e-001, + 3.515349e+000, + 5.571477e-001, + -1.648190e+000, + -7.024227e-001, + -2.925797e-002, + 1.658094e+000, + 4.229924e+000, + 3.502683e-001, + 3.180108e-002, + 1.430955e+000, + 5.739552e-001, + -9.589189e-001, + 2.559557e-002, + 2.192186e-001, + -5.276316e+000, + -4.153922e+000, + 1.855574e+000, + 3.052317e-002, + 4.323694e+000, + 9.839497e-001, + -1.076589e+000, + -1.936109e-001, + -4.162615e-001, + 1.202609e+001, + -9.327314e+000, + -2.326508e+000, + 7.983253e-001, + 2.100845e-001, + 3.135170e-001, + -1.049437e+000, + -1.694738e-001, + 1.062110e+000, + 5.575299e+000, + 4.846701e-001, + 3.089474e+000, + -1.584214e-001, + 1.369457e+000, + 8.995377e-001, + -1.069986e+000, + -1.830827e-001, + 5.006422e-001, + -3.063835e-003, + -2.768514e+000, + -1.258027e+000, + 6.679955e-001, + 1.840288e+000, + 6.498676e-001, + // albedo 0, turbidity 7 + -1.328971e+000, + -3.853230e-001, + -2.343098e-001, + -6.505414e-003, + -4.859294e+000, + 3.752993e-001, + 1.670718e-001, + 3.474961e+000, + 4.998573e-001, + -2.023062e+000, + -1.023840e+000, + 4.308501e-001, + 1.473146e+000, + 6.112105e+000, + 5.767265e-001, + -3.107377e-002, + 7.748759e-002, + 5.016978e-001, + -8.575747e-001, + 1.580212e-001, + -7.365004e-001, + -4.007773e+000, + -4.051657e+000, + 8.889282e-001, + 1.978413e-001, + 6.282132e+000, + 1.063928e+000, + -1.073428e+000, + -3.228761e-001, + 4.793085e-001, + 5.455778e+000, + -7.830559e+000, + -9.794478e-001, + 5.370543e-001, + -3.022750e+000, + 2.818600e-001, + -1.057120e+000, + -1.266841e-001, + 4.555368e-001, + 1.201278e+001, + -9.293773e-001, + 1.439595e+000, + 3.262182e-002, + 2.890364e+000, + 8.821540e-001, + -1.060079e+000, + -1.816680e-001, + 3.541107e-001, + -2.642196e-003, + -2.588317e+000, + -5.640010e-001, + 6.643994e-001, + 1.673077e+000, + 6.658333e-001, + // albedo 0, turbidity 8 + -1.395409e+000, + -4.658947e-001, + -4.370597e-001, + 1.342039e+000, + -1.108674e+000, + 6.439316e-001, + 1.355229e-002, + 3.241153e+000, + 6.696079e-001, + -2.418167e+000, + -1.266061e+000, + 3.287382e-001, + -1.486721e+000, + -6.770180e-001, + 2.439008e-001, + 1.703788e-001, + 1.664559e-002, + -6.330217e-003, + -1.221212e+000, + -1.072571e-001, + -1.655914e+000, + 2.659047e+000, + 6.830770e+000, + 4.984792e-001, + 2.538158e-001, + 6.500660e+000, + 1.486576e+000, + -7.182331e-001, + -2.519055e-001, + 1.641261e+000, + -5.500375e+000, + -1.253143e+001, + -1.542672e-001, + 1.741161e-001, + -4.907497e+000, + 7.968864e-002, + -1.207117e+000, + -1.635739e-001, + -3.256308e-001, + 1.409033e+001, + 1.107883e+000, + 7.217342e-001, + 3.158860e-001, + 3.537550e+000, + 9.389751e-001, + -1.015927e+000, + -1.890895e-001, + 4.180376e-001, + 9.528535e+000, + -4.073979e+000, + -8.713087e-001, + 4.899379e-001, + 1.277831e+000, + 6.519818e-001, + // albedo 0, turbidity 9 + -1.551242e+000, + -6.400568e-001, + -3.673011e-001, + 1.623228e+000, + -1.482572e+000, + 5.625944e-001, + -1.130924e-005, + 2.792007e+000, + 9.000924e-001, + -1.971409e+000, + -9.004995e-001, + -2.337582e-001, + -1.511905e+000, + 6.645432e-002, + 6.149087e-001, + -3.184094e-002, + 2.026210e+000, + -2.799058e-001, + -3.464015e+000, + -1.604654e+000, + -1.514516e+000, + 2.768075e+000, + 4.084166e+000, + -4.287171e-001, + 7.112107e-001, + 2.896460e+000, + 1.502031e+000, + 4.069978e-001, + 2.775394e-001, + 1.525761e+000, + -5.264056e+000, + -7.108445e+000, + 1.134996e+000, + -4.122625e-001, + -2.558151e+000, + 2.009854e-001, + -1.504217e+000, + -3.618442e-001, + -2.305374e-001, + 1.434481e+001, + -1.713254e+000, + -5.670708e-001, + 5.206848e-001, + 1.704009e+000, + 8.447497e-001, + -9.753124e-001, + -2.080868e-001, + 2.450141e-001, + -3.535206e-003, + -2.121317e+000, + -1.425634e-001, + 4.670084e-001, + 1.027875e+000, + 6.735543e-001, + // albedo 0, turbidity 10 + -2.027207e+000, + -1.003600e+000, + -3.813114e-001, + 9.357907e-001, + -1.031886e+000, + 5.523389e-001, + -8.883940e-006, + 2.339379e+000, + 9.001659e-001, + -1.506235e+000, + -7.795241e-001, + -4.313309e-001, + 9.124054e-001, + -7.484352e-001, + -8.417756e-002, + -1.426561e-002, + 2.571178e+000, + -2.504298e-001, + -6.482777e+000, + -2.700075e+000, + -1.556622e+000, + -2.978497e+000, + 4.623255e+000, + 1.953868e+000, + 3.113178e-001, + 2.311303e+000, + 1.451021e+000, + 9.357272e-001, + -1.066566e-001, + 1.476763e+000, + 6.889797e+000, + -1.038036e+001, + -2.094856e+000, + 1.330069e-001, + -1.446404e+000, + 1.121890e-001, + -1.398229e+000, + -3.167573e-001, + -1.276866e-001, + 1.239440e+000, + 1.816678e+000, + 1.586775e+000, + 8.043533e-002, + 3.219192e-001, + 9.200620e-001, + -1.070734e+000, + -3.636167e-001, + 2.426490e-001, + 8.282765e+000, + -3.588710e+000, + -9.105402e-001, + 3.760276e-001, + 5.756358e-001, + 6.508161e-001, + // albedo 1, turbidity 1 + -1.120757e+000, + -1.756034e-001, + -3.557732e+000, + 5.117996e+000, + -1.042960e-001, + 1.269364e+000, + 1.318834e-002, + 3.718263e+000, + 5.393663e-001, + -1.170565e+000, + -1.845093e-001, + 1.081952e+000, + 1.330153e+000, + -2.486697e-001, + 7.864550e-001, + 3.709405e-003, + 4.567181e+000, + 4.998408e-001, + -1.036564e+000, + -2.605265e-001, + 3.803752e+000, + -3.585400e+000, + -9.070196e-001, + 2.380958e+000, + -1.320996e-002, + -4.210738e+000, + 1.085121e+000, + -1.193753e+000, + -1.236733e-001, + -2.036483e-001, + 4.137855e+000, + 1.566414e+000, + 8.510543e-001, + 1.652749e-002, + 5.488784e+000, + 2.335910e-001, + -9.950796e-001, + -2.103948e-001, + 2.992004e+000, + -4.050491e+000, + -6.354208e+000, + 2.250652e+000, + -1.548996e-002, + -1.876535e+000, + 9.733518e-001, + -1.106823e+000, + -1.804388e-001, + 1.960315e+000, + 3.667064e+000, + -2.460232e+000, + 9.553451e-001, + 1.237721e-002, + 1.307692e+000, + 5.564710e-001, + // albedo 1, turbidity 2 + -1.113356e+000, + -1.560185e-001, + -7.788803e+000, + 8.963658e+000, + -5.322872e-002, + 1.116670e+000, + 7.024842e-002, + 4.886694e+000, + 5.931909e-001, + -1.134232e+000, + -1.667475e-001, + 4.176259e+000, + -3.242194e+000, + -7.889230e-002, + 8.254326e-002, + 1.400333e-001, + 5.395289e+000, + 4.862375e-001, + -1.105040e+000, + -2.389195e-001, + 9.866260e-001, + 1.271557e+000, + -6.066849e-001, + 3.599900e+000, + -1.681445e-001, + -2.812867e+000, + 1.053791e+000, + -1.078302e+000, + -2.258635e-002, + 7.407482e-001, + 1.805864e-001, + 9.070580e-001, + -1.720820e+000, + 4.256187e-001, + 6.982502e+000, + 3.350778e-001, + -1.070883e+000, + -2.752054e-001, + 2.937203e+000, + -2.246366e+000, + -9.847865e+000, + 3.104714e+000, + -2.573859e-001, + -2.816401e+000, + 8.478900e-001, + -1.090880e+000, + -1.453755e-001, + 2.046382e+000, + 5.595795e+000, + -2.809181e+000, + -9.239576e-001, + 1.783176e-001, + 2.051350e+000, + 5.815062e-001, + // albedo 1, turbidity 3 + -1.136641e+000, + -1.825277e-001, + -3.464338e+000, + 4.413974e+000, + -1.123917e-001, + 1.009115e+000, + 5.542918e-002, + 4.702599e+000, + 6.799974e-001, + -1.146478e+000, + -1.593833e-001, + -9.055790e-001, + 8.991902e-001, + -4.711416e-002, + -3.813573e-001, + 2.290428e-001, + 6.961903e+000, + 4.206011e-001, + -1.136317e+000, + -3.103198e-001, + 4.219694e+000, + -2.031887e+000, + -7.184952e-001, + 3.795646e+000, + -1.650547e-001, + -5.402471e+000, + 1.118561e+000, + -1.044973e+000, + 7.826651e-002, + -2.043684e+000, + 3.410720e+000, + 1.974969e+000, + -2.736513e+000, + 6.828176e-001, + 1.049084e+001, + 1.894241e-001, + -1.076125e+000, + -2.930526e-001, + 3.722784e+000, + -7.364061e+000, + -7.399428e+000, + 4.034307e+000, + -3.489831e-001, + -3.438955e+000, + 1.077145e+000, + -1.100551e+000, + -1.533449e-001, + 1.767589e+000, + 1.479022e+001, + -2.910058e+000, + -1.732923e+000, + 2.193598e-001, + 1.880974e+000, + 4.999331e-001, + // albedo 1, turbidity 4 + -1.175282e+000, + -2.274651e-001, + -8.788053e-001, + 1.446934e+000, + -2.568124e-001, + 7.201567e-001, + 1.054963e-001, + 4.149007e+000, + 6.084060e-001, + -1.224868e+000, + -2.528005e-001, + -2.861303e+000, + 3.033667e+000, + 1.405049e-001, + 2.481768e-001, + 6.435189e-002, + 5.409907e+000, + 6.372238e-001, + -1.144647e+000, + -3.063749e-001, + 4.347579e+000, + -2.473291e+000, + -1.180139e+000, + 2.550631e+000, + 3.833967e-002, + -3.231444e+000, + 8.737219e-001, + -1.028428e+000, + 8.888974e-002, + -2.431225e+000, + 2.811511e+000, + 2.400771e+000, + -2.380403e+000, + 7.114868e-001, + 8.190106e+000, + 4.166861e-001, + -1.076730e+000, + -3.129260e-001, + 3.582560e+000, + -5.902417e+000, + -6.959342e+000, + 3.528030e+000, + -2.613596e-001, + -2.993803e+000, + 8.934226e-001, + -1.107957e+000, + -1.728652e-001, + 1.679540e+000, + 1.238391e+001, + -2.945620e+000, + -1.568811e+000, + 2.418421e-001, + 1.360652e+000, + 6.182405e-001, + // albedo 1, turbidity 5 + -1.215034e+000, + -2.755459e-001, + -1.477751e-001, + 4.448730e-001, + -4.027817e-001, + 4.787013e-001, + 1.200617e-001, + 3.613995e+000, + 5.999756e-001, + -1.443500e+000, + -5.194350e-001, + 1.588243e-001, + 1.429114e+000, + -2.310655e+000, + 3.033213e-001, + 2.308566e-002, + 1.894189e+000, + 6.066576e-001, + -1.051421e+000, + -9.990731e-002, + 5.187710e-001, + -3.890856e+000, + 7.794599e+000, + 1.810628e+000, + 6.532073e-002, + 2.564480e+000, + 9.334916e-001, + -1.034548e+000, + -6.777012e-002, + -2.587520e-002, + 1.062675e+001, + -2.266196e+001, + -2.002081e+000, + 7.508804e-001, + 2.022771e+000, + 3.517577e-001, + -1.090576e+000, + -2.542157e-001, + 2.213560e+000, + -3.563890e+000, + 9.180955e+000, + 2.780121e+000, + -2.656654e-001, + -5.012514e-002, + 8.968751e-001, + -1.104356e+000, + -1.955634e-001, + 1.782217e+000, + 1.085584e+000, + -5.011522e+000, + -1.075140e+000, + 3.828238e-001, + 6.133363e-001, + 6.448312e-001, + // albedo 1, turbidity 6 + -1.261147e+000, + -3.271435e-001, + 1.136430e-001, + -3.464762e-003, + -3.025565e+000, + 3.660675e-001, + 1.337332e-001, + 3.190374e+000, + 5.655627e-001, + -1.611753e+000, + -6.914768e-001, + 2.911405e-001, + 1.806475e+000, + 2.823240e+000, + 3.320241e-001, + 2.606391e-002, + 9.946717e-001, + 5.581393e-001, + -9.491151e-001, + 9.848038e-003, + 2.711804e-001, + -5.319331e+000, + 1.135835e-001, + 1.669815e+000, + 3.604115e-002, + 3.506230e+000, + 1.008650e+000, + -1.109597e+000, + -1.650703e-001, + -3.529912e-001, + 1.209251e+001, + -1.435008e+001, + -2.085063e+000, + 7.955493e-001, + 1.240407e+000, + 2.856509e-001, + -1.035803e+000, + -1.963707e-001, + 2.407913e+000, + -1.564693e+000, + 4.483717e+000, + 2.795295e+000, + -2.799711e-001, + 6.851892e-002, + 9.312311e-001, + -1.132687e+000, + -2.383551e-001, + 1.590132e+000, + 1.025733e+000, + -4.837236e+000, + -1.334195e+000, + 4.022060e-001, + 4.281273e-001, + 6.334802e-001, + // albedo 1, turbidity 7 + -1.310240e+000, + -3.819813e-001, + 2.469845e-002, + -7.043983e-003, + -5.009925e+000, + 3.560980e-001, + 1.582176e-001, + 2.966421e+000, + 4.998910e-001, + -1.993638e+000, + -1.029241e+000, + 7.780588e-001, + 1.080741e+000, + 7.179598e+000, + 2.478857e-001, + 1.935012e-002, + -3.434240e-001, + 4.813586e-001, + -8.209344e-001, + 1.728853e-001, + -7.045676e-001, + -3.384688e+000, + -4.855111e+000, + 1.661563e+000, + 4.252574e-002, + 5.701648e+000, + 1.110774e+000, + -1.130678e+000, + -3.273624e-001, + 5.555549e-001, + 5.800793e+000, + -8.817085e+000, + -2.344445e+000, + 7.532869e-001, + -2.418368e+000, + 2.201826e-001, + -1.032417e+000, + -1.335568e-001, + 1.707051e+000, + 8.168228e+000, + -5.151972e-003, + 2.785504e+000, + -2.123703e-001, + 1.770173e+000, + 9.064082e-001, + -1.125604e+000, + -2.328530e-001, + 1.537245e+000, + 4.347312e+000, + -4.368526e+000, + -1.527321e+000, + 3.574251e-001, + 5.982159e-001, + 6.705880e-001, + // albedo 1, turbidity 8 + -1.381743e+000, + -4.607543e-001, + -2.754732e-001, + 9.134243e-001, + -7.581174e-001, + 6.220814e-001, + 2.353878e-002, + 2.891536e+000, + 6.426078e-001, + -2.362341e+000, + -1.306326e+000, + 6.909936e-001, + -7.196658e-001, + -4.501812e-001, + -5.219928e-002, + 2.111683e-001, + -9.499603e-001, + 3.301774e-002, + -1.218829e+000, + -6.834768e-002, + -1.241760e+000, + 1.122890e+000, + 5.750762e+000, + 1.231058e+000, + 6.884716e-003, + 6.801032e+000, + 1.512485e+000, + -6.781560e-001, + -2.446588e-001, + 1.302166e+000, + -2.334650e+000, + -1.218960e+001, + -1.257952e+000, + 5.387955e-001, + -5.559859e+000, + -1.209718e-002, + -1.270037e+000, + -1.870204e-001, + 9.650201e-001, + 9.976613e+000, + 1.444014e+000, + 1.523442e+000, + -2.753646e-002, + 3.415790e+000, + 1.017645e+000, + -1.046712e+000, + -2.173979e-001, + 1.473981e+000, + 4.368847e+000, + -4.642506e+000, + -1.049951e+000, + 3.511771e-001, + 2.379457e-001, + 6.307946e-001, + // albedo 1, turbidity 9 + -1.532302e+000, + -6.390752e-001, + -1.369123e-001, + 1.480171e+000, + -1.313391e+000, + 5.210118e-001, + -1.053608e-005, + 2.352090e+000, + 9.000581e-001, + -2.042866e+000, + -1.015386e+000, + 1.750126e-001, + -9.921800e-001, + -9.449241e-002, + 4.791921e-001, + -2.744712e-002, + 9.337925e-001, + -2.902902e-001, + -3.413474e+000, + -1.485380e+000, + -1.301300e+000, + 1.266203e+000, + 3.869657e+000, + -1.405606e-002, + 6.109944e-001, + 3.883967e+000, + 1.540321e+000, + 5.838664e-001, + 2.370098e-001, + 1.420200e+000, + -1.803001e+000, + -6.672775e+000, + 2.866921e-001, + -2.599250e-001, + -4.162164e+000, + 1.296901e-001, + -1.654226e+000, + -3.296843e-001, + 6.245723e-001, + 7.899655e+000, + -1.079857e+000, + 3.145485e-001, + 4.085894e-001, + 2.258895e+000, + 9.071309e-001, + -9.748612e-001, + -2.545963e-001, + 1.374064e+000, + -2.816107e-003, + -2.589259e+000, + -5.960628e-001, + 2.656787e-001, + -1.458520e-001, + 6.529731e-001, + // albedo 1, turbidity 10 + -1.944006e+000, + -9.776516e-001, + -2.425412e-001, + 8.187180e-001, + -6.620102e-001, + 5.676187e-001, + -7.857556e-006, + 1.944153e+000, + 9.001463e-001, + -1.294455e+000, + -7.294996e-001, + -1.718682e-002, + 1.261264e+000, + -1.170104e+000, + -2.029198e-001, + -1.306023e-002, + 1.821821e+000, + -2.533820e-001, + -6.849943e+000, + -2.937611e+000, + -1.107710e+000, + -3.923478e+000, + 5.018293e+000, + 2.040419e+000, + 2.845113e-001, + 2.080902e+000, + 1.460328e+000, + 1.445166e+000, + 1.641979e-001, + 9.591325e-001, + 8.676572e+000, + -1.098801e+001, + -2.274573e+000, + 1.340040e-001, + -1.166380e+000, + 1.014270e-001, + -1.596800e+000, + -4.130457e-001, + 9.250919e-001, + -1.406592e+000, + 2.474727e+000, + 1.748285e+000, + 9.929937e-002, + -6.705073e-001, + 9.210646e-001, + -1.035617e+000, + -3.537996e-001, + 1.073337e+000, + 6.090616e+000, + -3.710420e+000, + -9.390485e-001, + 2.233788e-001, + -3.213961e-004, + 6.545784e-001, +}; + +double datasetRad600[] = +{ + // albedo 0, turbidity 1 + 1.605147e-002, + 1.028116e-002, + 2.949675e-002, + 7.265851e-002, + 4.608279e-002, + 5.069475e-002, + // albedo 0, turbidity 2 + 1.569474e-002, + 1.190744e-002, + 1.996322e-002, + 1.044303e-001, + 3.746120e-002, + 5.764085e-002, + // albedo 0, turbidity 3 + 1.507252e-002, + 1.350309e-002, + 7.291417e-003, + 1.433035e-001, + 3.625213e-002, + 6.291384e-002, + // albedo 0, turbidity 4 + 1.383183e-002, + 1.670171e-002, + -1.576321e-002, + 1.993796e-001, + 3.837478e-002, + 7.063028e-002, + // albedo 0, turbidity 5 + 1.253723e-002, + 2.261520e-002, + -4.847485e-002, + 2.646653e-001, + 2.855366e-002, + 8.568437e-002, + // albedo 0, turbidity 6 + 1.179552e-002, + 2.546904e-002, + -6.503150e-002, + 2.924065e-001, + 3.516626e-002, + 9.101182e-002, + // albedo 0, turbidity 7 + 1.070809e-002, + 3.005971e-002, + -8.793572e-002, + 3.255182e-001, + 4.780714e-002, + 1.014896e-001, + // albedo 0, turbidity 8 + 9.466972e-003, + 3.330913e-002, + -1.028545e-001, + 3.284098e-001, + 9.602966e-002, + 1.103224e-001, + // albedo 0, turbidity 9 + 8.190696e-003, + 3.248675e-002, + -9.882934e-002, + 2.798409e-001, + 1.829752e-001, + 1.263322e-001, + // albedo 0, turbidity 10 + 7.225549e-003, + 2.433471e-002, + -6.029571e-002, + 1.468935e-001, + 3.282492e-001, + 1.441367e-001, + // albedo 1, turbidity 1 + 1.676204e-002, + 1.269480e-002, + 2.674342e-002, + 7.380770e-002, + 1.072658e-001, + 1.211512e-001, + // albedo 1, turbidity 2 + 1.649305e-002, + 1.445974e-002, + 1.662432e-002, + 1.056364e-001, + 1.002831e-001, + 1.317330e-001, + // albedo 1, turbidity 3 + 1.577677e-002, + 1.637005e-002, + 2.821156e-003, + 1.465189e-001, + 9.971575e-002, + 1.424798e-001, + // albedo 1, turbidity 4 + 1.469049e-002, + 1.969668e-002, + -2.105278e-002, + 2.024104e-001, + 1.062768e-001, + 1.557134e-001, + // albedo 1, turbidity 5 + 1.339480e-002, + 2.402713e-002, + -4.671234e-002, + 2.518382e-001, + 1.135974e-001, + 1.711111e-001, + // albedo 1, turbidity 6 + 1.274349e-002, + 2.648472e-002, + -6.068209e-002, + 2.720113e-001, + 1.285128e-001, + 1.776298e-001, + // albedo 1, turbidity 7 + 1.165402e-002, + 2.958682e-002, + -7.746524e-002, + 2.912132e-001, + 1.536569e-001, + 1.896419e-001, + // albedo 1, turbidity 8 + 1.048769e-002, + 3.115400e-002, + -8.550235e-002, + 2.769964e-001, + 2.173505e-001, + 1.991057e-001, + // albedo 1, turbidity 9 + 9.312926e-003, + 2.881725e-002, + -7.387358e-002, + 2.079818e-001, + 3.221838e-001, + 2.120657e-001, + // albedo 1, turbidity 10 + 8.151793e-003, + 1.998414e-002, + -3.316224e-002, + 6.957927e-002, + 4.654511e-001, + 2.260782e-001, +}; + +double dataset640[] = +{ + // albedo 0, turbidity 1 + -1.113346e+000, + -1.715076e-001, + -2.657094e+000, + 4.632520e+000, + -1.092310e-001, + 1.421516e+000, + 3.230348e-003, + 2.697889e+000, + 6.262031e-001, + -1.193355e+000, + -2.074379e-001, + 1.431777e+000, + 8.245570e-001, + -1.936967e-001, + 9.392137e-001, + 1.972523e-002, + 3.001209e+000, + 4.415825e-001, + -9.337792e-001, + -2.037239e-001, + 3.943675e+000, + -2.487730e+000, + -9.876315e-001, + 2.772411e+000, + -4.919462e-002, + -4.176827e+000, + 1.026227e+000, + -1.297623e+000, + -1.296758e-001, + -3.144502e-001, + 2.454199e+000, + 2.433614e+000, + 5.298928e-001, + 7.814939e-002, + 6.564581e+000, + 5.587597e-001, + -9.325270e-001, + -1.997966e-001, + 3.363315e+000, + -1.887198e+000, + -8.905212e+000, + 2.808597e+000, + -9.537165e-002, + -3.059702e+000, + 5.403718e-001, + -1.125650e+000, + -1.904795e-001, + 2.099998e+000, + 1.251930e+000, + -1.899312e+000, + 5.255919e-001, + 9.848260e-002, + 9.627433e-001, + 6.251236e-001, + // albedo 0, turbidity 2 + -1.104956e+000, + -1.372068e-001, + -2.996624e+000, + 4.260021e+000, + -1.263137e-001, + 1.327775e+000, + 7.595887e-002, + 5.301229e+000, + 6.478109e-001, + -1.158426e+000, + -1.921879e-001, + 3.371987e-001, + 8.543727e-001, + -1.195421e-001, + 2.178871e-001, + 1.573997e-001, + 3.059646e+000, + 5.355391e-001, + -1.012076e+000, + -1.456275e-001, + 3.857821e+000, + -1.137640e+000, + -7.400821e-001, + 4.132381e+000, + -2.101470e-001, + -1.704290e-001, + 1.094519e+000, + -1.200085e+000, + -9.008631e-002, + -1.764929e+000, + 4.584027e-001, + 8.033799e-001, + -1.730728e+000, + 5.892683e-001, + 6.438112e+000, + 2.141131e-001, + -9.836248e-001, + -1.983419e-001, + 3.519957e+000, + -9.777763e-001, + -5.727911e+000, + 4.397457e+000, + -2.864495e-001, + -2.511187e+000, + 9.881415e-001, + -1.111842e+000, + -1.992363e-001, + 1.746814e+000, + 5.036170e+000, + -2.993753e+000, + -5.348114e-001, + 2.332738e-001, + 8.970344e-001, + 5.806194e-001, + // albedo 0, turbidity 3 + -1.120087e+000, + -1.577355e-001, + -1.165606e+000, + 1.782016e+000, + -1.771264e-001, + 8.928578e-001, + 1.613110e-001, + 4.975693e+000, + 6.258796e-001, + -1.182069e+000, + -2.047357e-001, + -4.041517e-001, + 1.732659e+000, + -4.322749e-001, + 6.549554e-001, + 5.392767e-002, + 4.838218e+000, + 6.441461e-001, + -1.071518e+000, + -2.057500e-001, + 2.808685e+000, + -1.990080e+000, + -8.491815e-001, + 2.193915e+000, + 2.411077e-001, + -3.251587e+000, + 7.470978e-001, + -1.113379e+000, + -6.708322e-003, + -2.181109e+000, + 2.107674e+000, + 2.216970e+000, + -6.233552e-001, + 3.558080e-001, + 9.251876e+000, + 6.319555e-001, + -1.026698e+000, + -2.260748e-001, + 3.031659e+000, + -1.615765e+000, + -1.323341e+000, + 2.835147e+000, + 1.186568e-001, + -3.366247e+000, + 6.850407e-001, + -1.088223e+000, + -1.817555e-001, + 1.435855e+000, + 1.845164e+000, + -3.488539e+000, + 2.554837e-001, + 2.144895e-001, + 1.558895e+000, + 7.315398e-001, + // albedo 0, turbidity 4 + -1.164089e+000, + -2.003003e-001, + -2.998423e-001, + 2.713689e-001, + -1.828861e-001, + 5.800779e-001, + 1.968402e-001, + 4.650130e+000, + 6.156174e-001, + -1.209796e+000, + -2.733887e-001, + -9.360003e-001, + 2.769100e+000, + -1.870929e+000, + 7.049322e-001, + -8.477045e-002, + 4.120960e+000, + 7.444509e-001, + -1.232839e+000, + -2.622151e-001, + 2.857050e+000, + -2.866256e+000, + 3.128232e+000, + 1.897877e+000, + 4.581244e-001, + -2.112943e+000, + 6.384882e-001, + -9.291113e-001, + 4.110508e-002, + -2.235781e+000, + 2.969741e+000, + -9.758544e+000, + -1.941571e+000, + 3.426656e-001, + 6.907158e+000, + 6.945892e-001, + -1.103614e+000, + -2.279953e-001, + 2.314490e+000, + -6.307971e-001, + 3.369674e+000, + 3.787928e+000, + 2.456513e-001, + -1.776073e+000, + 6.864316e-001, + -1.072160e+000, + -1.984678e-001, + 1.092192e+000, + 8.472734e-001, + -3.126637e+000, + -1.076607e+000, + 3.908469e-001, + 1.205671e+000, + 7.035925e-001, + // albedo 0, turbidity 5 + -1.222416e+000, + -2.654298e-001, + -1.149975e-001, + -6.277756e-003, + -1.369463e+000, + 4.402179e-001, + 1.881320e-001, + 3.896722e+000, + 6.037946e-001, + -1.407746e+000, + -4.603243e-001, + -3.071475e-001, + 2.937390e+000, + -9.164938e-001, + 6.696693e-001, + -6.608327e-002, + 2.444782e+000, + 6.905594e-001, + -1.120454e+000, + -1.466269e-001, + 7.829076e-001, + -7.009271e+000, + 5.364470e+000, + 1.294280e+000, + 4.109552e-001, + 1.525889e+000, + 7.709564e-001, + -9.792886e-001, + -4.325464e-002, + -4.059461e-001, + 1.522559e+001, + -1.867598e+001, + -1.169367e+000, + 3.589556e-001, + 2.368951e+000, + 5.526839e-001, + -1.091118e+000, + -2.286983e-001, + 9.896666e-001, + -6.655971e+000, + 8.168041e+000, + 1.923773e+000, + 3.116805e-001, + 1.852611e-001, + 7.524175e-001, + -1.053081e+000, + -1.598496e-001, + 9.684194e-001, + 3.620674e+000, + -5.015769e+000, + 8.125082e-002, + 4.669502e-001, + 1.415221e+000, + 7.044272e-001, + // albedo 0, turbidity 6 + -1.267172e+000, + -3.101221e-001, + -8.556526e-002, + -3.602153e-003, + -4.988229e+000, + 4.099753e-001, + 1.555248e-001, + 3.585489e+000, + 6.128833e-001, + -1.613116e+000, + -6.560485e-001, + 9.250270e-002, + 2.119268e+000, + 8.031058e+000, + 4.019483e-001, + 4.526662e-002, + 1.362051e+000, + 5.999628e-001, + -1.012405e+000, + -2.251592e-002, + 2.836289e-001, + -7.904006e+000, + -9.544755e+000, + 1.754891e+000, + 1.283266e-001, + 3.042478e+000, + 9.234755e-001, + -1.022835e+000, + -1.361070e-001, + -4.207218e-001, + 1.947050e+001, + -5.511234e+000, + -2.417169e+000, + 7.837822e-001, + 8.288902e-001, + 3.509734e-001, + -1.068370e+000, + -1.806143e-001, + 1.059217e+000, + 7.087518e-001, + -1.671865e+000, + 3.098645e+000, + -9.859822e-002, + 9.336021e-001, + 8.929147e-001, + -1.065467e+000, + -1.928982e-001, + 6.159162e-001, + -4.157538e-003, + -9.397621e-001, + -1.193139e+000, + 6.979501e-001, + 1.118894e+000, + 6.467115e-001, + // albedo 0, turbidity 7 + -1.345697e+000, + -3.906019e-001, + -1.921159e-001, + -7.410201e-003, + -4.683006e+000, + 4.591917e-001, + 1.919817e-001, + 3.158844e+000, + 5.319014e-001, + -2.096314e+000, + -1.056514e+000, + 7.665515e-001, + 1.602483e+000, + 6.290779e+000, + 4.693208e-001, + -6.258855e-002, + -3.745685e-001, + 5.853677e-001, + -7.573573e-001, + 2.265213e-001, + -1.283398e+000, + -4.696984e+000, + -4.261986e+000, + 1.197826e+000, + 3.444468e-001, + 6.004387e+000, + 9.413954e-001, + -1.140929e+000, + -3.489820e-001, + 1.095429e+000, + 7.531589e+000, + -8.153320e+000, + -1.722207e+000, + 4.427477e-001, + -3.072440e+000, + 3.874398e-001, + -1.009003e+000, + -9.087616e-002, + 4.181128e-002, + 1.154023e+001, + -5.092155e-001, + 2.166116e+000, + 1.620893e-001, + 2.824826e+000, + 8.289491e-001, + -1.080842e+000, + -2.166745e-001, + 6.939662e-001, + -2.316636e-003, + -2.616711e+000, + -1.012238e+000, + 6.132021e-001, + 7.579828e-001, + 6.813755e-001, + // albedo 0, turbidity 8 + -1.394668e+000, + -4.508268e-001, + -2.615024e-001, + -7.412740e-003, + -4.811648e+000, + 4.235635e-001, + 1.627041e-001, + 3.134174e+000, + 5.225016e-001, + -2.715734e+000, + -1.409574e+000, + 6.485110e-001, + 6.307101e-001, + 8.120123e+000, + 3.677567e-001, + 6.430919e-002, + -3.729191e-001, + 3.463130e-001, + -8.973624e-001, + 2.859206e-002, + -1.610007e+000, + -1.483136e+000, + -5.613288e+000, + 7.093329e-001, + 2.936945e-001, + 5.541210e+000, + 1.143952e+000, + -8.450858e-001, + -1.969825e-001, + 1.399585e+000, + 1.418708e-001, + -4.532026e+000, + -7.432040e-001, + 3.410858e-001, + -3.386293e+000, + 2.885614e-001, + -1.180533e+000, + -2.469972e-001, + -2.694505e-002, + 1.635998e+001, + -2.378676e+000, + 9.477733e-001, + 1.105776e-001, + 1.954485e+000, + 8.559872e-001, + -1.022908e+000, + -1.650807e-001, + 3.812483e-001, + -2.139201e-003, + -2.300711e+000, + -5.917998e-001, + 6.793527e-001, + 1.248273e+000, + 6.747565e-001, + // albedo 0, turbidity 9 + -1.557922e+000, + -6.294681e-001, + -2.355549e-001, + -8.743568e-003, + -5.017111e+000, + 4.034446e-001, + 1.005643e-001, + 2.735289e+000, + 5.667004e-001, + -3.061673e+000, + -1.398157e+000, + 1.597008e-001, + 1.066059e+000, + 8.207018e+000, + 4.785780e-001, + 4.629487e-002, + 1.324020e+000, + 2.540204e-001, + -2.371583e+000, + -1.100187e+000, + -1.279309e+000, + -3.340819e+000, + -6.556706e+000, + 2.636750e-001, + 4.298705e-001, + 2.649782e+000, + 1.060950e+000, + -5.315727e-002, + 2.306821e-001, + 1.091037e+000, + 5.297610e+000, + -2.412315e+000, + -7.083157e-002, + 7.256586e-002, + -1.330891e+000, + 4.168205e-001, + -1.375983e+000, + -4.677570e-001, + 2.271650e-001, + 8.771601e+000, + -2.511780e+000, + 1.487082e-001, + 8.542210e-002, + 5.509707e-003, + 7.821447e-001, + -1.006483e+000, + -1.435513e-001, + 5.802646e-002, + -3.181899e-003, + -2.010861e+000, + -1.746922e-001, + 7.487809e-001, + 1.623209e+000, + 6.848148e-001, + // albedo 0, turbidity 10 + -1.919035e+000, + -9.396362e-001, + -3.059418e-001, + 1.542398e+000, + -1.488273e+000, + 5.133825e-001, + -7.992185e-006, + 2.276361e+000, + 8.334381e-001, + -2.470138e+000, + -1.108577e+000, + -5.521438e-001, + -9.047033e-001, + 6.905739e-001, + 3.774300e-001, + -2.801883e-002, + 2.413470e+000, + -8.986266e-002, + -5.532450e+000, + -2.346497e+000, + -1.734654e+000, + 1.461689e+000, + 1.765938e+000, + 4.969811e-001, + 6.205943e-001, + 2.112232e+000, + 1.159488e+000, + 4.159150e-001, + -2.306809e-001, + 1.540502e+000, + -1.006923e+000, + -5.275092e+000, + -2.776202e-002, + -1.632884e-001, + -1.467491e+000, + 4.177919e-001, + -1.248112e+000, + -3.080519e-001, + -1.229235e-001, + 8.972757e+000, + -1.532948e+000, + -8.283794e-002, + 1.561573e-001, + 1.856113e-001, + 7.696948e-001, + -1.054499e+000, + -2.660558e-001, + 1.307025e-001, + -2.167883e-003, + -1.531056e+000, + 1.525856e-001, + 5.356892e-001, + 7.181428e-001, + 6.837654e-001, + // albedo 1, turbidity 1 + -1.113347e+000, + -1.715068e-001, + -2.657094e+000, + 4.632520e+000, + -1.092308e-001, + 1.421516e+000, + 3.229759e-003, + 2.697889e+000, + 6.262031e-001, + -1.193355e+000, + -2.074367e-001, + 1.431777e+000, + 8.245569e-001, + -1.936966e-001, + 9.392136e-001, + 1.972263e-002, + 3.001209e+000, + 4.415825e-001, + -9.337795e-001, + -2.037221e-001, + 3.943675e+000, + -2.487730e+000, + -9.876315e-001, + 2.772410e+000, + -4.919872e-002, + -4.176827e+000, + 1.026227e+000, + -1.297624e+000, + -1.296733e-001, + -3.144502e-001, + 2.454199e+000, + 2.433614e+000, + 5.298925e-001, + 7.814503e-002, + 6.564581e+000, + 5.587597e-001, + -9.325285e-001, + -1.997939e-001, + 3.363316e+000, + -1.887198e+000, + -8.905212e+000, + 2.808596e+000, + -9.537523e-002, + -3.059702e+000, + 5.403717e-001, + -1.125653e+000, + -1.904767e-001, + 2.099998e+000, + 1.251930e+000, + -1.899312e+000, + 5.255917e-001, + 9.848033e-002, + 9.627434e-001, + 6.251233e-001, + // albedo 1, turbidity 2 + -1.115892e+000, + -1.571450e-001, + -5.361081e+000, + 6.833528e+000, + -6.891479e-002, + 1.309709e+000, + 6.046362e-002, + 3.972373e+000, + 6.651606e-001, + -1.147479e+000, + -1.855896e-001, + 2.239259e+000, + -5.937930e-001, + -1.005125e-001, + 2.773971e-001, + 1.337105e-001, + 3.136906e+000, + 5.194230e-001, + -1.030450e+000, + -1.533626e-001, + 2.268967e+000, + -4.886576e-001, + -6.336865e-001, + 3.911080e+000, + -1.602643e-001, + 1.513730e-001, + 1.130153e+000, + -1.159297e+000, + -5.818314e-002, + -1.488690e-001, + 1.358829e+000, + 1.208889e+000, + -1.827456e+000, + 4.867277e-001, + 6.185880e+000, + 1.951064e-001, + -1.023581e+000, + -2.517540e-001, + 3.635148e+000, + -2.375150e+000, + -9.409992e+000, + 3.209554e+000, + -3.006489e-001, + -3.235953e+000, + 9.969505e-001, + -1.102864e+000, + -1.644399e-001, + 2.160645e+000, + 5.685422e+000, + -2.867248e+000, + -1.020916e+000, + 2.064591e-001, + 1.192668e+000, + 5.029621e-001, + // albedo 1, turbidity 3 + -1.120417e+000, + -1.543428e-001, + -2.173869e+000, + 2.965267e+000, + -1.062190e-001, + 8.112859e-001, + 1.448682e-001, + 4.993622e+000, + 6.373394e-001, + -1.168618e+000, + -1.948508e-001, + -6.247560e-001, + 2.203402e+000, + -2.724794e-001, + 8.364691e-001, + 5.608377e-002, + 4.262497e+000, + 6.310098e-001, + -1.080229e+000, + -2.282841e-001, + 2.194035e+000, + -1.203336e+000, + -3.861545e-001, + 2.234045e+000, + 1.553866e-001, + -3.266039e+000, + 8.246847e-001, + -1.101698e+000, + 2.182410e-002, + -1.179116e+000, + 8.533844e-001, + 8.777171e-001, + -1.222988e+000, + 5.021882e-001, + 9.364642e+000, + 4.790363e-001, + -1.047144e+000, + -2.539571e-001, + 3.684827e+000, + 9.827861e-002, + -2.297266e-001, + 3.038327e+000, + -2.609445e-001, + -3.685112e+000, + 8.596057e-001, + -1.103227e+000, + -1.861499e-001, + 2.098952e+000, + 1.030900e-001, + -4.268311e+000, + -1.120060e+000, + 2.879792e-001, + 7.160893e-001, + 6.213207e-001, + // albedo 1, turbidity 4 + -1.155288e+000, + -2.006105e-001, + -5.822630e-002, + 3.970794e-001, + -2.828885e-001, + 5.093569e-001, + 1.631119e-001, + 4.152479e+000, + 6.357376e-001, + -1.241627e+000, + -2.673712e-001, + -6.444494e-001, + 2.257014e+000, + -1.630843e+000, + 5.967071e-001, + 9.888683e-003, + 4.308732e+000, + 6.751366e-001, + -1.136812e+000, + -2.811418e-001, + 2.220215e+000, + -1.535870e+000, + 2.354743e+000, + 2.041362e+000, + 2.387976e-001, + -3.453756e+000, + 7.672245e-001, + -1.028322e+000, + 9.134962e-002, + -1.151053e+000, + 6.511620e-001, + -5.683098e+000, + -2.001006e+000, + 6.430642e-001, + 8.523367e+000, + 5.422240e-001, + -1.076830e+000, + -3.101207e-001, + 3.052794e+000, + 3.177593e-001, + 3.054756e+000, + 3.386727e+000, + -2.312489e-001, + -3.908802e+000, + 7.978614e-001, + -1.107083e+000, + -1.880372e-001, + 2.001810e+000, + -3.352202e-003, + -1.526356e+000, + -1.480550e+000, + 3.486524e-001, + 7.220325e-001, + 6.581821e-001, + // albedo 1, turbidity 5 + -1.214879e+000, + -2.719222e-001, + 2.247747e-001, + 1.509740e-002, + -5.438281e-001, + 3.728351e-001, + 1.749880e-001, + 3.132220e+000, + 6.001432e-001, + -1.424202e+000, + -4.768943e-001, + -6.396040e-001, + 2.060101e+000, + -1.113780e+000, + 6.993089e-001, + -2.098291e-002, + 2.504826e+000, + 6.757213e-001, + -1.048548e+000, + -1.173837e-001, + 1.885902e+000, + -3.700301e+000, + 4.667326e+000, + 1.344798e+000, + 2.140261e-001, + 1.525414e-001, + 8.450168e-001, + -1.056271e+000, + -5.272364e-002, + -1.391708e+000, + 9.711492e+000, + -1.742761e+001, + -1.677628e+000, + 6.906304e-001, + 4.107662e+000, + 4.268005e-001, + -1.072328e+000, + -2.450563e-001, + 3.125155e+000, + -2.470389e+000, + 6.794968e+000, + 2.678049e+000, + -2.092059e-001, + -1.651858e+000, + 8.708740e-001, + -1.107628e+000, + -2.089585e-001, + 1.799168e+000, + 4.621596e-001, + -5.008181e+000, + -1.121127e+000, + 3.917217e-001, + 2.703209e-001, + 6.449597e-001, + // albedo 1, turbidity 6 + -1.249741e+000, + -3.073987e-001, + 1.398829e-001, + -2.878563e-003, + -5.008845e+000, + 4.535605e-001, + 1.447766e-001, + 3.091173e+000, + 6.138128e-001, + -1.577209e+000, + -6.213162e-001, + 2.895282e-001, + 1.670732e+000, + 8.708786e+000, + 2.480283e-001, + 7.326386e-002, + 1.395638e+000, + 5.814691e-001, + -1.015394e+000, + -9.306378e-002, + 4.870291e-001, + -6.558243e+000, + -1.073347e+001, + 1.842159e+000, + 2.135043e-002, + 1.655269e+000, + 9.750505e-001, + -1.030222e+000, + -3.712071e-002, + -4.565649e-001, + 1.827249e+001, + -4.505703e+000, + -2.635230e+000, + 9.447498e-001, + 2.450865e+000, + 2.757082e-001, + -1.086063e+000, + -2.709359e-001, + 2.527868e+000, + -1.786375e+000, + -2.329338e+000, + 3.367729e+000, + -4.201670e-001, + -9.372873e-001, + 9.570917e-001, + -1.113156e+000, + -2.162986e-001, + 1.815038e+000, + 1.036606e-001, + -1.106537e+000, + -1.657558e+000, + 4.923976e-001, + -1.768985e-002, + 6.218745e-001, + // albedo 1, turbidity 7 + -1.345662e+000, + -4.038158e-001, + 1.601105e-001, + -6.892546e-003, + -5.010308e+000, + 3.903794e-001, + 1.543535e-001, + 2.538245e+000, + 5.555141e-001, + -1.998866e+000, + -9.786972e-001, + 5.763250e-001, + 1.007104e+000, + 8.983795e+000, + 3.752110e-001, + 7.375525e-002, + 1.792659e-001, + 4.969463e-001, + -7.854213e-001, + 1.186171e-001, + -1.925047e-001, + -3.567464e+000, + -8.901606e+000, + 1.181923e+000, + 4.049067e-002, + 3.603602e+000, + 1.081550e+000, + -1.113558e+000, + -1.964692e-001, + -6.175963e-002, + 7.345047e+000, + -5.293662e+000, + -1.720046e+000, + 8.863695e-001, + -1.699694e-001, + 2.184709e-001, + -1.077319e+000, + -2.429937e-001, + 2.226652e+000, + 8.082352e+000, + -5.647382e-001, + 2.187018e+000, + -3.571678e-001, + -2.370890e-001, + 9.528157e-001, + -1.101702e+000, + -2.020333e-001, + 1.637670e+000, + 5.276716e-001, + -4.006007e+000, + -1.066501e+000, + 4.548015e-001, + 4.055769e-001, + 6.485706e-001, + // albedo 1, turbidity 8 + -1.411469e+000, + -4.870956e-001, + 1.017578e-001, + -8.806763e-003, + -5.014847e+000, + 4.306981e-001, + 1.278033e-001, + 2.361142e+000, + 5.472925e-001, + -2.735007e+000, + -1.453253e+000, + 5.783189e-001, + 5.673243e-001, + 9.968637e+000, + 2.236397e-001, + 1.860109e-001, + -3.781953e-001, + 2.505082e-001, + -7.371503e-001, + 1.290592e-001, + -5.349577e-001, + -1.885854e+000, + -8.623054e+000, + 1.078614e+000, + -5.694996e-002, + 4.526279e+000, + 1.347569e+000, + -9.678370e-001, + -2.562830e-001, + 2.961987e-001, + 2.461144e+000, + -4.753928e+000, + -1.657373e+000, + 8.388825e-001, + -2.440974e+000, + 1.816225e-002, + -1.148918e+000, + -2.271366e-001, + 1.817890e+000, + 1.097345e+001, + -1.126160e+000, + 1.993895e+000, + -2.870862e-001, + 7.269217e-001, + 1.032783e+000, + -1.090291e+000, + -2.315314e-001, + 1.491197e+000, + 9.632479e+000, + -4.323932e+000, + -1.326631e+000, + 3.604933e-001, + 1.905995e-001, + 6.312241e-001, + // albedo 1, turbidity 9 + -1.552618e+000, + -6.336918e-001, + 4.605315e-002, + -8.452985e-003, + -4.979015e+000, + 3.484674e-001, + 8.791637e-002, + 2.297399e+000, + 5.705230e-001, + -2.770597e+000, + -1.302036e+000, + 3.421676e-001, + 1.220769e+000, + 7.584372e+000, + 4.050789e-001, + 4.478808e-002, + 9.435710e-001, + 2.393878e-001, + -2.631791e+000, + -1.247576e+000, + -8.423940e-001, + -3.955998e+000, + -5.341100e+000, + 6.385142e-001, + 3.872948e-001, + 2.279807e+000, + 1.101259e+000, + 1.875824e-001, + 3.564184e-001, + 7.973268e-001, + 7.159160e+000, + -3.857340e+000, + -9.227702e-001, + 8.283793e-002, + -1.444145e+000, + 3.654244e-001, + -1.489693e+000, + -4.947623e-001, + 1.253918e+000, + 3.949282e+000, + -1.320903e+000, + 1.088652e+000, + 1.489763e-001, + -3.855853e-001, + 8.130960e-001, + -1.042349e+000, + -2.134514e-001, + 1.289359e+000, + -3.129206e-003, + -2.385397e+000, + -7.642278e-001, + 3.772293e-001, + 3.683001e-001, + 6.811674e-001, + // albedo 1, turbidity 10 + -1.924886e+000, + -9.354584e-001, + -1.879067e-001, + 1.267892e+000, + -1.174622e+000, + 5.570232e-001, + -1.060836e-005, + 2.002481e+000, + 9.001398e-001, + -1.556107e+000, + -8.200410e-001, + -1.065249e-001, + -3.241942e-001, + 1.552504e-001, + 7.662815e-002, + -2.568474e-002, + 1.738474e+000, + -2.100942e-001, + -7.169297e+000, + -2.972878e+000, + -1.324108e+000, + 7.276378e-003, + 2.638975e+000, + 1.186150e+000, + 5.695709e-001, + 2.027718e+000, + 1.328077e+000, + 1.889259e+000, + 2.600110e-001, + 1.309033e+000, + 1.187864e+000, + -6.905754e+000, + -1.163025e+000, + -1.642758e-001, + -1.774036e+000, + 2.566466e-001, + -1.816439e+000, + -3.601966e-001, + 6.367922e-001, + 6.798160e+000, + -6.431562e-001, + 9.014269e-001, + 2.490693e-001, + -6.685128e-003, + 8.542883e-001, + -9.684886e-001, + -3.866519e-001, + 1.268224e+000, + -4.187273e-003, + -1.833316e+000, + -4.626197e-001, + 2.263859e-001, + -5.583963e-001, + 6.650112e-001, +}; + +double datasetRad640[] = +{ + // albedo 0, turbidity 1 + 1.479989e-002, + 9.575884e-003, + 2.973854e-002, + 4.822245e-002, + 3.622965e-002, + 3.714381e-002, + // albedo 0, turbidity 2 + 1.494233e-002, + 1.021187e-002, + 2.574697e-002, + 7.232352e-002, + 3.290719e-002, + 4.167409e-002, + // albedo 0, turbidity 3 + 1.434641e-002, + 1.147574e-002, + 1.506677e-002, + 1.142492e-001, + 2.532042e-002, + 4.995278e-002, + // albedo 0, turbidity 4 + 1.326292e-002, + 1.444403e-002, + -7.612369e-003, + 1.768500e-001, + 1.846871e-002, + 6.093428e-002, + // albedo 0, turbidity 5 + 1.210064e-002, + 1.800376e-002, + -3.160469e-002, + 2.285807e-001, + 2.227077e-002, + 6.824549e-002, + // albedo 0, turbidity 6 + 1.130890e-002, + 2.150486e-002, + -5.124749e-002, + 2.648020e-001, + 2.123060e-002, + 7.588774e-002, + // albedo 0, turbidity 7 + 1.023130e-002, + 2.633945e-002, + -7.626006e-002, + 3.042057e-001, + 3.007536e-002, + 8.597681e-002, + // albedo 0, turbidity 8 + 8.913856e-003, + 3.088076e-002, + -9.896179e-002, + 3.274618e-001, + 6.060024e-002, + 9.959796e-002, + // albedo 0, turbidity 9 + 7.548425e-003, + 3.088764e-002, + -9.837988e-002, + 2.862874e-001, + 1.450480e-001, + 1.121877e-001, + // albedo 0, turbidity 10 + 6.525594e-003, + 2.429771e-002, + -6.656565e-002, + 1.679199e-001, + 2.792664e-001, + 1.313366e-001, + // albedo 1, turbidity 1 + 1.534297e-002, + 1.199131e-002, + 2.491229e-002, + 5.492441e-002, + 7.679650e-002, + 9.300994e-002, + // albedo 1, turbidity 2 + 1.542409e-002, + 1.237811e-002, + 2.235351e-002, + 7.606092e-002, + 7.888526e-002, + 9.886009e-002, + // albedo 1, turbidity 3 + 1.501351e-002, + 1.379279e-002, + 1.162514e-002, + 1.159528e-001, + 7.784537e-002, + 1.097624e-001, + // albedo 1, turbidity 4 + 1.398757e-002, + 1.622679e-002, + -9.033929e-003, + 1.740587e-001, + 8.042195e-002, + 1.246928e-001, + // albedo 1, turbidity 5 + 1.276036e-002, + 2.055104e-002, + -3.597123e-002, + 2.310287e-001, + 8.109251e-002, + 1.421324e-001, + // albedo 1, turbidity 6 + 1.198617e-002, + 2.326685e-002, + -5.243143e-002, + 2.599544e-001, + 8.840775e-002, + 1.517899e-001, + // albedo 1, turbidity 7 + 1.092344e-002, + 2.669375e-002, + -7.074274e-002, + 2.830300e-001, + 1.143047e-001, + 1.610563e-001, + // albedo 1, turbidity 8 + 9.699402e-003, + 2.953350e-002, + -8.582613e-002, + 2.867195e-001, + 1.638123e-001, + 1.760228e-001, + // albedo 1, turbidity 9 + 8.432894e-003, + 2.784449e-002, + -7.740437e-002, + 2.250221e-001, + 2.667103e-001, + 1.889583e-001, + // albedo 1, turbidity 10 + 7.395069e-003, + 2.031820e-002, + -4.154554e-002, + 9.577204e-002, + 4.084819e-001, + 2.043633e-001, +}; + +double dataset680[] = +{ + // albedo 0, turbidity 1 + -1.112655e+000, + -1.844098e-001, + -3.170582e+000, + 5.334685e+000, + -6.690891e-002, + 1.561122e+000, + -2.792088e-006, + 1.400688e+000, + 6.639418e-001, + -1.138469e+000, + -1.797086e-001, + 1.271179e+000, + 1.158372e+000, + -1.687824e-001, + 1.414051e+000, + 4.258569e-003, + 2.135675e+000, + 5.322718e-001, + -1.026337e+000, + -1.861539e-001, + 2.119648e+000, + -6.753200e-001, + -1.972700e-001, + 2.384659e+000, + -1.304972e-002, + -1.804518e+000, + 1.207802e+000, + -1.198321e+000, + -1.585305e-001, + 1.339219e+000, + 5.796904e-001, + -5.143433e-002, + 1.107455e+000, + 2.551349e-002, + 3.346946e+000, + -3.387602e-002, + -9.935091e-001, + -1.747698e-001, + 2.816779e+000, + -3.496148e-001, + 1.832218e+000, + 2.324658e+000, + -3.408305e-002, + -1.618451e+000, + 1.189512e+000, + -1.092682e+000, + -1.840784e-001, + 2.455887e+000, + 1.441429e-001, + -4.002347e+000, + 1.186375e+000, + 3.634755e-002, + 3.070963e-001, + 5.512501e-001, + // albedo 0, turbidity 2 + -1.104975e+000, + -1.425541e-001, + -1.889148e+000, + 3.408593e+000, + -1.252648e-001, + 1.396095e+000, + 8.358812e-002, + 3.814297e+000, + 6.848154e-001, + -1.131570e+000, + -1.500053e-001, + -1.048539e+000, + 3.133642e+000, + -2.651219e-001, + 1.193999e+000, + 7.013543e-002, + 4.592749e+000, + 6.857750e-001, + -1.030016e+000, + -1.667752e-001, + 6.179600e+000, + -5.163198e+000, + -4.084328e-001, + 2.617798e+000, + 1.966627e-003, + -2.417731e+000, + 8.402310e-001, + -1.167563e+000, + -3.644294e-002, + -4.501893e+000, + 4.471663e+000, + -5.377956e-001, + 4.971351e-002, + 4.621337e-001, + 1.014187e+001, + 4.411276e-001, + -1.018402e+000, + -2.068288e-001, + 4.710566e+000, + -1.425858e+000, + 1.287815e-001, + 3.605281e+000, + -2.164599e-001, + -4.336932e+000, + 9.051639e-001, + -1.078985e+000, + -1.995548e-001, + 1.678948e+000, + 3.074167e-001, + -1.642830e+000, + -1.235470e-001, + 2.735898e-001, + 6.360197e-001, + 5.870665e-001, + // albedo 0, turbidity 3 + -1.132881e+000, + -1.676238e-001, + -1.179974e+000, + 1.902080e+000, + -7.980402e-002, + 8.946611e-001, + 1.939671e-001, + 3.793414e+000, + 6.357246e-001, + -1.138356e+000, + -1.681053e-001, + 1.548320e+000, + -6.001024e-001, + -4.138892e-001, + 2.586807e-001, + 2.126762e-001, + 4.742849e+000, + 5.910253e-001, + -1.093982e+000, + -1.847904e-001, + 1.234133e+000, + -4.707125e-001, + 1.076579e+000, + 3.355751e+000, + 5.394600e-002, + -2.314910e+000, + 8.900752e-001, + -1.117812e+000, + -6.182272e-002, + -4.681118e-001, + 5.075227e+000, + -1.561122e+001, + -2.343845e+000, + 5.618788e-001, + 7.005713e+000, + 4.622191e-001, + -1.013135e+000, + -1.529086e-001, + 1.960772e+000, + -3.022528e+000, + 8.938126e+000, + 4.411437e+000, + 3.156643e-002, + -1.449180e+000, + 8.181914e-001, + -1.087086e+000, + -2.231900e-001, + 1.871061e+000, + 1.830836e+000, + -4.397140e+000, + -5.441402e-001, + 2.728682e-001, + -5.607736e-002, + 6.741811e-001, + // albedo 0, turbidity 4 + -1.176035e+000, + -2.099056e-001, + -8.221907e-001, + 1.520994e+000, + -2.507738e-001, + 9.100863e-001, + 1.507234e-001, + 3.661138e+000, + 6.726424e-001, + -1.140180e+000, + -1.918480e-001, + 2.844393e-001, + -3.842927e-001, + -5.520764e-001, + -1.868484e-001, + 2.247948e-001, + 5.381202e+000, + 6.059726e-001, + -1.282085e+000, + -3.059464e-001, + 1.619956e+000, + -1.362117e+000, + 2.324649e+000, + 3.350678e+000, + 2.102082e-001, + -4.028753e+000, + 8.172091e-001, + -9.092985e-001, + 4.843416e-002, + -1.076741e+000, + 8.143038e+000, + -1.618418e+001, + -3.681285e+000, + 5.217800e-001, + 7.307672e+000, + 5.312006e-001, + -1.110248e+000, + -2.047143e-001, + 1.565253e+000, + -4.575474e+000, + 8.737741e+000, + 5.023419e+000, + 2.469230e-001, + -1.716906e+000, + 7.856742e-001, + -1.054900e+000, + -2.018466e-001, + 1.352034e+000, + 2.656066e+000, + -4.403444e+000, + -1.479998e+000, + 3.939305e-001, + 6.455032e-001, + 6.775162e-001, + // albedo 0, turbidity 5 + -1.237521e+000, + -2.734963e-001, + -4.554763e-001, + 3.417711e-001, + 2.054204e-001, + 3.954470e-001, + 2.366979e-001, + 3.239693e+000, + 6.083737e-001, + -1.354583e+000, + -4.251172e-001, + -3.241668e-001, + 2.077967e+000, + -1.910410e+000, + 8.755633e-001, + -8.365829e-002, + 2.443727e+000, + 7.260119e-001, + -1.152500e+000, + -1.277879e-001, + 1.089367e+000, + -4.497520e+000, + 5.636501e+000, + 1.249272e+000, + 5.829396e-001, + 9.198423e-001, + 7.039872e-001, + -9.782313e-001, + -8.253891e-002, + -5.673470e-001, + 1.098032e+001, + -1.689550e+001, + -1.619205e+000, + 2.125660e-001, + 2.080566e+000, + 6.315535e-001, + -1.064286e+000, + -1.710957e-001, + 9.336921e-001, + -5.525059e+000, + 8.053084e+000, + 2.664602e+000, + 4.815015e-001, + 4.884965e-001, + 7.093015e-001, + -1.067798e+000, + -1.817268e-001, + 1.095720e+000, + 3.551145e+000, + -5.009504e+000, + -4.802047e-001, + 4.854159e-001, + 8.021585e-001, + 7.133339e-001, + // albedo 0, turbidity 6 + -1.251896e+000, + -2.936510e-001, + -3.090944e-002, + -5.488869e-003, + -6.577788e-001, + 4.577691e-001, + 1.780002e-001, + 3.335561e+000, + 6.394482e-001, + -1.615603e+000, + -6.405318e-001, + -4.651954e-001, + 2.332689e+000, + -1.893131e-001, + 3.391170e-001, + 3.495888e-002, + 1.058634e+000, + 6.310524e-001, + -9.703572e-001, + 1.437971e-002, + 6.532383e-001, + -6.450045e+000, + 4.026380e+000, + 2.198628e+000, + 2.684967e-001, + 2.873804e+000, + 8.626816e-001, + -1.053437e+000, + -1.577255e-001, + -2.354526e-001, + 1.753047e+001, + -1.802766e+001, + -3.193379e+000, + 6.264380e-001, + 3.733714e-001, + 4.466776e-001, + -1.051388e+000, + -1.690749e-001, + 6.925698e-001, + -7.450365e+000, + 7.747780e+000, + 3.681960e+000, + 1.688173e-001, + 9.054528e-001, + 8.229209e-001, + -1.060369e+000, + -1.751603e-001, + 8.678290e-001, + 5.136962e+000, + -5.014566e+000, + -1.283438e+000, + 6.547844e-001, + 9.420523e-001, + 6.738511e-001, + // albedo 0, turbidity 7 + -1.358251e+000, + -3.909003e-001, + -7.590093e-002, + -8.010253e-003, + -2.417641e-001, + 5.031789e-001, + 1.882499e-001, + 2.807060e+000, + 5.884485e-001, + -2.043506e+000, + -9.923881e-001, + -4.530797e-001, + 1.750575e+000, + -4.362236e-001, + 2.997323e-001, + 2.328504e-002, + 1.626543e-001, + 5.806819e-001, + -7.280672e-001, + 2.228069e-001, + 2.169765e-001, + -3.681736e+000, + 4.308793e+000, + 1.308622e+000, + 3.451835e-001, + 4.037459e+000, + 9.113772e-001, + -1.155299e+000, + -3.079453e-001, + -1.640569e-001, + 7.663297e+000, + -1.327817e+001, + -1.431157e+000, + 4.096359e-001, + -9.185502e-001, + 4.578034e-001, + -1.006427e+000, + -1.250087e-001, + 7.477012e-001, + 2.612704e+000, + 2.531799e+000, + 1.565371e+000, + 3.452604e-001, + 9.129266e-001, + 7.684386e-001, + -1.068759e+000, + -1.729191e-001, + 5.265652e-001, + 7.074812e+000, + -4.259958e+000, + -4.833255e-001, + 6.043380e-001, + 1.489203e+000, + 7.089074e-001, + // albedo 0, turbidity 8 + -1.398983e+000, + -4.500153e-001, + -5.189309e-001, + 1.546325e-001, + 4.187327e-001, + 2.811516e-001, + 2.379667e-001, + 2.801040e+000, + 5.198375e-001, + -2.970455e+000, + -1.529948e+000, + 1.094532e-001, + 7.382263e-001, + -1.024683e+000, + 2.074091e-001, + 1.397605e-001, + -6.743828e-001, + 3.496944e-001, + -3.942086e-001, + 3.424842e-001, + -1.253259e+000, + -9.268654e-001, + 5.636065e+000, + 8.224289e-001, + 2.452235e-001, + 5.864258e+000, + 1.202820e+000, + -1.181174e+000, + -4.197175e-001, + 1.429102e+000, + -7.894317e-003, + -1.239152e+001, + -5.753431e-001, + 3.552180e-001, + -4.495555e+000, + 2.141883e-001, + -1.060281e+000, + -1.080598e-001, + -3.276480e-001, + 1.369250e+001, + 1.504389e+000, + 6.401191e-001, + 2.437501e-001, + 3.212918e+000, + 9.172133e-001, + -1.037564e+000, + -2.018083e-001, + 6.250668e-001, + -2.525843e-003, + -3.269998e+000, + -2.649814e-001, + 6.600589e-001, + 3.337508e-001, + 6.516131e-001, + // albedo 0, turbidity 9 + -1.610481e+000, + -6.353902e-001, + -5.968977e-001, + 1.414037e+000, + -7.941453e-001, + 7.888684e-001, + 2.209045e-002, + 2.615106e+000, + 6.870260e-001, + -3.073343e+000, + -1.365905e+000, + -2.651943e-001, + -1.685310e+000, + 4.755874e-001, + -1.110669e-001, + 2.561961e-001, + 1.222045e+000, + 3.362780e-002, + -2.207768e+000, + -1.009608e+000, + -1.329601e+000, + 3.393091e+000, + 3.419104e+000, + -4.733375e-002, + 5.989185e-001, + 2.814641e+000, + 1.245189e+000, + -1.981173e-002, + 2.018414e-001, + 1.457765e+000, + -6.316169e+000, + -6.640569e+000, + 7.150646e-001, + -2.993748e-001, + -2.703376e+000, + 3.218596e-001, + -1.435873e+000, + -3.390505e-001, + -3.859047e-001, + 1.457464e+001, + -1.121591e+000, + -6.089868e-002, + 5.319220e-001, + 1.852395e+000, + 8.379521e-001, + -9.812568e-001, + -2.273751e-001, + 5.108069e-001, + -3.735693e-003, + -2.547988e+000, + -4.492561e-001, + 5.069199e-001, + 2.977910e-001, + 6.639273e-001, + // albedo 0, turbidity 10 + -2.056405e+000, + -9.703512e-001, + -3.731953e-001, + 2.052022e+000, + -1.445283e+000, + 6.103743e-001, + -9.389644e-006, + 2.198652e+000, + 8.567335e-001, + -2.105651e+000, + -8.924283e-001, + -6.868702e-001, + -1.665838e+000, + 4.795702e-001, + 5.228080e-001, + -4.272483e-002, + 2.661317e+000, + -1.154062e-001, + -6.179767e+000, + -2.651580e+000, + -1.527652e+000, + 2.692054e+000, + 2.293427e+000, + -1.005611e-001, + 9.545323e-001, + 1.367438e+000, + 1.169193e+000, + 1.240848e+000, + 1.126706e-001, + 1.620422e+000, + -3.384604e+000, + -5.545532e+000, + 4.928203e-001, + -5.999585e-001, + -1.407078e+000, + 4.193816e-001, + -1.539149e+000, + -2.081890e-001, + -4.552234e-001, + 1.056410e+001, + -1.048637e+000, + -2.780921e-001, + 5.682296e-001, + 6.785092e-001, + 7.729892e-001, + -1.036841e+000, + -4.359099e-001, + 4.767834e-001, + -3.794262e-003, + -1.980492e+000, + 9.954067e-002, + 3.037557e-001, + 2.156592e-002, + 6.845201e-001, + // albedo 1, turbidity 1 + -1.110980e+000, + -1.799491e-001, + -3.168600e+000, + 5.336662e+000, + -6.318131e-002, + 1.559251e+000, + 3.204341e-003, + 1.401140e+000, + 6.638144e-001, + -1.132332e+000, + -1.786787e-001, + 1.272954e+000, + 1.160211e+000, + -1.685885e-001, + 1.409550e+000, + 7.140682e-003, + 2.136473e+000, + 5.320908e-001, + -1.015776e+000, + -1.825058e-001, + 2.122848e+000, + -6.725506e-001, + -1.976294e-001, + 2.376807e+000, + -1.859856e-002, + -1.803033e+000, + 1.207528e+000, + -1.189845e+000, + -1.509036e-001, + 1.345709e+000, + 5.832609e-001, + -5.130839e-002, + 1.097035e+000, + 2.686911e-002, + 3.349361e+000, + -3.431297e-002, + -1.000281e+000, + -1.696328e-001, + 2.829408e+000, + -3.466041e-001, + 1.832532e+000, + 2.314637e+000, + -2.721994e-002, + -1.614939e+000, + 1.188720e+000, + -1.120411e+000, + -1.974172e-001, + 2.474172e+000, + 1.453506e-001, + -4.002206e+000, + 1.180333e+000, + 2.229171e-002, + 3.112615e-001, + 5.505539e-001, + // albedo 1, turbidity 2 + -1.112667e+000, + -1.574855e-001, + -2.284814e+000, + 4.255050e+000, + -1.386097e-001, + 1.459506e+000, + 4.508931e-002, + 2.944474e+000, + 7.339984e-001, + -1.113577e+000, + -1.331062e-001, + -1.828757e+000, + 3.910596e+000, + -2.095519e-001, + 1.159335e+000, + 9.311608e-002, + 4.517295e+000, + 6.365313e-001, + -1.061651e+000, + -2.007134e-001, + 5.907472e+000, + -4.808769e+000, + -2.120206e-001, + 2.727568e+000, + -4.222666e-002, + -2.599674e+000, + 9.265659e-001, + -1.136633e+000, + -4.281875e-003, + -3.407541e+000, + 4.132332e+000, + -3.866153e-001, + -5.082717e-001, + 4.828348e-001, + 9.797167e+000, + 3.325034e-001, + -1.027909e+000, + -2.334388e-001, + 4.972147e+000, + -1.499736e+000, + 9.598438e-002, + 2.744895e+000, + -3.558702e-001, + -4.288054e+000, + 1.000138e+000, + -1.102843e+000, + -1.875642e-001, + 2.087760e+000, + 3.692600e-001, + -6.520835e-001, + -9.598766e-001, + 2.984231e-001, + 4.045786e-001, + 5.091931e-001, + // albedo 1, turbidity 3 + -1.117485e+000, + -1.492968e-001, + -2.639425e+000, + 3.672106e+000, + -1.058342e-001, + 1.098101e+000, + 1.544782e-001, + 4.496691e+000, + 6.582312e-001, + -1.123872e+000, + -1.467158e-001, + 3.049045e+000, + -2.607634e+000, + -2.505495e-001, + -8.310458e-002, + 3.333822e-001, + 4.631418e+000, + 5.120491e-001, + -1.118262e+000, + -2.462050e-001, + -8.333919e-002, + 2.438788e+000, + 6.143236e-001, + 3.745903e+000, + -2.043295e-001, + -3.451983e+000, + 1.056003e+000, + -1.095394e+000, + 2.009680e-002, + 8.468659e-001, + 1.230624e-002, + -8.638525e+000, + -2.989487e+000, + 8.735734e-001, + 8.533740e+000, + 2.548062e-001, + -1.035035e+000, + -2.296018e-001, + 2.722309e+000, + 1.849369e-001, + 3.440975e+000, + 4.372083e+000, + -4.747494e-001, + -2.984092e+000, + 1.009737e+000, + -1.113497e+000, + -1.931400e-001, + 2.288509e+000, + 4.973129e-002, + -1.353292e-001, + -1.587772e+000, + 4.073801e-001, + -8.180513e-003, + 5.682569e-001, + // albedo 1, turbidity 4 + -1.172242e+000, + -2.084847e-001, + -1.212027e+000, + 1.991627e+000, + -1.403495e-001, + 7.684996e-001, + 1.582914e-001, + 3.407597e+000, + 6.659386e-001, + -1.167834e+000, + -2.117291e-001, + 1.196578e+000, + -1.438719e+000, + -3.137939e-001, + -4.537552e-002, + 2.260096e-001, + 4.659389e+000, + 5.776369e-001, + -1.222298e+000, + -2.893306e-001, + 9.080116e-001, + 1.413518e+000, + 1.709237e+000, + 2.915962e+000, + 8.464584e-002, + -3.867076e+000, + 9.110543e-001, + -9.554071e-001, + 6.610246e-002, + -3.323811e-001, + 2.702543e+000, + -1.345592e+001, + -3.119309e+000, + 7.740473e-001, + 7.452516e+000, + 3.929172e-001, + -1.119763e+000, + -2.579942e-001, + 2.830634e+000, + -1.333418e+000, + 6.825773e+000, + 4.230596e+000, + -2.654108e-001, + -2.669457e+000, + 9.126183e-001, + -1.084261e+000, + -2.086570e-001, + 2.248616e+000, + 6.993871e-001, + -2.391760e+000, + -1.738827e+000, + 3.674794e-001, + -5.324741e-001, + 6.183292e-001, + // albedo 1, turbidity 5 + -1.226325e+000, + -2.688667e-001, + -1.462040e-001, + 4.749868e-001, + -8.718681e-002, + 4.956704e-001, + 1.752427e-001, + 2.933911e+000, + 6.470198e-001, + -1.359737e+000, + -3.985716e-001, + -1.570034e-001, + 1.277905e+000, + -1.314322e+000, + 4.320873e-001, + 8.532731e-002, + 2.774395e+000, + 6.318556e-001, + -1.088212e+000, + -1.688766e-001, + 1.399098e+000, + -3.254950e+000, + 4.733557e+000, + 2.079183e+000, + 1.907990e-001, + -9.540048e-001, + 8.714774e-001, + -1.034524e+000, + -1.050729e-002, + -8.054376e-001, + 1.166351e+001, + -1.879498e+001, + -3.021428e+000, + 7.755251e-001, + 4.516574e+000, + 4.092690e-001, + -1.076150e+000, + -2.551781e-001, + 2.797790e+000, + -5.437950e+000, + 9.156159e+000, + 3.988462e+000, + -2.324172e-001, + -2.124766e+000, + 8.863276e-001, + -1.103432e+000, + -2.058047e-001, + 2.117130e+000, + 2.401558e+000, + -5.015370e+000, + -1.829480e+000, + 4.046378e-001, + -2.078794e-001, + 6.449045e-001, + // albedo 1, turbidity 6 + -1.263516e+000, + -3.133966e-001, + 3.174560e-001, + -4.989246e-003, + -2.317630e+000, + 3.963746e-001, + 1.677262e-001, + 2.563898e+000, + 6.335899e-001, + -1.577927e+000, + -5.893907e-001, + -2.991531e-001, + 1.783728e+000, + 3.693827e+000, + 5.704918e-001, + 6.768069e-002, + 2.215180e+000, + 6.196162e-001, + -9.191335e-001, + -4.529201e-002, + 1.577262e+000, + -6.455191e+000, + -4.020064e+000, + 1.309911e+000, + 1.373281e-001, + -7.178508e-001, + 9.243738e-001, + -1.144508e+000, + -9.289247e-002, + -1.606387e+000, + 2.061805e+001, + -1.051527e+001, + -2.077164e+000, + 8.328239e-001, + 4.729795e+000, + 3.298487e-001, + -1.018834e+000, + -2.186851e-001, + 3.321767e+000, + -7.887012e+000, + 3.374834e+000, + 3.005232e+000, + -2.515037e-001, + -2.656610e+000, + 9.316017e-001, + -1.125230e+000, + -2.422532e-001, + 1.850916e+000, + 6.213105e+000, + -5.017914e+000, + -1.644457e+000, + 3.811828e-001, + -1.772362e-001, + 6.297360e-001, + // albedo 1, turbidity 7 + -1.365631e+000, + -4.017085e-001, + 1.942501e-001, + -7.073927e-003, + -1.461125e-001, + 4.898017e-001, + 1.623346e-001, + 2.330174e+000, + 5.983242e-001, + -1.957177e+000, + -9.640834e-001, + -2.217521e-001, + 1.316645e+000, + -1.907085e-001, + 1.134191e-002, + 9.704476e-002, + 3.828565e-002, + 5.538419e-001, + -7.832629e-001, + 1.949904e-001, + 6.232354e-001, + -2.947737e+000, + 3.702377e+000, + 2.212239e+000, + 9.128296e-002, + 3.131504e+000, + 9.923939e-001, + -1.121562e+000, + -2.704893e-001, + -5.161748e-001, + 8.115427e+000, + -1.443497e+001, + -3.292676e+000, + 8.232212e-001, + -1.548451e-002, + 3.199244e-001, + -1.059207e+000, + -1.613941e-001, + 2.375866e+000, + -9.517705e-002, + 4.514722e+000, + 3.755824e+000, + -1.696953e-001, + -2.539157e-001, + 8.992553e-001, + -1.108877e+000, + -2.404852e-001, + 1.830175e+000, + 2.808956e+000, + -4.932362e+000, + -2.042775e+000, + 4.168739e-001, + -2.534590e-001, + 6.533212e-001, + // albedo 1, turbidity 8 + -1.405398e+000, + -4.540068e-001, + -4.766512e-001, + 1.871207e-001, + 5.535070e-001, + -4.467365e-002, + 2.846366e-001, + 2.443422e+000, + 5.035706e-001, + -2.843953e+000, + -1.562366e+000, + 8.527921e-001, + 5.991182e-001, + -9.984088e-001, + 7.599314e-001, + -2.025184e-002, + -1.515050e+000, + 4.397429e-001, + -5.156586e-001, + 3.789775e-001, + -1.194407e+000, + -7.591558e-001, + 4.515532e+000, + 4.795814e-001, + 3.163186e-001, + 5.993132e+000, + 1.096327e+000, + -1.070353e+000, + -4.037269e-001, + 1.108932e+000, + 1.269159e+000, + -1.099135e+001, + -1.049849e+000, + 4.644725e-001, + -4.387074e+000, + 2.704008e-001, + -1.136211e+000, + -1.473182e-001, + 1.235769e+000, + 5.725364e+000, + 1.712036e+000, + 1.630777e+000, + 3.656685e-002, + 2.082798e+000, + 9.036801e-001, + -1.083101e+000, + -2.468910e-001, + 1.894919e+000, + 6.574012e+000, + -4.949098e+000, + -1.132033e+000, + 3.336584e-001, + -7.321133e-001, + 6.606587e-001, + // albedo 1, turbidity 9 + -1.609910e+000, + -6.550380e-001, + -5.773346e-001, + 1.426156e+000, + -5.000686e-001, + 8.257866e-001, + 1.839148e-002, + 2.106656e+000, + 6.957214e-001, + -3.047283e+000, + -1.421592e+000, + -4.003615e-001, + -6.531692e-001, + 5.643821e-001, + -2.693762e-001, + 2.295553e-001, + 5.533910e-001, + 2.751822e-002, + -2.160824e+000, + -9.212504e-001, + -8.438420e-001, + 1.466021e+000, + 1.124686e+000, + -6.848173e-002, + 6.224893e-001, + 3.137662e+000, + 1.224147e+000, + 1.444817e-002, + 1.418426e-001, + 7.055176e-001, + -1.787432e+000, + -1.625625e+000, + 7.638401e-001, + -3.309940e-001, + -3.414755e+000, + 3.580691e-001, + -1.480512e+000, + -3.141638e-001, + 1.193403e+000, + 6.152773e+000, + -3.314867e+000, + 1.345353e-001, + 5.359935e-001, + 1.409582e+000, + 8.072343e-001, + -1.016066e+000, + -2.346375e-001, + 1.457587e+000, + -2.761458e-003, + -2.546952e+000, + -6.058542e-001, + 3.134230e-001, + -2.232281e-001, + 6.760089e-001, + // albedo 1, turbidity 10 + -2.019395e+000, + -9.550942e-001, + -1.187885e-001, + 1.995372e+000, + -1.604228e+000, + 4.995785e-001, + -9.647137e-006, + 1.929333e+000, + 8.659254e-001, + -2.071307e+000, + -9.485438e-001, + -3.817151e-001, + -1.657017e+000, + 9.488626e-001, + 5.816145e-001, + -3.856514e-002, + 1.677756e+000, + -1.262572e-001, + -6.388445e+000, + -2.738739e+000, + -9.872469e-001, + 2.450058e+000, + 1.075999e+000, + 2.305434e-002, + 8.598771e-001, + 1.853582e+000, + 1.180017e+000, + 1.742851e+000, + 2.950102e-001, + 1.015937e+000, + -2.511194e+000, + -3.829361e+000, + -1.126698e-001, + -4.564605e-001, + -2.097128e+000, + 4.012648e-001, + -1.845177e+000, + -3.242819e-001, + 7.060963e-001, + 7.747868e+000, + -1.721532e+000, + 6.057347e-001, + 4.266212e-001, + 3.153697e-001, + 7.958222e-001, + -9.599955e-001, + -3.732025e-001, + 1.381129e+000, + -3.983023e-003, + -1.941446e+000, + -5.943490e-001, + 2.269207e-001, + -7.249738e-001, + 6.710888e-001, +}; + +double datasetRad680[] = +{ + // albedo 0, turbidity 1 + 1.320908e-002, + 9.179272e-003, + 2.540842e-002, + 3.413687e-002, + 2.736575e-002, + 2.799241e-002, + // albedo 0, turbidity 2 + 1.364418e-002, + 9.639315e-003, + 2.455688e-002, + 5.468867e-002, + 2.423200e-002, + 3.240293e-002, + // albedo 0, turbidity 3 + 1.356642e-002, + 9.864007e-003, + 2.017166e-002, + 8.738638e-002, + 2.138981e-002, + 3.828822e-002, + // albedo 0, turbidity 4 + 1.274664e-002, + 1.046958e-002, + 7.076299e-003, + 1.378101e-001, + 2.058352e-002, + 4.607358e-002, + // albedo 0, turbidity 5 + 1.151617e-002, + 1.429568e-002, + -1.804673e-002, + 1.974118e-001, + 1.313176e-002, + 5.733295e-002, + // albedo 0, turbidity 6 + 1.089311e-002, + 1.719127e-002, + -3.582843e-002, + 2.315641e-001, + 1.402940e-002, + 6.289477e-002, + // albedo 0, turbidity 7 + 9.705879e-003, + 2.218462e-002, + -6.221073e-002, + 2.771148e-001, + 1.651339e-002, + 7.346287e-002, + // albedo 0, turbidity 8 + 8.356372e-003, + 2.724501e-002, + -8.836051e-002, + 3.099528e-001, + 4.114206e-002, + 8.518889e-002, + // albedo 0, turbidity 9 + 7.026434e-003, + 2.944084e-002, + -9.824183e-002, + 2.940735e-001, + 1.048477e-001, + 1.012199e-001, + // albedo 0, turbidity 10 + 5.935885e-003, + 2.429070e-002, + -7.239967e-002, + 1.895904e-001, + 2.306596e-001, + 1.177261e-001, + // albedo 1, turbidity 1 + 1.370741e-002, + 1.011873e-002, + 2.499587e-002, + 3.362880e-002, + 6.416750e-002, + 6.673258e-002, + // albedo 1, turbidity 2 + 1.417558e-002, + 1.065771e-002, + 2.402602e-002, + 5.330606e-002, + 6.505571e-002, + 7.324558e-002, + // albedo 1, turbidity 3 + 1.406012e-002, + 1.182138e-002, + 1.636956e-002, + 9.161153e-002, + 6.031840e-002, + 8.638638e-002, + // albedo 1, turbidity 4 + 1.321071e-002, + 1.310944e-002, + 1.017467e-003, + 1.450040e-001, + 6.291618e-002, + 1.003625e-001, + // albedo 1, turbidity 5 + 1.194910e-002, + 1.687076e-002, + -2.332212e-002, + 2.021394e-001, + 6.093196e-002, + 1.177929e-001, + // albedo 1, turbidity 6 + 1.126778e-002, + 1.905450e-002, + -3.804088e-002, + 2.298767e-001, + 7.038318e-002, + 1.240367e-001, + // albedo 1, turbidity 7 + 1.025282e-002, + 2.337214e-002, + -6.236283e-002, + 2.708195e-001, + 7.801793e-002, + 1.406577e-001, + // albedo 1, turbidity 8 + 9.018216e-003, + 2.718840e-002, + -8.215497e-002, + 2.866465e-001, + 1.194106e-001, + 1.556975e-001, + // albedo 1, turbidity 9 + 7.747698e-003, + 2.701679e-002, + -8.076599e-002, + 2.419548e-001, + 2.126954e-001, + 1.683085e-001, + // albedo 1, turbidity 10 + 6.701188e-003, + 2.085440e-002, + -5.068221e-002, + 1.256935e-001, + 3.480598e-001, + 1.851691e-001, +}; + +double dataset720[] = +{ + // albedo 0, turbidity 1 + -1.110553e+000, + -1.675726e-001, + -2.349324e-001, + 2.433790e+000, + -1.342878e-001, + 1.755516e+000, + -1.879493e-006, + 1.509217e+000, + 7.216495e-001, + -1.149960e+000, + -2.418229e-001, + 2.341927e+000, + 1.486508e-001, + -4.333388e-001, + 9.028740e-001, + 9.450710e-003, + -3.134790e-001, + 5.923234e-001, + -9.702430e-001, + -5.384657e-002, + 3.025898e+000, + -6.450284e-001, + 9.728166e-001, + 3.532967e+000, + -2.429753e-002, + 1.343614e+000, + 1.067807e+000, + -1.278773e+000, + -2.072018e-001, + -2.458359e-001, + 3.749133e-001, + -9.580484e+000, + 3.066020e-001, + 4.056471e-002, + 4.343208e+000, + 1.865704e-001, + -9.511618e-001, + -1.674143e-001, + 4.195842e+000, + -1.205785e-001, + 2.160133e+000, + 3.048813e+000, + -4.826924e-002, + -3.779096e+000, + 1.024834e+000, + -1.095577e+000, + -1.855865e-001, + 1.973593e+000, + 7.894097e-002, + 9.578182e-001, + 8.565674e-001, + 4.663966e-002, + 7.375811e-001, + 5.577192e-001, + // albedo 0, turbidity 2 + -1.099352e+000, + -1.338612e-001, + -8.419373e-001, + 2.710346e+000, + -2.241044e-001, + 1.645463e+000, + 7.621625e-002, + 3.548772e+000, + 7.268231e-001, + -1.140694e+000, + -1.723890e-001, + 1.413194e+000, + 3.429051e-001, + -4.431396e-001, + 9.757402e-001, + 1.248306e-001, + 1.780103e+000, + 6.637254e-001, + -9.861499e-001, + -8.032931e-002, + 2.396682e+000, + 7.281382e-001, + 1.472495e-001, + 3.316479e+000, + -1.028439e-001, + 3.729469e+000, + 9.059004e-001, + -1.233397e+000, + -9.896833e-002, + -1.679568e+000, + 1.542653e+000, + -9.977726e+000, + -6.579124e-001, + 6.386315e-001, + 6.157752e+000, + 3.985939e-001, + -9.438092e-001, + -1.629239e-001, + 4.213446e+000, + -3.419684e-001, + 2.110121e+000, + 3.552183e+000, + -2.817116e-001, + -3.323718e+000, + 8.785077e-001, + -1.120794e+000, + -2.121477e-001, + 1.326767e+000, + 2.317528e-001, + 5.648291e-001, + 4.155089e-001, + 3.048162e-001, + 3.186797e-001, + 6.285665e-001, + // albedo 0, turbidity 3 + -1.117191e+000, + -1.510453e-001, + -3.511136e-001, + 1.706946e+000, + -3.820460e-001, + 1.228101e+000, + 1.641555e-001, + 3.663544e+000, + 6.846104e-001, + -1.130950e+000, + -1.622534e-001, + 1.197076e+000, + -1.342532e+000, + 6.608991e-002, + -1.955817e-001, + 3.515286e-001, + 3.237403e+000, + 5.732364e-001, + -1.103903e+000, + -1.810472e-001, + 1.254237e+000, + 3.367565e+000, + -1.746589e+000, + 4.464939e+000, + -2.831757e-001, + -2.424241e-001, + 9.961252e-001, + -1.107818e+000, + -2.407723e-002, + -7.518594e-001, + 7.115830e+000, + -1.603375e+001, + -4.077248e+000, + 1.210904e+000, + 6.281392e+000, + 2.496837e-001, + -1.012153e+000, + -1.911658e-001, + 2.357463e+000, + -2.392720e+000, + 7.080581e+000, + 6.002768e+000, + -5.120158e-001, + -2.039879e+000, + 1.008071e+000, + -1.083766e+000, + -1.889743e-001, + 1.669813e+000, + 1.205140e+000, + -2.973102e+000, + -1.420288e+000, + 5.838643e-001, + 1.338574e-001, + 5.902153e-001, + // albedo 0, turbidity 4 + -1.176390e+000, + -2.045914e-001, + -1.035177e+000, + 1.521425e+000, + -9.698257e-002, + 7.561111e-001, + 2.338582e-001, + 3.264500e+000, + 6.520267e-001, + -1.132876e+000, + -1.921539e-001, + 9.661015e-001, + -2.470184e-001, + -5.825797e-001, + 5.044517e-001, + 1.418233e-001, + 4.416172e+000, + 6.580570e-001, + -1.296062e+000, + -2.855719e-001, + 1.143329e+000, + -1.640682e+000, + 1.921828e+000, + 1.625086e+000, + 5.248871e-001, + -3.757434e+000, + 7.293814e-001, + -9.026255e-001, + 2.670242e-002, + -8.632572e-001, + 7.076787e+000, + -1.407525e+001, + -1.251814e+000, + 1.806495e-001, + 6.575978e+000, + 6.367149e-001, + -1.103623e+000, + -1.818983e-001, + 1.490037e+000, + -3.276017e+000, + 6.936153e+000, + 2.689183e+000, + 5.705211e-001, + -1.354153e+000, + 7.095230e-001, + -1.049370e+000, + -1.854814e-001, + 1.385509e+000, + 1.714977e+000, + -3.205204e+000, + -1.161420e-001, + 3.453320e-001, + 4.355508e-001, + 7.115006e-001, + // albedo 0, turbidity 5 + -1.225291e+000, + -2.574996e-001, + -4.766919e-001, + 4.951357e-001, + 5.242961e-002, + 4.702062e-001, + 2.428653e-001, + 3.095075e+000, + 6.424221e-001, + -1.318856e+000, + -3.713082e-001, + -4.987985e-001, + 2.026237e+000, + -1.457426e+000, + 7.809557e-001, + 1.419197e-003, + 2.776845e+000, + 7.058454e-001, + -1.168038e+000, + -1.572586e-001, + 1.786834e+000, + -4.594005e+000, + 4.780600e+000, + 1.639416e+000, + 5.324063e-001, + -1.000719e+000, + 7.325083e-001, + -9.862998e-001, + -7.482649e-002, + -1.332445e+000, + 1.329260e+001, + -1.803019e+001, + -2.669936e+000, + 3.591475e-001, + 3.852972e+000, + 5.714399e-001, + -1.049025e+000, + -1.404280e-001, + 1.342894e+000, + -5.633938e+000, + 8.396123e+000, + 3.809869e+000, + 4.313231e-001, + -5.373938e-001, + 7.693298e-001, + -1.069033e+000, + -2.091865e-001, + 1.088280e+000, + 3.125506e+000, + -4.664580e+000, + -1.191484e+000, + 5.195344e-001, + 3.961673e-001, + 6.817393e-001, + // albedo 0, turbidity 6 + -1.267895e+000, + -3.004228e-001, + -5.149611e-001, + 4.302967e-001, + 1.504018e-001, + 3.700643e-001, + 2.354209e-001, + 2.887788e+000, + 6.298388e-001, + -1.551925e+000, + -5.917820e-001, + -5.915642e-001, + 2.016019e+000, + -1.252286e+000, + 8.651065e-001, + 7.721402e-003, + 1.148828e+000, + 6.589887e-001, + -9.782795e-001, + 3.652455e-002, + 1.331304e+000, + -4.804135e+000, + 5.130801e+000, + 1.052586e+000, + 4.439877e-001, + 2.100157e+000, + 8.308236e-001, + -1.077598e+000, + -2.015253e-001, + -1.037818e+000, + 1.307045e+001, + -1.715211e+001, + -1.607252e+000, + 4.472382e-001, + 6.802371e-001, + 4.848934e-001, + -1.025969e+000, + -1.170376e-001, + 1.139546e+000, + -3.374680e+000, + 6.330035e+000, + 2.199093e+000, + 3.928627e-001, + 8.428666e-001, + 7.960910e-001, + -1.062382e+000, + -1.881842e-001, + 8.863153e-001, + 4.266858e+000, + -5.011692e+000, + -4.086830e-001, + 5.889147e-001, + 5.341939e-001, + 6.866073e-001, + // albedo 0, turbidity 7 + -1.352417e+000, + -3.836953e-001, + -5.951560e-001, + 4.053297e-001, + 2.468304e-001, + 2.565711e-001, + 2.321365e-001, + 2.512376e+000, + 6.089904e-001, + -1.976438e+000, + -9.152777e-001, + -4.417666e-001, + 1.790189e+000, + -1.085567e+000, + 4.562228e-001, + 2.133332e-002, + 4.989856e-001, + 6.257100e-001, + -7.197412e-001, + 2.165210e-001, + 6.233215e-001, + -3.960686e+000, + 4.694083e+000, + 2.062797e+000, + 3.121864e-001, + 2.942681e+000, + 8.846033e-001, + -1.189984e+000, + -3.151612e-001, + -5.020073e-001, + 1.015136e+001, + -1.483684e+001, + -3.476730e+000, + 6.049863e-001, + -1.941153e-001, + 4.281015e-001, + -9.781383e-001, + -8.764833e-002, + 8.290915e-001, + 1.086960e-001, + 4.467570e+000, + 3.905633e+000, + 1.975895e-001, + 6.964295e-001, + 8.333166e-001, + -1.081242e+000, + -2.051949e-001, + 6.056482e-001, + 5.219268e+000, + -4.410608e+000, + -1.963212e+000, + 7.277904e-001, + 8.509624e-001, + 6.689251e-001, + // albedo 0, turbidity 8 + -1.443212e+000, + -4.725757e-001, + -9.477961e-001, + 2.671049e-001, + 6.163577e-001, + -3.965036e-001, + 4.071134e-001, + 2.464218e+000, + 4.997820e-001, + -3.021428e+000, + -1.558459e+000, + 1.389763e-001, + 1.122031e+000, + -1.014816e+000, + 1.265687e+000, + -1.649604e-001, + -6.627923e-001, + 5.494665e-001, + -1.593477e-001, + 5.076305e-001, + -7.283933e-001, + -1.265076e+000, + 3.904153e+000, + -8.196757e-002, + 6.585734e-001, + 4.998464e+000, + 9.330667e-001, + -1.378374e+000, + -5.064534e-001, + 7.231197e-001, + 1.385088e+000, + -9.500118e+000, + -4.806746e-001, + 1.067642e-001, + -3.297209e+000, + 4.441955e-001, + -9.436176e-001, + -6.189764e-002, + 1.144482e-001, + 9.137694e+000, + 2.948867e-001, + 1.224655e+000, + 3.675148e-001, + 2.124090e+000, + 8.014519e-001, + -1.078915e+000, + -2.051854e-001, + 4.754209e-001, + 5.826389e-003, + -2.498632e+000, + -8.265078e-001, + 7.644670e-001, + 6.066256e-001, + 6.811963e-001, + // albedo 0, turbidity 9 + -1.621711e+000, + -6.425839e-001, + -7.307813e-001, + 1.109519e+000, + -4.107299e-001, + 7.789953e-001, + 7.764812e-002, + 2.335627e+000, + 6.230915e-001, + -4.003597e+000, + -1.736865e+000, + -6.062450e-001, + -7.370264e-001, + 7.002778e-001, + -4.140325e-001, + 3.926087e-001, + 8.316399e-001, + 1.516341e-001, + -7.696712e-001, + -3.872306e-001, + -1.159436e+000, + 1.660752e+000, + 2.031840e+000, + -7.697685e-001, + 5.481684e-001, + 2.788249e+000, + 1.112977e+000, + -8.506589e-001, + -5.430791e-002, + 1.088719e+000, + -2.513532e+000, + -4.144477e+000, + 2.760914e+000, + -3.011272e-001, + -2.383556e+000, + 4.496070e-001, + -1.150061e+000, + -3.009215e-001, + -9.176868e-002, + 8.996074e+000, + -1.753862e+000, + -2.428423e+000, + 5.764492e-001, + 1.218492e+000, + 7.552230e-001, + -1.020853e+000, + -1.499849e-001, + 3.437744e-001, + -2.339597e-003, + -2.646520e+000, + 1.378457e+000, + 6.708410e-001, + 9.149680e-001, + 6.961806e-001, + // albedo 0, turbidity 10 + -1.982394e+000, + -9.369621e-001, + -3.767595e-001, + 2.514582e+000, + -1.501415e+000, + 6.258952e-001, + -5.260430e-006, + 2.100142e+000, + 7.824077e-001, + -3.432415e+000, + -1.264283e+000, + -9.042363e-001, + -2.930432e+000, + 8.249096e-001, + 7.244840e-001, + 3.055253e-002, + 2.527405e+000, + -2.107031e-003, + -4.333533e+000, + -2.156157e+000, + -8.341654e-001, + 5.048387e+000, + 1.803580e+000, + -9.318434e-001, + 1.085401e+000, + 8.728330e-001, + 1.050061e+000, + 4.889224e-001, + 5.956721e-002, + 8.445388e-001, + -7.479177e+000, + -4.049292e+000, + 1.199966e+000, + -7.060560e-001, + -9.742353e-001, + 4.893674e-001, + -1.347508e+000, + -1.874523e-001, + -5.063342e-002, + 1.299813e+001, + -1.707387e+000, + -4.076088e-001, + 6.119042e-001, + 3.717790e-001, + 7.662157e-001, + -1.047037e+000, + -3.743109e-001, + 3.452375e-001, + -3.615559e-003, + -2.169432e+000, + -7.166880e-002, + 3.747046e-001, + 2.746126e-001, + 6.773818e-001, + // albedo 1, turbidity 1 + -1.105396e+000, + -1.663441e-001, + -2.359634e-001, + 2.476496e+000, + -1.329052e-001, + 1.715759e+000, + 2.103991e-003, + 1.421966e+000, + 6.270733e-001, + -1.132480e+000, + -2.330883e-001, + 2.273938e+000, + 2.422717e-001, + -4.159883e-001, + 9.350714e-001, + 1.432347e-002, + -4.176684e-001, + 4.664640e-001, + -1.036155e+000, + -9.432450e-002, + 3.117262e+000, + -6.369808e-001, + 1.060389e+000, + 3.386481e+000, + -4.605081e-002, + 1.248000e+000, + 9.701974e-001, + -1.162485e+000, + -1.382303e-001, + 1.544122e-001, + 3.716511e-001, + -9.520209e+000, + -2.739605e-001, + 8.489054e-002, + 4.371570e+000, + 7.694391e-002, + -1.031787e+000, + -2.165067e-001, + 4.446666e+000, + -1.470711e-001, + 2.143436e+000, + 1.922123e+000, + -9.589030e-002, + -3.594664e+000, + 8.629249e-001, + -1.081125e+000, + -1.623953e-001, + 2.048137e+000, + 8.639386e-002, + 1.225845e+000, + 1.239255e-001, + 8.366038e-002, + 8.322625e-001, + 5.604708e-001, + // albedo 1, turbidity 2 + -1.112606e+000, + -1.514491e-001, + -1.608942e+000, + 3.592344e+000, + -1.616115e-001, + 1.593861e+000, + 5.488306e-002, + 2.854783e+000, + 7.519999e-001, + -1.098630e+000, + -1.410161e-001, + 2.155487e+000, + -4.381610e-001, + -3.635146e-001, + 1.313843e+000, + 1.201277e-001, + 2.469958e+000, + 6.481071e-001, + -1.077575e+000, + -1.275645e-001, + 1.418205e+000, + 2.057232e+000, + -7.778503e-002, + 2.433840e+000, + -7.094034e-002, + 3.347259e+000, + 9.344752e-001, + -1.099714e+000, + -4.474282e-002, + -1.247041e-001, + -1.578342e-001, + -7.968895e+000, + 1.730912e-001, + 5.303765e-001, + 5.523179e+000, + 3.840340e-001, + -1.061945e+000, + -2.200148e-001, + 4.333103e+000, + 1.818948e-002, + 1.907751e+000, + 1.560633e+000, + -3.182192e-001, + -3.010282e+000, + 8.844351e-001, + -1.087782e+000, + -1.709041e-001, + 1.834683e+000, + 7.351214e-002, + 1.282669e+000, + 2.075884e-001, + 2.698971e-001, + 3.373859e-001, + 5.808336e-001, + // albedo 1, turbidity 3 + -1.121417e+000, + -1.551220e-001, + -1.527123e+000, + 2.788105e+000, + -1.477847e-001, + 1.152139e+000, + 1.742181e-001, + 3.473417e+000, + 6.737050e-001, + -1.118910e+000, + -1.496848e-001, + 2.736873e+000, + -1.829596e+000, + -3.411991e-001, + 1.177538e-001, + 2.960683e-001, + 3.273898e+000, + 5.743833e-001, + -1.121145e+000, + -1.980292e-001, + -5.407002e-001, + 2.886807e+000, + 4.877852e-001, + 3.692424e+000, + -1.104033e-001, + -2.358878e-001, + 9.976295e-001, + -1.078889e+000, + -1.541161e-003, + 1.370650e+000, + 1.644450e+000, + -1.425572e+001, + -3.075430e+000, + 9.346385e-001, + 5.871863e+000, + 2.618026e-001, + -1.053346e+000, + -2.262166e-001, + 2.532003e+000, + -8.720058e-001, + 7.667901e+000, + 4.357082e+000, + -5.367969e-001, + -2.073329e+000, + 1.023965e+000, + -1.100093e+000, + -1.810893e-001, + 2.566430e+000, + 4.757700e-001, + -2.069684e+000, + -1.585209e+000, + 4.693140e-001, + -6.719615e-001, + 5.569453e-001, + // albedo 1, turbidity 4 + -1.181528e+000, + -2.151896e-001, + -1.076470e+000, + 2.037517e+000, + -1.683559e-001, + 8.780110e-001, + 1.782773e-001, + 2.768650e+000, + 6.743293e-001, + -1.142132e+000, + -1.825403e-001, + 1.320992e+000, + -1.895472e+000, + -2.160241e-001, + -2.079637e-001, + 3.424953e-001, + 4.333355e+000, + 5.663420e-001, + -1.225408e+000, + -2.906477e-001, + 8.323962e-001, + 2.176300e+000, + 1.943859e+000, + 3.003671e+000, + 1.130255e-001, + -4.449977e+000, + 8.867390e-001, + -9.815988e-001, + 5.577004e-002, + -4.240348e-001, + 1.488466e+000, + -1.279361e+001, + -3.110899e+000, + 7.360104e-001, + 7.937751e+000, + 4.474817e-001, + -1.103439e+000, + -2.481553e-001, + 3.045691e+000, + -6.993993e-001, + 6.081464e+000, + 3.986228e+000, + -1.616828e-001, + -3.373973e+000, + 8.572294e-001, + -1.081695e+000, + -1.943361e-001, + 2.303236e+000, + 3.906537e-001, + -1.498982e+000, + -1.372140e+000, + 3.379214e-001, + -4.953601e-001, + 6.521383e-001, + // albedo 1, turbidity 5 + -1.235776e+000, + -2.745978e-001, + 2.205316e-002, + 4.505193e-001, + -1.569202e-001, + 5.065039e-001, + 2.016320e-001, + 2.449382e+000, + 6.535188e-001, + -1.268478e+000, + -3.078367e-001, + -2.041769e-001, + 1.189583e+000, + -1.311782e+000, + 4.724677e-001, + 1.025764e-001, + 3.300615e+000, + 6.689797e-001, + -1.190389e+000, + -2.597641e-001, + 1.377486e+000, + -2.289003e+000, + 4.214767e+000, + 1.900318e+000, + 3.126604e-001, + -2.537399e+000, + 7.980811e-001, + -9.632300e-001, + 7.067379e-002, + -6.690546e-001, + 9.507059e+000, + -1.721426e+001, + -2.850631e+000, + 6.931159e-001, + 5.722238e+000, + 4.856193e-001, + -1.119689e+000, + -3.019499e-001, + 2.657474e+000, + -5.208105e+000, + 1.015200e+001, + 3.863887e+000, + -1.603721e-001, + -3.132328e+000, + 8.543154e-001, + -1.078742e+000, + -1.840880e-001, + 2.341448e+000, + 2.576821e+000, + -5.011296e+000, + -1.671996e+000, + 3.955131e-001, + -4.700684e-001, + 6.516593e-001, + // albedo 1, turbidity 6 + -1.263449e+000, + -3.016185e-001, + -1.680842e-001, + 4.791728e-001, + -8.989862e-002, + 5.069014e-001, + 1.892810e-001, + 2.535339e+000, + 6.506411e-001, + -1.544305e+000, + -5.656222e-001, + -2.084263e-001, + 1.312304e+000, + -8.580598e-001, + 4.039133e-001, + 1.008588e-001, + 1.268784e+000, + 6.333075e-001, + -9.436041e-001, + -1.620107e-002, + 1.253874e+000, + -3.499120e+000, + 4.452594e+000, + 1.870490e+000, + 1.524710e-001, + 8.031346e-001, + 8.930942e-001, + -1.106718e+000, + -1.102586e-001, + -8.803979e-001, + 1.326904e+001, + -1.878253e+001, + -2.994671e+000, + 9.501205e-001, + 2.284893e+000, + 3.662824e-001, + -1.048783e+000, + -2.156089e-001, + 2.786728e+000, + -4.862603e+000, + 8.438175e+000, + 3.683031e+000, + -3.092444e-001, + -1.293934e+000, + 9.110045e-001, + -1.108140e+000, + -2.156079e-001, + 2.181504e+000, + 2.124553e+000, + -5.007442e+000, + -1.711417e+000, + 4.904871e-001, + -8.710312e-001, + 6.376965e-001, + // albedo 1, turbidity 7 + -1.345282e+000, + -3.856197e-001, + -1.975094e-001, + 3.016919e-001, + 2.765844e-001, + 2.092275e-001, + 2.251325e-001, + 2.058589e+000, + 6.014266e-001, + -1.907309e+000, + -8.881952e-001, + -4.827860e-001, + 1.495665e+000, + -9.243173e-001, + 3.864061e-001, + 7.491538e-002, + 2.719526e-001, + 6.046039e-001, + -7.540737e-001, + 1.800167e-001, + 1.174575e+000, + -3.052295e+000, + 4.669060e+000, + 1.793876e+000, + 1.664066e-001, + 2.376187e+000, + 9.261122e-001, + -1.165479e+000, + -2.500464e-001, + -9.603937e-001, + 8.919733e+000, + -1.561899e+001, + -2.850650e+000, + 8.368531e-001, + 3.404393e-001, + 3.694265e-001, + -1.032259e+000, + -1.593662e-001, + 2.621639e+000, + -5.369281e-001, + 6.011517e+000, + 3.234312e+000, + -1.842335e-001, + -3.749684e-001, + 8.913063e-001, + -1.119906e+000, + -2.533313e-001, + 2.017975e+000, + 4.776492e-001, + -5.005474e+000, + -1.503414e+000, + 4.694448e-001, + -1.039200e+000, + 6.438630e-001, + // albedo 1, turbidity 8 + -1.457842e+000, + -4.806585e-001, + -6.807833e-001, + 2.682520e-001, + 5.586195e-001, + -2.806536e-001, + 3.694491e-001, + 2.169304e+000, + 4.997873e-001, + -2.906600e+000, + -1.558470e+000, + 4.048869e-001, + 1.012321e+000, + -8.709928e-001, + 9.025637e-001, + -9.171486e-002, + -1.279805e+000, + 5.327924e-001, + -2.500868e-001, + 5.175467e-001, + -4.366020e-001, + -1.156645e+000, + 3.657335e+000, + 4.092973e-001, + 4.611188e-001, + 4.971048e+000, + 9.789196e-001, + -1.282240e+000, + -4.792753e-001, + 3.824491e-001, + 2.061672e+000, + -9.474747e+000, + -1.080446e+000, + 3.852100e-001, + -3.234591e+000, + 3.696703e-001, + -1.046065e+000, + -1.097023e-001, + 1.672284e+000, + 4.799701e+000, + 1.286403e+000, + 1.712569e+000, + 1.099301e-001, + 1.214451e+000, + 8.572886e-001, + -1.104124e+000, + -2.576744e-001, + 1.919030e+000, + -1.296687e-003, + -3.500874e+000, + -1.048831e+000, + 3.929400e-001, + -9.229794e-001, + 6.687909e-001, + // albedo 1, turbidity 9 + -1.658918e+000, + -6.637256e-001, + -1.162850e+000, + 1.829549e+000, + -2.525065e-001, + 8.624803e-001, + 5.214746e-002, + 1.977784e+000, + 6.455044e-001, + -3.553256e+000, + -1.639022e+000, + -8.821743e-001, + -2.660037e-001, + 5.168738e-001, + -8.582770e-001, + 4.110780e-001, + 1.034123e-001, + 1.039852e-001, + -1.299367e+000, + -4.890457e-001, + -5.595307e-001, + 1.129115e+000, + 5.445041e-001, + 5.361314e-001, + 4.579589e-001, + 3.385708e+000, + 1.184267e+000, + -4.366852e-001, + -2.303554e-002, + 5.417530e-001, + -9.106900e-001, + -4.398484e-001, + 3.178252e-001, + -2.132156e-001, + -3.682761e+000, + 3.754470e-001, + -1.334075e+000, + -2.466639e-001, + 1.293237e+000, + 4.685982e+000, + -4.032879e+000, + 4.666293e-001, + 5.337822e-001, + 1.603290e+000, + 8.067400e-001, + -1.052460e+000, + -2.501759e-001, + 1.601487e+000, + 1.713504e+000, + -2.810006e+000, + -8.042597e-001, + 3.216101e-001, + -5.944876e-001, + 6.740783e-001, + // albedo 1, turbidity 10 + -1.974746e+000, + -9.111910e-001, + -2.159155e-001, + 2.437415e+000, + -1.592257e+000, + 6.133797e-001, + -6.243023e-006, + 1.960399e+000, + 7.806415e-001, + -2.677119e+000, + -1.100702e+000, + -6.847246e-001, + -2.820855e+000, + 1.577837e+000, + 6.243833e-001, + 2.218481e-002, + 1.568717e+000, + 2.327673e-002, + -5.323827e+000, + -2.461050e+000, + -3.941307e-001, + 4.908417e+000, + -1.657232e-001, + -9.501763e-001, + 1.063520e+000, + 1.455622e+000, + 9.781890e-001, + 1.325000e+000, + 3.538115e-001, + 1.783573e-001, + -6.903650e+000, + -8.079921e-001, + 1.215973e+000, + -6.852540e-001, + -1.735835e+000, + 5.744662e-001, + -1.741196e+000, + -3.448017e-001, + 1.242377e+000, + 1.098613e+001, + -3.386782e+000, + -3.128683e-001, + 5.792848e-001, + 1.364330e-002, + 7.112763e-001, + -9.762671e-001, + -3.368355e-001, + 1.374728e+000, + -3.312353e-003, + -2.576919e+000, + -1.778015e-001, + 2.024288e-001, + -6.128666e-001, + 6.917938e-001, +}; + +double datasetRad720[] = +{ + // albedo 0, turbidity 1 + 1.130152e-002, + 8.671843e-003, + 2.004792e-002, + 2.515879e-002, + 2.020140e-002, + 2.117353e-002, + // albedo 0, turbidity 2 + 1.224368e-002, + 8.839480e-003, + 2.189489e-002, + 4.083873e-002, + 1.919064e-002, + 2.455945e-002, + // albedo 0, turbidity 3 + 1.252249e-002, + 8.009335e-003, + 2.371432e-002, + 6.397292e-002, + 2.042384e-002, + 2.862112e-002, + // albedo 0, turbidity 4 + 1.180325e-002, + 8.958479e-003, + 1.183940e-002, + 1.148189e-001, + 1.354571e-002, + 3.848691e-002, + // albedo 0, turbidity 5 + 1.085725e-002, + 1.134459e-002, + -7.554548e-003, + 1.671603e-001, + 8.431212e-003, + 4.772824e-002, + // albedo 0, turbidity 6 + 1.014547e-002, + 1.403737e-002, + -2.479898e-002, + 2.032831e-001, + 5.127749e-003, + 5.409735e-002, + // albedo 0, turbidity 7 + 9.143208e-003, + 1.825961e-002, + -4.902126e-002, + 2.473204e-001, + 7.992708e-003, + 6.238918e-002, + // albedo 0, turbidity 8 + 7.784746e-003, + 2.352715e-002, + -7.647231e-002, + 2.868914e-001, + 2.581232e-002, + 7.345921e-002, + // albedo 0, turbidity 9 + 6.425568e-003, + 2.680506e-002, + -9.216963e-002, + 2.866525e-001, + 7.712816e-002, + 8.877708e-002, + // albedo 0, turbidity 10 + 5.348459e-003, + 2.347534e-002, + -7.499904e-002, + 2.035369e-001, + 1.874982e-001, + 1.045961e-001, + // albedo 1, turbidity 1 + 1.168435e-002, + 9.445039e-003, + 1.950520e-002, + 2.563333e-002, + 4.729214e-002, + 5.096829e-002, + // albedo 1, turbidity 2 + 1.252521e-002, + 1.012940e-002, + 2.002302e-002, + 4.276714e-002, + 4.778275e-002, + 5.748908e-002, + // albedo 1, turbidity 3 + 1.285682e-002, + 9.705956e-003, + 2.018767e-002, + 6.797612e-002, + 5.181662e-002, + 6.548541e-002, + // albedo 1, turbidity 4 + 1.218970e-002, + 1.070161e-002, + 8.436124e-003, + 1.177409e-001, + 5.124773e-002, + 8.069723e-002, + // albedo 1, turbidity 5 + 1.129406e-002, + 1.339498e-002, + -1.193989e-002, + 1.709051e-001, + 5.001995e-002, + 9.558448e-002, + // albedo 1, turbidity 6 + 1.056724e-002, + 1.570995e-002, + -2.759057e-002, + 2.030760e-001, + 5.311962e-002, + 1.037882e-001, + // albedo 1, turbidity 7 + 9.594077e-003, + 1.966415e-002, + -5.024827e-002, + 2.432607e-001, + 6.172355e-002, + 1.169276e-001, + // albedo 1, turbidity 8 + 8.348105e-003, + 2.415281e-002, + -7.475064e-002, + 2.748209e-001, + 8.753187e-002, + 1.356651e-001, + // albedo 1, turbidity 9 + 7.106169e-003, + 2.513833e-002, + -7.928946e-002, + 2.463668e-001, + 1.685984e-001, + 1.485820e-001, + // albedo 1, turbidity 10 + 6.031610e-003, + 2.016534e-002, + -5.448075e-002, + 1.436689e-001, + 2.971830e-001, + 1.639884e-001, +}; + +double* datasets[] = +{ + dataset320, + dataset360, + dataset400, + dataset440, + dataset480, + dataset520, + dataset560, + dataset600, + dataset640, + dataset680, + dataset720 +}; + +double* datasetsRad[] = +{ + datasetRad320, + datasetRad360, + datasetRad400, + datasetRad440, + datasetRad480, + datasetRad520, + datasetRad560, + datasetRad600, + datasetRad640, + datasetRad680, + datasetRad720 +}; + +// Uses Feb 9 dataset +double solarDataset320[] = +{ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.162049e+02, + 4.610588e+00, + 0, + 0, + -3.824759e+00, + 1.338698e+01, + 5.595274e-02, + 3.125000e-04, + -2.161500e+03, + 1.113209e+02, + 3.458172e-01, + 2.500000e-03, + 8.294600e+01, + 1.711252e+02, + 2.111274e+00, + 1.984375e-02, + -4.229939e+03, + 6.275308e+02, + 6.980643e+00, + 8.375000e-02, + -1.740178e+04, + 1.708634e+03, + 2.367820e+01, + 3.350000e-01, + -1.976851e+04, + 2.817040e+03, + 6.781352e+01, + 1.193125e+00, + -3.810737e+04, + 4.836590e+03, + 1.556846e+02, + 3.466250e+00, + -4.549929e+04, + 6.516914e+03, + 3.119331e+02, + 8.744219e+00, + -5.263436e+04, + 8.036785e+03, + 5.455303e+02, + 1.930562e+01, + -6.309578e+04, + 9.205958e+03, + 8.581439e+02, + 3.815516e+01, + -4.954890e+04, + 8.736703e+03, + 1.229615e+03, + 6.870672e+01, + -6.343828e+04, + 9.001550e+03, + 1.628815e+03, + 1.138184e+02, + -3.475406e+04, + 6.615408e+03, + 2.019023e+03, + 1.763652e+02, + -4.201833e+04, + 6.105544e+03, + 2.362030e+03, + 2.567578e+02, + -2.667604e+04, + 4.055614e+03, + 2.646799e+03, + 3.559691e+02, + -2.036310e+04, + 2.748587e+03, + 2.846313e+03, + 4.723367e+02, + -2.032124e+04, + 1.878732e+03, + 2.969980e+03, + 6.041547e+02, + -1.073640e+04, + 4.777580e+02, + 3.009645e+03, + 7.491283e+02, + -1.005389e+04, + -3.672131e+01, + 2.973858e+03, + 9.033814e+02, + -1.030868e+04, + -4.464229e+02, + 2.879841e+03, + 1.064085e+03, + -2.157918e+03, + -1.342683e+03, + 2.723843e+03, + 1.227711e+03, + -3.651657e+03, + -1.197013e+03, + 2.534012e+03, + 1.389789e+03, + -7.289195e+03, + -9.708760e+02, + 2.331442e+03, + 1.548851e+03, + -7.704469e+02, + -1.628402e+03, + 2.093848e+03, + 1.702493e+03, + -4.214558e+03, + -1.153021e+03, + 1.844767e+03, + 1.845862e+03, + -2.390689e+03, + -1.287373e+03, + 1.593697e+03, + 1.978602e+03, + -6.413034e+03, + -8.008887e+02, + 1.339243e+03, + 2.097559e+03, + -2.988481e+03, + -1.136665e+03, + 1.064931e+03, + 2.201486e+03, + -6.139876e+03, + -5.991924e+02, + 7.913266e+02, + 2.285209e+03, + -1.196221e+04, + 1.344918e+02, + 5.186582e+02, + 2.348895e+03, + -5.971683e+03, + -6.555303e+01, + 2.013157e+02, + 2.389728e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.229445e+02, + 7.374485e+00, + 0, + 0, + -1.231740e+01, + 1.262553e+01, + 7.960490e-02, + 4.687500e-04, + -2.643352e+02, + 5.605647e+01, + 3.498905e-01, + 2.812500e-03, + -2.454452e+03, + 2.369608e+02, + 1.620789e+00, + 1.531250e-02, + -4.320948e+03, + 5.952227e+02, + 6.834726e+00, + 7.828125e-02, + -1.272903e+04, + 1.474486e+03, + 2.244014e+01, + 3.187500e-01, + -1.829132e+04, + 2.679893e+03, + 6.267850e+01, + 1.107500e+00, + -3.969700e+04, + 4.797859e+03, + 1.468690e+02, + 3.237813e+00, + -4.233637e+04, + 6.288595e+03, + 2.991805e+02, + 8.289531e+00, + -5.378742e+04, + 8.016312e+03, + 5.272841e+02, + 1.845875e+01, + -6.132387e+04, + 9.078358e+03, + 8.364539e+02, + 3.679578e+01, + -5.902508e+04, + 9.037411e+03, + 1.204972e+03, + 6.666500e+01, + -4.718111e+04, + 8.049720e+03, + 1.595444e+03, + 1.110180e+02, + -4.077260e+04, + 7.049147e+03, + 1.976792e+03, + 1.719842e+02, + -4.205766e+04, + 6.112440e+03, + 2.327488e+03, + 2.511269e+02, + -2.791505e+04, + 4.115557e+03, + 2.612616e+03, + 3.489953e+02, + -1.609988e+04, + 2.510900e+03, + 2.810607e+03, + 4.639409e+02, + -2.314164e+04, + 2.163386e+03, + 2.938786e+03, + 5.940591e+02, + -1.330257e+04, + 6.221024e+02, + 2.986256e+03, + 7.378767e+02, + -5.675969e+03, + -3.846177e+02, + 2.945011e+03, + 8.909630e+02, + -6.495665e+03, + -5.518256e+02, + 2.852178e+03, + 1.049766e+03, + -1.215437e+04, + -4.405937e+02, + 2.722478e+03, + 1.212177e+03, + 2.719602e+03, + -1.879784e+03, + 2.530070e+03, + 1.375258e+03, + -8.647169e+03, + -7.569952e+02, + 2.319694e+03, + 1.532926e+03, + -1.867684e+03, + -1.528257e+03, + 2.092233e+03, + 1.686330e+03, + -4.025935e+03, + -1.211125e+03, + 1.840308e+03, + 1.829689e+03, + -1.081717e+03, + -1.411956e+03, + 1.583655e+03, + 1.961830e+03, + -7.350389e+03, + -6.622648e+02, + 1.334664e+03, + 2.079855e+03, + -2.343916e+03, + -1.205267e+03, + 1.063635e+03, + 2.183818e+03, + -7.430550e+03, + -4.556049e+02, + 7.931502e+02, + 2.267336e+03, + -1.068232e+04, + -2.114828e+01, + 5.135211e+02, + 2.331394e+03, + -6.217560e+03, + -3.350260e+01, + 2.024873e+02, + 2.371433e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.203441e+02, + 4.171995e+00, + 0, + 0, + 1.426480e+02, + -4.022426e-01, + 2.425240e-02, + 1.562500e-04, + -4.009478e+01, + 1.125399e+01, + 5.471435e-02, + 4.687500e-04, + -6.200072e+02, + 5.758122e+01, + 2.853042e-01, + 2.343750e-03, + -6.987267e+02, + 1.643846e+02, + 1.429285e+00, + 1.359375e-02, + -5.632468e+03, + 5.971678e+02, + 5.643686e+00, + 6.437500e-02, + -1.136274e+04, + 1.361972e+03, + 2.032334e+01, + 2.812500e-01, + -1.952933e+04, + 2.607796e+03, + 5.786257e+01, + 1.004844e+00, + -3.532941e+04, + 4.461645e+03, + 1.377803e+02, + 3.003125e+00, + -4.143687e+04, + 6.064540e+03, + 2.816662e+02, + 7.743281e+00, + -5.085245e+04, + 7.694233e+03, + 5.005985e+02, + 1.737797e+01, + -6.042859e+04, + 8.861458e+03, + 7.989383e+02, + 3.484813e+01, + -5.375945e+04, + 8.686126e+03, + 1.157257e+03, + 6.348969e+01, + -4.609594e+04, + 8.037224e+03, + 1.541142e+03, + 1.061803e+02, + -5.818693e+04, + 7.796026e+03, + 1.925333e+03, + 1.653475e+02, + -1.234873e+04, + 4.326471e+03, + 2.261366e+03, + 2.427720e+02, + -4.100578e+04, + 5.301137e+03, + 2.543132e+03, + 3.370997e+02, + -2.570418e+04, + 3.036407e+03, + 2.771427e+03, + 4.502481e+02, + -9.930667e+03, + 1.185082e+03, + 2.888544e+03, + 5.787917e+02, + -1.540011e+04, + 1.011847e+03, + 2.933616e+03, + 7.193989e+02, + -8.074592e+03, + -9.360958e+01, + 2.915801e+03, + 8.705267e+02, + -1.229699e+04, + -1.891092e+02, + 2.833288e+03, + 1.028212e+03, + 1.425166e+02, + -1.460737e+03, + 2.687065e+03, + 1.189614e+03, + -7.667229e+03, + -7.968169e+02, + 2.508850e+03, + 1.349517e+03, + -2.347845e+03, + -1.408348e+03, + 2.307273e+03, + 1.507527e+03, + -4.419120e+03, + -1.175822e+03, + 2.079767e+03, + 1.659044e+03, + -4.704423e+03, + -1.172710e+03, + 1.838621e+03, + 1.802379e+03, + -3.231727e+01, + -1.540847e+03, + 1.575896e+03, + 1.934311e+03, + -7.381753e+03, + -6.308022e+02, + 1.326603e+03, + 2.051421e+03, + -2.673977e+03, + -1.159966e+03, + 1.060234e+03, + 2.154908e+03, + -6.512200e+03, + -5.471063e+02, + 7.899642e+02, + 2.238250e+03, + -9.505497e+03, + -1.111579e+02, + 5.172803e+02, + 2.301960e+03, + -6.085971e+03, + -7.278179e+01, + 2.224392e+02, + 2.342608e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.398243e+02, + 5.776206e+00, + 0, + 0, + 2.463155e+02, + -2.094592e-01, + 4.496203e-02, + 3.125000e-04, + -1.010040e+03, + 5.790287e+01, + 1.278306e-01, + 1.093750e-03, + -3.545764e+02, + 1.294156e+02, + 1.099066e+00, + 9.687500e-03, + -6.451710e+03, + 5.563384e+02, + 4.533285e+00, + 4.984375e-02, + -5.934123e+03, + 1.056602e+03, + 1.730255e+01, + 2.356250e-01, + -2.331347e+04, + 2.539950e+03, + 4.913378e+01, + 8.401563e-01, + -2.454544e+04, + 3.778662e+03, + 1.219910e+02, + 2.611719e+00, + -4.570703e+04, + 5.952157e+03, + 2.514711e+02, + 6.796719e+00, + -4.332230e+04, + 7.038252e+03, + 4.577067e+02, + 1.558687e+01, + -6.059598e+04, + 8.589735e+03, + 7.371821e+02, + 3.161938e+01, + -4.538550e+04, + 8.101580e+03, + 1.079569e+03, + 5.827141e+01, + -5.158798e+04, + 8.232570e+03, + 1.451372e+03, + 9.823734e+01, + -4.012520e+04, + 6.957081e+03, + 1.830066e+03, + 1.543975e+02, + -3.793394e+04, + 5.939944e+03, + 2.176636e+03, + 2.281206e+02, + -3.211292e+04, + 4.482161e+03, + 2.467196e+03, + 3.200717e+02, + -1.588792e+04, + 2.521470e+03, + 2.673764e+03, + 4.292442e+02, + -1.756764e+04, + 1.927386e+03, + 2.804183e+03, + 5.532441e+02, + -1.277374e+04, + 8.843716e+02, + 2.867650e+03, + 6.906603e+02, + -8.721587e+03, + 7.343786e+01, + 2.857501e+03, + 8.384222e+02, + -1.210720e+04, + -1.134775e+02, + 2.787446e+03, + 9.933153e+02, + -7.324531e+02, + -1.323481e+03, + 2.651921e+03, + 1.152349e+03, + -7.693693e+03, + -7.693487e+02, + 2.480657e+03, + 1.310405e+03, + -2.653371e+03, + -1.366675e+03, + 2.282324e+03, + 1.466687e+03, + -3.648018e+03, + -1.230454e+03, + 2.056210e+03, + 1.616582e+03, + -2.664373e+03, + -1.284624e+03, + 1.819352e+03, + 1.758212e+03, + -5.222558e+03, + -9.816239e+02, + 1.575433e+03, + 1.888928e+03, + -2.865965e+03, + -1.196481e+03, + 1.315007e+03, + 2.006915e+03, + -3.599541e+03, + -9.578621e+02, + 1.050151e+03, + 2.108105e+03, + -6.734962e+03, + -5.085043e+02, + 7.938554e+02, + 2.191497e+03, + -1.211854e+04, + 1.393363e+02, + 5.225520e+02, + 2.255726e+03, + -5.940851e+03, + -7.200209e+01, + 2.016666e+02, + 2.296840e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -5.810245e+01, + 2.305294e+00, + 0, + 0, + -4.677095e+01, + 7.181418e+00, + 2.797637e-02, + 1.562500e-04, + -2.390763e+02, + 3.399401e+01, + 1.676014e-01, + 1.250000e-03, + -1.572353e+03, + 1.448172e+02, + 9.018003e-01, + 8.125000e-03, + -1.932258e+03, + 3.555380e+02, + 4.045229e+00, + 4.515625e-02, + -8.021604e+03, + 1.011597e+03, + 1.385505e+01, + 1.907813e-01, + -1.760146e+04, + 2.142284e+03, + 4.213012e+01, + 7.085938e-01, + -2.771190e+04, + 3.598579e+03, + 1.059734e+02, + 2.232031e+00, + -2.685562e+04, + 4.912314e+03, + 2.231363e+02, + 5.951250e+00, + -5.816933e+04, + 7.488614e+03, + 4.119772e+02, + 1.372719e+01, + -5.375236e+04, + 7.934157e+03, + 6.844993e+02, + 2.860453e+01, + -4.429083e+04, + 7.764848e+03, + 1.006186e+03, + 5.337641e+01, + -4.260900e+04, + 7.623473e+03, + 1.360246e+03, + 9.077234e+01, + -4.165134e+04, + 7.075685e+03, + 1.728438e+03, + 1.435205e+02, + -4.199611e+04, + 6.142734e+03, + 2.077584e+03, + 2.136358e+02, + -1.823240e+04, + 3.778736e+03, + 2.365364e+03, + 3.017798e+02, + -2.860530e+04, + 3.604470e+03, + 2.586318e+03, + 4.064622e+02, + -1.609512e+04, + 1.794040e+03, + 2.736939e+03, + 5.275606e+02, + -1.254070e+04, + 8.805854e+02, + 2.797800e+03, + 6.615970e+02, + -6.090084e+03, + -5.143658e+01, + 2.789103e+03, + 8.057959e+02, + -1.308790e+04, + 9.060229e+01, + 2.728964e+03, + 9.570091e+02, + -1.747122e+03, + -1.183227e+03, + 2.607217e+03, + 1.113144e+03, + -4.502060e+03, + -9.631705e+02, + 2.441686e+03, + 1.268743e+03, + -4.925191e+03, + -1.030626e+03, + 2.258761e+03, + 1.422545e+03, + -4.605435e+03, + -1.142309e+03, + 2.046600e+03, + 1.571669e+03, + -2.008970e+03, + -1.371278e+03, + 1.807372e+03, + 1.712698e+03, + -4.054953e+03, + -1.064272e+03, + 1.561721e+03, + 1.842282e+03, + -4.186489e+03, + -1.014859e+03, + 1.310764e+03, + 1.959238e+03, + -4.536370e+03, + -8.990475e+02, + 1.048215e+03, + 2.060568e+03, + -4.732931e+03, + -7.451517e+02, + 7.801005e+02, + 2.143593e+03, + -1.235209e+04, + 2.174097e+02, + 5.169935e+02, + 2.206104e+03, + -6.154950e+03, + -5.382014e+01, + 2.046788e+02, + 2.247203e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.126883e+02, + 5.520338e+00, + 0, + 0, + 1.263603e+02, + 2.194173e+00, + 4.737462e-02, + 3.125000e-04, + -1.508116e+01, + 2.129591e+01, + 1.399562e-01, + 1.250000e-03, + -9.018236e+02, + 1.098378e+02, + 6.623187e-01, + 6.250000e-03, + -3.504771e+03, + 3.721805e+02, + 3.219475e+00, + 3.484375e-02, + -6.289506e+03, + 8.722241e+02, + 1.237269e+01, + 1.653125e-01, + -1.480606e+04, + 1.913931e+03, + 3.734160e+01, + 6.228125e-01, + -2.450066e+04, + 3.351021e+03, + 9.544644e+01, + 1.985000e+00, + -3.693950e+04, + 5.083189e+03, + 2.063989e+02, + 5.391406e+00, + -4.358414e+04, + 6.496516e+03, + 3.861177e+02, + 1.272703e+01, + -4.530622e+04, + 7.428171e+03, + 6.366847e+02, + 2.650891e+01, + -4.733767e+04, + 7.964659e+03, + 9.501384e+02, + 4.969906e+01, + -5.370278e+04, + 8.090009e+03, + 1.307795e+03, + 8.545641e+01, + -3.321384e+04, + 6.411379e+03, + 1.669725e+03, + 1.365462e+02, + -3.641652e+04, + 5.884973e+03, + 2.004006e+03, + 2.040570e+02, + -2.540098e+04, + 4.300449e+03, + 2.297230e+03, + 2.892628e+02, + -2.760640e+04, + 3.474278e+03, + 2.524065e+03, + 3.914722e+02, + -8.048468e+03, + 1.366510e+03, + 2.669037e+03, + 5.095961e+02, + -2.029543e+04, + 1.620800e+03, + 2.744637e+03, + 6.402722e+02, + -3.964493e+03, + -2.191741e+02, + 2.750646e+03, + 7.826442e+02, + -1.106059e+04, + 3.180232e+01, + 2.691209e+03, + 9.316025e+02, + -4.643371e+03, + -8.533850e+02, + 2.583124e+03, + 1.085744e+03, + -4.533634e+03, + -9.829180e+02, + 2.425278e+03, + 1.240435e+03, + -6.144697e+03, + -9.649133e+02, + 2.239377e+03, + 1.393075e+03, + 1.615287e+03, + -1.671132e+03, + 2.018903e+03, + 1.540777e+03, + -9.492625e+03, + -5.137586e+02, + 1.801463e+03, + 1.679387e+03, + -4.863360e+02, + -1.552130e+03, + 1.555354e+03, + 1.810186e+03, + -4.150248e+03, + -9.569455e+02, + 1.295372e+03, + 1.925326e+03, + -3.336249e+03, + -9.666328e+02, + 1.043430e+03, + 2.025790e+03, + -8.928017e+03, + -2.828557e+02, + 7.918380e+02, + 2.108700e+03, + -8.901351e+03, + -2.240739e+02, + 5.052828e+02, + 2.172922e+03, + -6.226979e+03, + -2.346247e+01, + 2.056987e+02, + 2.211881e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.915526e+02, + 7.366238e+00, + 0, + 0, + 6.163369e+01, + 1.204175e+01, + 9.225802e-02, + 6.250000e-04, + -6.773000e+02, + 7.896783e+01, + 4.201401e-01, + 3.750000e-03, + -1.616556e+03, + 2.639201e+02, + 2.241390e+00, + 2.343750e-02, + -1.059666e+04, + 9.232364e+02, + 9.386152e+00, + 1.187500e-01, + -8.791318e+03, + 1.500107e+03, + 3.211158e+01, + 5.154688e-01, + -2.227497e+04, + 2.999099e+03, + 8.091825e+01, + 1.660469e+00, + -3.111629e+04, + 4.548813e+03, + 1.797262e+02, + 4.607656e+00, + -4.734025e+04, + 6.313047e+03, + 3.438787e+02, + 1.107969e+01, + -3.301271e+04, + 6.534868e+03, + 5.771119e+02, + 2.356234e+01, + -5.497932e+04, + 8.077472e+03, + 8.696235e+02, + 4.460859e+01, + -3.691249e+04, + 7.075388e+03, + 1.212190e+03, + 7.774641e+01, + -4.535714e+04, + 7.102579e+03, + 1.562845e+03, + 1.251120e+02, + -3.169379e+04, + 5.490801e+03, + 1.899280e+03, + 1.890709e+02, + -1.728180e+04, + 3.949454e+03, + 2.183344e+03, + 2.698602e+02, + -3.714132e+04, + 4.285851e+03, + 2.423673e+03, + 3.672678e+02, + -5.215022e+03, + 1.183427e+03, + 2.583754e+03, + 4.816480e+02, + -1.863398e+04, + 1.625851e+03, + 2.661413e+03, + 6.081128e+02, + -6.406195e+03, + 7.803378e+01, + 2.681066e+03, + 7.464519e+02, + -1.136441e+04, + 7.752814e+01, + 2.632242e+03, + 8.920981e+02, + -2.047264e+03, + -1.002831e+03, + 2.526395e+03, + 1.042912e+03, + -6.248742e+03, + -7.263883e+02, + 2.379661e+03, + 1.194150e+03, + -5.489763e+03, + -9.816353e+02, + 2.205342e+03, + 1.344432e+03, + -1.167746e+02, + -1.486682e+03, + 1.991891e+03, + 1.489923e+03, + -6.259862e+03, + -8.113410e+02, + 1.773796e+03, + 1.626878e+03, + -1.374682e+03, + -1.342055e+03, + 1.539054e+03, + 1.755264e+03, + -5.056021e+03, + -8.353907e+02, + 1.295621e+03, + 1.869990e+03, + -4.537758e+03, + -8.790940e+02, + 1.044749e+03, + 1.970797e+03, + -6.706975e+03, + -5.509051e+02, + 7.801558e+02, + 2.053670e+03, + -1.020946e+04, + -4.372454e+01, + 5.016635e+02, + 2.116272e+03, + -6.221044e+03, + -1.982749e+01, + 1.997960e+02, + 2.155378e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.471287e+01, + 3.454011e+00, + 0, + 0, + -5.151738e+01, + 1.088983e+01, + 4.862104e-02, + 3.125000e-04, + -5.554154e+02, + 5.853337e+01, + 2.954357e-01, + 2.500000e-03, + -1.401631e+03, + 1.899381e+02, + 1.613639e+00, + 1.671875e-02, + -3.677010e+03, + 5.381794e+02, + 6.576231e+00, + 8.437500e-02, + -1.130930e+04, + 1.351274e+03, + 2.217409e+01, + 3.490625e-01, + -1.610460e+04, + 2.382976e+03, + 6.220396e+01, + 1.221875e+00, + -3.182774e+04, + 4.050808e+03, + 1.429730e+02, + 3.534531e+00, + -2.661339e+04, + 4.911419e+03, + 2.820920e+02, + 8.833438e+00, + -4.684400e+04, + 6.742349e+03, + 4.845560e+02, + 1.910938e+01, + -3.607371e+04, + 6.710619e+03, + 7.550675e+02, + 3.735891e+01, + -4.154781e+04, + 7.152810e+03, + 1.067429e+03, + 6.618859e+01, + -4.204317e+04, + 6.774326e+03, + 1.407564e+03, + 1.085970e+02, + -2.942193e+04, + 5.355563e+03, + 1.733269e+03, + 1.666419e+02, + -2.313904e+04, + 4.280577e+03, + 2.017180e+03, + 2.408670e+02, + -2.385720e+04, + 3.520820e+03, + 2.254320e+03, + 3.314445e+02, + -1.513209e+04, + 2.112956e+03, + 2.426267e+03, + 4.378639e+02, + -9.126023e+03, + 1.113924e+03, + 2.524502e+03, + 5.577991e+02, + -1.571455e+04, + 1.029708e+03, + 2.566730e+03, + 6.890491e+02, + -7.238440e+03, + -2.206829e+02, + 2.538549e+03, + 8.297720e+02, + -3.160979e+03, + -7.760560e+02, + 2.439782e+03, + 9.749502e+02, + -5.602452e+03, + -6.902848e+02, + 2.308307e+03, + 1.121456e+03, + -3.553157e+03, + -1.014479e+03, + 2.146930e+03, + 1.267419e+03, + -4.461083e+03, + -9.863057e+02, + 1.956534e+03, + 1.409364e+03, + -2.326809e+03, + -1.209321e+03, + 1.742287e+03, + 1.544723e+03, + -4.135229e+03, + -9.712685e+02, + 1.515864e+03, + 1.670126e+03, + -3.963535e+03, + -9.751278e+02, + 1.278348e+03, + 1.783945e+03, + -3.590545e+03, + -9.317344e+02, + 1.027352e+03, + 1.882948e+03, + -7.816601e+03, + -3.861471e+02, + 7.759248e+02, + 1.964524e+03, + -8.824559e+03, + -1.916167e+02, + 4.991662e+02, + 2.027263e+03, + -6.003275e+03, + -4.576937e+01, + 2.081407e+02, + 2.066007e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -5.625582e+01, + 1.932575e+00, + 0, + 0, + 6.414978e+01, + 1.472767e+00, + 2.207452e-02, + 1.562500e-04, + -2.922836e+02, + 2.777474e+01, + 8.841004e-02, + 7.812500e-04, + -8.188740e+02, + 1.059625e+02, + 6.968160e-01, + 6.718750e-03, + -2.889488e+03, + 3.500503e+02, + 3.437535e+00, + 4.109375e-02, + -6.748480e+03, + 8.561885e+02, + 1.311485e+01, + 1.956250e-01, + -9.511546e+03, + 1.611095e+03, + 3.896265e+01, + 7.334375e-01, + -2.290021e+04, + 3.066546e+03, + 9.552066e+01, + 2.243906e+00, + -2.821286e+04, + 4.251733e+03, + 2.028843e+02, + 5.967656e+00, + -2.913541e+04, + 5.203704e+03, + 3.675117e+02, + 1.368859e+01, + -4.048369e+04, + 6.372044e+03, + 5.934689e+02, + 2.775234e+01, + -3.547831e+04, + 6.262590e+03, + 8.720572e+02, + 5.110688e+01, + -3.218587e+04, + 5.921591e+03, + 1.172909e+03, + 8.616875e+01, + -2.477427e+04, + 5.121564e+03, + 1.475680e+03, + 1.350383e+02, + -2.868072e+04, + 4.746820e+03, + 1.762617e+03, + 1.991086e+02, + -1.754454e+04, + 3.266592e+03, + 2.009591e+03, + 2.794042e+02, + -1.913506e+04, + 2.655854e+03, + 2.197015e+03, + 3.748694e+02, + -9.992284e+03, + 1.320722e+03, + 2.319693e+03, + 4.845859e+02, + -1.419455e+04, + 1.062222e+03, + 2.376302e+03, + 6.057533e+02, + -2.694677e+03, + -3.023730e+02, + 2.365281e+03, + 7.364186e+02, + -9.185589e+03, + -8.118530e+00, + 2.302949e+03, + 8.721534e+02, + -2.847409e+03, + -8.444596e+02, + 2.197532e+03, + 1.011741e+03, + -3.035145e+03, + -8.775668e+02, + 2.051168e+03, + 1.150592e+03, + -5.533588e+03, + -7.385513e+02, + 1.887015e+03, + 1.286758e+03, + -3.565998e+03, + -1.040906e+03, + 1.691788e+03, + 1.417959e+03, + -2.327347e+03, + -1.126813e+03, + 1.469339e+03, + 1.539923e+03, + -3.906176e+03, + -8.827879e+02, + 1.242034e+03, + 1.649925e+03, + -6.221863e+03, + -6.310295e+02, + 1.007942e+03, + 1.746547e+03, + -3.114073e+03, + -8.975397e+02, + 7.474580e+02, + 1.826920e+03, + -1.186080e+04, + 2.407749e+02, + 4.982586e+02, + 1.886371e+03, + -6.394004e+03, + -1.686521e+01, + 2.046311e+02, + 1.926321e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.355371e+02, + 8.998932e+00, + 0, + 0, + -3.468260e+02, + 4.003623e+01, + 1.728223e-01, + 1.406250e-03, + -1.659534e+03, + 1.606414e+02, + 1.180182e+00, + 1.281250e-02, + -5.133751e+02, + 3.182364e+02, + 5.307610e+00, + 7.484375e-02, + -1.044783e+04, + 1.132211e+03, + 1.723019e+01, + 2.984375e-01, + -1.232620e+04, + 1.809523e+03, + 5.164214e+01, + 1.100625e+00, + -1.492798e+04, + 2.716347e+03, + 1.170312e+02, + 3.201250e+00, + -2.509641e+04, + 4.034536e+03, + 2.285777e+02, + 7.860000e+00, + -3.139992e+04, + 4.936112e+03, + 3.976305e+02, + 1.709562e+01, + -1.992734e+04, + 4.752382e+03, + 6.133259e+02, + 3.325813e+01, + -3.583565e+04, + 5.733661e+03, + 8.653644e+02, + 5.850203e+01, + -1.864658e+04, + 4.463079e+03, + 1.140041e+03, + 9.577875e+01, + -2.806870e+04, + 4.628337e+03, + 1.403590e+03, + 1.460806e+02, + -1.224450e+04, + 3.007469e+03, + 1.643849e+03, + 2.111303e+02, + -1.837221e+04, + 2.895966e+03, + 1.840158e+03, + 2.900925e+02, + -1.305949e+04, + 1.813863e+03, + 1.991237e+03, + 3.832811e+02, + -7.995788e+03, + 9.019857e+02, + 2.074227e+03, + 4.884772e+02, + -5.202137e+03, + 3.292653e+02, + 2.101192e+03, + 6.031734e+02, + -9.894927e+03, + 3.490710e+02, + 2.086841e+03, + 7.252181e+02, + -2.081824e+03, + -6.584184e+02, + 2.017335e+03, + 8.526909e+02, + -5.753047e+03, + -4.455308e+02, + 1.904978e+03, + 9.807998e+02, + -2.548608e+03, + -9.027576e+02, + 1.761653e+03, + 1.108055e+03, + -4.593746e+03, + -7.480921e+02, + 1.589904e+03, + 1.230419e+03, + -2.237374e+03, + -1.028298e+03, + 1.394230e+03, + 1.345830e+03, + -4.404710e+03, + -7.547906e+02, + 1.184581e+03, + 1.450460e+03, + -3.128602e+03, + -8.687342e+02, + 9.614427e+02, + 1.542825e+03, + -7.364928e+03, + -3.355787e+02, + 7.322318e+02, + 1.619357e+03, + -9.377841e+03, + -7.234116e+01, + 4.767442e+02, + 1.678824e+03, + -6.106783e+03, + -2.487557e+00, + 1.931677e+02, + 1.715997e+03, +}; + +double solarDataset360[] = +{ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.078413e+03, + 7.118205e+01, + 0, + 0, + 4.658139e+03, + -1.838006e+01, + 1.514489e-01, + 5.208333e-04, + -1.266691e+04, + 2.223605e+02, + 2.846817e-01, + 1.302083e-03, + 5.376673e+03, + 1.263979e+02, + 1.585011e+00, + 7.812500e-03, + -6.287382e+03, + 6.310960e+02, + 4.070404e+00, + 2.630208e-02, + -1.089068e+04, + 1.566596e+03, + 1.304182e+01, + 9.713542e-02, + -5.578495e+04, + 4.275269e+03, + 3.968016e+01, + 3.502604e-01, + -7.874206e+04, + 8.041790e+03, + 1.128851e+02, + 1.215885e+00, + -1.523996e+05, + 1.484058e+04, + 2.762902e+02, + 3.709896e+00, + -2.545257e+05, + 2.361556e+04, + 6.036183e+02, + 1.011875e+01, + -2.941122e+05, + 3.066092e+04, + 1.160209e+03, + 2.459557e+01, + -3.612497e+05, + 3.709042e+04, + 1.969276e+03, + 5.311250e+01, + -2.820800e+05, + 3.689189e+04, + 3.009049e+03, + 1.034445e+02, + -3.813699e+05, + 4.027793e+04, + 4.213037e+03, + 1.833859e+02, + -3.197931e+05, + 3.414742e+04, + 5.485024e+03, + 3.019268e+02, + -1.923698e+05, + 2.458254e+04, + 6.615509e+03, + 4.632190e+02, + -2.078027e+05, + 2.080724e+04, + 7.548980e+03, + 6.677510e+02, + -1.360611e+05, + 1.255134e+04, + 8.240067e+03, + 9.159479e+02, + -6.729497e+04, + 5.762938e+03, + 8.622622e+03, + 1.202090e+03, + -9.900171e+04, + 4.710833e+03, + 8.774927e+03, + 1.519642e+03, + -3.788016e+04, + -1.223413e+03, + 8.689075e+03, + 1.864136e+03, + -3.007086e+04, + -2.674663e+03, + 8.385744e+03, + 2.224184e+03, + -1.454468e+04, + -4.149445e+03, + 7.962237e+03, + 2.593449e+03, + -3.313233e+04, + -3.256536e+03, + 7.461974e+03, + 2.965295e+03, + -2.461750e+03, + -5.667421e+03, + 6.865987e+03, + 3.335167e+03, + -5.859709e+03, + -4.818237e+03, + 6.224765e+03, + 3.692920e+03, + -1.114171e+04, + -4.055929e+03, + 5.606249e+03, + 4.036827e+03, + -2.940298e+01, + -4.599486e+03, + 4.980260e+03, + 4.363959e+03, + -8.192323e+03, + -3.332635e+03, + 4.380331e+03, + 4.669007e+03, + -1.314651e+02, + -3.690650e+03, + 3.804426e+03, + 4.952310e+03, + -9.321444e+03, + -2.355513e+03, + 3.265525e+03, + 5.209421e+03, + -4.323778e+03, + -2.664833e+03, + 2.740069e+03, + 5.441705e+03, + -4.030446e+03, + -2.268601e+03, + 2.225562e+03, + 5.643180e+03, + -7.709530e+03, + -1.532269e+03, + 1.753678e+03, + 5.813184e+03, + -9.915496e+03, + -1.081222e+03, + 1.297245e+03, + 5.951777e+03, + -1.918399e+04, + 1.650147e+02, + 8.356870e+02, + 6.055439e+03, + -9.182623e+03, + -1.363456e+02, + 3.168424e+02, + 6.120820e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.007459e+06, + 1.920534e+03, + 0, + 0, + 4.479837e+05, + -7.065871e+02, + 0, + 2.604167e-04, + 0, + 0, + 0, + 0, + -4.964101e+04, + 1.630114e+02, + 0, + 0, + 2.106646e+04, + -9.205597e+01, + 0, + 2.604167e-04, + 0, + 0, + 0, + 0, + -1.305437e+04, + 1.325834e+02, + 0, + 0, + 7.455004e+03, + -2.985865e+01, + 3.840792e-01, + 1.562500e-03, + -2.055425e+04, + 4.505399e+02, + 7.714470e-01, + 4.166667e-03, + 1.086675e+04, + 2.797690e+02, + 4.050099e+00, + 2.395833e-02, + -1.873506e+04, + 1.575040e+03, + 1.070445e+01, + 8.072917e-02, + -4.327245e+04, + 3.801002e+03, + 3.540976e+01, + 3.059896e-01, + -1.102894e+05, + 8.242103e+03, + 1.027385e+02, + 1.085156e+00, + -7.645743e+04, + 1.218373e+04, + 2.565037e+02, + 3.423437e+00, + -3.095499e+05, + 2.422173e+04, + 5.541844e+02, + 9.238802e+00, + -1.908061e+05, + 2.675484e+04, + 1.088555e+03, + 2.286589e+01, + -3.934663e+05, + 3.821301e+04, + 1.856451e+03, + 4.946328e+01, + -3.390953e+05, + 3.834252e+04, + 2.902994e+03, + 9.776536e+01, + -3.420266e+05, + 3.790490e+04, + 4.089229e+03, + 1.755013e+02, + -2.686944e+05, + 3.228911e+04, + 5.315213e+03, + 2.902633e+02, + -2.564538e+05, + 2.755072e+04, + 6.453482e+03, + 4.467523e+02, + -1.509348e+05, + 1.825991e+04, + 7.399666e+03, + 6.475846e+02, + -1.630120e+05, + 1.453409e+04, + 8.097017e+03, + 8.903924e+02, + -9.950958e+04, + 7.104934e+03, + 8.521488e+03, + 1.172941e+03, + -2.923012e+04, + 1.025880e+03, + 8.643788e+03, + 1.487047e+03, + -8.585662e+04, + 2.418502e+03, + 8.589889e+03, + 1.824949e+03, + -1.614087e+04, + -3.639570e+03, + 8.338546e+03, + 2.183701e+03, + -2.320497e+04, + -3.485113e+03, + 7.912837e+03, + 2.550157e+03, + -2.187702e+04, + -3.972423e+03, + 7.416360e+03, + 2.920199e+03, + -1.034810e+04, + -4.884562e+03, + 6.835820e+03, + 3.287367e+03, + -2.759089e+03, + -5.058797e+03, + 6.209527e+03, + 3.644522e+03, + -9.328274e+03, + -4.074038e+03, + 5.594421e+03, + 3.987341e+03, + -4.936422e+03, + -4.126474e+03, + 4.986817e+03, + 4.314099e+03, + -3.321617e+03, + -3.792265e+03, + 4.386012e+03, + 4.620225e+03, + -1.003521e+04, + -2.819991e+03, + 3.816137e+03, + 4.903331e+03, + 2.907803e+03, + -3.685267e+03, + 3.246729e+03, + 5.162089e+03, + -7.981799e+03, + -2.001596e+03, + 2.732990e+03, + 5.390627e+03, + -8.279987e+03, + -1.868805e+03, + 2.254065e+03, + 5.593927e+03, + -5.136369e+03, + -1.945934e+03, + 1.758273e+03, + 5.766632e+03, + -9.493658e+03, + -1.095077e+03, + 1.289392e+03, + 5.904171e+03, + -1.816478e+04, + 8.782733e+01, + 8.362875e+02, + 6.007321e+03, + -1.016501e+04, + -5.757161e+01, + 3.316172e+02, + 6.072978e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.106646e+04, + 9.205597e+01, + 0, + 0, + 9.951134e+03, + -5.583492e+01, + 0, + 2.604167e-04, + -6.862369e+03, + 7.979095e+01, + 0, + 0, + 3.093701e+03, + 1.042453e+01, + 2.962179e-01, + 1.041667e-03, + -3.848975e+03, + 1.884300e+02, + 7.173252e-01, + 3.645833e-03, + -1.922464e+03, + 4.118046e+02, + 2.755566e+00, + 1.614583e-02, + -1.029728e+04, + 1.238807e+03, + 9.037110e+00, + 6.432292e-02, + -5.326510e+04, + 3.551966e+03, + 2.965222e+01, + 2.510417e-01, + -5.119148e+04, + 6.178442e+03, + 8.801668e+01, + 9.252604e-01, + -1.102076e+05, + 1.208818e+04, + 2.178717e+02, + 2.875260e+00, + -2.455519e+05, + 2.133109e+04, + 4.927790e+02, + 8.033333e+00, + -2.314605e+05, + 2.675653e+04, + 9.837470e+02, + 2.021667e+01, + -3.383926e+05, + 3.503899e+04, + 1.713479e+03, + 4.473359e+01, + -3.279210e+05, + 3.710837e+04, + 2.699082e+03, + 8.941484e+01, + -3.295655e+05, + 3.695410e+04, + 3.847503e+03, + 1.622500e+02, + -2.654830e+05, + 3.200589e+04, + 5.049391e+03, + 2.708594e+02, + -2.374300e+05, + 2.701443e+04, + 6.179434e+03, + 4.202516e+02, + -1.686326e+05, + 1.951749e+04, + 7.141543e+03, + 6.132620e+02, + -1.530711e+05, + 1.439417e+04, + 7.865806e+03, + 8.487388e+02, + -8.333989e+04, + 7.055607e+03, + 8.314596e+03, + 1.123732e+03, + -8.130111e+04, + 4.141743e+03, + 8.497304e+03, + 1.431033e+03, + -3.575768e+04, + -5.696968e+02, + 8.448170e+03, + 1.764856e+03, + -3.255295e+04, + -1.826416e+03, + 8.210999e+03, + 2.116095e+03, + -3.660834e+04, + -2.550753e+03, + 7.848763e+03, + 2.478988e+03, + -7.337777e+03, + -5.008166e+03, + 7.349120e+03, + 2.846617e+03, + -5.379678e+03, + -4.784496e+03, + 6.777142e+03, + 3.209571e+03, + -2.374637e+04, + -3.331316e+03, + 6.206260e+03, + 3.564630e+03, + 1.080518e+04, + -5.854954e+03, + 5.579585e+03, + 3.908975e+03, + -1.909992e+04, + -2.668851e+03, + 4.981595e+03, + 4.232768e+03, + 1.911058e+03, + -4.437068e+03, + 4.390299e+03, + 4.540824e+03, + -3.848120e+03, + -3.213454e+03, + 3.806091e+03, + 4.822876e+03, + -9.851976e+03, + -2.361374e+03, + 3.277626e+03, + 5.081202e+03, + -1.578794e+03, + -2.943684e+03, + 2.741918e+03, + 5.314140e+03, + -5.601199e+03, + -2.034313e+03, + 2.236027e+03, + 5.515390e+03, + -8.507381e+03, + -1.484607e+03, + 1.769983e+03, + 5.687009e+03, + -8.981222e+03, + -1.217297e+03, + 1.303053e+03, + 5.826869e+03, + -1.807778e+04, + 6.647867e+01, + 8.405294e+02, + 5.930647e+03, + -1.028919e+04, + -5.100950e+01, + 3.341801e+02, + 5.996596e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.528365e+03, + 1.907311e+01, + 0, + 0, + 1.516070e+03, + 1.652342e+00, + 7.814024e-02, + 2.604167e-04, + -1.566422e+04, + 2.938113e+02, + 2.450638e-01, + 1.041667e-03, + 9.323103e+03, + 7.951170e+01, + 2.065634e+00, + 1.145833e-02, + -7.689699e+03, + 8.647270e+02, + 5.179331e+00, + 3.828125e-02, + -4.120250e+04, + 2.746625e+03, + 1.943548e+01, + 1.575521e-01, + -5.390461e+04, + 5.341204e+03, + 6.456184e+01, + 6.408854e-01, + -1.009697e+05, + 1.038629e+04, + 1.723484e+02, + 2.164844e+00, + -1.920166e+05, + 1.804640e+04, + 4.048162e+02, + 6.370052e+00, + -2.372478e+05, + 2.492915e+04, + 8.320197e+02, + 1.654844e+01, + -2.793231e+05, + 3.114679e+04, + 1.491609e+03, + 3.777448e+01, + -3.104765e+05, + 3.519482e+04, + 2.392658e+03, + 7.703568e+01, + -3.177075e+05, + 3.568983e+04, + 3.482617e+03, + 1.424852e+02, + -2.494221e+05, + 3.108444e+04, + 4.644386e+03, + 2.418099e+02, + -2.364069e+05, + 2.715189e+04, + 5.759209e+03, + 3.802539e+02, + -1.404746e+05, + 1.898809e+04, + 6.731675e+03, + 5.613974e+02, + -2.017016e+05, + 1.743282e+04, + 7.504484e+03, + 7.844820e+02, + -4.320413e+04, + 5.367012e+03, + 7.992650e+03, + 1.048910e+03, + -9.571801e+04, + 5.908238e+03, + 8.211533e+03, + 1.344214e+03, + -3.686322e+04, + 6.522573e+01, + 8.234419e+03, + 1.668699e+03, + -4.436791e+04, + -8.088656e+02, + 8.044739e+03, + 2.011998e+03, + -2.002588e+04, + -3.383672e+03, + 7.702298e+03, + 2.368391e+03, + -1.741256e+04, + -3.854559e+03, + 7.237658e+03, + 2.728893e+03, + -7.888695e+03, + -4.546112e+03, + 6.704484e+03, + 3.087804e+03, + -6.588850e+03, + -4.351038e+03, + 6.137185e+03, + 3.439195e+03, + -1.547834e+04, + -3.487809e+03, + 5.565533e+03, + 3.779451e+03, + 3.267247e+03, + -4.786579e+03, + 4.960190e+03, + 4.105218e+03, + -6.089460e+03, + -3.295662e+03, + 4.377885e+03, + 4.409076e+03, + -1.218322e+04, + -2.582626e+03, + 3.837023e+03, + 4.693073e+03, + 3.616890e+03, + -3.794143e+03, + 3.268057e+03, + 4.953780e+03, + -9.102661e+03, + -1.913822e+03, + 2.750126e+03, + 5.183632e+03, + -6.696343e+03, + -2.063778e+03, + 2.263473e+03, + 5.388297e+03, + -3.048448e+03, + -2.093974e+03, + 1.768789e+03, + 5.561364e+03, + -1.551802e+04, + -4.318095e+02, + 1.323227e+03, + 5.700141e+03, + -1.234976e+04, + -6.368560e+02, + 8.363357e+02, + 5.807329e+03, + -9.311490e+03, + -1.488186e+02, + 3.568924e+02, + 5.871500e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.492148e+03, + 2.451223e+01, + 0, + 0, + 1.641003e+03, + 8.115125e+00, + 1.339882e-01, + 5.208333e-04, + -1.214574e+04, + 3.860017e+02, + 4.756144e-01, + 2.343750e-03, + -1.064944e+04, + 7.243819e+02, + 4.335378e+00, + 2.500000e-02, + -6.266723e+03, + 1.498871e+03, + 1.515545e+01, + 1.213542e-01, + -4.724146e+04, + 4.315847e+03, + 4.553783e+01, + 4.554687e-01, + -8.443089e+04, + 8.583278e+03, + 1.309248e+02, + 1.597396e+00, + -1.541231e+05, + 1.527165e+04, + 3.224487e+02, + 4.907813e+00, + -2.382286e+05, + 2.297833e+04, + 6.902681e+02, + 1.323568e+01, + -2.235609e+05, + 2.735690e+04, + 1.279864e+03, + 3.133542e+01, + -2.906342e+05, + 3.320621e+04, + 2.096545e+03, + 6.539010e+01, + -3.123834e+05, + 3.467834e+04, + 3.128177e+03, + 1.236672e+02, + -2.393461e+05, + 3.025589e+04, + 4.250709e+03, + 2.140122e+02, + -2.028333e+05, + 2.609503e+04, + 5.342867e+03, + 3.417609e+02, + -2.151191e+05, + 2.250055e+04, + 6.337131e+03, + 5.109326e+02, + -9.763169e+04, + 1.271519e+04, + 7.112202e+03, + 7.229203e+02, + -1.312211e+05, + 1.094586e+04, + 7.636174e+03, + 9.727784e+02, + -3.907836e+04, + 2.892178e+03, + 7.911983e+03, + 1.258277e+03, + -5.691819e+04, + 2.234234e+03, + 7.958878e+03, + 1.569822e+03, + -4.605984e+04, + -2.949351e+02, + 7.845258e+03, + 1.903886e+03, + -9.288844e+03, + -3.584873e+03, + 7.538797e+03, + 2.252188e+03, + -3.275040e+04, + -2.362390e+03, + 7.129354e+03, + 2.605553e+03, + 7.240576e+03, + -5.434321e+03, + 6.628154e+03, + 2.960763e+03, + -2.435119e+04, + -2.700395e+03, + 6.099256e+03, + 3.307801e+03, + -3.407342e+03, + -4.548247e+03, + 5.539707e+03, + 3.647942e+03, + -4.437134e+03, + -3.961614e+03, + 4.941027e+03, + 3.970917e+03, + -3.090062e+03, + -3.635715e+03, + 4.368076e+03, + 4.274897e+03, + -6.315304e+03, + -2.954206e+03, + 3.823070e+03, + 4.557586e+03, + -5.534764e+03, + -2.764660e+03, + 3.293166e+03, + 4.817570e+03, + -7.186551e+03, + -2.326088e+03, + 2.771736e+03, + 5.051273e+03, + -2.914677e+03, + -2.446875e+03, + 2.255978e+03, + 5.256005e+03, + -7.073055e+03, + -1.589272e+03, + 1.777935e+03, + 5.427988e+03, + -1.092444e+04, + -9.714652e+02, + 1.326496e+03, + 5.568739e+03, + -1.803434e+04, + 5.807577e+00, + 8.590316e+02, + 5.675268e+03, + -1.059246e+04, + -4.287520e+01, + 3.420559e+02, + 5.742487e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -5.109094e+03, + 3.580031e+01, + 0, + 0, + 2.803934e+03, + -2.399769e+01, + 0, + 2.604167e-04, + -3.970877e+03, + 8.834116e+01, + 0, + 0, + -5.636564e+02, + 1.192399e+02, + 6.512142e-01, + 2.864583e-03, + -6.086357e+02, + 3.883172e+02, + 2.468692e+00, + 1.562500e-02, + -2.893914e+04, + 1.718661e+03, + 9.629309e+00, + 7.291667e-02, + -2.076572e+04, + 3.183627e+03, + 3.674586e+01, + 3.437500e-01, + -1.011023e+05, + 8.189104e+03, + 1.062582e+02, + 1.252344e+00, + -1.095898e+05, + 1.282006e+04, + 2.767597e+02, + 4.090625e+00, + -2.297269e+05, + 2.151665e+04, + 6.004328e+02, + 1.125651e+01, + -2.107325e+05, + 2.568211e+04, + 1.146269e+03, + 2.735495e+01, + -2.800842e+05, + 3.166650e+04, + 1.911957e+03, + 5.823177e+01, + -2.923688e+05, + 3.303608e+04, + 2.891607e+03, + 1.118773e+02, + -2.033237e+05, + 2.870850e+04, + 3.969933e+03, + 1.959010e+02, + -2.617431e+05, + 2.851329e+04, + 5.055149e+03, + 3.158836e+02, + -1.440848e+05, + 1.921772e+04, + 6.043374e+03, + 4.774372e+02, + -1.420361e+05, + 1.553418e+04, + 6.820003e+03, + 6.792667e+02, + -9.006131e+04, + 9.284458e+03, + 7.382916e+03, + 9.207971e+02, + -7.093812e+04, + 5.455005e+03, + 7.700927e+03, + 1.196878e+03, + -3.964068e+04, + 1.575567e+03, + 7.802084e+03, + 1.502182e+03, + -7.280366e+04, + 1.632438e+03, + 7.724594e+03, + 1.829778e+03, + 1.690897e+04, + -5.252913e+03, + 7.429101e+03, + 2.174115e+03, + -4.574865e+04, + -9.598807e+02, + 7.041073e+03, + 2.521259e+03, + 2.816103e+03, + -5.134375e+03, + 6.581128e+03, + 2.873876e+03, + -1.565202e+04, + -3.351712e+03, + 6.045391e+03, + 3.218518e+03, + -2.906298e+03, + -4.297581e+03, + 5.498150e+03, + 3.555040e+03, + -9.963636e+03, + -3.361737e+03, + 4.936026e+03, + 3.876524e+03, + -2.334266e+02, + -3.922430e+03, + 4.370841e+03, + 4.181196e+03, + -1.330539e+04, + -2.367708e+03, + 3.827009e+03, + 4.463648e+03, + 2.006252e+03, + -3.636281e+03, + 3.271498e+03, + 4.724332e+03, + -6.128696e+03, + -2.215009e+03, + 2.749376e+03, + 4.954650e+03, + -5.894247e+03, + -2.020601e+03, + 2.272207e+03, + 5.158856e+03, + -8.330230e+03, + -1.530492e+03, + 1.802163e+03, + 5.333464e+03, + -8.185462e+03, + -1.311486e+03, + 1.331275e+03, + 5.475951e+03, + -2.089177e+04, + 3.374858e+02, + 8.719856e+02, + 5.582192e+03, + -9.930639e+03, + -1.239258e+02, + 3.378337e+02, + 5.651177e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -5.109094e+03, + 3.580031e+01, + 0, + 0, + 2.803934e+03, + -2.399769e+01, + 0, + 2.604167e-04, + -5.944797e+02, + 2.075013e+01, + 0, + 0, + -4.117657e+03, + 1.320064e+02, + 2.004808e-01, + 7.812500e-04, + 2.833792e+03, + 1.774131e+02, + 1.527515e+00, + 8.854167e-03, + -2.276165e+04, + 1.257648e+03, + 5.629040e+00, + 4.140625e-02, + -1.581115e+04, + 2.383463e+03, + 2.490926e+01, + 2.221354e-01, + -8.271046e+04, + 6.514143e+03, + 7.682795e+01, + 8.695312e-01, + -7.892773e+04, + 1.023660e+04, + 2.110950e+02, + 3.012500e+00, + -1.833413e+05, + 1.835639e+04, + 4.760003e+02, + 8.611719e+00, + -2.594243e+05, + 2.515475e+04, + 9.535555e+02, + 2.177422e+01, + -1.626629e+05, + 2.553274e+04, + 1.641990e+03, + 4.828620e+01, + -3.138765e+05, + 3.311180e+04, + 2.521424e+03, + 9.437135e+01, + -2.023791e+05, + 2.790945e+04, + 3.566488e+03, + 1.692937e+02, + -2.361401e+05, + 2.715103e+04, + 4.611801e+03, + 2.781815e+02, + -1.387146e+05, + 1.936281e+04, + 5.584871e+03, + 4.265570e+02, + -1.260435e+05, + 1.563798e+04, + 6.386036e+03, + 6.144526e+02, + -1.326077e+05, + 1.212714e+04, + 7.010195e+03, + 8.421141e+02, + -3.897682e+04, + 3.959405e+03, + 7.366325e+03, + 1.106369e+03, + -5.889334e+04, + 3.350540e+03, + 7.497170e+03, + 1.398210e+03, + -3.933554e+04, + 2.719489e+02, + 7.466882e+03, + 1.714702e+03, + -2.390631e+04, + -1.853368e+03, + 7.252314e+03, + 2.047736e+03, + -2.178522e+04, + -2.640984e+03, + 6.907977e+03, + 2.389698e+03, + -6.125885e+03, + -4.003762e+03, + 6.464812e+03, + 2.734296e+03, + -1.126017e+04, + -3.477681e+03, + 5.972548e+03, + 3.074501e+03, + -1.131751e+04, + -3.475106e+03, + 5.455067e+03, + 3.407229e+03, + -5.340261e+02, + -4.136362e+03, + 4.898586e+03, + 3.727215e+03, + -8.792165e+03, + -2.990082e+03, + 4.352596e+03, + 4.028768e+03, + -4.742079e+03, + -3.169825e+03, + 3.815352e+03, + 4.311590e+03, + -4.254148e+03, + -2.851538e+03, + 3.279048e+03, + 4.570477e+03, + -4.354544e+03, + -2.480152e+03, + 2.766874e+03, + 4.803165e+03, + -7.432540e+03, + -1.878460e+03, + 2.281570e+03, + 5.007989e+03, + -6.205415e+03, + -1.788706e+03, + 1.802434e+03, + 5.183474e+03, + -1.145931e+04, + -9.481364e+02, + 1.336118e+03, + 5.325439e+03, + -1.587470e+04, + -2.321854e+02, + 8.590106e+02, + 5.432634e+03, + -1.049374e+04, + -6.518902e+01, + 3.575002e+02, + 5.499596e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -8.531048e+02, + 1.695939e+01, + 0, + 0, + 6.095111e+02, + 9.076932e+00, + 1.122616e-01, + 5.208333e-04, + -6.857359e+02, + 1.069152e+02, + 3.785397e-01, + 2.343750e-03, + -6.528912e+03, + 5.478130e+02, + 2.211863e+00, + 1.484375e-02, + -2.807616e+04, + 1.924054e+03, + 1.181174e+01, + 9.531250e-02, + -4.135252e+04, + 3.975660e+03, + 4.662733e+01, + 4.854167e-01, + -6.513897e+04, + 7.571929e+03, + 1.340027e+02, + 1.815104e+00, + -1.130550e+05, + 1.330006e+04, + 3.248641e+02, + 5.579167e+00, + -2.128461e+05, + 2.104638e+04, + 6.894764e+02, + 1.487135e+01, + -1.938231e+05, + 2.394323e+04, + 1.270357e+03, + 3.495443e+01, + -2.250683e+05, + 2.733125e+04, + 2.036520e+03, + 7.189036e+01, + -1.878061e+05, + 2.633878e+04, + 2.957468e+03, + 1.331286e+02, + -2.270545e+05, + 2.650296e+04, + 3.950502e+03, + 2.252544e+02, + -1.452222e+05, + 1.974198e+04, + 4.908788e+03, + 3.544242e+02, + -9.739988e+04, + 1.480522e+04, + 5.714679e+03, + 5.215013e+02, + -1.391311e+05, + 1.365247e+04, + 6.380017e+03, + 7.267320e+02, + -4.788766e+04, + 5.382256e+03, + 6.821131e+03, + 9.697984e+02, + -5.285286e+04, + 3.809721e+03, + 7.022384e+03, + 1.241959e+03, + -3.337682e+04, + 9.042881e+02, + 7.062654e+03, + 1.539764e+03, + -4.007437e+04, + -2.699339e+01, + 6.941219e+03, + 1.856429e+03, + -6.051283e+03, + -3.209377e+03, + 6.660347e+03, + 2.185851e+03, + -2.435908e+04, + -2.124954e+03, + 6.283149e+03, + 2.518370e+03, + 2.551445e+03, + -4.363071e+03, + 5.832923e+03, + 2.851286e+03, + -1.489483e+04, + -2.673771e+03, + 5.352245e+03, + 3.175629e+03, + -9.389643e+03, + -3.278006e+03, + 4.853753e+03, + 3.491487e+03, + 3.161923e+03, + -4.031601e+03, + 4.306797e+03, + 3.791312e+03, + -1.194090e+04, + -2.196499e+03, + 3.796276e+03, + 4.069944e+03, + -2.953957e+03, + -3.004063e+03, + 3.287319e+03, + 4.329823e+03, + -6.149918e+03, + -2.304854e+03, + 2.774682e+03, + 4.562834e+03, + -3.373794e+03, + -2.296007e+03, + 2.282599e+03, + 4.768486e+03, + -1.034299e+04, + -1.265867e+03, + 1.820241e+03, + 4.943532e+03, + -1.110375e+04, + -1.092537e+03, + 1.348590e+03, + 5.088307e+03, + -1.629907e+04, + -2.127533e+02, + 8.538122e+02, + 5.195697e+03, + -1.089887e+04, + -2.417175e+00, + 3.439132e+02, + 5.261939e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.508513e+01, + 4.753078e+00, + 0, + 0, + -7.542336e+02, + 4.194538e+01, + 5.820865e-02, + 2.604167e-04, + -1.284200e+03, + 1.590937e+02, + 6.480504e-01, + 3.906250e-03, + -7.617453e+03, + 6.908946e+02, + 3.653193e+00, + 2.812500e-02, + -2.285529e+04, + 2.070239e+03, + 1.729678e+01, + 1.656250e-01, + -4.265825e+04, + 4.564970e+03, + 6.200908e+01, + 7.559896e-01, + -8.135927e+04, + 8.796250e+03, + 1.745256e+02, + 2.714323e+00, + -1.186992e+05, + 1.383851e+04, + 4.094748e+02, + 8.109375e+00, + -1.729788e+05, + 1.934059e+04, + 8.160818e+02, + 2.061328e+01, + -1.630315e+05, + 2.150283e+04, + 1.411697e+03, + 4.571406e+01, + -1.624940e+05, + 2.289915e+04, + 2.160330e+03, + 8.952969e+01, + -1.678006e+05, + 2.296466e+04, + 3.025299e+03, + 1.588792e+02, + -1.625820e+05, + 2.081553e+04, + 3.926482e+03, + 2.601164e+02, + -1.026208e+05, + 1.529805e+04, + 4.748836e+03, + 3.972128e+02, + -9.110283e+04, + 1.222390e+04, + 5.429607e+03, + 5.703201e+02, + -7.839298e+04, + 8.798951e+03, + 5.957019e+03, + 7.792841e+02, + -4.969894e+04, + 4.718760e+03, + 6.285543e+03, + 1.021049e+03, + -3.394798e+04, + 2.050471e+03, + 6.418885e+03, + 1.289738e+03, + -2.926526e+04, + 4.598630e+02, + 6.397153e+03, + 1.579698e+03, + -1.911569e+04, + -1.195949e+03, + 6.238186e+03, + 1.885275e+03, + -2.090631e+04, + -1.729267e+03, + 5.964421e+03, + 2.199667e+03, + -1.444247e+03, + -3.487510e+03, + 5.588336e+03, + 2.516915e+03, + -1.151447e+04, + -2.536741e+03, + 5.168912e+03, + 2.829230e+03, + -1.111331e+04, + -2.723565e+03, + 4.725716e+03, + 3.135111e+03, + 1.710810e+03, + -3.676459e+03, + 4.229067e+03, + 3.428469e+03, + -1.164580e+04, + -2.096150e+03, + 3.746819e+03, + 3.702957e+03, + -1.692949e+03, + -2.995892e+03, + 3.257140e+03, + 3.959883e+03, + -8.118107e+03, + -2.006853e+03, + 2.767986e+03, + 4.191197e+03, + -4.383850e+03, + -2.223397e+03, + 2.285550e+03, + 4.397215e+03, + -9.697211e+03, + -1.380502e+03, + 1.813706e+03, + 4.572417e+03, + -7.068293e+03, + -1.463914e+03, + 1.337003e+03, + 4.716157e+03, + -2.122598e+04, + 3.866204e+02, + 8.784811e+02, + 4.822514e+03, + -1.022737e+04, + -1.101296e+02, + 3.443440e+02, + 4.892292e+03, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.856739e+02, + 1.195308e+01, + 0, + 0, + 0, + 0, + 0, + 2.604167e-04, + -1.720472e+02, + 1.507814e+01, + 0, + 2.604167e-04, + -5.197869e+03, + 2.521753e+02, + 2.669468e-01, + 1.822917e-03, + -1.789035e+03, + 4.897775e+02, + 4.126558e+00, + 3.411458e-02, + -2.356297e+04, + 1.990572e+03, + 1.685742e+01, + 1.843750e-01, + -3.079983e+04, + 3.806333e+03, + 6.218522e+01, + 8.572917e-01, + -5.867444e+04, + 7.219324e+03, + 1.679956e+02, + 2.980208e+00, + -9.193536e+04, + 1.140888e+04, + 3.838865e+02, + 8.630729e+00, + -1.093232e+05, + 1.496515e+04, + 7.495575e+02, + 2.142161e+01, + -1.454474e+05, + 1.835651e+04, + 1.277678e+03, + 4.640313e+01, + -1.060384e+05, + 1.738770e+04, + 1.939819e+03, + 8.983255e+01, + -1.317236e+05, + 1.829440e+04, + 2.673577e+03, + 1.569544e+02, + -9.918836e+04, + 1.511239e+04, + 3.428617e+03, + 2.536474e+02, + -6.597280e+04, + 1.172004e+04, + 4.108547e+03, + 3.822750e+02, + -8.933787e+04, + 1.089011e+04, + 4.698809e+03, + 5.437974e+02, + -3.303439e+04, + 5.345711e+03, + 5.140684e+03, + 7.388943e+02, + -4.639993e+04, + 4.646300e+03, + 5.414926e+03, + 9.618318e+02, + -2.854970e+04, + 1.826186e+03, + 5.551188e+03, + 1.210728e+03, + -2.483031e+04, + 4.061465e+02, + 5.528659e+03, + 1.478848e+03, + -1.065058e+04, + -1.391460e+03, + 5.374176e+03, + 1.760276e+03, + -7.673933e+03, + -1.880549e+03, + 5.126809e+03, + 2.047961e+03, + -1.467883e+04, + -1.593262e+03, + 4.830964e+03, + 2.337684e+03, + -7.526978e+03, + -2.499826e+03, + 4.467952e+03, + 2.625599e+03, + -4.169590e+03, + -2.726037e+03, + 4.046171e+03, + 2.904100e+03, + -4.507799e+03, + -2.496923e+03, + 3.611144e+03, + 3.168575e+03, + -6.215844e+03, + -2.180448e+03, + 3.176433e+03, + 3.416260e+03, + -9.828176e+03, + -1.778987e+03, + 2.732565e+03, + 3.644142e+03, + -2.786098e+03, + -2.382096e+03, + 2.253500e+03, + 3.847887e+03, + -6.796697e+03, + -1.565581e+03, + 1.789222e+03, + 4.020204e+03, + -1.447871e+04, + -6.111844e+02, + 1.348581e+03, + 4.162343e+03, + -1.363735e+04, + -5.238507e+02, + 8.553840e+02, + 4.271182e+03, + -9.848364e+03, + -1.203178e+02, + 3.610664e+02, + 4.337093e+03, +}; + +double solarDataset400[] = +{ + 1.117129e+12, + -1.629427e+07, + -4.340837e+02, + 2.288813e-02, + -3.507469e+09, + 6.348417e+05, + 0, + 1.628578e-02, + 2.505700e+07, + -1.230995e+04, + 0, + 1.936688e-02, + -1.719863e+07, + 2.178956e+04, + 0, + 1.892672e-02, + 1.438988e+06, + -1.616402e+03, + 6.806146e+00, + 2.332828e-02, + 1.696702e+05, + 1.495455e+03, + 8.179956e+00, + 3.037078e-02, + -1.912560e+06, + 7.286691e+03, + 1.412411e+01, + 4.753688e-02, + 1.068454e+06, + -3.820033e+03, + 1.852974e+01, + 9.331313e-02, + -4.480441e+05, + 7.070752e+03, + 2.347567e+01, + 1.412902e-01, + -2.844742e+05, + 7.763926e+03, + 5.756619e+01, + 3.045881e-01, + 3.820870e+05, + 5.835991e+03, + 1.114800e+02, + 7.139334e-01, + -5.903447e+05, + 2.442660e+04, + 2.153938e+02, + 1.610972e+00, + -2.022151e+05, + 3.048178e+04, + 4.667749e+02, + 4.039754e+00, + -7.774876e+05, + 5.556041e+04, + 9.199868e+02, + 9.698843e+00, + -7.414445e+05, + 7.551752e+04, + 1.760381e+03, + 2.266144e+01, + -1.531201e+06, + 1.128349e+05, + 3.140037e+03, + 4.978959e+01, + -1.554180e+06, + 1.298094e+05, + 5.235208e+03, + 1.033051e+02, + -1.695156e+06, + 1.421715e+05, + 7.966732e+03, + 1.984392e+02, + -1.678161e+06, + 1.399827e+05, + 1.119495e+04, + 3.535841e+02, + -1.463039e+06, + 1.225635e+05, + 1.457341e+04, + 5.863313e+02, + -1.215237e+06, + 9.771091e+04, + 1.769675e+04, + 9.092475e+02, + -8.636409e+05, + 6.734484e+04, + 2.022204e+04, + 1.327606e+03, + -6.651680e+05, + 4.343026e+04, + 2.196126e+04, + 1.837785e+03, + -3.857503e+05, + 1.929567e+04, + 2.286749e+04, + 2.430659e+03, + -3.671416e+05, + 8.823173e+03, + 2.302563e+04, + 3.090578e+03, + -1.503106e+05, + -7.693949e+03, + 2.251190e+04, + 3.802935e+03, + -1.434123e+05, + -1.080121e+04, + 2.148437e+04, + 4.545612e+03, + -7.621756e+04, + -1.576213e+04, + 2.013222e+04, + 5.304807e+03, + -7.041412e+04, + -1.599827e+04, + 1.854944e+04, + 6.063558e+03, + 1.247797e+04, + -1.940579e+04, + 1.683252e+04, + 6.809340e+03, + -4.230704e+04, + -1.372257e+04, + 1.516152e+04, + 7.528765e+03, + -1.341378e+04, + -1.442508e+04, + 1.354734e+04, + 8.221723e+03, + 1.305159e+04, + -1.404328e+04, + 1.196086e+04, + 8.877132e+03, + -3.228613e+04, + -8.830029e+03, + 1.054343e+04, + 9.490735e+03, + 6.334330e+03, + -1.081216e+04, + 9.192167e+03, + 1.006662e+04, + -1.320077e+04, + -7.485103e+03, + 7.933060e+03, + 1.059296e+04, + 9.474767e+03, + -8.180859e+03, + 6.789131e+03, + 1.107455e+04, + -1.394154e+04, + -4.679057e+03, + 5.796750e+03, + 1.150659e+04, + -3.468549e+03, + -5.125712e+03, + 4.894953e+03, + 1.189805e+04, + -1.168377e+04, + -3.552944e+03, + 4.047968e+03, + 1.224160e+04, + -3.595156e+03, + -3.828358e+03, + 3.246376e+03, + 1.253896e+04, + -9.636883e+03, + -2.443091e+03, + 2.519269e+03, + 1.278460e+04, + -1.695233e+04, + -1.289283e+03, + 1.854717e+03, + 1.298280e+04, + -1.903977e+04, + -6.528410e+02, + 1.170083e+03, + 1.313098e+04, + -1.350669e+04, + -1.652916e+02, + 4.953127e+02, + 1.322139e+04, + 1.427101e+11, + -1.957428e+06, + -5.973210e+01, + 1.232438e-02, + -2.505335e+09, + 4.534583e+05, + 0, + 1.144406e-02, + 2.505700e+07, + -1.230995e+04, + 0, + 1.364484e-02, + -1.530567e+07, + 1.841817e+04, + 0, + 1.320469e-02, + 1.680202e+06, + -2.365652e+03, + 4.815713e+00, + 1.672594e-02, + -1.426389e+06, + 3.973627e+03, + 5.413944e+00, + 2.112750e-02, + 6.318979e+05, + -1.710393e+03, + 7.350863e+00, + 3.389203e-02, + -1.473582e+05, + 2.336923e+03, + 8.947389e+00, + 4.841719e-02, + 6.750351e+04, + 2.142457e+03, + 1.881145e+01, + 9.067219e-02, + -6.137863e+04, + 5.312427e+03, + 3.767319e+01, + 1.945491e-01, + -2.368579e+05, + 1.056334e+04, + 8.328836e+01, + 4.802105e-01, + -3.502458e+04, + 1.450254e+04, + 1.806983e+02, + 1.255326e+00, + -3.536828e+05, + 2.941026e+04, + 3.742713e+02, + 3.159882e+00, + -5.525650e+05, + 4.829087e+04, + 7.804581e+02, + 7.921052e+00, + -1.131425e+06, + 7.774385e+04, + 1.543754e+03, + 1.911026e+01, + -9.674282e+05, + 9.542627e+04, + 2.833425e+03, + 4.364369e+01, + -1.726176e+06, + 1.303805e+05, + 4.757123e+03, + 9.174177e+01, + -1.560050e+06, + 1.354377e+05, + 7.402393e+03, + 1.797757e+02, + -1.659007e+06, + 1.378766e+05, + 1.051897e+04, + 3.248278e+02, + -1.371101e+06, + 1.198850e+05, + 1.384088e+04, + 5.450543e+02, + -1.299875e+06, + 1.013112e+05, + 1.696555e+04, + 8.532262e+02, + -7.373351e+05, + 6.441420e+04, + 1.952739e+04, + 1.256523e+03, + -6.447884e+05, + 4.627416e+04, + 2.134307e+04, + 1.750144e+03, + -5.825478e+05, + 2.880250e+04, + 2.244015e+04, + 2.329148e+03, + -1.914632e+05, + 1.757698e+03, + 2.265971e+04, + 2.980030e+03, + -2.801179e+05, + 8.443567e+01, + 2.221525e+04, + 3.679473e+03, + -9.016021e+04, + -1.353444e+04, + 2.127045e+04, + 4.416034e+03, + -5.848055e+04, + -1.550950e+04, + 1.993050e+04, + 5.166405e+03, + -8.007881e+04, + -1.426653e+04, + 1.844888e+04, + 5.918714e+03, + 4.462178e+03, + -1.832929e+04, + 1.682629e+04, + 6.662612e+03, + -8.309437e+04, + -1.148821e+04, + 1.520348e+04, + 7.383206e+03, + 4.995264e+04, + -1.893244e+04, + 1.352107e+04, + 8.078812e+03, + -3.495005e+04, + -9.918410e+03, + 1.197260e+04, + 8.729566e+03, + -2.254439e+03, + -1.140785e+04, + 1.057610e+04, + 9.348295e+03, + -1.194317e+04, + -9.037030e+03, + 9.229099e+03, + 9.923259e+03, + 4.037681e+03, + -8.955305e+03, + 7.980764e+03, + 1.045434e+04, + -1.351607e+04, + -6.061553e+03, + 6.864874e+03, + 1.093757e+04, + 7.338831e+03, + -6.963548e+03, + 5.837108e+03, + 1.137736e+04, + -2.292706e+04, + -3.086934e+03, + 4.940689e+03, + 1.176787e+04, + 4.648356e+03, + -5.474011e+03, + 4.063248e+03, + 1.211814e+04, + -1.227871e+04, + -2.657876e+03, + 3.270644e+03, + 1.241280e+04, + -8.698683e+03, + -2.708755e+03, + 2.554663e+03, + 1.266362e+04, + -1.098022e+04, + -1.900095e+03, + 1.865115e+03, + 1.286352e+04, + -2.959044e+04, + 5.140675e+02, + 1.222700e+03, + 1.301222e+04, + -1.386763e+04, + -1.800631e+02, + 4.732027e+02, + 1.310906e+04, + -2.250626e+10, + 2.821518e+05, + 2.735822e+01, + 3.081094e-03, + 1.015964e+08, + -6.264336e+04, + 1.702289e+01, + 3.521250e-03, + -1.603967e+07, + -1.803368e+03, + 6.342924e+00, + 4.841719e-03, + 2.035804e+07, + -1.947652e+04, + 0, + 6.162188e-03, + -6.628634e+06, + 1.134906e+04, + 0, + 3.521250e-03, + 5.620458e+05, + -1.364648e+03, + 1.880042e+00, + 8.362969e-03, + -3.417573e+05, + 2.062172e+03, + 1.747725e+00, + 1.012359e-02, + -7.534766e+03, + 8.619116e+02, + 5.863022e+00, + 2.024719e-02, + 8.599540e+04, + 9.720702e+02, + 1.069301e+01, + 4.445578e-02, + -1.156890e+05, + 3.868880e+03, + 2.157506e+01, + 1.025564e-01, + 7.657473e+04, + 4.835159e+03, + 5.014776e+01, + 2.759780e-01, + -2.781167e+05, + 1.440504e+04, + 1.128026e+02, + 7.337405e-01, + -2.634244e+05, + 2.323850e+04, + 2.708874e+02, + 2.091182e+00, + -5.456420e+05, + 4.153386e+04, + 5.949804e+02, + 5.660850e+00, + -7.962351e+05, + 6.431258e+04, + 1.232698e+03, + 1.450623e+01, + -1.197053e+06, + 9.234505e+04, + 2.349153e+03, + 3.449857e+01, + -1.230918e+06, + 1.114998e+05, + 4.089853e+03, + 7.566110e+01, + -1.644144e+06, + 1.336157e+05, + 6.498004e+03, + 1.519362e+02, + -1.555109e+06, + 1.322636e+05, + 9.493547e+03, + 2.818699e+02, + -1.357583e+06, + 1.188301e+05, + 1.271440e+04, + 4.827603e+02, + -1.116449e+06, + 9.761383e+04, + 1.581326e+04, + 7.684710e+02, + -9.139236e+05, + 7.403173e+04, + 1.847437e+04, + 1.146857e+03, + -6.990817e+05, + 4.906624e+04, + 2.044711e+04, + 1.618387e+03, + -3.467195e+05, + 2.202997e+04, + 2.157873e+04, + 2.174869e+03, + -4.305811e+05, + 1.548297e+04, + 2.198860e+04, + 2.801117e+03, + -1.289765e+05, + -5.992939e+03, + 2.170495e+04, + 3.485799e+03, + -1.198868e+05, + -8.943475e+03, + 2.086422e+04, + 4.204074e+03, + -1.470410e+05, + -1.001341e+04, + 1.974012e+04, + 4.944323e+03, + 1.334018e+03, + -1.882254e+04, + 1.828199e+04, + 5.692294e+03, + -3.345755e+04, + -1.481065e+04, + 1.670764e+04, + 6.427177e+03, + -4.222028e+04, + -1.336937e+04, + 1.517112e+04, + 7.146100e+03, + -1.048132e+04, + -1.430800e+04, + 1.359152e+04, + 7.840347e+03, + -2.882922e+03, + -1.287178e+04, + 1.204023e+04, + 8.498728e+03, + -1.162564e+04, + -1.046185e+04, + 1.060814e+04, + 9.117565e+03, + 8.458319e+02, + -9.934087e+03, + 9.276245e+03, + 9.695744e+03, + -1.175585e+04, + -7.451056e+03, + 8.062850e+03, + 1.022931e+04, + 3.308565e+02, + -7.420070e+03, + 6.941772e+03, + 1.071991e+04, + -1.318812e+04, + -5.104680e+03, + 5.924005e+03, + 1.116308e+04, + 2.440679e+03, + -5.803752e+03, + 4.972255e+03, + 1.156184e+04, + -1.312707e+04, + -3.300552e+03, + 4.125489e+03, + 1.190999e+04, + -6.642305e+03, + -3.582143e+03, + 3.336437e+03, + 1.221449e+04, + -7.838423e+03, + -2.777393e+03, + 2.585322e+03, + 1.246768e+04, + -1.594267e+04, + -1.412070e+03, + 1.904021e+03, + 1.267038e+04, + -2.650924e+04, + 5.450457e+01, + 1.222878e+03, + 1.282292e+04, + -1.407506e+04, + -1.421113e+02, + 4.719557e+02, + 1.291827e+04, + 0, + 0, + 0, + 0, + -1.002134e+09, + 1.813833e+05, + 0, + 0, + 2.505700e+07, + -1.230995e+04, + 0, + 8.803125e-04, + -3.540684e+06, + 4.422303e+03, + 0, + 4.401563e-04, + -1.077551e+06, + 1.071832e+03, + 1.320161e+00, + 1.320469e-03, + 4.561374e+05, + -1.073274e+03, + 0, + 2.640938e-03, + -1.241178e+05, + 7.309221e+02, + 0, + 1.760625e-03, + -6.807449e+03, + 4.155531e+02, + 1.415729e+00, + 3.961406e-03, + -5.892697e+04, + 1.065543e+03, + 3.663583e+00, + 1.144406e-02, + 7.462404e+04, + 7.963727e+02, + 9.161593e+00, + 3.697313e-02, + -1.449805e+05, + 4.808397e+03, + 2.148746e+01, + 1.047572e-01, + -7.483031e+04, + 7.438418e+03, + 6.219855e+01, + 3.569667e-01, + -1.551526e+05, + 1.519258e+04, + 1.534935e+02, + 1.106993e+00, + -3.869766e+05, + 3.031932e+04, + 3.687213e+02, + 3.258917e+00, + -7.418804e+05, + 5.270793e+04, + 8.372727e+02, + 9.106833e+00, + -8.892984e+05, + 7.452028e+04, + 1.720571e+03, + 2.349510e+01, + -1.173248e+06, + 9.980147e+04, + 3.160816e+03, + 5.468281e+01, + -1.451666e+06, + 1.199829e+05, + 5.273780e+03, + 1.157149e+02, + -1.406590e+06, + 1.229404e+05, + 7.982304e+03, + 2.235989e+02, + -1.256174e+06, + 1.143387e+05, + 1.101269e+04, + 3.956375e+02, + -1.047141e+06, + 9.726801e+04, + 1.405257e+04, + 6.469126e+02, + -9.893584e+05, + 7.986424e+04, + 1.679688e+04, + 9.875755e+02, + -6.207149e+05, + 4.968663e+04, + 1.891915e+04, + 1.421301e+03, + -4.129199e+05, + 2.877273e+04, + 2.024445e+04, + 1.939607e+03, + -3.571950e+05, + 1.606478e+04, + 2.087749e+04, + 2.531703e+03, + -1.930391e+05, + 8.010621e+02, + 2.084215e+04, + 3.184647e+03, + -1.137334e+05, + -6.987208e+03, + 2.024103e+04, + 3.879152e+03, + -9.850133e+04, + -9.863565e+03, + 1.928338e+04, + 4.599642e+03, + -9.788409e+04, + -1.144184e+04, + 1.805974e+04, + 5.332882e+03, + 1.245732e+04, + -1.762258e+04, + 1.658022e+04, + 6.064098e+03, + -5.720841e+04, + -1.160080e+04, + 1.506961e+04, + 6.775777e+03, + 1.067936e+04, + -1.514209e+04, + 1.355611e+04, + 7.467565e+03, + -2.175393e+04, + -1.083518e+04, + 1.208639e+04, + 8.124791e+03, + -1.089978e+04, + -1.053521e+04, + 1.070786e+04, + 8.749151e+03, + 1.343549e+03, + -9.970273e+03, + 9.374791e+03, + 9.333012e+03, + -1.328865e+04, + -7.346112e+03, + 8.162598e+03, + 9.872624e+03, + -1.034417e+03, + -7.407299e+03, + 7.035667e+03, + 1.036975e+04, + -5.754438e+03, + -5.779644e+03, + 6.000216e+03, + 1.081900e+04, + -9.018099e+03, + -4.670102e+03, + 5.068244e+03, + 1.122259e+04, + -9.313739e+02, + -4.706751e+03, + 4.193278e+03, + 1.157960e+04, + -1.674258e+04, + -2.394722e+03, + 3.415508e+03, + 1.188682e+04, + -4.162404e+03, + -3.416222e+03, + 2.647810e+03, + 1.214910e+04, + -1.641018e+04, + -1.375684e+03, + 1.940197e+03, + 1.235489e+04, + -2.597781e+04, + -4.072350e+01, + 1.253613e+03, + 1.251075e+04, + -1.550160e+04, + -5.658062e+01, + 4.993210e+02, + 1.260869e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.571821e+05, + 1.194273e+03, + 0, + 0, + 2.280687e+05, + -5.366371e+02, + 0, + 4.401563e-04, + -3.880904e+04, + 2.686421e+02, + 0, + 0, + -1.184002e+05, + 6.513468e+02, + 6.182344e-01, + 8.803125e-04, + 6.120952e+04, + -2.568675e+02, + 1.398755e+00, + 5.281875e-03, + -2.456577e+04, + 8.465396e+02, + 2.046431e+00, + 1.012359e-02, + -5.560163e+04, + 2.207308e+03, + 8.347310e+00, + 3.565266e-02, + -6.365941e+04, + 4.514850e+03, + 2.810550e+01, + 1.448114e-01, + -1.150207e+05, + 9.826355e+03, + 8.095553e+01, + 5.281875e-01, + -2.675326e+05, + 2.088122e+04, + 2.172854e+02, + 1.764146e+00, + -4.855776e+05, + 3.851471e+04, + 5.397100e+02, + 5.445173e+00, + -8.721331e+05, + 6.367194e+04, + 1.205217e+03, + 1.524745e+01, + -9.184539e+05, + 8.282197e+04, + 2.383759e+03, + 3.838735e+01, + -1.307361e+06, + 1.073647e+05, + 4.170076e+03, + 8.581991e+01, + -1.216270e+06, + 1.119986e+05, + 6.587459e+03, + 1.736267e+02, + -1.276352e+06, + 1.124177e+05, + 9.409381e+03, + 3.185987e+02, + -9.788697e+05, + 9.416016e+04, + 1.235028e+04, + 5.374427e+02, + -7.995613e+05, + 7.618671e+04, + 1.505625e+04, + 8.403357e+02, + -7.460602e+05, + 5.950676e+04, + 1.732816e+04, + 1.232937e+03, + -4.349269e+05, + 3.288320e+04, + 1.890991e+04, + 1.714067e+03, + -2.903175e+05, + 1.679987e+04, + 1.972389e+04, + 2.270884e+03, + -2.341700e+05, + 6.717412e+03, + 1.992757e+04, + 2.890724e+03, + -1.591140e+05, + -2.541145e+03, + 1.958483e+04, + 3.559598e+03, + -9.377026e+04, + -9.049582e+03, + 1.877055e+04, + 4.259945e+03, + -3.112181e+04, + -1.324477e+04, + 1.763230e+04, + 4.974656e+03, + -6.713941e+04, + -1.097160e+04, + 1.635475e+04, + 5.689683e+03, + -1.171086e+04, + -1.418498e+04, + 1.495911e+04, + 6.397430e+03, + -1.203079e+04, + -1.259366e+04, + 1.351290e+04, + 7.082987e+03, + -2.735949e+04, + -1.036650e+04, + 1.212531e+04, + 7.741638e+03, + 8.398267e+03, + -1.176714e+04, + 1.074781e+04, + 8.368608e+03, + -2.360952e+04, + -7.700526e+03, + 9.466757e+03, + 8.954412e+03, + 3.871276e+03, + -9.056076e+03, + 8.250344e+03, + 9.502464e+03, + -6.443405e+03, + -6.671943e+03, + 7.119198e+03, + 1.000279e+04, + -7.871410e+03, + -5.649041e+03, + 6.108047e+03, + 1.045952e+04, + -8.718557e+03, + -4.829450e+03, + 5.161480e+03, + 1.087083e+04, + -1.292495e+03, + -4.766287e+03, + 4.267365e+03, + 1.123419e+04, + -9.861345e+03, + -3.065607e+03, + 3.472933e+03, + 1.154681e+04, + -1.727524e+04, + -2.001187e+03, + 2.739962e+03, + 1.181333e+04, + -9.339880e+03, + -2.491882e+03, + 1.972342e+03, + 1.202929e+04, + -2.480383e+04, + -8.960043e+01, + 1.262307e+03, + 1.218417e+04, + -1.550976e+04, + -1.052398e+02, + 5.321763e+02, + 1.228360e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.280687e+05, + 5.366371e+02, + 0, + 0, + 0, + 0, + 0, + 4.401563e-04, + 0, + 0, + 0, + 4.401563e-04, + -1.733338e+04, + 2.221243e+02, + 0, + 4.401563e-04, + -1.275858e+04, + 4.042146e+02, + 9.341664e-01, + 2.640938e-03, + 1.648620e+03, + 8.526882e+02, + 3.875433e+00, + 1.452516e-02, + -1.019729e+05, + 3.723777e+03, + 1.376684e+01, + 6.470297e-02, + -5.222279e+04, + 6.376447e+03, + 5.040666e+01, + 3.006267e-01, + -1.972467e+05, + 1.575596e+04, + 1.432681e+02, + 1.097310e+00, + -4.522255e+05, + 3.224516e+04, + 3.877865e+02, + 3.683668e+00, + -6.472011e+05, + 5.229836e+04, + 9.287428e+02, + 1.113463e+01, + -9.846451e+05, + 7.751316e+04, + 1.928807e+03, + 2.951336e+01, + -1.120147e+06, + 9.516690e+04, + 3.526207e+03, + 6.930084e+01, + -1.060774e+06, + 1.024968e+05, + 5.698072e+03, + 1.445909e+02, + -1.080278e+06, + 1.054362e+05, + 8.329768e+03, + 2.717027e+02, + -1.167184e+06, + 1.012812e+05, + 1.122358e+04, + 4.681035e+02, + -8.134116e+05, + 7.589663e+04, + 1.397221e+04, + 7.479364e+02, + -5.142486e+05, + 5.263146e+04, + 1.620649e+04, + 1.114264e+03, + -5.840860e+05, + 4.293903e+04, + 1.790499e+04, + 1.565472e+03, + -2.806635e+05, + 1.804160e+04, + 1.892835e+04, + 2.098314e+03, + -1.902676e+05, + 6.983141e+03, + 1.923705e+04, + 2.694941e+03, + -2.082007e+05, + 2.150441e+03, + 1.906114e+04, + 3.342563e+03, + -5.374742e+04, + -9.636906e+03, + 1.839341e+04, + 4.027727e+03, + -9.427047e+04, + -8.455175e+03, + 1.739289e+04, + 4.729183e+03, + -1.263315e+04, + -1.383242e+04, + 1.618343e+04, + 5.437924e+03, + -5.405956e+04, + -1.051530e+04, + 1.486152e+04, + 6.137134e+03, + 4.123323e+03, + -1.373276e+04, + 1.347434e+04, + 6.821774e+03, + -1.966848e+04, + -1.038438e+04, + 1.209746e+04, + 7.477629e+03, + -1.751199e+04, + -9.652355e+03, + 1.078686e+04, + 8.104279e+03, + 3.295847e+03, + -1.002127e+04, + 9.489445e+03, + 8.694407e+03, + -1.938731e+03, + -7.963785e+03, + 8.293167e+03, + 9.241338e+03, + -2.615570e+04, + -5.085764e+03, + 7.230361e+03, + 9.747489e+03, + 1.004382e+04, + -7.737635e+03, + 6.157052e+03, + 1.021296e+04, + -1.151870e+04, + -4.264058e+03, + 5.190961e+03, + 1.062368e+04, + -5.395239e+03, + -4.360268e+03, + 4.334166e+03, + 1.099135e+04, + -1.187237e+04, + -3.068215e+03, + 3.525120e+03, + 1.130985e+04, + -8.828785e+03, + -2.951184e+03, + 2.748294e+03, + 1.157956e+04, + -1.425606e+04, + -1.790576e+03, + 2.012464e+03, + 1.179469e+04, + -3.104649e+04, + 4.096561e+02, + 1.304758e+03, + 1.195543e+04, + -1.414188e+04, + -2.345618e+02, + 4.929940e+02, + 1.205795e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.284378e+03, + 4.000235e+01, + 0, + 0, + -1.596943e+04, + 2.327633e+02, + 2.033762e-01, + 4.401563e-04, + 1.547436e+04, + 9.728437e+01, + 1.332585e+00, + 4.841719e-03, + -4.391863e+04, + 1.611874e+03, + 3.954053e+00, + 1.848656e-02, + -1.774277e+04, + 3.338879e+03, + 1.984506e+01, + 1.069580e-01, + -2.636354e+05, + 1.231744e+04, + 7.035266e+01, + 4.762491e-01, + -1.523250e+05, + 1.881496e+04, + 2.323194e+02, + 2.013715e+00, + -5.937322e+05, + 4.171430e+04, + 5.875574e+02, + 6.570653e+00, + -7.266381e+05, + 6.055013e+04, + 1.349311e+03, + 1.917673e+01, + -8.860678e+05, + 8.010778e+04, + 2.622440e+03, + 4.815926e+01, + -1.086569e+06, + 9.639717e+04, + 4.493415e+03, + 1.062836e+02, + -9.745768e+05, + 9.666372e+04, + 6.884892e+03, + 2.100144e+02, + -1.047773e+06, + 9.496512e+04, + 9.556296e+03, + 3.754075e+02, + -6.732150e+05, + 7.257512e+04, + 1.219959e+04, + 6.172408e+02, + -6.412646e+05, + 6.073496e+04, + 1.451547e+04, + 9.412046e+02, + -4.770761e+05, + 4.172546e+04, + 1.637709e+04, + 1.351410e+03, + -3.658491e+05, + 2.573258e+04, + 1.759304e+04, + 1.842114e+03, + -1.459050e+05, + 7.797252e+03, + 1.813296e+04, + 2.402150e+03, + -2.270501e+05, + 6.345087e+03, + 1.816235e+04, + 3.015249e+03, + -5.163556e+04, + -7.248933e+03, + 1.772472e+04, + 3.672398e+03, + -9.784000e+04, + -6.113061e+03, + 1.692069e+04, + 4.351479e+03, + -4.721276e+04, + -1.058933e+04, + 1.588911e+04, + 5.044252e+03, + -2.325812e+04, + -1.187676e+04, + 1.464898e+04, + 5.733633e+03, + -7.615191e+03, + -1.186838e+04, + 1.334468e+04, + 6.408326e+03, + -2.309797e+04, + -9.681961e+03, + 1.206642e+04, + 7.060851e+03, + -1.619285e+04, + -9.482512e+03, + 1.080185e+04, + 7.687342e+03, + 2.078178e+03, + -9.714292e+03, + 9.537486e+03, + 8.279170e+03, + -1.618945e+04, + -6.927762e+03, + 8.365159e+03, + 8.829938e+03, + 7.335199e+02, + -7.533587e+03, + 7.255793e+03, + 9.341236e+03, + -1.450326e+03, + -6.043556e+03, + 6.228118e+03, + 9.805634e+03, + -1.816953e+04, + -3.758371e+03, + 5.326053e+03, + 1.022606e+04, + -1.744599e+03, + -5.007206e+03, + 4.429541e+03, + 1.060407e+04, + -1.013527e+04, + -3.265815e+03, + 3.587398e+03, + 1.092797e+04, + -1.259356e+04, + -2.582008e+03, + 2.814548e+03, + 1.120259e+04, + -1.274805e+04, + -2.097313e+03, + 2.054883e+03, + 1.142390e+04, + -2.791789e+04, + 7.523855e+01, + 1.329347e+03, + 1.158716e+04, + -1.719612e+04, + -4.713965e+00, + 5.420132e+02, + 1.169180e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.176421e+02, + 3.113526e+01, + 0, + 0, + -1.800870e+04, + 5.044997e+02, + 2.852090e-01, + 8.803125e-04, + -6.298356e+03, + 1.097487e+03, + 4.660042e+00, + 2.068734e-02, + -8.791947e+04, + 4.920687e+03, + 2.117041e+01, + 1.267650e-01, + -1.511792e+05, + 1.141104e+04, + 9.051543e+01, + 6.901650e-01, + -3.106193e+05, + 2.415462e+04, + 2.850943e+02, + 2.830205e+00, + -5.405713e+05, + 4.217464e+04, + 7.415631e+02, + 9.508255e+00, + -5.706933e+05, + 5.709472e+04, + 1.607830e+03, + 2.680684e+01, + -8.596668e+05, + 7.785137e+04, + 2.987113e+03, + 6.433676e+01, + -8.771786e+05, + 8.485822e+04, + 4.935285e+03, + 1.368477e+02, + -8.102174e+05, + 8.281917e+04, + 7.255334e+03, + 2.600694e+02, + -6.674694e+05, + 7.297462e+04, + 9.707332e+03, + 4.485879e+02, + -6.717545e+05, + 6.389033e+04, + 1.205217e+04, + 7.132714e+02, + -3.554819e+05, + 4.055708e+04, + 1.401631e+04, + 1.060593e+03, + -4.167811e+05, + 3.366675e+04, + 1.546312e+04, + 1.485747e+03, + -1.323838e+05, + 1.206436e+04, + 1.634842e+04, + 1.985782e+03, + -2.565296e+05, + 1.235833e+04, + 1.671070e+04, + 2.544205e+03, + -7.754431e+04, + -2.778930e+03, + 1.659321e+04, + 3.155150e+03, + -6.065238e+04, + -5.532359e+03, + 1.601994e+04, + 3.795263e+03, + -6.016013e+04, + -6.874641e+03, + 1.523403e+04, + 4.453979e+03, + -3.842724e+04, + -9.051155e+03, + 1.424960e+04, + 5.120220e+03, + -1.505812e+04, + -1.038403e+04, + 1.311185e+04, + 5.780549e+03, + -1.932609e+04, + -9.311433e+03, + 1.192713e+04, + 6.424029e+03, + -2.567878e+03, + -9.668649e+03, + 1.073681e+04, + 7.044632e+03, + -2.137310e+04, + -7.226824e+03, + 9.588529e+03, + 7.634721e+03, + -4.048428e+03, + -8.024655e+03, + 8.455858e+03, + 8.192586e+03, + -9.345105e+03, + -6.504380e+03, + 7.358232e+03, + 8.708498e+03, + 1.110868e+03, + -6.498387e+03, + 6.328846e+03, + 9.181543e+03, + -1.038927e+04, + -4.423289e+03, + 5.401265e+03, + 9.607874e+03, + -8.382929e+03, + -4.148725e+03, + 4.539967e+03, + 9.991244e+03, + -1.284061e+04, + -3.196734e+03, + 3.706702e+03, + 1.032616e+04, + -7.952644e+03, + -3.238144e+03, + 2.887171e+03, + 1.060975e+04, + -2.012766e+04, + -1.354531e+03, + 2.121075e+03, + 1.083559e+04, + -2.131326e+04, + -8.004748e+02, + 1.341130e+03, + 1.100550e+04, + -1.524196e+04, + -2.164961e+02, + 5.721496e+02, + 1.110911e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.811733e+03, + 6.623464e+01, + 0, + 0, + 2.568464e+03, + 8.432503e+01, + 5.115023e-01, + 2.200781e-03, + -2.004794e+04, + 1.119994e+03, + 2.378582e+00, + 1.320469e-02, + -5.899960e+04, + 3.846531e+03, + 1.815237e+01, + 1.184020e-01, + -1.105061e+05, + 9.320633e+03, + 8.088947e+01, + 6.950067e-01, + -2.221620e+05, + 1.985802e+04, + 2.613633e+02, + 2.927919e+00, + -4.065581e+05, + 3.551385e+04, + 6.885058e+02, + 9.926844e+00, + -5.094984e+05, + 4.979654e+04, + 1.507612e+03, + 2.812995e+01, + -6.336678e+05, + 6.263542e+04, + 2.791695e+03, + 6.759920e+01, + -5.771321e+05, + 6.548998e+04, + 4.520174e+03, + 1.419161e+02, + -5.870919e+05, + 6.615160e+04, + 6.549199e+03, + 2.651867e+02, + -5.916423e+05, + 6.099313e+04, + 8.705613e+03, + 4.515611e+02, + -3.105146e+05, + 4.215730e+04, + 1.068282e+04, + 7.107075e+02, + -3.690182e+05, + 3.754835e+04, + 1.233110e+04, + 1.043000e+03, + -2.480750e+05, + 2.322678e+04, + 1.359551e+04, + 1.450970e+03, + -1.497117e+05, + 1.185092e+04, + 1.431604e+04, + 1.925035e+03, + -8.514757e+04, + 4.263741e+03, + 1.458441e+04, + 2.453455e+03, + -1.505205e+05, + 4.067158e+03, + 1.452717e+04, + 3.025317e+03, + -3.556097e+03, + -7.629858e+03, + 1.407200e+04, + 3.631602e+03, + -5.542532e+04, + -4.547126e+03, + 1.336358e+04, + 4.249173e+03, + -2.492334e+04, + -7.511616e+03, + 1.254118e+04, + 4.875408e+03, + -3.228374e+04, + -7.095606e+03, + 1.157333e+04, + 5.495835e+03, + 8.005456e+03, + -9.642728e+03, + 1.050910e+04, + 6.101611e+03, + -2.540419e+04, + -5.998865e+03, + 9.470682e+03, + 6.680639e+03, + -1.534258e+03, + -7.644748e+03, + 8.443364e+03, + 7.234962e+03, + -1.521422e+04, + -5.588894e+03, + 7.427301e+03, + 7.752369e+03, + 2.151713e+03, + -6.514804e+03, + 6.440484e+03, + 8.232600e+03, + -1.841369e+04, + -3.729884e+03, + 5.527030e+03, + 8.667363e+03, + 1.579701e+03, + -5.323167e+03, + 4.630580e+03, + 9.060834e+03, + -1.605496e+04, + -2.666378e+03, + 3.802381e+03, + 9.400648e+03, + -1.363337e+04, + -2.777913e+03, + 3.003439e+03, + 9.694207e+03, + -9.563748e+03, + -2.638621e+03, + 2.184130e+03, + 9.930046e+03, + -3.556888e+04, + 7.624686e+02, + 1.440821e+03, + 1.010325e+04, + -1.690964e+04, + -1.764955e+02, + 5.681839e+02, + 1.021822e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.643694e+03, + 1.140404e+02, + 0, + 0, + -6.562979e+03, + 4.816660e+02, + 1.445460e+00, + 7.922813e-03, + -1.299063e+04, + 1.609270e+03, + 9.594276e+00, + 7.218563e-02, + -7.131240e+04, + 5.726209e+03, + 4.357593e+01, + 4.150673e-01, + -1.117634e+05, + 1.180640e+04, + 1.624316e+02, + 1.965298e+00, + -2.304253e+05, + 2.279086e+04, + 4.523525e+02, + 7.057025e+00, + -3.315911e+05, + 3.411993e+04, + 1.042647e+03, + 2.092943e+01, + -3.603710e+05, + 4.191874e+04, + 1.999991e+03, + 5.211274e+01, + -3.916216e+05, + 4.727670e+04, + 3.311539e+03, + 1.116914e+02, + -3.844057e+05, + 4.753490e+04, + 4.900611e+03, + 2.125391e+02, + -3.148316e+05, + 4.217486e+04, + 6.599279e+03, + 3.665476e+02, + -2.947627e+05, + 3.672338e+04, + 8.238001e+03, + 5.821150e+02, + -1.877393e+05, + 2.615824e+04, + 9.665892e+03, + 8.644409e+02, + -1.939038e+05, + 2.109766e+04, + 1.078832e+04, + 1.211959e+03, + -1.268775e+05, + 1.194889e+04, + 1.155350e+04, + 1.622333e+03, + -5.212276e+04, + 4.145660e+03, + 1.190591e+04, + 2.084908e+03, + -1.041510e+05, + 4.464942e+03, + 1.197827e+04, + 2.588510e+03, + -1.984863e+04, + -3.569719e+03, + 1.174725e+04, + 3.127176e+03, + -3.741808e+04, + -3.091579e+03, + 1.126593e+04, + 3.681872e+03, + -2.888744e+04, + -4.650632e+03, + 1.065302e+04, + 4.246808e+03, + -6.248874e+03, + -6.533785e+03, + 9.886316e+03, + 4.810160e+03, + -1.492326e+04, + -5.462305e+03, + 9.064728e+03, + 5.360728e+03, + -1.612605e+04, + -5.277340e+03, + 8.222609e+03, + 5.894540e+03, + -1.302281e+04, + -5.381978e+03, + 7.329188e+03, + 6.403576e+03, + 1.844868e+03, + -6.123135e+03, + 6.402092e+03, + 6.878745e+03, + -1.598640e+04, + -3.668586e+03, + 5.540739e+03, + 7.312670e+03, + -3.218371e+03, + -4.662379e+03, + 4.696477e+03, + 7.708645e+03, + -1.404880e+04, + -2.925585e+03, + 3.881197e+03, + 8.055558e+03, + -1.463165e+04, + -2.666220e+03, + 3.081586e+03, + 8.355163e+03, + -1.277586e+04, + -2.405669e+03, + 2.258415e+03, + 8.598143e+03, + -3.742817e+04, + 7.803610e+02, + 1.474543e+03, + 8.777701e+03, + -1.548654e+04, + -3.160486e+02, + 5.519917e+02, + 8.894396e+03, +}; + +double solarDataset440[] = +{ + -6.439155e+11, + 7.682264e+06, + 1.061520e+03, + 2.039373e+00, + -1.551568e+09, + -1.644546e+06, + 7.523669e+02, + 2.056656e+00, + 1.570174e+09, + -8.522139e+05, + 2.877172e+02, + 2.120770e+00, + -3.012090e+08, + 4.421119e+05, + 2.347757e+02, + 2.178751e+00, + -2.081867e+07, + 7.272809e+04, + 4.311484e+02, + 2.430188e+00, + 7.899508e+06, + 1.295109e+04, + 5.150411e+02, + 2.939752e+00, + 4.151745e+06, + 2.883739e+04, + 6.139858e+02, + 3.810026e+00, + 3.293018e+06, + 4.361918e+04, + 7.999407e+02, + 5.335932e+00, + -3.828120e+06, + 9.429242e+04, + 1.137923e+03, + 8.117909e+00, + 2.986346e+06, + 6.726090e+04, + 1.682654e+03, + 1.349342e+01, + -1.518315e+06, + 1.401839e+05, + 2.506574e+03, + 2.312609e+01, + -2.560500e+06, + 1.889565e+05, + 3.957987e+03, + 4.170958e+01, + -3.827648e+06, + 2.429145e+05, + 6.184460e+03, + 7.682438e+01, + -3.299120e+06, + 2.716569e+05, + 9.361640e+03, + 1.406772e+02, + -4.786591e+06, + 3.230548e+05, + 1.360464e+04, + 2.503356e+02, + -5.235884e+06, + 3.347402e+05, + 1.893351e+04, + 4.303752e+02, + -4.344959e+06, + 2.992049e+05, + 2.482781e+04, + 7.073441e+02, + -4.495848e+06, + 2.671507e+05, + 3.067007e+04, + 1.104209e+03, + -2.904965e+06, + 1.819224e+05, + 3.574947e+04, + 1.639240e+03, + -2.295257e+06, + 1.245881e+05, + 3.945941e+04, + 2.313019e+03, + -2.021822e+06, + 7.712727e+04, + 4.169658e+04, + 3.119853e+03, + -5.892701e+05, + 4.095196e+03, + 4.218370e+04, + 4.041884e+03, + -1.166644e+06, + 8.504980e+03, + 4.136899e+04, + 5.044736e+03, + -1.972687e+05, + -4.070728e+04, + 3.941477e+04, + 6.112839e+03, + -2.093258e+05, + -3.893157e+04, + 3.660650e+04, + 7.200837e+03, + -2.639589e+05, + -3.598837e+04, + 3.358396e+04, + 8.293512e+03, + 8.246154e+03, + -4.584505e+04, + 3.026767e+04, + 9.372228e+03, + -6.438522e+04, + -3.581717e+04, + 2.697011e+04, + 1.041147e+04, + -7.353188e+04, + -3.121684e+04, + 2.387281e+04, + 1.140770e+04, + 5.933961e+04, + -3.366294e+04, + 2.086077e+04, + 1.235002e+04, + -3.538054e+04, + -2.202528e+04, + 1.819119e+04, + 1.322614e+04, + -2.443121e+04, + -1.981273e+04, + 1.582620e+04, + 1.404641e+04, + 3.781173e+04, + -2.036056e+04, + 1.359973e+04, + 1.480309e+04, + -1.650133e+04, + -1.256169e+04, + 1.171377e+04, + 1.549140e+04, + -1.983390e+04, + -1.069497e+04, + 1.008886e+04, + 1.612572e+04, + 1.056101e+04, + -1.130558e+04, + 8.546710e+03, + 1.670160e+04, + -2.713816e+03, + -7.912829e+03, + 7.207588e+03, + 1.721354e+04, + -4.452889e+03, + -6.395793e+03, + 6.078559e+03, + 1.767169e+04, + -6.835308e+03, + -5.126471e+03, + 5.077617e+03, + 1.807822e+04, + -9.922932e+03, + -4.054774e+03, + 4.171164e+03, + 1.843425e+04, + -4.659839e+03, + -3.888745e+03, + 3.322981e+03, + 1.873921e+04, + -9.547958e+03, + -2.601152e+03, + 2.562645e+03, + 1.899026e+04, + -1.701043e+04, + -1.361229e+03, + 1.872053e+03, + 1.919113e+04, + -1.872608e+04, + -7.127307e+02, + 1.172457e+03, + 1.934026e+04, + -1.350361e+04, + -1.647467e+02, + 4.949774e+02, + 1.943062e+04, + 2.157451e+11, + 1.943248e+06, + -2.593158e+02, + 9.505553e-01, + -7.114316e+10, + 1.371541e+07, + 0, + 9.477677e-01, + 1.280844e+09, + -7.152589e+05, + 2.024044e+02, + 1.022474e+00, + -3.379517e+08, + 4.237257e+05, + 1.460656e+02, + 1.057040e+00, + 3.483677e+07, + -4.170331e+04, + 2.741455e+02, + 1.234886e+00, + -6.107958e+06, + 4.113951e+04, + 3.019965e+02, + 1.517543e+00, + 6.609522e+06, + 7.210950e+03, + 3.859744e+02, + 2.068921e+00, + 6.293178e+05, + 4.235131e+04, + 5.125775e+02, + 3.017804e+00, + -8.119125e+05, + 6.395016e+04, + 7.753549e+02, + 4.886021e+00, + -1.001544e+06, + 8.369718e+04, + 1.219698e+03, + 8.638624e+00, + 2.469002e+05, + 1.020158e+05, + 1.936104e+03, + 1.606076e+01, + -3.071414e+06, + 1.744496e+05, + 3.124365e+03, + 3.047463e+01, + -2.398553e+06, + 2.065189e+05, + 5.080502e+03, + 5.904147e+01, + -4.148108e+06, + 2.720416e+05, + 7.949415e+03, + 1.123456e+02, + -4.421216e+06, + 3.044491e+05, + 1.197323e+04, + 2.080105e+02, + -4.886328e+06, + 3.225125e+05, + 1.702702e+04, + 3.685740e+02, + -4.260302e+06, + 2.983774e+05, + 2.277937e+04, + 6.206306e+02, + -4.488843e+06, + 2.719539e+05, + 2.864869e+04, + 9.887191e+02, + -3.035307e+06, + 1.911892e+05, + 3.388554e+04, + 1.492962e+03, + -2.303207e+06, + 1.301134e+05, + 3.780104e+04, + 2.135924e+03, + -1.695747e+06, + 7.533493e+04, + 4.024633e+04, + 2.912218e+03, + -1.131339e+06, + 2.856670e+04, + 4.111774e+04, + 3.805227e+03, + -7.045700e+05, + -4.867972e+03, + 4.054360e+04, + 4.789173e+03, + -3.620224e+05, + -2.694148e+04, + 3.883948e+04, + 5.834790e+03, + -4.066279e+05, + -2.925181e+04, + 3.641435e+04, + 6.913749e+03, + -1.132796e+05, + -4.305023e+04, + 3.342235e+04, + 8.003883e+03, + 3.570589e+03, + -4.331910e+04, + 3.014234e+04, + 9.074909e+03, + -1.133431e+05, + -3.225022e+04, + 2.700976e+04, + 1.011271e+04, + 1.186040e+03, + -3.456607e+04, + 2.396680e+04, + 1.111301e+04, + -4.979073e+04, + -2.665824e+04, + 2.106894e+04, + 1.205891e+04, + 1.592532e+04, + -2.657005e+04, + 1.836669e+04, + 1.294864e+04, + 8.401869e+03, + -2.123268e+04, + 1.592066e+04, + 1.377255e+04, + -2.611279e+04, + -1.551961e+04, + 1.380784e+04, + 1.453477e+04, + 1.246222e+04, + -1.579531e+04, + 1.187851e+04, + 1.523848e+04, + -6.658919e+03, + -1.142901e+04, + 1.017094e+04, + 1.587713e+04, + 1.928404e+03, + -1.015849e+04, + 8.688190e+03, + 1.645836e+04, + -1.608648e+04, + -7.006837e+03, + 7.388582e+03, + 1.698200e+04, + 6.840295e+03, + -7.868280e+03, + 6.193951e+03, + 1.745255e+04, + -1.757879e+04, + -4.203383e+03, + 5.158025e+03, + 1.786403e+04, + 6.926599e+03, + -5.876158e+03, + 4.203700e+03, + 1.822680e+04, + -1.598552e+04, + -2.390669e+03, + 3.390699e+03, + 1.853138e+04, + -6.027778e+03, + -3.175285e+03, + 2.640031e+03, + 1.879204e+04, + -1.851678e+04, + -1.220782e+03, + 1.930943e+03, + 1.899774e+04, + -2.290692e+04, + -3.911046e+02, + 1.218154e+03, + 1.915237e+04, + -1.519600e+04, + -2.633004e+01, + 4.835101e+02, + 1.924636e+04, + -3.704596e+12, + 5.454497e+07, + 1.421905e+03, + 2.926930e-01, + 3.173305e+09, + -5.743591e+05, + 0, + 3.144359e-01, + -3.364539e+06, + 6.299289e+03, + 0, + 3.116483e-01, + -3.980029e+08, + 4.573928e+05, + 3.043542e+00, + 3.122058e-01, + 4.559887e+07, + -6.916950e+04, + 1.007848e+02, + 3.969474e-01, + -2.443350e+07, + 8.526024e+04, + 1.065719e+02, + 4.794590e-01, + 5.589237e+06, + -4.160307e+03, + 1.936915e+02, + 7.621167e-01, + 9.451238e+04, + 2.614347e+04, + 2.558371e+02, + 1.224850e+00, + 3.067526e+04, + 3.723230e+04, + 4.105653e+02, + 2.194361e+00, + -7.036798e+05, + 5.911092e+04, + 6.903957e+02, + 4.252689e+00, + -5.513797e+05, + 8.299526e+04, + 1.196595e+03, + 8.696047e+00, + -2.191497e+06, + 1.345808e+05, + 2.089839e+03, + 1.812299e+01, + -2.070793e+06, + 1.743475e+05, + 3.623925e+03, + 3.802500e+01, + -4.038717e+06, + 2.455242e+05, + 6.036923e+03, + 7.762385e+01, + -3.761674e+06, + 2.746045e+05, + 9.589842e+03, + 1.529898e+02, + -5.050391e+06, + 3.152332e+05, + 1.422849e+04, + 2.849469e+02, + -4.033593e+06, + 2.876971e+05, + 1.972387e+04, + 5.007826e+02, + -3.837058e+06, + 2.611389e+05, + 2.542725e+04, + 8.243544e+02, + -3.415481e+06, + 2.122601e+05, + 3.081216e+04, + 1.277441e+03, + -2.263710e+06, + 1.384666e+05, + 3.511626e+04, + 1.870490e+03, + -1.502418e+06, + 8.143096e+04, + 3.793597e+04, + 2.597510e+03, + -1.629920e+06, + 5.437166e+04, + 3.934644e+04, + 3.445165e+03, + -3.463979e+05, + -1.248103e+04, + 3.915122e+04, + 4.394698e+03, + -4.796136e+05, + -1.400399e+04, + 3.778512e+04, + 5.405067e+03, + -4.525999e+05, + -2.265499e+04, + 3.581125e+04, + 6.461725e+03, + -3.180239e+04, + -4.281554e+04, + 3.309592e+04, + 7.538118e+03, + -1.696614e+05, + -3.260128e+04, + 3.010816e+04, + 8.601531e+03, + 2.216761e+03, + -3.819533e+04, + 2.706857e+04, + 9.643927e+03, + -5.840964e+04, + -2.977311e+04, + 2.409090e+04, + 1.064435e+04, + -5.917126e+04, + -2.642897e+04, + 2.128022e+04, + 1.159950e+04, + 7.415464e+04, + -2.984562e+04, + 1.854160e+04, + 1.249835e+04, + -4.015798e+04, + -1.708081e+04, + 1.618474e+04, + 1.332958e+04, + -2.724330e+04, + -1.610742e+04, + 1.411441e+04, + 1.410972e+04, + 3.392267e+04, + -1.758161e+04, + 1.211073e+04, + 1.482824e+04, + -1.941985e+04, + -1.017686e+04, + 1.041268e+04, + 1.547855e+04, + -1.295582e+04, + -9.453817e+03, + 8.939028e+03, + 1.607642e+04, + 1.103183e+04, + -9.749963e+03, + 7.541593e+03, + 1.661529e+04, + -1.309367e+04, + -5.774869e+03, + 6.355166e+03, + 1.709222e+04, + -6.434020e+03, + -5.622814e+03, + 5.307434e+03, + 1.751883e+04, + -4.996029e+03, + -4.764721e+03, + 4.331959e+03, + 1.788974e+04, + -4.447507e+03, + -3.893715e+03, + 3.465440e+03, + 1.820564e+04, + -1.239499e+04, + -2.374546e+03, + 2.708845e+03, + 1.846887e+04, + -1.791766e+04, + -1.467369e+03, + 1.990862e+03, + 1.868255e+04, + -2.061413e+04, + -6.862093e+02, + 1.247688e+03, + 1.884111e+04, + -1.468218e+04, + -1.400460e+02, + 5.211565e+02, + 1.893732e+04, + 1.308076e+12, + -1.882941e+07, + -5.168990e+02, + 4.404332e-02, + -8.250594e+09, + 1.493334e+06, + 0, + 3.623818e-02, + 6.347536e+07, + -3.118404e+04, + 0, + 4.348581e-02, + -6.744998e+07, + 8.687614e+04, + 0, + 4.237079e-02, + -1.059940e+06, + 1.737933e+03, + 2.850557e+01, + 6.021112e-02, + 3.873147e+06, + -6.437214e+03, + 2.864464e+01, + 9.087420e-02, + -2.038775e+06, + 1.383359e+04, + 3.704050e+01, + 1.349175e-01, + 1.734783e+06, + 9.982716e+02, + 6.829641e+01, + 2.609149e-01, + -1.300032e+06, + 2.675349e+04, + 1.182804e+02, + 5.112371e-01, + -4.406929e+05, + 3.149201e+04, + 2.638582e+02, + 1.259974e+00, + -8.366025e+05, + 5.266660e+04, + 5.292339e+02, + 3.134881e+00, + -7.924932e+05, + 7.942542e+04, + 1.048528e+03, + 7.713714e+00, + -2.114312e+06, + 1.343945e+05, + 2.024267e+03, + 1.835492e+01, + -3.185798e+06, + 1.914041e+05, + 3.782729e+03, + 4.238696e+01, + -3.032631e+06, + 2.279831e+05, + 6.542534e+03, + 9.240122e+01, + -4.568244e+06, + 2.833195e+05, + 1.042573e+04, + 1.866350e+02, + -3.365946e+06, + 2.645481e+05, + 1.535126e+04, + 3.512042e+02, + -4.471630e+06, + 2.758277e+05, + 2.079988e+04, + 6.104689e+02, + -2.224000e+06, + 1.886401e+05, + 2.617243e+04, + 9.914146e+02, + -2.922616e+06, + 1.750678e+05, + 3.076047e+04, + 1.501533e+03, + -1.487031e+06, + 9.279157e+04, + 3.425527e+04, + 2.152028e+03, + -1.120184e+06, + 5.413495e+04, + 3.618144e+04, + 2.925201e+03, + -9.574249e+05, + 2.560661e+04, + 3.684905e+04, + 3.805894e+03, + -4.688823e+05, + -8.953231e+03, + 3.622075e+04, + 4.771127e+03, + -2.008025e+05, + -2.566219e+04, + 3.456168e+04, + 5.787472e+03, + -2.845628e+05, + -2.408577e+04, + 3.238769e+04, + 6.829708e+03, + -9.819349e+04, + -3.380507e+04, + 2.980207e+04, + 7.880871e+03, + -2.605063e+04, + -3.403133e+04, + 2.695787e+04, + 8.913987e+03, + -6.318205e+04, + -2.810438e+04, + 2.417620e+04, + 9.914760e+03, + -4.302365e+04, + -2.624841e+04, + 2.148046e+04, + 1.087609e+04, + 6.156530e+04, + -2.811597e+04, + 1.885622e+04, + 1.178578e+04, + -7.492135e+04, + -1.496397e+04, + 1.657837e+04, + 1.263475e+04, + 1.109430e+04, + -1.929611e+04, + 1.445066e+04, + 1.343597e+04, + 2.424357e+04, + -1.637395e+04, + 1.244181e+04, + 1.416959e+04, + -4.234273e+04, + -8.757096e+03, + 1.078613e+04, + 1.484129e+04, + 2.003718e+04, + -1.262376e+04, + 9.226693e+03, + 1.546219e+04, + -1.526070e+04, + -7.207988e+03, + 7.836505e+03, + 1.601547e+04, + -1.628001e+03, + -7.394836e+03, + 6.625916e+03, + 1.651619e+04, + -7.377006e+03, + -5.561068e+03, + 5.524485e+03, + 1.695833e+04, + -6.725890e+03, + -4.724347e+03, + 4.541853e+03, + 1.734582e+04, + -4.572217e+03, + -4.074851e+03, + 3.648060e+03, + 1.767801e+04, + -1.896547e+04, + -1.949759e+03, + 2.858043e+03, + 1.795535e+04, + -1.298453e+04, + -2.311439e+03, + 2.059357e+03, + 1.818104e+04, + -2.551484e+04, + -2.163187e+02, + 1.287627e+03, + 1.834266e+04, + -1.600338e+04, + -4.270993e+01, + 5.122679e+02, + 1.844268e+04, + -1.846467e+11, + 2.613334e+06, + 7.450276e+01, + 3.902573e-03, + 1.667286e+09, + -3.160544e+05, + 0, + 5.017594e-03, + -3.902174e+05, + 5.452947e+03, + -3.446309e+00, + 3.345062e-03, + -2.708707e+06, + 4.468648e+03, + 0, + 2.787552e-03, + -1.153853e+06, + 2.969827e+03, + 2.394593e+00, + 3.902573e-03, + 3.457846e+05, + 1.456899e+01, + 4.812851e+00, + 8.362656e-03, + 2.322128e+04, + 1.682256e+03, + 7.411109e+00, + 1.728282e-02, + -9.250953e+04, + 3.491170e+03, + 1.511058e+01, + 4.181328e-02, + -1.140402e+04, + 5.499039e+03, + 3.309618e+01, + 1.131746e-01, + 2.602436e+05, + 9.641526e+03, + 7.375697e+01, + 3.133209e-01, + -1.325523e+06, + 3.732442e+04, + 1.808742e+02, + 8.948042e-01, + -4.382676e+05, + 4.642239e+04, + 4.773414e+02, + 2.895709e+00, + -1.636631e+06, + 9.209222e+04, + 1.051141e+03, + 8.195961e+00, + -2.042284e+06, + 1.355507e+05, + 2.219278e+03, + 2.184828e+01, + -2.868143e+06, + 1.895901e+05, + 4.230793e+03, + 5.311346e+01, + -3.378460e+06, + 2.314211e+05, + 7.337166e+03, + 1.178716e+02, + -3.383704e+06, + 2.485497e+05, + 1.152400e+04, + 2.383223e+02, + -3.611693e+06, + 2.504024e+05, + 1.651144e+04, + 4.404639e+02, + -2.710830e+06, + 2.062171e+05, + 2.172585e+04, + 7.505122e+02, + -2.193920e+06, + 1.640529e+05, + 2.647851e+04, + 1.184719e+03, + -1.888746e+06, + 1.220847e+05, + 3.038570e+04, + 1.752278e+03, + -1.180573e+06, + 6.785978e+04, + 3.301593e+04, + 2.451054e+03, + -9.119347e+05, + 3.479131e+04, + 3.423626e+04, + 3.263083e+03, + -4.432393e+05, + 6.671025e+02, + 3.418252e+04, + 4.167016e+03, + -3.338143e+05, + -1.199384e+04, + 3.313578e+04, + 5.133589e+03, + -1.979577e+05, + -2.245575e+04, + 3.142588e+04, + 6.140752e+03, + -1.443444e+05, + -2.612535e+04, + 2.924376e+04, + 7.164707e+03, + -1.039579e+05, + -2.759601e+04, + 2.677478e+04, + 8.185464e+03, + 6.889591e+03, + -3.078271e+04, + 2.413897e+04, + 9.184259e+03, + -7.514438e+04, + -2.239874e+04, + 2.158917e+04, + 1.014449e+04, + 4.257686e+04, + -2.654203e+04, + 1.911626e+04, + 1.106395e+04, + -6.392534e+04, + -1.575459e+04, + 1.685800e+04, + 1.192695e+04, + 3.833671e+04, + -2.059340e+04, + 1.473601e+04, + 1.274193e+04, + -4.175233e+04, + -1.138346e+04, + 1.282932e+04, + 1.349170e+04, + 1.568732e+04, + -1.428547e+04, + 1.108599e+04, + 1.418980e+04, + -1.592132e+04, + -9.200685e+03, + 9.505594e+03, + 1.482175e+04, + 9.423744e+03, + -9.833787e+03, + 8.103365e+03, + 1.539779e+04, + -2.081387e+04, + -5.508437e+03, + 6.882485e+03, + 1.591251e+04, + 2.938513e+03, + -6.992832e+03, + 5.751007e+03, + 1.637591e+04, + -1.006852e+04, + -4.396123e+03, + 4.730716e+03, + 1.677699e+04, + -9.845785e+03, + -3.800704e+03, + 3.824602e+03, + 1.712480e+04, + -1.466034e+04, + -2.720469e+03, + 2.967253e+03, + 1.741587e+04, + -1.131802e+04, + -2.508277e+03, + 2.133736e+03, + 1.764822e+04, + -2.788700e+04, + -1.062039e+01, + 1.368856e+03, + 1.781643e+04, + -1.738426e+04, + -4.486282e+01, + 5.656062e+02, + 1.792414e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -4.297648e+06, + 4.111555e+03, + 0, + 0, + 0, + 0, + 0, + 5.575104e-04, + -5.581082e+05, + 1.781758e+03, + 0, + 5.575104e-04, + 1.843572e+05, + -3.770991e+02, + 1.469976e+00, + 2.787552e-03, + -3.952308e+05, + 2.931368e+03, + 2.469540e+00, + 6.132615e-03, + 2.621871e+05, + -9.011830e+01, + 9.486217e+00, + 2.843303e-02, + -1.562634e+05, + 6.783349e+03, + 1.981770e+01, + 7.637893e-02, + -5.987073e+05, + 1.920998e+04, + 7.296369e+01, + 3.010556e-01, + -4.734045e+05, + 3.233755e+04, + 2.337040e+02, + 1.231541e+00, + -1.292884e+06, + 6.785280e+04, + 6.097906e+02, + 4.193593e+00, + -1.682559e+06, + 1.071776e+05, + 1.453400e+03, + 1.287515e+01, + -2.404541e+06, + 1.584818e+05, + 3.025797e+03, + 3.469778e+01, + -3.146009e+06, + 2.066665e+05, + 5.619983e+03, + 8.326530e+01, + -2.709797e+06, + 2.201851e+05, + 9.299217e+03, + 1.789965e+02, + -3.778700e+06, + 2.492082e+05, + 1.388870e+04, + 3.460623e+02, + -2.343804e+06, + 1.957822e+05, + 1.893955e+04, + 6.135988e+02, + -2.283303e+06, + 1.718623e+05, + 2.366783e+04, + 9.972451e+02, + -1.924180e+06, + 1.288603e+05, + 2.777848e+04, + 1.511863e+03, + -9.241237e+05, + 6.747835e+04, + 3.065304e+04, + 2.156804e+03, + -1.086438e+06, + 5.116178e+04, + 3.229492e+04, + 2.915626e+03, + -4.632157e+05, + 7.870416e+03, + 3.273955e+04, + 3.776818e+03, + -3.230504e+05, + -6.985506e+03, + 3.205541e+04, + 4.707586e+03, + -2.475074e+05, + -1.596795e+04, + 3.068760e+04, + 5.686358e+03, + -1.378401e+05, + -2.375715e+04, + 2.877374e+04, + 6.690937e+03, + -8.940252e+04, + -2.589151e+04, + 2.650252e+04, + 7.698058e+03, + -2.683560e+04, + -2.716741e+04, + 2.406685e+04, + 8.689683e+03, + -5.526493e+04, + -2.270183e+04, + 2.164225e+04, + 9.650765e+03, + -8.489383e+03, + -2.300292e+04, + 1.926287e+04, + 1.057381e+04, + -1.388131e+04, + -1.936649e+04, + 1.699055e+04, + 1.144637e+04, + 7.094209e+03, + -1.780787e+04, + 1.489322e+04, + 1.226540e+04, + -2.836236e+04, + -1.264700e+04, + 1.301116e+04, + 1.302698e+04, + 2.092988e+04, + -1.443269e+04, + 1.125648e+04, + 1.373400e+04, + -2.156834e+04, + -8.504181e+03, + 9.717555e+03, + 1.437710e+04, + -6.708749e+03, + -8.789276e+03, + 8.334151e+03, + 1.496836e+04, + -1.692188e+03, + -7.736227e+03, + 7.027454e+03, + 1.549866e+04, + -4.473494e+03, + -6.083076e+03, + 5.875349e+03, + 1.596817e+04, + -1.208879e+04, + -4.407527e+03, + 4.863871e+03, + 1.638080e+04, + -8.618245e+03, + -4.133615e+03, + 3.916455e+03, + 1.673821e+04, + -8.899190e+03, + -3.323467e+03, + 3.029126e+03, + 1.703543e+04, + -1.897729e+04, + -1.633485e+03, + 2.225304e+03, + 1.727258e+04, + -3.279575e+04, + 2.298052e+02, + 1.423357e+03, + 1.745072e+04, + -1.484592e+04, + -2.882339e+02, + 5.261383e+02, + 1.756148e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -5.090528e+04, + 4.110663e+02, + 0, + 0, + 2.437332e+04, + 1.728558e+02, + 1.098978e+00, + 2.230042e-03, + -5.251004e+04, + 1.839037e+03, + 3.415254e+00, + 1.003519e-02, + -1.034817e+05, + 5.494798e+03, + 1.715950e+01, + 6.076864e-02, + -3.817933e+05, + 1.664499e+04, + 6.975643e+01, + 3.183384e-01, + -5.260784e+05, + 3.421596e+04, + 2.439328e+02, + 1.452872e+00, + -1.288699e+06, + 7.236937e+04, + 6.940201e+02, + 5.383321e+00, + -1.884821e+06, + 1.157847e+05, + 1.715049e+03, + 1.728115e+01, + -2.068708e+06, + 1.540029e+05, + 3.564861e+03, + 4.720887e+01, + -2.701302e+06, + 1.965799e+05, + 6.434261e+03, + 1.113315e+02, + -2.916540e+06, + 2.134724e+05, + 1.036392e+04, + 2.333911e+02, + -2.526077e+06, + 1.969947e+05, + 1.493163e+04, + 4.395490e+02, + -1.965767e+06, + 1.637507e+05, + 1.953147e+04, + 7.516110e+02, + -1.697977e+06, + 1.315705e+05, + 2.369155e+04, + 1.184152e+03, + -1.124648e+06, + 8.674265e+04, + 2.700457e+04, + 1.743860e+03, + -9.015866e+05, + 5.643048e+04, + 2.922375e+04, + 2.423722e+03, + -7.506628e+05, + 3.028053e+04, + 3.032450e+04, + 3.211428e+03, + -1.502096e+05, + -6.976241e+03, + 3.021703e+04, + 4.084801e+03, + -4.313262e+05, + -4.280012e+02, + 2.934955e+04, + 5.011680e+03, + -8.356901e+04, + -2.305404e+04, + 2.785722e+04, + 5.981843e+03, + -6.447470e+04, + -2.307799e+04, + 2.585185e+04, + 6.959204e+03, + -6.518919e+04, + -2.177705e+04, + 2.375067e+04, + 7.931175e+03, + -6.379765e+04, + -2.063416e+04, + 2.157590e+04, + 8.885643e+03, + 3.719946e+02, + -2.246051e+04, + 1.933079e+04, + 9.809115e+03, + -2.302765e+04, + -1.787789e+04, + 1.717219e+04, + 1.068719e+04, + -8.297077e+03, + -1.659973e+04, + 1.515538e+04, + 1.151822e+04, + 7.842093e+02, + -1.472122e+04, + 1.326753e+04, + 1.229522e+04, + -1.859957e+04, + -1.110603e+04, + 1.156662e+04, + 1.301583e+04, + 4.434424e+03, + -1.134157e+04, + 9.987902e+03, + 1.368140e+04, + -2.070461e+04, + -7.474109e+03, + 8.566013e+03, + 1.428543e+04, + 1.277143e+04, + -9.241875e+03, + 7.241224e+03, + 1.483337e+04, + -1.508531e+04, + -4.897739e+03, + 6.099617e+03, + 1.531603e+04, + -1.471159e+04, + -4.527480e+03, + 5.082794e+03, + 1.574803e+04, + -3.968351e+03, + -4.893573e+03, + 4.064790e+03, + 1.612095e+04, + -1.081038e+04, + -3.174699e+03, + 3.148908e+03, + 1.642812e+04, + -2.027976e+04, + -1.650839e+03, + 2.326102e+03, + 1.667577e+04, + -2.971391e+04, + -2.147712e+02, + 1.486818e+03, + 1.686212e+04, + -1.842872e+04, + -5.515463e+01, + 5.911260e+02, + 1.697771e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.548164e+03, + 5.832732e+01, + 0, + 0, + -4.254350e+04, + 1.106875e+03, + 4.435921e-01, + 1.115021e-03, + -6.186367e+04, + 3.476985e+03, + 8.919585e+00, + 3.177809e-02, + -2.400450e+05, + 1.236929e+04, + 4.781682e+01, + 2.358269e-01, + -5.044807e+05, + 3.042742e+04, + 2.007490e+02, + 1.304017e+00, + -1.089476e+06, + 6.341001e+04, + 6.399979e+02, + 5.479212e+00, + -1.227911e+06, + 9.442542e+04, + 1.632738e+03, + 1.854057e+01, + -1.843917e+06, + 1.380790e+05, + 3.410850e+03, + 5.106126e+01, + -2.151846e+06, + 1.665970e+05, + 6.202903e+03, + 1.213332e+02, + -2.042129e+06, + 1.709803e+05, + 9.861164e+03, + 2.528505e+02, + -2.013808e+06, + 1.629299e+05, + 1.399494e+04, + 4.696808e+02, + -1.226414e+06, + 1.227890e+05, + 1.806697e+04, + 7.926443e+02, + -1.415486e+06, + 1.097980e+05, + 2.166666e+04, + 1.230785e+03, + -7.867272e+05, + 6.384606e+04, + 2.448953e+04, + 1.792229e+03, + -6.455655e+05, + 4.083803e+04, + 2.621488e+04, + 2.463119e+03, + -4.555601e+05, + 1.792048e+04, + 2.696774e+04, + 3.230170e+03, + -9.267617e+04, + -6.476458e+03, + 2.676322e+04, + 4.071033e+03, + -2.927601e+05, + -1.052446e+03, + 2.601313e+04, + 4.960256e+03, + -1.217774e+05, + -1.516011e+04, + 2.477810e+04, + 5.889640e+03, + -3.133872e+04, + -2.038053e+04, + 2.303332e+04, + 6.828298e+03, + -8.323439e+04, + -1.637279e+04, + 2.115509e+04, + 7.757606e+03, + 2.477021e+04, + -2.169634e+04, + 1.917545e+04, + 8.668998e+03, + -6.502164e+04, + -1.334719e+04, + 1.725980e+04, + 9.544082e+03, + 5.350009e+03, + -1.721099e+04, + 1.537623e+04, + 1.038587e+04, + -1.384803e+04, + -1.325894e+04, + 1.354377e+04, + 1.117533e+04, + 4.594548e+03, + -1.274668e+04, + 1.186473e+04, + 1.191404e+04, + -3.094085e+04, + -8.212376e+03, + 1.034769e+04, + 1.259716e+04, + 2.132700e+04, + -1.145801e+04, + 8.882879e+03, + 1.322813e+04, + -3.035282e+04, + -4.902982e+03, + 7.607703e+03, + 1.379274e+04, + 5.411916e+03, + -7.830371e+03, + 6.412932e+03, + 1.430841e+04, + -1.810219e+04, + -4.158606e+03, + 5.307838e+03, + 1.475643e+04, + -3.007288e+02, + -5.370719e+03, + 4.283134e+03, + 1.514813e+04, + -2.178750e+04, + -2.173925e+03, + 3.365475e+03, + 1.547263e+04, + -1.511740e+04, + -2.655632e+03, + 2.459696e+03, + 1.573975e+04, + -3.355339e+04, + 7.946364e+01, + 1.567829e+03, + 1.593402e+04, + -1.896481e+04, + -1.109393e+02, + 6.194191e+02, + 1.605676e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.491786e+03, + 2.774529e+02, + 0, + 0, + -4.543511e+04, + 1.887313e+03, + 2.744877e+00, + 1.059270e-02, + -6.058786e+04, + 5.419371e+03, + 2.435209e+01, + 1.321300e-01, + -2.888232e+05, + 1.859427e+04, + 1.103914e+02, + 7.927798e-01, + -6.056967e+05, + 4.106824e+04, + 4.123811e+02, + 3.821734e+00, + -8.632473e+05, + 6.819488e+04, + 1.152532e+03, + 1.412787e+01, + -1.223397e+06, + 9.931776e+04, + 2.559702e+03, + 4.147376e+01, + -1.340520e+06, + 1.187963e+05, + 4.785345e+03, + 1.020841e+02, + -1.331923e+06, + 1.258200e+05, + 7.731127e+03, + 2.165939e+02, + -1.384212e+06, + 1.233902e+05, + 1.113473e+04, + 4.071911e+02, + -6.897551e+05, + 8.991942e+04, + 1.453688e+04, + 6.933099e+02, + -1.214735e+06, + 9.534407e+04, + 1.765376e+04, + 1.082844e+03, + -4.097940e+05, + 4.438210e+04, + 2.014827e+04, + 1.588657e+03, + -3.878253e+05, + 3.305638e+04, + 2.168065e+04, + 2.190812e+03, + -4.045554e+05, + 2.233340e+04, + 2.261177e+04, + 2.884151e+03, + -1.793317e+05, + 1.946184e+03, + 2.274125e+04, + 3.654479e+03, + -6.062687e+04, + -7.801344e+03, + 2.217293e+04, + 4.474418e+03, + -1.596910e+05, + -4.718906e+03, + 2.128443e+04, + 5.326097e+03, + -4.954925e+04, + -1.385354e+04, + 2.004253e+04, + 6.200059e+03, + -1.408864e+04, + -1.539126e+04, + 1.849437e+04, + 7.069552e+03, + -3.886102e+04, + -1.263844e+04, + 1.691557e+04, + 7.922135e+03, + -2.899779e+04, + -1.274985e+04, + 1.531142e+04, + 8.751657e+03, + 3.490567e+03, + -1.374791e+04, + 1.365887e+04, + 9.545296e+03, + -1.297414e+04, + -1.056211e+04, + 1.209829e+04, + 1.029242e+04, + -9.319178e+03, + -9.642875e+03, + 1.065048e+04, + 1.099410e+04, + -9.836923e+03, + -8.388618e+03, + 9.274745e+03, + 1.164472e+04, + -1.192357e+04, + -7.167599e+03, + 7.978709e+03, + 1.224070e+04, + 1.301938e+03, + -7.300621e+03, + 6.746966e+03, + 1.277847e+04, + -2.409152e+04, + -3.801826e+03, + 5.650636e+03, + 1.325335e+04, + 2.135069e+03, + -6.018935e+03, + 4.566522e+03, + 1.367190e+04, + -2.471835e+04, + -2.111991e+03, + 3.591472e+03, + 1.401725e+04, + -1.336144e+04, + -3.118779e+03, + 2.626973e+03, + 1.430292e+04, + -3.618346e+04, + 1.887078e+02, + 1.694546e+03, + 1.451020e+04, + -2.192421e+04, + -1.048766e+01, + 6.919574e+02, + 1.464393e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.298658e+02, + 1.891811e+01, + 0, + 0, + -1.240277e+04, + 5.345032e+02, + 2.608164e-01, + 1.115021e-03, + -1.596284e+04, + 1.741852e+03, + 7.032467e+00, + 4.069826e-02, + -1.027246e+05, + 7.361202e+03, + 3.925922e+01, + 3.027282e-01, + -2.060335e+05, + 1.759016e+04, + 1.746335e+02, + 1.730512e+00, + -4.143519e+05, + 3.512883e+04, + 5.474948e+02, + 7.103240e+00, + -5.194204e+05, + 5.235380e+04, + 1.348534e+03, + 2.294490e+01, + -7.226607e+05, + 7.188365e+04, + 2.713832e+03, + 6.034437e+01, + -8.224504e+05, + 8.236982e+04, + 4.702827e+03, + 1.360303e+02, + -5.759747e+05, + 7.532407e+04, + 7.117950e+03, + 2.687273e+02, + -7.814308e+05, + 7.950876e+04, + 9.732035e+03, + 4.740952e+02, + -4.677243e+05, + 5.706459e+04, + 1.228851e+04, + 7.694051e+02, + -3.405356e+05, + 4.326742e+04, + 1.440361e+04, + 1.156059e+03, + -3.661262e+05, + 3.527188e+04, + 1.610547e+04, + 1.634736e+03, + -2.050564e+05, + 1.800520e+04, + 1.723562e+04, + 2.202346e+03, + -1.739701e+05, + 9.803099e+03, + 1.773202e+04, + 2.842272e+03, + -4.267503e+04, + -1.775289e+03, + 1.770045e+04, + 3.540405e+03, + -1.174590e+05, + 2.979865e+02, + 1.732537e+04, + 4.277679e+03, + -6.005372e+04, + -6.416114e+03, + 1.663838e+04, + 5.047353e+03, + -1.009872e+04, + -1.033768e+04, + 1.560400e+04, + 5.826299e+03, + -4.043125e+04, + -7.878538e+03, + 1.446322e+04, + 6.598461e+03, + -2.113247e+04, + -9.484497e+03, + 1.324051e+04, + 7.358438e+03, + 2.589035e+03, + -1.043233e+04, + 1.192600e+04, + 8.090833e+03, + -2.651877e+04, + -6.981116e+03, + 1.067108e+04, + 8.786026e+03, + -6.138087e+03, + -8.355998e+03, + 9.423123e+03, + 9.444529e+03, + -1.199978e+04, + -6.803323e+03, + 8.184259e+03, + 1.005210e+04, + -5.136721e+03, + -6.606467e+03, + 7.004292e+03, + 1.060672e+04, + -8.765806e+03, + -5.278347e+03, + 5.900880e+03, + 1.110251e+04, + -2.318204e+04, + -3.325419e+03, + 4.877837e+03, + 1.153968e+04, + -6.973830e+03, + -4.679254e+03, + 3.813233e+03, + 1.191537e+04, + -2.198839e+04, + -2.109273e+03, + 2.813720e+03, + 1.221296e+04, + -4.232767e+04, + 4.552064e+02, + 1.844062e+03, + 1.243947e+04, + -2.133196e+04, + -2.242884e+02, + 7.171137e+02, + 1.258462e+04, +}; + +double solarDataset480[] = +{ + -2.547404e+13, + 3.635631e+08, + 1.293910e+04, + 3.796038e+01, + 1.491564e+11, + -3.082064e+07, + 2.764923e+03, + 3.816097e+01, + -4.508309e+10, + 2.784696e+07, + 1.842137e+03, + 3.830790e+01, + 1.877320e+09, + -2.075191e+06, + 5.574952e+03, + 4.031446e+01, + 1.363759e+08, + 1.060735e+05, + 5.218855e+03, + 4.351307e+01, + -4.042173e+07, + 4.168932e+05, + 5.894289e+03, + 4.927657e+01, + -1.979427e+07, + 3.130223e+05, + 6.903811e+03, + 5.939239e+01, + 6.227794e+07, + 3.355382e+04, + 7.989751e+03, + 7.579875e+01, + -2.611063e+07, + 5.428849e+05, + 9.770848e+03, + 1.008989e+02, + 6.751575e+06, + 3.486580e+05, + 1.273626e+04, + 1.436773e+02, + -7.094370e+06, + 5.158292e+05, + 1.643574e+04, + 2.114709e+02, + -9.375221e+06, + 5.686982e+05, + 2.162922e+04, + 3.207238e+02, + -9.044998e+06, + 5.787047e+05, + 2.809570e+04, + 4.923702e+02, + -1.059918e+07, + 5.884594e+05, + 3.567928e+04, + 7.525556e+02, + -1.032559e+07, + 5.383256e+05, + 4.394951e+04, + 1.132412e+03, + -9.508141e+06, + 4.496710e+05, + 5.199543e+04, + 1.660855e+03, + -6.314974e+06, + 3.051184e+05, + 5.876680e+04, + 2.358284e+03, + -6.086400e+06, + 2.212357e+05, + 6.360343e+04, + 3.228792e+03, + -3.788528e+06, + 9.381155e+04, + 6.603062e+04, + 4.267693e+03, + -2.077730e+06, + 4.085149e+03, + 6.579013e+04, + 5.445031e+03, + -1.998244e+06, + -2.581562e+04, + 6.353956e+04, + 6.724786e+03, + -5.455764e+05, + -8.455452e+04, + 5.958479e+04, + 8.073218e+03, + -5.401502e+05, + -8.066396e+04, + 5.460598e+04, + 9.442031e+03, + -4.626920e+05, + -7.878633e+04, + 4.927072e+04, + 1.080685e+04, + 4.307696e+04, + -8.866941e+04, + 4.363750e+04, + 1.213911e+04, + -9.896498e+04, + -6.809587e+04, + 3.825652e+04, + 1.340968e+04, + -4.046726e+04, + -6.013412e+04, + 3.334045e+04, + 1.461550e+04, + 2.465424e+04, + -5.267288e+04, + 2.881215e+04, + 1.574516e+04, + -6.606890e+04, + -3.886479e+04, + 2.480495e+04, + 1.679298e+04, + 8.625368e+04, + -3.988716e+04, + 2.118987e+04, + 1.776151e+04, + -5.094497e+04, + -2.400663e+04, + 1.812357e+04, + 1.864229e+04, + 3.521782e+04, + -2.523723e+04, + 1.545985e+04, + 1.945299e+04, + -2.910575e+04, + -1.612809e+04, + 1.314789e+04, + 2.018464e+04, + 2.987436e+04, + -1.729633e+04, + 1.112528e+04, + 2.084999e+04, + -2.392041e+04, + -9.871844e+03, + 9.419435e+03, + 2.144328e+04, + 1.318656e+04, + -1.113363e+04, + 7.932171e+03, + 2.198012e+04, + -8.189886e+03, + -7.083342e+03, + 6.648923e+03, + 2.245346e+04, + 8.760018e+02, + -6.634529e+03, + 5.556208e+03, + 2.287527e+04, + -7.219063e+03, + -4.650361e+03, + 4.605098e+03, + 2.324459e+04, + -7.443951e+03, + -3.898973e+03, + 3.764874e+03, + 2.356703e+04, + -5.229746e+03, + -3.417661e+03, + 2.990255e+03, + 2.384152e+04, + -9.160621e+03, + -2.339852e+03, + 2.297538e+03, + 2.406739e+04, + -1.337575e+04, + -1.443204e+03, + 1.662712e+03, + 2.424699e+04, + -1.609842e+04, + -6.573803e+02, + 1.042947e+03, + 2.437881e+04, + -1.154888e+04, + -2.049765e+02, + 4.517902e+02, + 2.445949e+04, + 4.227183e+11, + 1.389648e+06, + 1.036346e+03, + 1.739462e+01, + -4.523986e+10, + 1.309428e+07, + 1.461077e+03, + 1.741507e+01, + -1.974469e+09, + 2.075506e+06, + 2.645040e+03, + 1.770254e+01, + -1.554063e+09, + 1.591460e+06, + 3.369179e+03, + 1.872211e+01, + 5.672809e+08, + -8.382778e+05, + 3.502720e+03, + 2.111515e+01, + -1.132935e+08, + 5.257210e+05, + 3.621481e+03, + 2.453096e+01, + 5.367205e+07, + 3.863978e+04, + 4.434495e+03, + 3.106808e+01, + -7.651470e+05, + 2.973158e+05, + 5.375363e+03, + 4.152440e+01, + -5.641271e+06, + 3.520079e+05, + 7.088158e+03, + 5.968817e+01, + -3.575740e+05, + 3.595429e+05, + 9.484804e+03, + 9.083227e+01, + -5.432283e+06, + 4.570748e+05, + 1.282057e+04, + 1.429497e+02, + -8.493195e+06, + 5.345880e+05, + 1.750590e+04, + 2.299714e+02, + -9.361727e+06, + 5.742448e+05, + 2.362945e+04, + 3.720855e+02, + -1.230376e+07, + 6.089220e+05, + 3.107881e+04, + 5.957043e+02, + -8.209413e+06, + 5.098829e+05, + 3.928027e+04, + 9.325726e+02, + -9.315159e+06, + 4.745999e+05, + 4.745855e+04, + 1.409587e+03, + -8.627264e+06, + 3.733993e+05, + 5.493900e+04, + 2.054851e+03, + -4.714765e+06, + 2.032292e+05, + 6.032301e+04, + 2.878534e+03, + -3.679437e+06, + 1.165562e+05, + 6.321237e+04, + 3.866403e+03, + -2.929350e+06, + 4.492419e+04, + 6.387975e+04, + 5.001581e+03, + -1.392612e+06, + -3.265661e+04, + 6.224732e+04, + 6.253081e+03, + -1.117804e+06, + -5.501965e+04, + 5.885362e+04, + 7.576411e+03, + -4.075604e+05, + -8.239287e+04, + 5.430578e+04, + 8.936806e+03, + -2.459750e+05, + -8.099482e+04, + 4.915270e+04, + 1.029496e+04, + -3.665911e+05, + -6.851276e+04, + 4.392374e+04, + 1.162710e+04, + 2.205685e+05, + -8.274490e+04, + 3.860977e+04, + 1.291372e+04, + -3.040342e+05, + -4.570146e+04, + 3.379260e+04, + 1.412701e+04, + 1.469667e+05, + -6.087770e+04, + 2.926964e+04, + 1.527950e+04, + -6.797871e+04, + -3.790137e+04, + 2.518196e+04, + 1.633998e+04, + 3.949307e+04, + -3.733814e+04, + 2.163770e+04, + 1.732591e+04, + -7.975621e+03, + -2.732830e+04, + 1.851668e+04, + 1.822774e+04, + -4.377782e+03, + -2.272640e+04, + 1.583173e+04, + 1.905445e+04, + 1.693589e+04, + -1.978767e+04, + 1.346464e+04, + 1.980645e+04, + -1.488896e+04, + -1.382418e+04, + 1.145439e+04, + 2.048569e+04, + -5.303294e+03, + -1.226164e+04, + 9.699219e+03, + 2.110102e+04, + 2.706972e+04, + -1.214607e+04, + 8.129372e+03, + 2.165037e+04, + -3.562524e+04, + -4.676288e+03, + 6.891074e+03, + 2.213611e+04, + 2.093737e+04, + -9.026232e+03, + 5.739331e+03, + 2.257705e+04, + -2.006414e+04, + -3.337389e+03, + 4.758662e+03, + 2.295476e+04, + -1.964465e+03, + -4.781112e+03, + 3.893292e+03, + 2.329090e+04, + -7.979526e+03, + -3.208613e+03, + 3.083342e+03, + 2.357289e+04, + -3.882281e+03, + -2.975486e+03, + 2.366732e+03, + 2.380648e+04, + -1.970221e+04, + -7.385175e+02, + 1.744297e+03, + 2.399093e+04, + -2.049545e+04, + -4.245408e+02, + 1.090574e+03, + 2.413137e+04, + -1.271643e+04, + -9.063678e+01, + 4.186658e+02, + 2.421482e+04, + -3.562425e+12, + 4.547613e+07, + 3.869422e+03, + 4.918330e+00, + 4.689183e+10, + -1.281786e+07, + 2.261597e+03, + 4.980296e+00, + 2.022864e+09, + -1.220456e+06, + 1.216501e+03, + 5.148946e+00, + 2.776720e+08, + -1.053418e+05, + 1.068025e+03, + 5.487525e+00, + -1.590271e+08, + 4.112991e+05, + 1.272512e+03, + 6.197900e+00, + 6.495931e+07, + -3.603970e+04, + 1.609987e+03, + 7.805828e+00, + -2.064038e+07, + 2.320516e+05, + 1.976444e+03, + 1.049337e+01, + 1.765744e+07, + 1.028749e+05, + 2.695696e+03, + 1.571579e+01, + -1.181768e+07, + 3.056096e+05, + 3.744644e+03, + 2.487848e+01, + 3.197837e+06, + 2.544026e+05, + 5.534911e+03, + 4.254333e+01, + -9.201137e+06, + 4.284098e+05, + 8.121123e+03, + 7.427706e+01, + -8.890947e+06, + 4.785445e+05, + 1.211126e+04, + 1.328518e+02, + -7.071586e+06, + 5.059339e+05, + 1.741186e+04, + 2.352960e+02, + -1.166674e+07, + 5.930738e+05, + 2.420576e+04, + 4.053939e+02, + -1.014664e+07, + 5.469944e+05, + 3.227826e+04, + 6.765805e+02, + -8.709155e+06, + 4.717684e+05, + 4.057628e+04, + 1.079331e+03, + -6.589641e+06, + 3.640900e+05, + 4.826717e+04, + 1.639785e+03, + -5.956205e+06, + 2.764700e+05, + 5.460139e+04, + 2.373352e+03, + -4.410054e+06, + 1.636818e+05, + 5.887661e+04, + 3.284026e+03, + -2.573675e+06, + 5.767791e+04, + 6.052561e+04, + 4.353163e+03, + -1.725557e+06, + -2.089540e+03, + 5.980763e+04, + 5.546333e+03, + -7.726710e+05, + -4.982537e+04, + 5.727085e+04, + 6.827655e+03, + -9.367723e+05, + -5.118449e+04, + 5.356326e+04, + 8.157893e+03, + -2.139498e+05, + -7.920098e+04, + 4.895601e+04, + 9.508497e+03, + -1.552485e+05, + -7.235301e+04, + 4.390792e+04, + 1.083723e+04, + -1.628579e+04, + -6.809604e+04, + 3.896658e+04, + 1.212598e+04, + -1.983318e+05, + -5.059195e+04, + 3.433105e+04, + 1.335883e+04, + 8.171771e+04, + -5.652750e+04, + 2.987115e+04, + 1.452950e+04, + -1.382147e+04, + -4.085430e+04, + 2.582431e+04, + 1.561625e+04, + -1.903892e+04, + -3.373542e+04, + 2.231868e+04, + 1.662797e+04, + 1.630797e+04, + -2.980642e+04, + 1.916625e+04, + 1.756241e+04, + -1.470429e+04, + -2.241600e+04, + 1.641147e+04, + 1.841734e+04, + 1.183830e+04, + -2.013913e+04, + 1.399466e+04, + 1.919851e+04, + -7.425767e+03, + -1.497561e+04, + 1.190037e+04, + 1.990483e+04, + 2.348122e+04, + -1.430663e+04, + 1.008697e+04, + 2.054362e+04, + -3.407580e+04, + -7.210622e+03, + 8.592568e+03, + 2.111580e+04, + 8.410728e+03, + -9.841158e+03, + 7.218391e+03, + 2.163577e+04, + 5.333101e+03, + -7.356348e+03, + 5.982069e+03, + 2.208915e+04, + -1.934314e+04, + -3.841909e+03, + 4.996690e+03, + 2.248734e+04, + 3.189408e+03, + -5.483261e+03, + 4.066681e+03, + 2.283908e+04, + -1.021377e+04, + -2.980445e+03, + 3.244087e+03, + 2.313320e+04, + -9.790041e+03, + -2.583961e+03, + 2.517956e+03, + 2.338071e+04, + -1.444370e+04, + -1.591158e+03, + 1.824665e+03, + 2.357756e+04, + -2.379887e+04, + -1.133726e+02, + 1.149303e+03, + 2.372235e+04, + -1.332327e+04, + -1.181356e+02, + 4.433913e+02, + 2.381143e+04, + -4.062495e+12, + 5.889514e+07, + 1.822539e+03, + 5.934704e-01, + 1.116655e+10, + -2.476749e+06, + 2.315678e+02, + 6.215788e-01, + -2.883849e+08, + 3.186874e+05, + 1.216092e+02, + 6.330776e-01, + -3.334973e+08, + 3.506258e+05, + 2.375575e+02, + 6.969603e-01, + 9.502123e+07, + -1.388013e+05, + 2.778272e+02, + 9.045791e-01, + -3.169474e+07, + 1.355526e+05, + 3.011117e+02, + 1.153722e+00, + 1.354177e+07, + 8.549983e+03, + 4.924110e+02, + 1.837267e+00, + -9.788296e+06, + 1.268912e+05, + 7.245476e+02, + 3.098311e+00, + 8.321999e+06, + 5.975755e+04, + 1.214653e+03, + 6.043943e+00, + -9.981085e+06, + 2.455768e+05, + 2.011040e+03, + 1.185919e+01, + -2.885803e+06, + 2.397529e+05, + 3.652004e+03, + 2.559525e+01, + -6.329634e+06, + 3.478969e+05, + 6.106085e+03, + 5.370172e+01, + -7.960277e+06, + 4.345711e+05, + 9.978396e+03, + 1.097524e+02, + -7.895936e+06, + 4.855802e+05, + 1.544416e+04, + 2.146203e+02, + -1.056970e+07, + 5.455151e+05, + 2.249529e+04, + 3.967972e+02, + -8.772676e+06, + 4.836844e+05, + 3.061098e+04, + 6.924183e+02, + -6.125317e+06, + 3.824122e+05, + 3.856863e+04, + 1.130737e+03, + -6.234374e+06, + 3.223025e+05, + 4.569520e+04, + 1.732649e+03, + -4.135207e+06, + 1.989626e+05, + 5.121311e+04, + 2.512630e+03, + -2.831010e+06, + 1.064359e+05, + 5.436969e+04, + 3.458681e+03, + -1.771421e+06, + 3.391272e+04, + 5.527105e+04, + 4.547677e+03, + -1.352058e+06, + -6.747689e+03, + 5.423442e+04, + 5.746928e+03, + -4.737948e+05, + -5.056302e+04, + 5.159311e+04, + 7.021275e+03, + -5.178401e+05, + -5.085618e+04, + 4.797068e+04, + 8.329029e+03, + -3.165613e+05, + -5.894560e+04, + 4.379803e+04, + 9.645661e+03, + -3.525713e+04, + -6.498724e+04, + 3.922274e+04, + 1.093910e+04, + -1.698033e+03, + -5.646027e+04, + 3.473194e+04, + 1.218335e+04, + -8.252137e+04, + -4.418587e+04, + 3.062394e+04, + 1.337026e+04, + -4.452976e+04, + -4.012949e+04, + 2.678876e+04, + 1.449551e+04, + 1.756583e+04, + -3.688401e+04, + 2.318145e+04, + 1.554675e+04, + 2.497374e+04, + -3.028839e+04, + 1.996805e+04, + 1.651698e+04, + -4.542787e+04, + -2.074654e+04, + 1.722708e+04, + 1.741034e+04, + 4.577114e+04, + -2.317554e+04, + 1.473888e+04, + 1.823360e+04, + -2.941513e+04, + -1.335336e+04, + 1.261663e+04, + 1.897704e+04, + 9.540414e+03, + -1.422160e+04, + 1.076932e+04, + 1.965858e+04, + -1.333019e+04, + -9.795617e+03, + 9.126910e+03, + 2.026983e+04, + 6.872783e+03, + -9.753800e+03, + 7.680151e+03, + 2.081939e+04, + -6.794840e+03, + -6.642494e+03, + 6.433964e+03, + 2.130449e+04, + -6.512347e+03, + -5.595285e+03, + 5.359979e+03, + 2.173466e+04, + -7.453009e+03, + -4.569078e+03, + 4.387344e+03, + 2.210973e+04, + -8.453112e+03, + -3.685525e+03, + 3.504406e+03, + 2.243008e+04, + -1.058157e+04, + -2.798516e+03, + 2.696662e+03, + 2.269567e+04, + -1.175275e+04, + -2.070349e+03, + 1.946314e+03, + 2.290618e+04, + -2.725053e+04, + 1.473825e+02, + 1.251869e+03, + 2.306034e+04, + -1.529872e+04, + -8.045642e+01, + 4.978280e+02, + 2.315872e+04, + 0, + 0, + 0, + 3.002487e-02, + -1.090846e+10, + 1.974400e+06, + 0, + 3.002487e-02, + 3.636683e+07, + -1.786622e+04, + 0, + 3.960728e-02, + -7.026847e+07, + 9.507055e+04, + 0, + 3.896845e-02, + 1.333478e+06, + 3.529875e+03, + 3.551876e+01, + 5.941092e-02, + 2.003892e+06, + 3.786981e+03, + 4.736528e+01, + 1.022123e-01, + -1.002646e+05, + 1.491867e+04, + 7.403866e+01, + 1.935646e-01, + 8.840045e+05, + 2.053897e+04, + 1.379171e+02, + 4.260977e-01, + -1.799941e+06, + 5.585624e+04, + 2.800918e+02, + 1.024040e+00, + -1.272606e+06, + 8.353843e+04, + 6.224092e+02, + 2.759094e+00, + -3.142945e+06, + 1.498386e+05, + 1.319586e+03, + 7.359927e+00, + -5.325514e+06, + 2.353986e+05, + 2.722502e+03, + 1.918334e+01, + -4.367873e+06, + 2.950794e+05, + 5.196144e+03, + 4.713202e+01, + -8.293792e+06, + 4.208244e+05, + 9.110856e+03, + 1.061188e+02, + -8.395418e+06, + 4.579295e+05, + 1.483469e+04, + 2.224875e+02, + -6.520037e+06, + 4.312038e+05, + 2.181675e+04, + 4.272194e+02, + -7.601962e+06, + 4.292473e+05, + 2.951377e+04, + 7.524578e+02, + -5.359980e+06, + 3.235804e+05, + 3.708090e+04, + 1.232011e+03, + -4.257096e+06, + 2.366275e+05, + 4.329759e+04, + 1.879326e+03, + -2.362298e+06, + 1.320983e+05, + 4.767316e+04, + 2.696374e+03, + -2.586387e+06, + 9.404854e+04, + 5.012795e+04, + 3.667154e+03, + -1.346937e+06, + 1.521702e+04, + 5.055045e+04, + 4.774654e+03, + -6.311932e+05, + -2.761653e+04, + 4.896823e+04, + 5.973547e+03, + -2.859925e+05, + -4.535140e+04, + 4.622372e+04, + 7.225477e+03, + -5.833449e+05, + -3.576030e+04, + 4.293299e+04, + 8.502104e+03, + 5.723729e+03, + -6.133686e+04, + 3.902591e+04, + 9.783052e+03, + -8.123325e+04, + -4.879934e+04, + 3.491969e+04, + 1.102637e+04, + -5.068165e+04, + -4.411026e+04, + 3.105343e+04, + 1.222640e+04, + -3.207428e+04, + -3.889547e+04, + 2.737029e+04, + 1.337046e+04, + -1.066219e+04, + -3.412928e+04, + 2.393260e+04, + 1.444923e+04, + -1.141680e+04, + -2.854544e+04, + 2.079563e+04, + 1.545628e+04, + -4.908479e+03, + -2.421760e+04, + 1.796966e+04, + 1.638943e+04, + 2.053346e+04, + -2.145813e+04, + 1.544534e+04, + 1.724714e+04, + -3.179755e+04, + -1.406796e+04, + 1.328479e+04, + 1.803018e+04, + 3.081852e+04, + -1.632250e+04, + 1.133044e+04, + 1.874762e+04, + -2.520860e+04, + -8.744463e+03, + 9.671271e+03, + 1.939042e+04, + -5.258707e+02, + -9.682975e+03, + 8.210156e+03, + 1.997663e+04, + -3.603629e+03, + -7.596047e+03, + 6.868361e+03, + 2.049617e+04, + -1.284514e+04, + -5.501197e+03, + 5.706315e+03, + 2.095412e+04, + 5.408753e+03, + -6.215871e+03, + 4.636466e+03, + 2.135343e+04, + -1.729670e+04, + -2.725560e+03, + 3.738994e+03, + 2.168992e+04, + -8.133455e+03, + -3.384342e+03, + 2.903206e+03, + 2.197692e+04, + -1.400569e+04, + -2.007834e+03, + 2.106764e+03, + 2.220291e+04, + -3.787921e+04, + 9.695897e+02, + 1.365023e+03, + 2.237077e+04, + -1.169926e+04, + -4.806728e+02, + 4.665493e+02, + 2.247814e+04, + 6.525532e+11, + -9.597776e+06, + -2.508142e+02, + 5.110617e-03, + -7.272307e+08, + 1.316266e+05, + 0, + 1.277654e-03, + 7.273367e+07, + -3.573244e+04, + 0, + 1.916481e-03, + -9.307074e+05, + 2.164022e+03, + 0, + 6.388271e-04, + -3.846153e+06, + 8.276968e+03, + 1.624622e+00, + 1.277654e-03, + 7.045428e+05, + -9.506031e+02, + 6.273509e+00, + 7.665925e-03, + 5.471221e+05, + 7.881141e+02, + 8.492069e+00, + 1.788716e-02, + -1.157790e+06, + 1.343443e+04, + 1.980918e+01, + 4.599555e-02, + 5.648178e+05, + 1.177962e+04, + 6.860591e+01, + 1.890928e-01, + -2.168944e+06, + 5.449721e+04, + 1.804408e+02, + 6.401047e-01, + -1.936415e+06, + 8.671467e+04, + 5.476078e+02, + 2.451180e+00, + -2.778014e+06, + 1.502939e+05, + 1.348026e+03, + 8.039000e+00, + -5.988957e+06, + 2.595586e+05, + 3.014769e+03, + 2.341237e+01, + -4.953844e+06, + 3.123771e+05, + 6.037281e+03, + 6.158549e+01, + -8.072078e+06, + 4.188727e+05, + 1.060684e+04, + 1.421314e+02, + -6.102258e+06, + 4.036899e+05, + 1.685401e+04, + 2.966719e+02, + -7.081157e+06, + 4.155400e+05, + 2.406072e+04, + 5.567832e+02, + -5.275326e+06, + 3.322858e+05, + 3.155165e+04, + 9.582758e+02, + -3.846919e+06, + 2.463955e+05, + 3.810789e+04, + 1.520520e+03, + -3.514763e+06, + 1.822427e+05, + 4.321496e+04, + 2.251031e+03, + -1.456565e+06, + 7.443224e+04, + 4.630479e+04, + 3.144755e+03, + -1.859068e+06, + 5.498326e+04, + 4.747600e+04, + 4.171486e+03, + -4.928980e+05, + -1.792985e+04, + 4.691705e+04, + 5.312605e+03, + -8.773971e+05, + -1.418775e+04, + 4.496428e+04, + 6.519951e+03, + -2.751454e+04, + -5.502387e+04, + 4.200632e+04, + 7.772248e+03, + -1.594475e+05, + -4.385961e+04, + 3.851029e+04, + 9.022491e+03, + -2.928118e+05, + -3.624179e+04, + 3.501918e+04, + 1.026196e+04, + 9.244874e+04, + -5.182584e+04, + 3.122779e+04, + 1.147202e+04, + -7.298447e+04, + -3.463156e+04, + 2.759798e+04, + 1.261967e+04, + -2.297138e+04, + -3.303978e+04, + 2.430195e+04, + 1.371250e+04, + -7.257520e+03, + -2.883089e+04, + 2.118824e+04, + 1.473725e+04, + 1.617806e+04, + -2.529034e+04, + 1.836369e+04, + 1.568909e+04, + -1.048687e+04, + -1.906491e+04, + 1.589586e+04, + 1.656705e+04, + -2.280875e+03, + -1.656326e+04, + 1.371907e+04, + 1.737679e+04, + -1.173034e+04, + -1.313659e+04, + 1.177337e+04, + 1.811680e+04, + 1.764221e+03, + -1.200134e+04, + 1.002274e+04, + 1.878901e+04, + -5.443919e+03, + -9.216609e+03, + 8.480824e+03, + 1.939176e+04, + -2.042247e+03, + -7.901444e+03, + 7.133254e+03, + 1.993055e+04, + -8.037811e+03, + -5.968600e+03, + 5.951562e+03, + 2.040675e+04, + -1.379071e+04, + -4.556409e+03, + 4.894801e+03, + 2.082428e+04, + -5.451456e+02, + -5.063627e+03, + 3.890115e+03, + 2.118233e+04, + -2.023326e+04, + -2.060668e+03, + 3.019280e+03, + 2.147555e+04, + -2.864907e+03, + -3.469182e+03, + 2.170665e+03, + 2.171383e+04, + -4.564474e+04, + 1.914149e+03, + 1.447545e+03, + 2.188399e+04, + -1.285998e+04, + -5.186207e+02, + 5.108418e+02, + 2.200120e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.075985e+04, + 4.214961e+02, + 0, + 0, + 5.562181e+04, + 8.061994e+01, + 8.281078e-01, + 1.277654e-03, + -3.121437e+05, + 4.825055e+03, + 2.713965e+00, + 5.749444e-03, + -1.563799e+05, + 9.395735e+03, + 2.570856e+01, + 6.707684e-02, + -7.453272e+05, + 3.122976e+04, + 1.032542e+02, + 3.762692e-01, + -1.989081e+06, + 7.880134e+04, + 3.868377e+02, + 1.843655e+00, + -3.098191e+06, + 1.440545e+05, + 1.185918e+03, + 7.543909e+00, + -4.215556e+06, + 2.225784e+05, + 2.907656e+03, + 2.490978e+01, + -4.786020e+06, + 2.938944e+05, + 5.980692e+03, + 6.858128e+01, + -6.298563e+06, + 3.655079e+05, + 1.067540e+04, + 1.622455e+02, + -5.412413e+06, + 3.568233e+05, + 1.684205e+04, + 3.392913e+02, + -4.918343e+06, + 3.291889e+05, + 2.367207e+04, + 6.321366e+02, + -3.916896e+06, + 2.666399e+05, + 3.039895e+04, + 1.070198e+03, + -3.234356e+06, + 2.003322e+05, + 3.615701e+04, + 1.670192e+03, + -2.040334e+06, + 1.180905e+05, + 4.028384e+04, + 2.434229e+03, + -1.401604e+06, + 6.196017e+04, + 4.252555e+04, + 3.344716e+03, + -8.510153e+05, + 1.754662e+04, + 4.308474e+04, + 4.377716e+03, + -5.868429e+05, + -7.897552e+03, + 4.225322e+04, + 5.502610e+03, + -4.777308e+05, + -2.215277e+04, + 4.036574e+04, + 6.689373e+03, + -2.027395e+05, + -3.838610e+04, + 3.760893e+04, + 7.906894e+03, + 4.688571e+04, + -4.650040e+04, + 3.433909e+04, + 9.120592e+03, + -1.731682e+05, + -3.045624e+04, + 3.114684e+04, + 1.030870e+04, + -9.393385e+04, + -3.336297e+04, + 2.796966e+04, + 1.146998e+04, + 5.520659e+04, + -3.698224e+04, + 2.466929e+04, + 1.257910e+04, + -3.127735e+04, + -2.548739e+04, + 2.167580e+04, + 1.361953e+04, + -2.886510e+04, + -2.234154e+04, + 1.900618e+04, + 1.459990e+04, + 4.803892e+04, + -2.356220e+04, + 1.648513e+04, + 1.551250e+04, + -6.916297e+04, + -1.140155e+04, + 1.434094e+04, + 1.635055e+04, + 2.995112e+04, + -1.761090e+04, + 1.231851e+04, + 1.713096e+04, + -1.131187e+04, + -1.076782e+04, + 1.049085e+04, + 1.782950e+04, + -5.672132e+03, + -9.605872e+03, + 8.943086e+03, + 1.846438e+04, + -2.342928e+02, + -8.391650e+03, + 7.538626e+03, + 1.903310e+04, + -1.356312e+04, + -5.763390e+03, + 6.314320e+03, + 1.953688e+04, + -1.029218e+04, + -5.313462e+03, + 5.191616e+03, + 1.998094e+04, + -4.820491e+03, + -4.883491e+03, + 4.133093e+03, + 2.035985e+04, + -1.332017e+04, + -3.043612e+03, + 3.200526e+03, + 2.067237e+04, + -1.507804e+04, + -2.298738e+03, + 2.341341e+03, + 2.092387e+04, + -3.372668e+04, + 2.668844e+02, + 1.517180e+03, + 2.111023e+04, + -1.829462e+04, + -1.213923e+02, + 6.004736e+02, + 2.122965e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.017242e+04, + 1.750194e+02, + 0, + 0, + -1.457144e+04, + 7.281291e+02, + 8.823561e-01, + 1.916481e-03, + -8.138557e+04, + 3.915626e+03, + 6.731239e+00, + 2.044247e-02, + -3.416115e+05, + 1.616098e+04, + 4.346558e+01, + 1.712057e-01, + -1.112109e+06, + 4.948532e+04, + 2.166628e+02, + 1.116031e+00, + -1.851122e+06, + 9.973810e+04, + 7.987332e+02, + 5.514355e+00, + -2.976474e+06, + 1.703720e+05, + 2.185875e+03, + 2.036134e+01, + -3.752852e+06, + 2.346189e+05, + 4.835726e+03, + 6.046371e+01, + -3.916406e+06, + 2.725329e+05, + 8.928559e+03, + 1.496005e+02, + -4.124056e+06, + 2.880126e+05, + 1.427455e+04, + 3.184585e+02, + -3.454381e+06, + 2.560391e+05, + 2.029483e+04, + 6.004725e+02, + -2.730599e+06, + 2.065880e+05, + 2.611242e+04, + 1.020835e+03, + -2.156132e+06, + 1.532252e+05, + 3.106996e+04, + 1.593564e+03, + -1.423653e+06, + 9.444510e+04, + 3.467497e+04, + 2.319182e+03, + -1.066952e+06, + 5.365130e+04, + 3.674970e+04, + 3.182752e+03, + -5.913676e+05, + 1.479975e+04, + 3.736478e+04, + 4.162645e+03, + -4.507312e+05, + -3.442068e+03, + 3.676283e+04, + 5.228191e+03, + -3.349898e+05, + -1.694648e+04, + 3.524585e+04, + 6.352700e+03, + -5.373997e+04, + -3.272371e+04, + 3.296933e+04, + 7.506143e+03, + -1.042929e+05, + -2.794349e+04, + 3.037961e+04, + 8.657850e+03, + -1.338463e+05, + -2.558203e+04, + 2.771508e+04, + 9.797088e+03, + 4.568200e+04, + -3.329463e+04, + 2.485715e+04, + 1.090629e+04, + -6.786858e+04, + -2.165789e+04, + 2.213772e+04, + 1.196178e+04, + 1.306047e+04, + -2.435543e+04, + 1.958249e+04, + 1.296915e+04, + -3.322576e+04, + -1.756840e+04, + 1.718597e+04, + 1.391169e+04, + 2.749390e+04, + -1.920271e+04, + 1.496912e+04, + 1.479267e+04, + -3.110219e+04, + -1.154084e+04, + 1.301793e+04, + 1.560216e+04, + -6.075291e+03, + -1.225057e+04, + 1.124355e+04, + 1.635251e+04, + 6.180475e+02, + -1.069972e+04, + 9.569241e+03, + 1.703160e+04, + -6.748771e+03, + -8.170462e+03, + 8.103632e+03, + 1.764032e+04, + -1.585713e+04, + -6.165047e+03, + 6.808130e+03, + 1.818386e+04, + -6.803412e+01, + -6.704295e+03, + 5.583407e+03, + 1.866238e+04, + -1.271216e+04, + -4.147672e+03, + 4.500136e+03, + 1.906922e+04, + -1.789297e+04, + -3.078470e+03, + 3.522047e+03, + 1.941335e+04, + -1.300839e+04, + -2.995513e+03, + 2.547822e+03, + 1.968999e+04, + -3.739496e+04, + 4.124892e+02, + 1.647666e+03, + 1.989124e+04, + -1.991360e+04, + -1.343689e+02, + 6.540701e+02, + 2.002139e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -3.836497e+03, + 1.200044e+02, + 0, + 0, + -6.317725e+03, + 7.299639e+02, + 9.947280e-01, + 3.194135e-03, + -1.879736e+05, + 7.112439e+03, + 1.009800e+01, + 4.216259e-02, + -2.264187e+05, + 1.783873e+04, + 8.824183e+01, + 4.893415e-01, + -1.027429e+06, + 5.516548e+04, + 3.642565e+02, + 2.717570e+00, + -1.310055e+06, + 9.297558e+04, + 1.199666e+03, + 1.188410e+01, + -2.088964e+06, + 1.472067e+05, + 2.903674e+03, + 3.864073e+01, + -2.404946e+06, + 1.832584e+05, + 5.807015e+03, + 1.028959e+02, + -2.419199e+06, + 1.963782e+05, + 9.802613e+03, + 2.313167e+02, + -2.144173e+06, + 1.846474e+05, + 1.448111e+04, + 4.529782e+02, + -1.755673e+06, + 1.566924e+05, + 1.925615e+04, + 7.929135e+02, + -1.556385e+06, + 1.260006e+05, + 2.357954e+04, + 1.267487e+03, + -9.670740e+05, + 7.884178e+04, + 2.693555e+04, + 1.882001e+03, + -5.837683e+05, + 4.472897e+04, + 2.907526e+04, + 2.623982e+03, + -5.604275e+05, + 2.840427e+04, + 3.020165e+04, + 3.477349e+03, + -3.582842e+05, + 6.067834e+03, + 3.034485e+04, + 4.425576e+03, + -2.245319e+05, + -8.290479e+03, + 2.953728e+04, + 5.439338e+03, + -1.015845e+05, + -1.802273e+04, + 2.804648e+04, + 6.490440e+03, + -4.708202e+04, + -2.097995e+04, + 2.617044e+04, + 7.553762e+03, + -9.140648e+04, + -1.778019e+04, + 2.415851e+04, + 8.612631e+03, + -3.474920e+04, + -2.078888e+04, + 2.200252e+04, + 9.655604e+03, + 2.006550e+04, + -2.169175e+04, + 1.976088e+04, + 1.066217e+04, + -7.457237e+04, + -1.281394e+04, + 1.769310e+04, + 1.162183e+04, + 1.660390e+04, + -1.849862e+04, + 1.562554e+04, + 1.253795e+04, + -1.242914e+03, + -1.387174e+04, + 1.364603e+04, + 1.338579e+04, + -2.136653e+04, + -1.038594e+04, + 1.192412e+04, + 1.417293e+04, + 8.461670e+02, + -1.092230e+04, + 1.029799e+04, + 1.490007e+04, + -1.726136e+04, + -7.648424e+03, + 8.804960e+03, + 1.555802e+04, + -5.951019e+03, + -7.711382e+03, + 7.418584e+03, + 1.615128e+04, + -1.124333e+04, + -5.937896e+03, + 6.131419e+03, + 1.667197e+04, + -7.000456e+03, + -5.382316e+03, + 4.953545e+03, + 1.712215e+04, + -1.739957e+04, + -3.384351e+03, + 3.889292e+03, + 1.749934e+04, + -2.766408e+04, + -1.885413e+03, + 2.872322e+03, + 1.780661e+04, + -2.473009e+04, + -1.511121e+03, + 1.795912e+03, + 1.803592e+04, + -1.893613e+04, + -4.433274e+02, + 7.896820e+02, + 1.817402e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.795339e+03, + 1.024806e+02, + 0, + 0, + -2.505222e+04, + 1.240280e+03, + 1.304988e+00, + 5.749444e-03, + -4.666245e+04, + 4.461716e+03, + 1.801239e+01, + 1.073229e-01, + -2.724635e+05, + 1.761495e+04, + 9.851115e+01, + 7.710643e-01, + -4.861356e+05, + 3.717743e+04, + 4.101052e+02, + 4.193261e+00, + -6.383714e+05, + 6.152061e+04, + 1.168007e+03, + 1.598473e+01, + -1.205391e+06, + 9.889684e+04, + 2.636565e+03, + 4.738883e+01, + -1.147720e+06, + 1.106241e+05, + 5.004828e+03, + 1.183715e+02, + -1.133494e+06, + 1.155726e+05, + 8.024451e+03, + 2.508700e+02, + -1.063750e+06, + 1.090501e+05, + 1.144213e+04, + 4.682622e+02, + -7.206625e+05, + 8.651512e+04, + 1.483243e+04, + 7.896286e+02, + -8.230661e+05, + 7.733914e+04, + 1.788080e+04, + 1.224383e+03, + -3.893929e+05, + 4.348949e+04, + 2.028440e+04, + 1.779031e+03, + -4.194027e+05, + 3.349138e+04, + 2.185878e+04, + 2.439030e+03, + -1.895883e+05, + 1.198418e+04, + 2.268839e+04, + 3.196090e+03, + -2.138071e+05, + 6.670906e+03, + 2.280864e+04, + 4.026859e+03, + -6.125361e+04, + -6.683706e+03, + 2.234923e+04, + 4.916377e+03, + -1.266566e+05, + -5.092214e+03, + 2.146339e+04, + 5.838900e+03, + -3.668092e+04, + -1.292182e+04, + 2.023530e+04, + 6.783060e+03, + -4.502149e+04, + -1.220835e+04, + 1.873724e+04, + 7.722602e+03, + -6.724879e+03, + -1.428205e+04, + 1.712856e+04, + 8.645906e+03, + -3.147242e+04, + -1.120290e+04, + 1.550800e+04, + 9.537867e+03, + 4.822493e+03, + -1.299009e+04, + 1.388952e+04, + 1.039406e+04, + -3.661611e+04, + -8.222351e+03, + 1.234509e+04, + 1.120095e+04, + 7.706524e+02, + -1.086522e+04, + 1.080666e+04, + 1.196049e+04, + -1.428372e+04, + -7.903936e+03, + 9.320418e+03, + 1.265373e+04, + -1.558705e+04, + -6.942237e+03, + 7.944124e+03, + 1.328427e+04, + 3.569541e+03, + -7.689284e+03, + 6.605008e+03, + 1.384543e+04, + -2.207606e+04, + -3.799092e+03, + 5.433831e+03, + 1.433020e+04, + -2.173362e+04, + -3.685308e+03, + 4.312741e+03, + 1.475032e+04, + -1.842206e+04, + -3.390404e+03, + 3.139013e+03, + 1.508986e+04, + -4.332377e+04, + 1.904433e+02, + 2.023367e+03, + 1.533848e+04, + -2.551285e+04, + -6.475346e+01, + 8.159825e+02, + 1.549771e+04, +}; + +double solarDataset520[] = +{ + 3.441260e+12, + 4.257012e+05, + 9.159649e+03, + 2.155997e+02, + -3.813319e+11, + 9.728458e+07, + 1.224196e+04, + 2.157753e+02, + -8.993466e+09, + 5.812620e+06, + 1.906304e+04, + 2.179990e+02, + 2.219112e+09, + -1.465148e+06, + 1.997638e+04, + 2.245501e+02, + -4.029785e+08, + 1.497071e+06, + 2.081556e+04, + 2.372707e+02, + 7.073014e+07, + 4.201511e+05, + 2.262724e+04, + 2.603452e+02, + 1.148052e+08, + 3.113398e+05, + 2.446750e+04, + 2.971461e+02, + -6.975728e+07, + 9.816228e+05, + 2.748132e+04, + 3.534071e+02, + 4.543997e+07, + 3.776559e+05, + 3.142461e+04, + 4.400715e+02, + -1.929005e+07, + 8.214878e+05, + 3.615734e+04, + 5.652811e+02, + -6.188209e+06, + 6.920153e+05, + 4.256955e+04, + 7.501487e+02, + -2.183429e+07, + 7.943841e+05, + 4.986206e+04, + 1.014418e+03, + -1.140788e+07, + 5.966216e+05, + 5.766701e+04, + 1.385850e+03, + -1.246868e+07, + 5.332061e+05, + 6.507698e+04, + 1.885028e+03, + -1.535117e+07, + 4.615705e+05, + 7.180659e+04, + 2.535598e+03, + -6.922309e+06, + 2.072982e+05, + 7.639904e+04, + 3.351496e+03, + -7.654747e+06, + 1.405907e+05, + 7.834404e+04, + 4.319751e+03, + -3.608348e+06, + -1.032324e+04, + 7.774929e+04, + 5.429596e+03, + -3.310273e+06, + -5.122568e+04, + 7.470562e+04, + 6.644330e+03, + -1.803698e+06, + -1.089710e+05, + 6.977953e+04, + 7.932441e+03, + -4.481058e+05, + -1.414144e+05, + 6.339972e+04, + 9.249011e+03, + -8.474652e+05, + -1.138910e+05, + 5.661672e+04, + 1.055570e+04, + 9.091255e+04, + -1.286682e+05, + 4.971740e+04, + 1.183266e+04, + -3.296997e+05, + -9.203473e+04, + 4.316623e+04, + 1.304789e+04, + 6.138098e+04, + -9.130578e+04, + 3.710169e+04, + 1.419808e+04, + 8.019984e+04, + -7.334147e+04, + 3.160993e+04, + 1.526375e+04, + -1.056039e+05, + -5.125085e+04, + 2.694897e+04, + 1.624692e+04, + 3.523169e+04, + -4.850597e+04, + 2.280818e+04, + 1.715304e+04, + 6.870219e+04, + -3.957775e+04, + 1.917548e+04, + 1.797303e+04, + -1.326338e+04, + -2.682913e+04, + 1.621399e+04, + 1.871381e+04, + 1.157345e+03, + -2.265762e+04, + 1.371834e+04, + 1.938801e+04, + 1.114799e+04, + -1.872180e+04, + 1.154622e+04, + 1.999570e+04, + 4.035315e+02, + -1.421776e+04, + 9.712803e+03, + 2.054042e+04, + -8.685193e+01, + -1.141822e+04, + 8.163078e+03, + 2.102864e+04, + 2.765763e+03, + -9.358492e+03, + 6.836780e+03, + 2.146394e+04, + 9.596016e+02, + -7.320212e+03, + 5.716072e+03, + 2.184997e+04, + -3.591287e+03, + -5.538701e+03, + 4.774094e+03, + 2.219169e+04, + 4.877164e+02, + -4.837933e+03, + 3.959721e+03, + 2.249316e+04, + -3.944127e+03, + -3.487922e+03, + 3.263769e+03, + 2.275573e+04, + -8.194186e+03, + -2.533610e+03, + 2.659495e+03, + 2.298365e+04, + 1.810861e+03, + -3.022148e+03, + 2.090564e+03, + 2.317744e+04, + -8.870991e+03, + -1.251568e+03, + 1.616934e+03, + 2.333414e+04, + -1.072378e+04, + -9.168446e+02, + 1.182863e+03, + 2.346196e+04, + -1.120528e+04, + -5.191012e+02, + 7.308553e+02, + 2.355571e+04, + -8.359487e+03, + -1.040853e+02, + 3.073388e+02, + 2.361176e+04, + 2.035431e+12, + 2.901375e+07, + 4.780096e+03, + 9.809298e+01, + -5.474072e+11, + 1.251406e+08, + 7.594803e+03, + 9.819442e+01, + 1.394761e+10, + -7.629265e+06, + 1.388420e+04, + 9.997117e+01, + -1.679680e+09, + 2.117312e+06, + 1.337516e+04, + 1.041901e+02, + 8.766416e+08, + -9.398136e+05, + 1.402618e+04, + 1.131463e+02, + -1.075785e+08, + 9.687180e+05, + 1.495756e+04, + 1.278750e+02, + 2.864970e+07, + 5.123123e+05, + 1.720256e+04, + 1.533065e+02, + 9.381308e+06, + 5.907406e+05, + 1.985760e+04, + 1.937223e+02, + 6.513705e+05, + 6.528921e+05, + 2.353833e+04, + 2.568166e+02, + -5.060574e+06, + 7.148069e+05, + 2.845009e+04, + 3.540337e+02, + -2.618546e+07, + 8.664181e+05, + 3.479716e+04, + 5.020198e+02, + -3.042888e+06, + 6.182842e+05, + 4.212681e+04, + 7.239051e+02, + -2.186162e+07, + 7.922891e+05, + 5.016165e+04, + 1.040177e+03, + -1.315392e+07, + 5.761193e+05, + 5.868562e+04, + 1.485943e+03, + -1.193382e+07, + 4.596976e+05, + 6.604172e+04, + 2.079489e+03, + -1.054882e+07, + 3.262631e+05, + 7.180635e+04, + 2.836858e+03, + -7.325607e+06, + 1.634016e+05, + 7.502793e+04, + 3.759447e+03, + -3.572050e+06, + 1.753149e+04, + 7.527153e+04, + 4.828034e+03, + -3.650321e+06, + -2.059097e+04, + 7.313771e+04, + 6.010651e+03, + -1.306615e+06, + -1.038379e+05, + 6.897657e+04, + 7.278719e+03, + -1.434776e+06, + -1.010734e+05, + 6.337556e+04, + 8.585264e+03, + -2.928626e+05, + -1.291286e+05, + 5.694775e+04, + 9.900359e+03, + -2.016734e+05, + -1.130713e+05, + 5.027089e+04, + 1.118410e+04, + -2.496937e+05, + -9.435927e+04, + 4.393471e+04, + 1.241926e+04, + 2.877942e+04, + -8.902541e+04, + 3.793319e+04, + 1.359137e+04, + -4.486830e+04, + -6.924231e+04, + 3.248876e+04, + 1.468407e+04, + 6.596483e+04, + -6.067637e+04, + 2.767914e+04, + 1.569668e+04, + 1.919128e+03, + -4.535751e+04, + 2.353265e+04, + 1.662511e+04, + -1.625891e+04, + -3.587718e+04, + 1.999336e+04, + 1.747626e+04, + 4.744522e+02, + -2.997748e+04, + 1.689298e+04, + 1.825163e+04, + 4.486151e+04, + -2.618098e+04, + 1.419742e+04, + 1.895127e+04, + -1.216274e+04, + -1.716435e+04, + 1.198976e+04, + 1.957871e+04, + -1.352060e+03, + -1.478644e+04, + 1.013202e+04, + 2.014715e+04, + 1.854542e+04, + -1.309060e+04, + 8.504452e+03, + 2.065628e+04, + -1.365895e+04, + -8.081327e+03, + 7.172319e+03, + 2.110940e+04, + 7.774980e+03, + -8.328556e+03, + 6.022138e+03, + 2.151710e+04, + -1.162068e+04, + -5.117308e+03, + 5.035574e+03, + 2.187637e+04, + 5.375795e+02, + -5.332525e+03, + 4.164918e+03, + 2.219523e+04, + 4.583329e+03, + -4.486221e+03, + 3.397818e+03, + 2.247013e+04, + -1.191642e+04, + -2.061146e+03, + 2.790819e+03, + 2.270630e+04, + -4.488671e+02, + -2.946084e+03, + 2.225430e+03, + 2.291181e+04, + -1.079293e+04, + -1.286923e+03, + 1.715923e+03, + 2.307911e+04, + -7.008889e+03, + -1.462410e+03, + 1.229813e+03, + 2.321411e+04, + -1.789120e+04, + 1.465535e+02, + 7.731271e+02, + 2.331052e+04, + -8.173676e+03, + -1.495901e+02, + 2.878103e+02, + 2.337081e+04, + 1.247757e+12, + -4.159768e+06, + 4.106319e+03, + 2.671606e+01, + -1.699001e+11, + 3.477713e+07, + 5.075193e+03, + 2.679200e+01, + 7.370859e+09, + -4.831578e+06, + 6.046716e+03, + 2.761225e+01, + 1.300189e+09, + -8.314183e+05, + 5.253834e+03, + 2.933335e+01, + -4.200184e+08, + 1.179100e+06, + 5.779982e+03, + 3.268336e+01, + 1.995671e+08, + -6.254952e+04, + 6.866446e+03, + 3.957643e+01, + -6.307859e+07, + 7.234239e+05, + 8.143396e+03, + 5.096381e+01, + 2.152375e+07, + 3.977221e+05, + 1.040391e+04, + 7.159662e+01, + -8.539422e+06, + 6.140945e+05, + 1.326918e+04, + 1.058127e+02, + -1.078821e+07, + 6.779304e+05, + 1.750490e+04, + 1.635930e+02, + -1.275937e+07, + 7.382400e+05, + 2.313246e+04, + 2.590606e+02, + -1.872188e+07, + 8.098821e+05, + 3.031069e+04, + 4.127114e+02, + -1.831776e+07, + 7.681029e+05, + 3.876504e+04, + 6.520684e+02, + -1.327143e+07, + 6.348936e+05, + 4.759282e+04, + 1.005990e+03, + -1.250117e+07, + 5.390875e+05, + 5.602596e+04, + 1.500068e+03, + -1.108426e+07, + 4.074780e+05, + 6.331628e+04, + 2.157158e+03, + -7.144209e+06, + 2.282751e+05, + 6.830848e+04, + 2.985745e+03, + -5.593622e+06, + 1.138962e+05, + 7.048728e+04, + 3.973074e+03, + -2.744275e+06, + -8.550059e+03, + 6.988463e+04, + 5.096047e+03, + -2.060504e+06, + -5.271929e+04, + 6.700169e+04, + 6.315326e+03, + -1.188937e+06, + -8.943405e+04, + 6.253661e+04, + 7.597067e+03, + -7.019956e+05, + -1.025893e+05, + 5.696328e+04, + 8.901951e+03, + -1.520013e+05, + -1.094255e+05, + 5.085384e+04, + 1.019564e+04, + -4.279199e+05, + -8.501426e+04, + 4.481075e+04, + 1.144946e+04, + 2.473795e+05, + -9.671243e+04, + 3.890686e+04, + 1.265006e+04, + -1.850617e+05, + -6.070952e+04, + 3.361721e+04, + 1.377212e+04, + -1.055200e+04, + -5.889414e+04, + 2.890583e+04, + 1.482700e+04, + 8.554444e+04, + -5.153152e+04, + 2.458599e+04, + 1.579867e+04, + -3.284826e+04, + -3.517891e+04, + 2.094752e+04, + 1.668657e+04, + 2.250379e+04, + -3.169404e+04, + 1.781798e+04, + 1.750203e+04, + 7.187402e+02, + -2.410799e+04, + 1.510178e+04, + 1.824183e+04, + -1.312021e+04, + -1.879373e+04, + 1.278706e+04, + 1.891267e+04, + 2.993219e+04, + -1.781145e+04, + 1.075453e+04, + 1.951760e+04, + -4.534421e+03, + -1.160389e+04, + 9.076530e+03, + 2.005681e+04, + -9.759605e+03, + -9.241454e+03, + 7.683732e+03, + 2.054363e+04, + 1.191358e+04, + -9.141714e+03, + 6.435051e+03, + 2.097932e+04, + -8.934994e+03, + -5.555194e+03, + 5.395231e+03, + 2.136320e+04, + -6.609238e+03, + -4.931263e+03, + 4.502483e+03, + 2.170563e+04, + 5.379062e+03, + -5.019351e+03, + 3.680346e+03, + 2.200446e+04, + -1.353400e+04, + -2.242077e+03, + 3.005639e+03, + 2.225951e+04, + 2.319882e+03, + -3.483057e+03, + 2.379456e+03, + 2.248033e+04, + -1.195571e+04, + -1.258098e+03, + 1.838619e+03, + 2.265852e+04, + -8.857921e+03, + -1.424507e+03, + 1.329970e+03, + 2.280386e+04, + -1.138151e+04, + -6.455122e+02, + 8.319621e+02, + 2.290844e+04, + -8.381217e+03, + -2.582078e+02, + 3.786418e+02, + 2.297301e+04, + -6.454234e+12, + 9.523189e+07, + 2.495739e+03, + 3.168572e+00, + 1.564445e+09, + -3.199648e+05, + 2.543842e+01, + 3.206831e+00, + -1.131465e+10, + 7.292156e+06, + 1.655634e+01, + 3.207991e+00, + 4.572081e+08, + -3.622419e+05, + 1.152075e+03, + 3.598120e+00, + -1.359952e+08, + 3.523478e+05, + 1.247960e+03, + 4.304180e+00, + 8.530206e+07, + -7.761152e+04, + 1.537856e+03, + 5.847887e+00, + -4.046656e+06, + 2.350133e+05, + 1.924059e+03, + 8.398513e+00, + -9.369154e+06, + 3.013373e+05, + 2.894860e+03, + 1.369454e+01, + 1.558148e+05, + 3.157345e+05, + 4.412027e+03, + 2.445354e+01, + -9.593296e+06, + 4.737070e+05, + 6.780646e+03, + 4.538315e+01, + -1.399124e+07, + 5.975570e+05, + 1.057839e+04, + 8.641807e+01, + -1.458432e+07, + 6.713753e+05, + 1.603092e+04, + 1.636301e+02, + -1.575957e+07, + 7.190945e+05, + 2.317086e+04, + 3.001042e+02, + -1.469259e+07, + 6.919930e+05, + 3.170783e+04, + 5.261023e+02, + -1.349217e+07, + 6.160599e+05, + 4.083870e+04, + 8.742847e+02, + -1.067177e+07, + 4.778233e+05, + 4.945175e+04, + 1.374014e+03, + -7.035158e+06, + 3.153236e+05, + 5.638367e+04, + 2.041943e+03, + -6.267557e+06, + 2.139302e+05, + 6.107922e+04, + 2.878901e+03, + -3.507150e+06, + 7.645845e+04, + 6.313857e+04, + 3.875261e+03, + -2.677493e+06, + 9.369796e+03, + 6.254822e+04, + 4.997522e+03, + -1.075512e+06, + -6.097170e+04, + 5.980948e+04, + 6.210996e+03, + -7.903147e+05, + -7.423698e+04, + 5.563430e+04, + 7.471213e+03, + -4.489454e+05, + -8.347235e+04, + 5.072914e+04, + 8.748128e+03, + -2.919591e+05, + -8.138940e+04, + 4.543441e+04, + 1.001114e+04, + -1.257206e+05, + -7.734475e+04, + 4.007037e+04, + 1.123568e+04, + 7.103736e+04, + -7.237268e+04, + 3.490447e+04, + 1.240137e+04, + -1.651301e+05, + -4.973913e+04, + 3.027758e+04, + 1.349609e+04, + 2.019954e+05, + -5.792714e+04, + 2.601103e+04, + 1.452225e+04, + -2.203643e+05, + -2.570562e+04, + 2.240670e+04, + 1.546308e+04, + 1.590559e+05, + -4.244143e+04, + 1.908034e+04, + 1.634265e+04, + -4.466576e+04, + -2.108640e+04, + 1.622655e+04, + 1.712995e+04, + -3.174091e+03, + -2.048205e+04, + 1.388742e+04, + 1.785684e+04, + 2.790637e+04, + -1.838833e+04, + 1.176019e+04, + 1.851513e+04, + -2.641650e+04, + -1.106596e+04, + 1.000103e+04, + 1.910723e+04, + 1.001047e+04, + -1.197742e+04, + 8.449539e+03, + 1.964524e+04, + -6.360157e+03, + -8.288998e+03, + 7.088763e+03, + 2.012232e+04, + 9.035106e+03, + -7.929982e+03, + 5.927220e+03, + 2.054736e+04, + -1.377516e+04, + -4.429300e+03, + 4.963148e+03, + 2.092106e+04, + -1.844206e+03, + -4.907418e+03, + 4.100319e+03, + 2.125328e+04, + -1.021359e+03, + -3.955754e+03, + 3.315436e+03, + 2.153793e+04, + -1.171826e+04, + -2.188327e+03, + 2.657105e+03, + 2.177916e+04, + -3.402617e+03, + -2.688462e+03, + 2.032883e+03, + 2.198166e+04, + -1.058462e+04, + -1.288381e+03, + 1.472992e+03, + 2.213899e+04, + -1.978474e+04, + 9.938386e+00, + 9.552157e+02, + 2.225671e+04, + -1.234013e+04, + -2.436993e+00, + 3.887609e+02, + 2.233175e+04, + 0, + 0, + 0, + 1.826016e-01, + -1.781927e+10, + 3.424198e+06, + 0, + 1.826016e-01, + 3.387426e+08, + -1.818905e+05, + 4.801526e+01, + 2.011516e-01, + -1.332156e+08, + 1.980034e+05, + 3.787939e+01, + 2.092672e-01, + 7.713524e+06, + 2.074307e+04, + 1.278808e+02, + 2.794094e-01, + -1.191841e+07, + 6.762032e+04, + 1.970895e+02, + 4.457797e-01, + 1.168172e+07, + 9.597587e+03, + 3.212529e+02, + 8.753281e-01, + -7.375921e+06, + 1.272459e+05, + 5.312329e+02, + 1.747178e+00, + -1.857624e+06, + 1.420437e+05, + 1.084825e+03, + 4.192300e+00, + -4.445982e+06, + 2.336181e+05, + 2.069508e+03, + 1.014047e+01, + -9.256611e+06, + 3.691046e+05, + 3.961112e+03, + 2.445296e+01, + -1.146668e+07, + 4.853842e+05, + 7.269072e+03, + 5.735080e+01, + -1.079778e+07, + 5.581243e+05, + 1.230141e+04, + 1.261528e+02, + -1.490989e+07, + 6.582014e+05, + 1.920854e+04, + 2.563772e+02, + -1.194617e+07, + 5.952954e+05, + 2.764421e+04, + 4.835162e+02, + -1.014583e+07, + 5.122274e+05, + 3.635427e+04, + 8.392605e+02, + -7.408351e+06, + 3.853587e+05, + 4.438509e+04, + 1.350733e+03, + -6.570506e+06, + 2.855657e+05, + 5.083123e+04, + 2.031559e+03, + -3.758086e+06, + 1.418179e+05, + 5.493214e+04, + 2.882348e+03, + -2.683018e+06, + 6.098002e+04, + 5.642001e+04, + 3.878421e+03, + -1.659085e+06, + -4.330207e+03, + 5.570503e+04, + 4.991285e+03, + -7.795872e+05, + -4.882689e+04, + 5.316507e+04, + 6.183054e+03, + -5.845028e+05, + -5.942304e+04, + 4.949336e+04, + 7.415604e+03, + -5.798157e+05, + -6.026377e+04, + 4.517923e+04, + 8.660316e+03, + 1.100702e+05, + -8.130453e+04, + 4.031747e+04, + 9.888095e+03, + -6.137872e+04, + -6.032203e+04, + 3.558748e+04, + 1.106470e+04, + -1.487668e+05, + -4.829607e+04, + 3.132184e+04, + 1.219098e+04, + 6.027672e+04, + -5.086659e+04, + 2.722487e+04, + 1.325775e+04, + -5.216647e+04, + -3.589720e+04, + 2.352245e+04, + 1.424838e+04, + 3.877460e+04, + -3.464697e+04, + 2.023029e+04, + 1.516931e+04, + 2.888551e+03, + -2.575328e+04, + 1.734715e+04, + 1.601318e+04, + -2.191980e+04, + -1.979610e+04, + 1.488919e+04, + 1.678848e+04, + 2.034645e+04, + -1.902784e+04, + 1.268427e+04, + 1.749745e+04, + -1.314803e+04, + -1.300850e+04, + 1.078756e+04, + 1.813689e+04, + 7.781400e+03, + -1.225965e+04, + 9.144667e+03, + 1.871660e+04, + -1.204517e+04, + -8.419968e+03, + 7.723806e+03, + 1.923488e+04, + 7.765000e+03, + -8.536896e+03, + 6.472742e+03, + 1.969918e+04, + -4.584280e+03, + -5.708889e+03, + 5.406950e+03, + 2.010716e+04, + -7.904211e+03, + -4.491134e+03, + 4.503836e+03, + 2.046843e+04, + -5.550058e+03, + -3.997071e+03, + 3.675945e+03, + 2.078373e+04, + -5.689591e+03, + -3.236437e+03, + 2.922488e+03, + 2.105140e+04, + -7.906009e+03, + -2.378643e+03, + 2.250590e+03, + 2.127255e+04, + -9.071692e+03, + -1.745359e+03, + 1.638712e+03, + 2.144855e+04, + -2.806270e+04, + 6.649150e+02, + 1.075166e+03, + 2.157900e+04, + -1.103646e+04, + -2.530936e+02, + 3.990825e+02, + 2.166428e+04, + 1.172160e+12, + -1.700048e+07, + -4.587932e+02, + 9.275000e-03, + -5.008907e+09, + 9.229085e+05, + 0, + 2.318750e-03, + 3.111030e+07, + -1.680365e+04, + 3.936294e+00, + 6.956250e-03, + -5.703770e+07, + 5.741850e+04, + 2.940735e+00, + 7.535938e-03, + 4.750408e+06, + -7.579855e+03, + 6.576946e+00, + 1.797031e-02, + -4.550239e+06, + 1.931719e+04, + 6.393513e+00, + 2.202812e-02, + 1.542980e+06, + 4.706168e+03, + 3.340755e+01, + 6.202656e-02, + -1.997114e+06, + 3.649206e+04, + 7.619777e+01, + 1.739063e-01, + -1.593482e+06, + 6.356589e+04, + 2.379679e+02, + 6.562062e-01, + -4.537893e+06, + 1.384804e+05, + 6.466292e+02, + 2.352372e+00, + -5.704782e+06, + 2.258349e+05, + 1.643354e+03, + 7.932444e+00, + -8.516026e+06, + 3.526078e+05, + 3.663294e+03, + 2.360140e+01, + -1.066595e+07, + 4.742071e+05, + 7.292901e+03, + 6.245495e+01, + -1.234505e+07, + 5.621427e+05, + 1.286902e+04, + 1.467728e+02, + -1.044587e+07, + 5.508898e+05, + 2.017730e+04, + 3.077457e+02, + -9.750714e+06, + 5.176087e+05, + 2.845385e+04, + 5.789490e+02, + -8.773548e+06, + 4.361175e+05, + 3.680154e+04, + 9.938209e+02, + -4.887482e+06, + 2.768423e+05, + 4.386506e+04, + 1.574100e+03, + -4.580514e+06, + 2.042767e+05, + 4.895668e+04, + 2.319036e+03, + -3.037548e+06, + 1.001684e+05, + 5.188273e+04, + 3.224335e+03, + -1.252849e+06, + 9.423824e+03, + 5.229785e+04, + 4.260421e+03, + -1.512708e+06, + -4.514040e+03, + 5.093166e+04, + 5.388799e+03, + -3.330454e+05, + -5.840272e+04, + 4.812166e+04, + 6.583262e+03, + -4.555910e+05, + -5.259927e+04, + 4.437818e+04, + 7.797270e+03, + -2.055898e+05, + -6.043330e+04, + 4.025830e+04, + 9.011318e+03, + -6.518244e+04, + -5.931446e+04, + 3.591151e+04, + 1.019675e+04, + -4.788129e+04, + -5.148756e+04, + 3.170073e+04, + 1.133492e+04, + -1.294721e+04, + -4.516239e+04, + 2.777118e+04, + 1.241608e+04, + -4.132531e+04, + -3.650926e+04, + 2.417892e+04, + 1.343242e+04, + 4.353457e+04, + -3.480201e+04, + 2.089273e+04, + 1.438065e+04, + -3.999510e+04, + -2.363060e+04, + 1.802457e+04, + 1.525446e+04, + 1.132551e+04, + -2.302607e+04, + 1.547307e+04, + 1.606249e+04, + 2.024966e+04, + -1.900290e+04, + 1.319929e+04, + 1.679741e+04, + -2.275982e+04, + -1.253345e+04, + 1.130444e+04, + 1.746504e+04, + 2.065540e+03, + -1.244152e+04, + 9.619555e+03, + 1.807448e+04, + 1.308942e+04, + -1.073860e+04, + 8.111327e+03, + 1.861996e+04, + -1.540943e+04, + -6.359948e+03, + 6.878335e+03, + 1.910663e+04, + -6.509802e+03, + -6.323129e+03, + 5.782487e+03, + 1.954531e+04, + 2.137483e+03, + -5.897918e+03, + 4.759477e+03, + 1.992990e+04, + -1.089014e+04, + -3.529000e+03, + 3.892929e+03, + 2.026106e+04, + -7.464418e+03, + -3.372208e+03, + 3.110704e+03, + 2.054648e+04, + -4.499778e+03, + -2.965848e+03, + 2.377458e+03, + 2.078153e+04, + -1.809100e+04, + -9.389300e+02, + 1.742044e+03, + 2.096658e+04, + -1.603605e+04, + -8.315728e+02, + 1.093057e+03, + 2.110637e+04, + -1.205302e+04, + -2.096724e+02, + 4.696001e+02, + 2.119034e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -6.475609e+04, + 3.371635e+02, + 0, + 0, + 1.073009e+04, + 4.374122e+02, + 5.797537e-01, + 5.796875e-04, + -1.153454e+05, + 2.841920e+03, + 2.649198e+00, + 4.057812e-03, + -4.687182e+05, + 1.144817e+04, + 1.627061e+01, + 3.304219e-02, + -6.252477e+05, + 3.031476e+04, + 8.224170e+01, + 2.295562e-01, + -3.526268e+06, + 9.906712e+04, + 3.245361e+02, + 1.211547e+00, + -3.609003e+06, + 1.630030e+05, + 1.110639e+03, + 5.633403e+00, + -5.915653e+06, + 2.810662e+05, + 2.834579e+03, + 1.971111e+01, + -9.862311e+06, + 4.241441e+05, + 6.219224e+03, + 5.787194e+01, + -8.614873e+06, + 4.527786e+05, + 1.158730e+04, + 1.459555e+02, + -7.889704e+06, + 4.557367e+05, + 1.837941e+04, + 3.144735e+02, + -7.157548e+06, + 4.205437e+05, + 2.605154e+04, + 5.981511e+02, + -6.360659e+06, + 3.497342e+05, + 3.363796e+04, + 1.028460e+03, + -4.118223e+06, + 2.292622e+05, + 3.992991e+04, + 1.623818e+03, + -2.878278e+06, + 1.400867e+05, + 4.417527e+04, + 2.379710e+03, + -1.927495e+06, + 6.762589e+04, + 4.634548e+04, + 3.280857e+03, + -1.164354e+06, + 1.289313e+04, + 4.655326e+04, + 4.300420e+03, + -7.359802e+05, + -1.922557e+04, + 4.517303e+04, + 5.404912e+03, + -4.551779e+05, + -3.785206e+04, + 4.265242e+04, + 6.561340e+03, + -2.858538e+05, + -4.634143e+04, + 3.937600e+04, + 7.738135e+03, + -3.103799e+04, + -5.354515e+04, + 3.567211e+04, + 8.907358e+03, + -1.299037e+05, + -4.253021e+04, + 3.196524e+04, + 1.004530e+04, + -2.685978e+04, + -4.253756e+04, + 2.836175e+04, + 1.114396e+04, + -1.368389e+04, + -3.669976e+04, + 2.491097e+04, + 1.218658e+04, + -2.352848e+04, + -3.043266e+04, + 2.175512e+04, + 1.316727e+04, + -1.339091e+03, + -2.684603e+04, + 1.887271e+04, + 1.408263e+04, + 1.046307e+04, + -2.278972e+04, + 1.628025e+04, + 1.492832e+04, + 9.352423e+03, + -1.845807e+04, + 1.402391e+04, + 1.570518e+04, + -4.319180e+04, + -1.193961e+04, + 1.209103e+04, + 1.641770e+04, + 4.028668e+04, + -1.613776e+04, + 1.026860e+04, + 1.707080e+04, + -3.050514e+04, + -7.295972e+03, + 8.739795e+03, + 1.765114e+04, + 8.928799e+03, + -9.664089e+03, + 7.399996e+03, + 1.818133e+04, + -7.753111e+03, + -6.276519e+03, + 6.195452e+03, + 1.864823e+04, + -6.909366e+03, + -5.375705e+03, + 5.159494e+03, + 1.906262e+04, + -3.726578e+03, + -4.729953e+03, + 4.213524e+03, + 1.942343e+04, + -9.907304e+03, + -3.262236e+03, + 3.377412e+03, + 1.973067e+04, + -4.707397e+03, + -3.194871e+03, + 2.610089e+03, + 1.998764e+04, + -2.459705e+04, + -5.431231e+02, + 1.928936e+03, + 2.019144e+04, + -1.504684e+04, + -1.268530e+03, + 1.183585e+03, + 2.034684e+04, + -1.274940e+04, + -2.357602e+02, + 5.030266e+02, + 2.043642e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.625111e+03, + 1.942406e+02, + 0, + 0, + -7.931768e+04, + 2.359336e+03, + 1.133080e+00, + 2.318750e-03, + -4.492099e+05, + 1.342479e+04, + 1.798340e+01, + 5.101250e-02, + -7.104236e+05, + 3.641425e+04, + 1.273072e+02, + 5.072266e-01, + -2.419312e+06, + 1.031931e+05, + 5.258904e+02, + 2.856120e+00, + -3.805147e+06, + 1.873084e+05, + 1.720050e+03, + 1.257400e+01, + -5.317208e+06, + 2.798090e+05, + 4.237425e+03, + 4.225574e+01, + -5.851424e+06, + 3.374836e+05, + 8.437182e+03, + 1.146083e+02, + -5.507526e+06, + 3.474492e+05, + 1.411444e+04, + 2.603661e+02, + -4.895399e+06, + 3.204240e+05, + 2.062382e+04, + 5.126727e+02, + -3.869675e+06, + 2.596800e+05, + 2.709028e+04, + 9.003364e+02, + -3.250395e+06, + 1.961919e+05, + 3.264631e+04, + 1.439837e+03, + -1.719326e+06, + 1.064571e+05, + 3.659167e+04, + 2.133101e+03, + -1.508329e+06, + 6.693764e+04, + 3.878265e+04, + 2.961132e+03, + -7.388517e+05, + 1.449523e+04, + 3.939682e+04, + 3.906030e+03, + -7.540220e+05, + -5.614775e+02, + 3.863621e+04, + 4.934280e+03, + -7.321527e+04, + -3.634823e+04, + 3.675864e+04, + 6.019820e+03, + -3.975025e+05, + -2.269491e+04, + 3.429005e+04, + 7.123780e+03, + 3.467499e+04, + -4.367236e+04, + 3.141477e+04, + 8.236199e+03, + -1.266303e+05, + -3.044243e+04, + 2.837963e+04, + 9.321237e+03, + -4.572541e+04, + -3.225554e+04, + 2.541711e+04, + 1.037709e+04, + 8.047126e+03, + -3.069461e+04, + 2.246501e+04, + 1.138452e+04, + 2.719321e+02, + -2.520116e+04, + 1.975091e+04, + 1.233417e+04, + -3.455116e+04, + -1.935606e+04, + 1.732791e+04, + 1.322610e+04, + -4.689464e+03, + -1.871996e+04, + 1.506835e+04, + 1.405968e+04, + 1.058268e+04, + -1.648905e+04, + 1.298115e+04, + 1.482619e+04, + -7.793109e+03, + -1.216890e+04, + 1.117406e+04, + 1.552613e+04, + -1.325167e+04, + -9.935753e+03, + 9.587327e+03, + 1.616604e+04, + 5.085932e+03, + -9.803685e+03, + 8.123301e+03, + 1.674503e+04, + -3.985046e+03, + -7.120467e+03, + 6.844793e+03, + 1.725984e+04, + -1.845867e+04, + -4.797864e+03, + 5.745869e+03, + 1.771845e+04, + 5.144229e+03, + -6.303880e+03, + 4.684891e+03, + 1.812240e+04, + -1.572588e+04, + -2.947990e+03, + 3.768049e+03, + 1.846208e+04, + -1.031994e+04, + -3.174327e+03, + 2.928434e+03, + 1.875090e+04, + -1.099561e+04, + -2.380398e+03, + 2.117366e+03, + 1.897926e+04, + -3.437355e+04, + 6.816807e+02, + 1.384817e+03, + 1.914731e+04, + -1.532091e+04, + -2.375851e+02, + 5.307093e+02, + 1.925714e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.099496e+03, + 3.170007e+01, + 0, + 0, + -4.582160e+03, + 2.717530e+02, + 2.241895e-01, + 5.796875e-04, + -3.585634e+04, + 2.139538e+03, + 2.877762e+00, + 9.854688e-03, + -2.609433e+05, + 1.233333e+04, + 2.712355e+01, + 1.182562e-01, + -6.784321e+05, + 3.792404e+04, + 1.753766e+02, + 1.005758e+00, + -1.704870e+06, + 9.086509e+04, + 7.096012e+02, + 5.462395e+00, + -2.182629e+06, + 1.428588e+05, + 2.081180e+03, + 2.173712e+01, + -3.045174e+06, + 2.017171e+05, + 4.620780e+03, + 6.547976e+01, + -3.120058e+06, + 2.258261e+05, + 8.490531e+03, + 1.620580e+02, + -2.909976e+06, + 2.219603e+05, + 1.329642e+04, + 3.408296e+02, + -2.611518e+06, + 1.958497e+05, + 1.841926e+04, + 6.296374e+02, + -1.382570e+06, + 1.339214e+05, + 2.309259e+04, + 1.047807e+03, + -1.998218e+06, + 1.265819e+05, + 2.695490e+04, + 1.598845e+03, + -5.702259e+05, + 4.570461e+04, + 2.958101e+04, + 2.288355e+03, + -8.368829e+05, + 3.927422e+04, + 3.080162e+04, + 3.084010e+03, + -1.837335e+05, + -2.241597e+03, + 3.099690e+04, + 3.976339e+03, + -5.682648e+05, + 6.527088e+03, + 3.032646e+04, + 4.930989e+03, + 5.233127e+04, + -2.991358e+04, + 2.883729e+04, + 5.936664e+03, + -1.539996e+05, + -1.717267e+04, + 2.687146e+04, + 6.947084e+03, + -8.235537e+04, + -2.202557e+04, + 2.482136e+04, + 7.962612e+03, + -7.507519e+04, + -2.154411e+04, + 2.253483e+04, + 8.960347e+03, + 3.590736e+04, + -2.572879e+04, + 2.013928e+04, + 9.924107e+03, + -6.467983e+03, + -1.870191e+04, + 1.791295e+04, + 1.083747e+04, + -6.478698e+04, + -1.295785e+04, + 1.594240e+04, + 1.170658e+04, + 2.068703e+04, + -1.780974e+04, + 1.394673e+04, + 1.252823e+04, + 1.440187e+03, + -1.297839e+04, + 1.208844e+04, + 1.328175e+04, + -2.660685e+04, + -8.967767e+03, + 1.050701e+04, + 1.397703e+04, + 7.110755e+03, + -1.063004e+04, + 8.998969e+03, + 1.461637e+04, + -5.590234e+03, + -7.510638e+03, + 7.635425e+03, + 1.518826e+04, + -2.267292e+04, + -5.019825e+03, + 6.454280e+03, + 1.570168e+04, + 7.270321e+03, + -7.162343e+03, + 5.284981e+03, + 1.615674e+04, + -1.519724e+04, + -3.427299e+03, + 4.271128e+03, + 1.654037e+04, + -1.855140e+04, + -2.800418e+03, + 3.361608e+03, + 1.686874e+04, + -6.231274e+03, + -3.489017e+03, + 2.421245e+03, + 1.713283e+04, + -4.271753e+04, + 1.261302e+03, + 1.606297e+03, + 1.732348e+04, + -1.812555e+04, + -2.715809e+02, + 6.259157e+02, + 1.745271e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.063987e+03, + 3.054462e+02, + 0, + 0, + -2.813574e+04, + 1.877042e+03, + 3.553681e+00, + 1.623125e-02, + -1.257337e+05, + 8.447415e+03, + 3.144681e+01, + 1.930359e-01, + -3.207497e+05, + 2.447929e+04, + 1.705861e+02, + 1.372700e+00, + -8.991627e+05, + 5.794734e+04, + 6.304306e+02, + 6.658291e+00, + -8.788635e+05, + 7.984047e+04, + 1.727592e+03, + 2.451846e+01, + -1.340991e+06, + 1.142918e+05, + 3.595521e+03, + 6.842863e+01, + -1.502817e+06, + 1.295800e+05, + 6.381372e+03, + 1.604604e+02, + -1.121162e+06, + 1.171558e+05, + 9.734555e+03, + 3.246644e+02, + -1.189577e+06, + 1.116388e+05, + 1.323854e+04, + 5.801037e+02, + -7.285780e+05, + 8.048449e+04, + 1.653685e+04, + 9.441805e+02, + -7.755311e+05, + 6.738083e+04, + 1.925313e+04, + 1.419287e+03, + -3.489333e+05, + 3.413203e+04, + 2.120419e+04, + 2.006116e+03, + -3.711578e+05, + 2.473199e+04, + 2.231455e+04, + 2.686863e+03, + -1.949665e+05, + 6.860180e+03, + 2.271868e+04, + 3.451178e+03, + -2.043607e+05, + 1.205191e+03, + 2.244544e+04, + 4.276031e+03, + -2.253753e+04, + -1.242250e+04, + 2.160182e+04, + 5.143546e+03, + -1.162624e+05, + -7.671662e+03, + 2.043880e+04, + 6.027415e+03, + -1.819840e+04, + -1.508886e+04, + 1.904169e+04, + 6.921183e+03, + -3.748045e+04, + -1.282426e+04, + 1.746345e+04, + 7.800341e+03, + -2.463956e+04, + -1.307192e+04, + 1.585114e+04, + 8.657676e+03, + 1.800068e+04, + -1.453209e+04, + 1.420241e+04, + 9.480546e+03, + -5.751030e+04, + -7.191141e+03, + 1.269744e+04, + 1.025942e+04, + 2.143863e+04, + -1.325078e+04, + 1.115837e+04, + 1.100036e+04, + -2.937991e+04, + -6.800654e+03, + 9.704313e+03, + 1.167727e+04, + 6.744357e+03, + -9.354022e+03, + 8.348776e+03, + 1.230400e+04, + -1.635229e+04, + -5.637506e+03, + 7.095223e+03, + 1.286429e+04, + -9.355270e+03, + -5.739525e+03, + 5.942650e+03, + 1.336770e+04, + -1.379714e+04, + -4.465673e+03, + 4.833668e+03, + 1.380493e+04, + -1.440112e+04, + -3.753966e+03, + 3.778207e+03, + 1.417440e+04, + -1.584389e+04, + -2.861359e+03, + 2.766756e+03, + 1.447096e+04, + -4.596605e+04, + 9.777166e+02, + 1.817438e+03, + 1.469152e+04, + -1.955254e+04, + -3.565949e+02, + 6.882263e+02, + 1.483566e+04, +}; + +double solarDataset560[] = +{ + 9.427478e+12, + -2.974054e+07, + 3.050751e+04, + 6.870437e+02, + -1.142007e+12, + 2.473531e+08, + 3.788610e+04, + 6.876090e+02, + 6.030303e+10, + -3.189085e+07, + 4.769687e+04, + 6.937756e+02, + -1.001912e+10, + 1.190166e+07, + 4.621301e+04, + 7.080949e+02, + 2.017518e+09, + -2.733973e+06, + 4.916779e+04, + 7.398116e+02, + -1.421427e+08, + 1.460792e+06, + 5.011031e+04, + 7.908346e+02, + -1.387029e+07, + 8.966726e+05, + 5.364395e+04, + 8.724855e+02, + 9.871561e+06, + 7.113724e+05, + 5.737052e+04, + 9.940749e+02, + 1.877554e+07, + 6.336258e+05, + 6.176658e+04, + 1.167487e+03, + -3.308155e+07, + 8.873357e+05, + 6.729500e+04, + 1.408380e+03, + -9.604436e+06, + 6.024616e+05, + 7.341952e+04, + 1.738737e+03, + -2.182764e+07, + 6.203282e+05, + 7.935645e+04, + 2.175477e+03, + -1.396323e+07, + 4.168430e+05, + 8.478006e+04, + 2.740602e+03, + -1.869470e+07, + 3.550893e+05, + 8.878213e+04, + 3.445876e+03, + -8.924426e+06, + 9.938325e+04, + 9.049216e+04, + 4.298909e+03, + -6.077214e+06, + -9.169328e+03, + 8.948659e+04, + 5.283471e+03, + -9.030289e+06, + -1.361099e+04, + 8.644249e+04, + 6.382569e+03, + -6.018017e+05, + -2.166279e+05, + 8.068593e+04, + 7.572041e+03, + -2.261151e+06, + -1.582668e+05, + 7.336941e+04, + 8.793475e+03, + -1.285988e+06, + -1.711686e+05, + 6.563977e+04, + 1.003020e+04, + -3.781520e+05, + -1.714659e+05, + 5.741413e+04, + 1.124523e+04, + 6.312955e+04, + -1.524940e+05, + 4.942384e+04, + 1.240834e+04, + -2.965801e+05, + -1.122897e+05, + 4.224018e+04, + 1.350369e+04, + 3.140122e+04, + -1.022589e+05, + 3.574972e+04, + 1.452741e+04, + 6.861713e+04, + -8.171721e+04, + 2.998492e+04, + 1.546584e+04, + 8.598786e+04, + -6.438726e+04, + 2.510945e+04, + 1.632002e+04, + -5.450437e+04, + -4.482419e+04, + 2.107040e+04, + 1.709492e+04, + 3.899927e+04, + -4.009451e+04, + 1.759867e+04, + 1.779846e+04, + 3.081603e+04, + -3.072117e+04, + 1.464125e+04, + 1.842779e+04, + 2.777883e+04, + -2.372218e+04, + 1.222329e+04, + 1.899091e+04, + -2.403858e+04, + -1.592528e+04, + 1.025673e+04, + 1.949554e+04, + 2.604334e+04, + -1.580705e+04, + 8.557456e+03, + 1.994946e+04, + -6.779180e+03, + -1.020950e+04, + 7.140866e+03, + 2.035049e+04, + 1.072751e+04, + -9.367305e+03, + 5.964755e+03, + 2.070901e+04, + -7.568154e+03, + -6.091544e+03, + 4.985814e+03, + 2.102574e+04, + 7.747026e+03, + -6.090631e+03, + 4.149838e+03, + 2.130780e+04, + -5.115560e+03, + -3.749778e+03, + 3.454636e+03, + 2.155454e+04, + 2.055488e+03, + -3.682627e+03, + 2.865067e+03, + 2.177309e+04, + -8.313760e+03, + -2.062212e+03, + 2.362034e+03, + 2.196277e+04, + 2.244934e+03, + -2.716908e+03, + 1.899309e+03, + 2.212797e+04, + -8.606358e+03, + -1.085119e+03, + 1.504703e+03, + 2.226472e+04, + 7.692302e+02, + -1.849182e+03, + 1.134821e+03, + 2.237930e+04, + -4.992822e+03, + -7.414604e+02, + 8.237234e+02, + 2.246625e+04, + -2.212781e+04, + 1.130582e+03, + 5.545028e+02, + 2.253265e+04, + -2.342747e+03, + -3.239579e+02, + 1.400637e+02, + 2.257701e+04, + -5.454661e+13, + 6.695227e+08, + 7.553013e+04, + 3.151823e+02, + 1.134950e+12, + -2.733669e+08, + 4.998801e+04, + 3.164039e+02, + 2.457067e+09, + -5.372394e+05, + 3.359107e+04, + 3.204494e+02, + 1.705050e+09, + -3.885735e+05, + 3.402986e+04, + 3.314798e+02, + -4.762097e+08, + 1.872482e+06, + 3.561497e+04, + 3.534683e+02, + 2.502076e+08, + 3.098756e+05, + 3.797324e+04, + 3.924344e+02, + 9.657814e+05, + 9.594652e+05, + 4.079242e+04, + 4.537291e+02, + 2.387841e+07, + 8.134300e+05, + 4.500723e+04, + 5.476404e+02, + -3.806754e+07, + 1.053126e+06, + 5.035453e+04, + 6.862488e+02, + 1.459099e+06, + 7.335645e+05, + 5.663526e+04, + 8.873484e+02, + -2.588512e+07, + 8.852511e+05, + 6.358440e+04, + 1.168074e+03, + -2.562254e+07, + 7.542671e+05, + 7.115830e+04, + 1.554880e+03, + -1.380731e+07, + 5.011328e+05, + 7.788194e+04, + 2.068958e+03, + -1.739894e+07, + 4.295264e+05, + 8.327746e+04, + 2.724056e+03, + -1.402960e+07, + 2.469259e+05, + 8.673685e+04, + 3.532888e+03, + -5.683137e+06, + 1.809832e+04, + 8.712896e+04, + 4.487490e+03, + -7.386279e+06, + -5.267831e+03, + 8.494526e+04, + 5.562255e+03, + -2.550597e+06, + -1.428422e+05, + 8.040191e+04, + 6.736888e+03, + -2.244178e+06, + -1.494782e+05, + 7.395598e+04, + 7.964592e+03, + -9.741098e+05, + -1.707178e+05, + 6.655347e+04, + 9.214554e+03, + -7.847748e+05, + -1.541107e+05, + 5.870751e+04, + 1.045010e+04, + 4.829605e+04, + -1.529932e+05, + 5.089533e+04, + 1.164534e+04, + -2.588837e+05, + -1.146882e+05, + 4.366237e+04, + 1.277539e+04, + 8.471593e+04, + -1.046703e+05, + 3.712384e+04, + 1.383538e+04, + -3.204309e+04, + -7.873300e+04, + 3.135177e+04, + 1.481233e+04, + 3.884792e+04, + -6.547482e+04, + 2.637054e+04, + 1.570881e+04, + 3.311172e+04, + -5.122588e+04, + 2.209839e+04, + 1.652310e+04, + 5.272904e+04, + -4.098012e+04, + 1.850837e+04, + 1.725973e+04, + -2.098666e+04, + -2.870596e+04, + 1.554469e+04, + 1.792411e+04, + -7.645698e+03, + -2.392850e+04, + 1.302179e+04, + 1.852490e+04, + 4.529440e+04, + -2.168625e+04, + 1.082138e+04, + 1.906182e+04, + 7.563854e+03, + -1.438042e+04, + 9.049216e+03, + 1.953729e+04, + -2.029968e+04, + -9.904209e+03, + 7.633053e+03, + 1.996482e+04, + 2.455605e+04, + -1.104624e+04, + 6.369259e+03, + 2.034892e+04, + -2.217501e+04, + -5.312960e+03, + 5.335176e+03, + 2.068618e+04, + 1.389523e+04, + -7.222185e+03, + 4.429009e+03, + 2.098929e+04, + 3.350305e+03, + -4.596824e+03, + 3.664659e+03, + 2.125113e+04, + -1.643678e+04, + -2.165698e+03, + 3.078933e+03, + 2.148290e+04, + 8.244762e+03, + -4.103965e+03, + 2.503118e+03, + 2.168904e+04, + -4.309852e+03, + -1.906462e+03, + 2.019271e+03, + 2.186052e+04, + -4.502906e+03, + -1.615093e+03, + 1.627422e+03, + 2.200877e+04, + -6.673494e+03, + -1.145054e+03, + 1.256210e+03, + 2.213245e+04, + -4.431929e+03, + -1.125020e+03, + 8.934107e+02, + 2.223054e+04, + -1.277831e+04, + 1.017818e+02, + 5.672148e+02, + 2.230057e+04, + -6.550689e+03, + -6.795150e+01, + 2.200245e+02, + 2.234508e+04, + 7.028093e+11, + -5.632931e+06, + 1.212518e+04, + 8.786962e+01, + 1.096934e+10, + 3.427657e+06, + 1.255748e+04, + 8.808056e+01, + -8.620693e+09, + 6.311300e+06, + 1.386382e+04, + 8.966498e+01, + 1.905895e+09, + -7.785063e+05, + 1.522377e+04, + 9.457978e+01, + -6.642623e+08, + 2.069152e+06, + 1.655659e+04, + 1.044673e+02, + 2.755384e+08, + 1.270856e+05, + 1.870469e+04, + 1.233922e+02, + -1.858521e+07, + 9.802503e+05, + 2.113739e+04, + 1.541094e+02, + 1.127113e+07, + 8.555788e+05, + 2.516211e+04, + 2.048864e+02, + -2.155426e+07, + 1.035915e+06, + 3.043400e+04, + 2.857281e+02, + -2.670990e+07, + 1.046843e+06, + 3.727913e+04, + 4.129363e+02, + -2.064658e+07, + 9.583745e+05, + 4.531105e+04, + 6.072056e+02, + -2.771027e+07, + 9.488663e+05, + 5.423102e+04, + 8.931027e+02, + -2.275812e+07, + 7.675189e+05, + 6.332478e+04, + 1.299785e+03, + -1.807120e+07, + 5.679364e+05, + 7.127246e+04, + 1.849876e+03, + -1.307118e+07, + 3.611235e+05, + 7.716269e+04, + 2.557254e+03, + -1.108885e+07, + 2.095800e+05, + 8.037925e+04, + 3.422462e+03, + -4.138438e+06, + -1.246738e+03, + 8.045019e+04, + 4.432538e+03, + -5.721080e+06, + -1.375766e+04, + 7.795263e+04, + 5.553735e+03, + -1.846673e+06, + -1.340584e+05, + 7.320954e+04, + 6.762429e+03, + -7.381453e+05, + -1.533237e+05, + 6.672674e+04, + 8.006215e+03, + -1.220612e+06, + -1.255252e+05, + 5.983885e+04, + 9.253691e+03, + -4.493834e+05, + -1.350154e+05, + 5.265160e+04, + 1.048256e+04, + 2.241188e+05, + -1.320572e+05, + 4.542483e+04, + 1.165807e+04, + -1.586451e+05, + -9.300775e+04, + 3.897017e+04, + 1.276097e+04, + -8.185331e+04, + -7.944104e+04, + 3.326870e+04, + 1.379450e+04, + 1.437491e+05, + -7.221282e+04, + 2.809949e+04, + 1.474832e+04, + -8.452171e+04, + -4.730130e+04, + 2.373007e+04, + 1.561713e+04, + 7.065088e+04, + -4.526031e+04, + 1.995960e+04, + 1.641256e+04, + -1.228967e+04, + -3.137736e+04, + 1.674335e+04, + 1.712822e+04, + 8.313530e+04, + -2.961873e+04, + 1.404205e+04, + 1.777530e+04, + -9.556767e+04, + -1.350497e+04, + 1.188112e+04, + 1.835489e+04, + 7.279899e+04, + -2.152115e+04, + 9.918036e+03, + 1.888459e+04, + -1.801529e+04, + -1.047619e+04, + 8.284368e+03, + 1.934672e+04, + 1.422292e+04, + -1.081166e+04, + 6.978533e+03, + 1.976507e+04, + -1.971096e+04, + -6.232236e+03, + 5.867255e+03, + 2.013646e+04, + 2.555580e+04, + -8.493675e+03, + 4.875924e+03, + 2.046942e+04, + -2.220971e+04, + -2.736626e+03, + 4.094432e+03, + 2.075821e+04, + 6.086730e+03, + -4.963141e+03, + 3.401028e+03, + 2.102006e+04, + -4.421174e+03, + -2.900042e+03, + 2.775707e+03, + 2.124349e+04, + -4.520515e+03, + -2.411202e+03, + 2.253152e+03, + 2.143723e+04, + -2.508622e+03, + -2.146013e+03, + 1.775733e+03, + 2.160097e+04, + -2.936199e+03, + -1.618598e+03, + 1.357499e+03, + 2.173462e+04, + -9.367685e+03, + -6.231229e+02, + 9.992896e+02, + 2.184062e+04, + -1.206672e+04, + -1.719530e+02, + 6.376552e+02, + 2.192089e+04, + -8.102102e+03, + -5.838292e+00, + 2.573335e+02, + 2.197034e+04, + -4.403129e+12, + 5.670988e+07, + 4.522792e+03, + 1.062499e+01, + 1.009104e+11, + -2.052389e+07, + 2.552832e+03, + 1.069725e+01, + -1.358716e+10, + 8.667774e+06, + 2.007574e+03, + 1.088375e+01, + 9.860870e+08, + -7.696195e+05, + 3.312868e+03, + 1.199369e+01, + -7.263205e+07, + 5.079683e+05, + 3.534528e+03, + 1.404941e+01, + 6.095618e+07, + 2.370154e+05, + 4.361871e+03, + 1.824319e+01, + 1.451466e+07, + 4.286776e+05, + 5.555429e+03, + 2.590389e+01, + -1.400850e+07, + 6.184504e+05, + 7.641043e+03, + 4.027263e+01, + -1.241073e+07, + 6.950653e+05, + 1.088771e+04, + 6.743470e+01, + -1.795027e+07, + 8.260387e+05, + 1.556669e+04, + 1.172372e+02, + -2.319572e+07, + 9.411195e+05, + 2.210913e+04, + 2.061525e+02, + -3.010013e+07, + 1.015888e+06, + 3.058323e+04, + 3.586307e+02, + -2.022242e+07, + 8.484787e+05, + 4.025853e+04, + 6.058539e+02, + -1.910299e+07, + 7.492166e+05, + 5.001245e+04, + 9.760963e+02, + -1.557142e+07, + 5.745389e+05, + 5.904610e+04, + 1.498265e+03, + -1.230740e+07, + 3.873126e+05, + 6.601791e+04, + 2.188449e+03, + -6.940073e+06, + 1.748956e+05, + 6.994206e+04, + 3.045149e+03, + -5.177292e+06, + 6.314485e+04, + 7.073880e+04, + 4.045467e+03, + -2.366516e+06, + -4.755500e+04, + 6.884163e+04, + 5.161344e+03, + -2.358205e+06, + -6.773915e+04, + 6.493284e+04, + 6.352030e+03, + -5.046368e+05, + -1.245616e+05, + 5.953143e+04, + 7.585005e+03, + -7.352958e+05, + -1.050440e+05, + 5.340095e+04, + 8.814996e+03, + -4.712122e+04, + -1.140651e+05, + 4.711703e+04, + 1.002166e+04, + -1.940792e+05, + -9.000891e+04, + 4.104669e+04, + 1.117633e+04, + -5.334300e+04, + -8.040981e+04, + 3.542982e+04, + 1.227079e+04, + 3.617207e+04, + -6.882656e+04, + 3.028288e+04, + 1.329163e+04, + 3.113110e+04, + -5.478774e+04, + 2.577621e+04, + 1.423360e+04, + -6.129565e+04, + -4.010649e+04, + 2.191962e+04, + 1.509901e+04, + 8.799100e+04, + -3.960913e+04, + 1.850097e+04, + 1.589132e+04, + -3.273914e+04, + -2.471044e+04, + 1.563896e+04, + 1.660515e+04, + 5.062606e+04, + -2.465741e+04, + 1.321567e+04, + 1.725598e+04, + -4.331664e+04, + -1.394978e+04, + 1.119464e+04, + 1.784036e+04, + 2.151457e+04, + -1.584838e+04, + 9.420701e+03, + 1.837225e+04, + 2.057252e+04, + -1.209662e+04, + 7.881816e+03, + 1.884308e+04, + -3.218097e+04, + -5.996226e+03, + 6.685549e+03, + 1.926382e+04, + 1.272473e+04, + -8.675284e+03, + 5.581521e+03, + 1.964513e+04, + 1.293397e+04, + -6.525058e+03, + 4.612838e+03, + 1.997558e+04, + -2.512579e+04, + -2.085553e+03, + 3.897889e+03, + 2.026666e+04, + 9.631166e+03, + -5.124486e+03, + 3.195860e+03, + 2.052944e+04, + -8.369392e+03, + -2.217471e+03, + 2.579994e+03, + 2.074865e+04, + -4.945385e+03, + -2.272369e+03, + 2.058660e+03, + 2.093800e+04, + -3.084443e+03, + -1.973310e+03, + 1.566386e+03, + 2.109326e+04, + -7.303688e+03, + -1.067347e+03, + 1.141462e+03, + 2.121494e+04, + -1.970787e+04, + 4.640662e+02, + 7.508659e+02, + 2.130630e+04, + -7.520008e+03, + -1.899019e+02, + 2.755003e+02, + 2.136575e+04, + 1.985745e+12, + -2.912097e+07, + -7.661830e+02, + 6.684121e-01, + -6.636634e+08, + 2.990354e+05, + 0, + 6.567228e-01, + -2.343986e+09, + 1.611661e+06, + 4.317728e+01, + 6.599108e-01, + 2.254208e+07, + 4.359743e+04, + 3.445681e+02, + 7.645827e-01, + 1.156883e+07, + 5.539843e+04, + 4.276905e+02, + 1.007931e+00, + 1.328478e+07, + 6.727963e+04, + 5.825680e+02, + 1.532353e+00, + -1.427828e+06, + 1.497926e+05, + 8.917103e+02, + 2.663022e+00, + 9.122115e+05, + 2.061081e+05, + 1.527034e+03, + 5.318074e+00, + -1.436027e+07, + 3.894326e+05, + 2.751124e+03, + 1.153834e+01, + -1.297819e+07, + 4.891972e+05, + 5.061759e+03, + 2.652661e+01, + -1.440164e+07, + 6.231437e+05, + 8.782631e+03, + 5.952481e+01, + -2.071955e+07, + 7.895515e+05, + 1.448705e+04, + 1.272475e+02, + -2.105556e+07, + 8.342286e+05, + 2.238247e+04, + 2.567244e+02, + -1.730582e+07, + 7.638287e+05, + 3.174262e+04, + 4.810755e+02, + -1.649409e+07, + 6.787079e+05, + 4.153117e+04, + 8.337819e+02, + -1.213281e+07, + 4.915370e+05, + 5.044160e+04, + 1.344592e+03, + -7.204027e+06, + 2.923513e+05, + 5.703735e+04, + 2.024137e+03, + -6.395770e+06, + 1.876444e+05, + 6.098537e+04, + 2.865273e+03, + -3.652266e+06, + 5.084202e+04, + 6.211538e+04, + 3.853040e+03, + -1.242084e+06, + -4.545439e+04, + 6.048160e+04, + 4.948354e+03, + -2.077700e+06, + -3.761168e+04, + 5.725210e+04, + 6.110893e+03, + -4.035125e+05, + -9.878235e+04, + 5.267188e+04, + 7.316266e+03, + -2.774259e+05, + -9.184399e+04, + 4.725635e+04, + 8.513608e+03, + -7.489327e+04, + -8.630250e+04, + 4.187600e+04, + 9.683030e+03, + -1.824318e+05, + -6.931827e+04, + 3.676257e+04, + 1.080698e+04, + -2.043178e+04, + -6.528394e+04, + 3.193106e+04, + 1.187602e+04, + -2.125564e+04, + -5.356901e+04, + 2.747061e+04, + 1.287528e+04, + 3.802628e+04, + -4.622590e+04, + 2.349523e+04, + 1.380133e+04, + -1.011949e+04, + -3.479996e+04, + 2.005371e+04, + 1.465185e+04, + 1.957445e+04, + -2.979789e+04, + 1.707635e+04, + 1.543211e+04, + -2.310000e+04, + -2.169519e+04, + 1.451302e+04, + 1.614210e+04, + 4.887815e+04, + -2.176628e+04, + 1.226507e+04, + 1.678755e+04, + -3.010570e+04, + -1.212523e+04, + 1.041726e+04, + 1.736624e+04, + 1.141261e+04, + -1.307324e+04, + 8.823028e+03, + 1.789421e+04, + 2.115730e+03, + -9.658469e+03, + 7.420827e+03, + 1.836449e+04, + -3.130044e+03, + -7.419199e+03, + 6.255799e+03, + 1.878518e+04, + -1.015496e+04, + -5.605767e+03, + 5.248800e+03, + 1.916053e+04, + 1.197197e+04, + -6.387298e+03, + 4.331709e+03, + 1.949224e+04, + -9.451760e+03, + -3.045742e+03, + 3.592623e+03, + 1.977809e+04, + -9.143314e+03, + -2.779727e+03, + 2.959049e+03, + 2.003133e+04, + -4.060531e+02, + -3.138927e+03, + 2.331861e+03, + 2.024720e+04, + -8.374759e+03, + -1.630913e+03, + 1.790562e+03, + 2.042217e+04, + -9.631227e+03, + -1.214229e+03, + 1.300725e+03, + 2.056279e+04, + -1.757971e+04, + -7.909526e+00, + 8.217597e+02, + 2.066585e+04, + -9.360190e+03, + -1.008561e+02, + 3.151603e+02, + 2.072972e+04, + 7.057544e+11, + -1.002630e+07, + -2.834657e+02, + 2.019051e-02, + -5.762712e+09, + 1.096773e+06, + 0, + 1.593987e-02, + 9.580494e+07, + -5.116182e+04, + 1.296875e+01, + 2.178450e-02, + -7.314732e+07, + 8.930245e+04, + 1.028639e+01, + 2.390981e-02, + 1.212836e+07, + -1.522072e+04, + 3.493413e+01, + 4.781962e-02, + 1.107723e+06, + 1.523353e+04, + 4.315452e+01, + 8.182469e-02, + -3.122114e+06, + 4.692205e+04, + 9.912353e+01, + 1.912785e-01, + -1.218946e+05, + 6.710879e+04, + 2.596781e+02, + 6.004020e-01, + -7.767512e+06, + 1.781769e+05, + 6.475762e+02, + 1.923412e+00, + -7.081599e+06, + 2.703169e+05, + 1.654503e+03, + 6.432271e+00, + -1.388268e+07, + 4.599894e+05, + 3.716433e+03, + 1.933826e+01, + -1.677008e+07, + 6.152583e+05, + 7.609712e+03, + 5.293951e+01, + -1.773788e+07, + 7.158283e+05, + 1.367450e+04, + 1.284552e+02, + -1.673161e+07, + 7.330517e+05, + 2.177075e+04, + 2.764208e+02, + -1.582636e+07, + 6.844310e+05, + 3.113206e+04, + 5.328466e+02, + -1.143484e+07, + 5.250286e+05, + 4.040399e+04, + 9.320810e+02, + -7.912410e+06, + 3.651709e+05, + 4.815568e+04, + 1.493388e+03, + -6.534461e+06, + 2.459158e+05, + 5.373328e+04, + 2.221905e+03, + -3.824178e+06, + 1.046254e+05, + 5.660509e+04, + 3.108860e+03, + -2.225738e+06, + 1.563807e+04, + 5.671396e+04, + 4.122526e+03, + -1.458328e+06, + -3.221722e+04, + 5.474607e+04, + 5.227111e+03, + -8.183570e+05, + -6.333746e+04, + 5.127832e+04, + 6.386920e+03, + -2.794557e+05, + -7.986545e+04, + 4.684627e+04, + 7.565535e+03, + -3.250386e+05, + -7.038672e+04, + 4.208904e+04, + 8.732396e+03, + -1.754872e+05, + -6.847775e+04, + 3.727257e+04, + 9.869589e+03, + 1.159607e+05, + -6.912938e+04, + 3.251333e+04, + 1.095548e+04, + -9.178916e+04, + -4.742331e+04, + 2.825702e+04, + 1.197515e+04, + -3.478289e+04, + -4.291868e+04, + 2.444894e+04, + 1.293450e+04, + 4.096451e+04, + -3.883179e+04, + 2.093198e+04, + 1.382302e+04, + 1.018149e+04, + -2.939198e+04, + 1.788632e+04, + 1.463685e+04, + -6.312718e+03, + -2.298834e+04, + 1.530245e+04, + 1.538327e+04, + 8.853193e+01, + -1.922555e+04, + 1.304664e+04, + 1.606557e+04, + -4.315150e+03, + -1.538511e+04, + 1.107414e+04, + 1.668446e+04, + 2.613878e+04, + -1.434570e+04, + 9.354640e+03, + 1.724279e+04, + -3.056698e+04, + -7.440654e+03, + 7.953552e+03, + 1.774252e+04, + 1.201257e+04, + -9.709738e+03, + 6.690044e+03, + 1.819679e+04, + 2.315698e+03, + -6.742600e+03, + 5.577442e+03, + 1.859490e+04, + -9.440768e+03, + -4.516726e+03, + 4.681297e+03, + 1.894793e+04, + 1.196941e+03, + -4.741381e+03, + 3.874527e+03, + 1.926086e+04, + -7.702191e+03, + -2.981726e+03, + 3.168711e+03, + 1.953055e+04, + -8.882011e+03, + -2.461540e+03, + 2.537074e+03, + 1.976277e+04, + -1.422894e+03, + -2.714319e+03, + 1.927726e+03, + 1.995485e+04, + -1.333538e+04, + -8.409366e+02, + 1.410345e+03, + 2.010401e+04, + -1.909208e+04, + -3.880590e+01, + 9.041545e+02, + 2.021755e+04, + -1.040053e+04, + -1.016679e+02, + 3.480591e+02, + 2.028776e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.747318e+05, + 3.472389e+03, + 0, + 0, + 4.067195e+05, + -3.625279e+02, + 3.698487e+00, + 4.781962e-03, + -2.201325e+05, + 7.112541e+03, + 7.958936e+00, + 1.540855e-02, + -1.375506e+06, + 3.099300e+04, + 4.379474e+01, + 9.351393e-02, + -2.748196e+06, + 8.093983e+04, + 2.179212e+02, + 6.189985e-01, + -4.968397e+06, + 1.759744e+05, + 7.942168e+02, + 3.123153e+00, + -9.224231e+06, + 3.310828e+05, + 2.317096e+03, + 1.246073e+01, + -1.172345e+07, + 4.760308e+05, + 5.552592e+03, + 4.086665e+01, + -1.364940e+07, + 5.855323e+05, + 1.095084e+04, + 1.106753e+02, + -1.160214e+07, + 5.818835e+05, + 1.835230e+04, + 2.545476e+02, + -1.186484e+07, + 5.618680e+05, + 2.689271e+04, + 5.080793e+02, + -8.404699e+06, + 4.221755e+05, + 3.536085e+04, + 9.063264e+02, + -5.194575e+06, + 2.784763e+05, + 4.225115e+04, + 1.464581e+03, + -5.350129e+06, + 2.094167e+05, + 4.716334e+04, + 2.183139e+03, + -1.602308e+06, + 5.042204e+04, + 4.954778e+04, + 3.054031e+03, + -2.214826e+06, + 3.646787e+04, + 4.967168e+04, + 4.035868e+03, + -9.356126e+05, + -3.084597e+04, + 4.811762e+04, + 5.110060e+03, + -4.549349e+05, + -5.386665e+04, + 4.503815e+04, + 6.230077e+03, + -3.040345e+05, + -5.796460e+04, + 4.128150e+04, + 7.364268e+03, + -1.176667e+05, + -6.013046e+04, + 3.722607e+04, + 8.489020e+03, + -2.285004e+05, + -4.899339e+04, + 3.315231e+04, + 9.583239e+03, + 1.171614e+05, + -5.738783e+04, + 2.908158e+04, + 1.063408e+04, + -6.209781e+04, + -3.832039e+04, + 2.537658e+04, + 1.162023e+04, + -2.092407e+04, + -3.477457e+04, + 2.209397e+04, + 1.255044e+04, + 7.150074e+03, + -3.032506e+04, + 1.906153e+04, + 1.341566e+04, + -1.872806e+04, + -2.346902e+04, + 1.637525e+04, + 1.421280e+04, + 3.845397e+04, + -2.256213e+04, + 1.398698e+04, + 1.494422e+04, + -2.212050e+04, + -1.416819e+04, + 1.197514e+04, + 1.560777e+04, + 1.117884e+04, + -1.415931e+04, + 1.022919e+04, + 1.621605e+04, + -9.805903e+03, + -9.936432e+03, + 8.698553e+03, + 1.676423e+04, + -6.284957e+03, + -8.619152e+03, + 7.363785e+03, + 1.725975e+04, + 8.194854e+03, + -8.133936e+03, + 6.160163e+03, + 1.770134e+04, + -1.348632e+03, + -5.585066e+03, + 5.156021e+03, + 1.808984e+04, + -2.129218e+04, + -3.033875e+03, + 4.322259e+03, + 1.843476e+04, + 1.090528e+04, + -5.636095e+03, + 3.481772e+03, + 1.873867e+04, + -1.576162e+04, + -1.719787e+03, + 2.785226e+03, + 1.898864e+04, + -3.646745e+03, + -2.827982e+03, + 2.153210e+03, + 1.920291e+04, + -1.365574e+04, + -1.131453e+03, + 1.562656e+03, + 1.936968e+04, + -1.907849e+04, + -2.359625e+02, + 9.938042e+02, + 1.949465e+04, + -1.267951e+04, + -2.792363e+00, + 3.995119e+02, + 1.957176e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -4.253495e+03, + 7.499863e+01, + 0, + 0, + -1.750552e+04, + 6.611353e+02, + 3.286766e-01, + 5.313292e-04, + -1.773001e+05, + 5.748574e+03, + 4.539952e+00, + 1.009525e-02, + -9.223470e+05, + 2.879966e+04, + 4.664094e+01, + 1.386769e-01, + -1.930323e+06, + 7.899737e+04, + 2.852048e+02, + 1.171049e+00, + -4.376965e+06, + 1.804810e+05, + 1.095224e+03, + 6.203799e+00, + -6.199410e+06, + 2.925007e+05, + 3.155202e+03, + 2.454156e+01, + -8.265951e+06, + 3.988727e+05, + 7.017706e+03, + 7.510072e+01, + -7.418139e+06, + 4.164357e+05, + 1.276099e+04, + 1.879864e+02, + -7.040578e+06, + 4.038613e+05, + 1.967473e+04, + 3.966702e+02, + -5.686102e+06, + 3.336694e+05, + 2.686086e+04, + 7.341906e+02, + -4.304528e+06, + 2.438082e+05, + 3.315168e+04, + 1.220839e+03, + -2.692813e+06, + 1.463149e+05, + 3.773689e+04, + 1.860259e+03, + -1.797320e+06, + 7.842619e+04, + 4.036734e+04, + 2.638594e+03, + -1.480552e+06, + 3.567044e+04, + 4.122917e+04, + 3.534651e+03, + -4.691014e+05, + -1.943763e+04, + 4.039585e+04, + 4.520549e+03, + -4.771614e+05, + -2.551283e+04, + 3.841306e+04, + 5.556536e+03, + -2.993912e+05, + -3.669547e+04, + 3.578773e+04, + 6.621797e+03, + -7.863820e+04, + -4.472026e+04, + 3.264362e+04, + 7.688512e+03, + -7.947163e+04, + -3.968368e+04, + 2.936882e+04, + 8.732777e+03, + -4.626689e+04, + -3.655540e+04, + 2.617168e+04, + 9.743299e+03, + -3.298749e+04, + -3.228438e+04, + 2.309979e+04, + 1.070825e+04, + 7.557068e+03, + -2.951923e+04, + 2.021271e+04, + 1.161922e+04, + -1.131117e+04, + -2.346075e+04, + 1.760143e+04, + 1.246985e+04, + -8.138479e+02, + -2.029297e+04, + 1.526546e+04, + 1.326110e+04, + -6.482612e+03, + -1.648920e+04, + 1.317628e+04, + 1.399093e+04, + -9.595959e+02, + -1.408842e+04, + 1.131675e+04, + 1.466044e+04, + -8.934017e+03, + -1.109881e+04, + 9.671678e+03, + 1.526962e+04, + 1.509275e+04, + -1.089459e+04, + 8.203717e+03, + 1.582083e+04, + -1.453210e+04, + -6.361619e+03, + 6.975921e+03, + 1.631342e+04, + -1.009911e+04, + -6.003604e+03, + 5.892338e+03, + 1.675910e+04, + 4.806694e+03, + -6.254916e+03, + 4.858851e+03, + 1.715199e+04, + -1.071047e+04, + -3.527770e+03, + 3.984625e+03, + 1.748987e+04, + -8.640748e+03, + -3.280218e+03, + 3.206107e+03, + 1.778279e+04, + -5.456272e+03, + -2.969433e+03, + 2.463075e+03, + 1.802588e+04, + -1.521043e+04, + -1.321653e+03, + 1.804258e+03, + 1.821785e+04, + -2.367697e+04, + -9.087804e+01, + 1.159175e+03, + 1.836246e+04, + -1.433487e+04, + -4.953068e+01, + 4.611681e+02, + 1.845283e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -3.175559e+04, + 9.319479e+02, + 0, + 0, + -1.155952e+05, + 5.362912e+03, + 7.533434e+00, + 2.444114e-02, + -4.781473e+05, + 2.294213e+04, + 6.469392e+01, + 2.901057e-01, + -1.186903e+06, + 6.363668e+04, + 3.418921e+02, + 2.059963e+00, + -2.457058e+06, + 1.339813e+05, + 1.225389e+03, + 9.946482e+00, + -3.689532e+06, + 2.089429e+05, + 3.267949e+03, + 3.596461e+01, + -3.635500e+06, + 2.440573e+05, + 6.751900e+03, + 1.017719e+02, + -4.240893e+06, + 2.702413e+05, + 1.146298e+04, + 2.351121e+02, + -2.806952e+06, + 2.203272e+05, + 1.683224e+04, + 4.676621e+02, + -2.755320e+06, + 1.948001e+05, + 2.199412e+04, + 8.191252e+02, + -2.060483e+06, + 1.377770e+05, + 2.645927e+04, + 1.306106e+03, + -1.097631e+06, + 7.499210e+04, + 2.952827e+04, + 1.925185e+03, + -1.000923e+06, + 4.815843e+04, + 3.123190e+04, + 2.659039e+03, + -4.315165e+05, + 8.335406e+03, + 3.169514e+04, + 3.491872e+03, + -4.699637e+05, + -3.883861e+02, + 3.111515e+04, + 4.393927e+03, + -1.358086e+05, + -2.181426e+04, + 2.973216e+04, + 5.345470e+03, + -2.102148e+05, + -1.969387e+04, + 2.780408e+04, + 6.315553e+03, + -2.056386e+03, + -3.015444e+04, + 2.554160e+04, + 7.289349e+03, + -1.214515e+05, + -2.109060e+04, + 2.317332e+04, + 8.242094e+03, + 2.283767e+04, + -2.752130e+04, + 2.075837e+04, + 9.169350e+03, + 7.777847e+02, + -2.167302e+04, + 1.841980e+04, + 1.004997e+04, + -5.404760e+04, + -1.555831e+04, + 1.633979e+04, + 1.088609e+04, + 2.732346e+04, + -1.905176e+04, + 1.431599e+04, + 1.167632e+04, + -2.032427e+04, + -1.233088e+04, + 1.247912e+04, + 1.240595e+04, + -1.714066e+04, + -1.113399e+04, + 1.084237e+04, + 1.308473e+04, + 1.575944e+04, + -1.185483e+04, + 9.276789e+03, + 1.370596e+04, + -1.758306e+04, + -6.912145e+03, + 7.932318e+03, + 1.426459e+04, + -4.249523e+03, + -7.239515e+03, + 6.729422e+03, + 1.477256e+04, + -2.329697e+03, + -6.114440e+03, + 5.608986e+03, + 1.522204e+04, + -5.910026e+03, + -4.665776e+03, + 4.630493e+03, + 1.561502e+04, + -1.798960e+04, + -2.846416e+03, + 3.762089e+03, + 1.595518e+04, + -3.910095e+03, + -3.884273e+03, + 2.890839e+03, + 1.624284e+04, + -1.926873e+04, + -1.391269e+03, + 2.105855e+03, + 1.646675e+04, + -2.740709e+04, + -1.634349e+02, + 1.341530e+03, + 1.663561e+04, + -1.586965e+04, + -1.115448e+02, + 5.221589e+02, + 1.673964e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.127396e+02, + 4.028231e+01, + 0, + 0, + -2.922208e+03, + 3.533675e+02, + 4.231000e-01, + 1.593987e-03, + -7.834748e+04, + 3.913683e+03, + 5.563741e+00, + 2.656646e-02, + -1.794238e+05, + 1.330030e+04, + 5.847158e+01, + 3.613038e-01, + -7.133529e+05, + 4.140932e+04, + 2.841249e+02, + 2.339974e+00, + -8.219289e+05, + 6.765098e+04, + 9.828657e+02, + 1.089809e+01, + -1.608881e+06, + 1.135553e+05, + 2.399301e+03, + 3.586206e+01, + -1.380790e+06, + 1.250011e+05, + 4.785818e+03, + 9.597186e+01, + -1.681694e+06, + 1.416683e+05, + 7.913429e+03, + 2.122113e+02, + -1.342164e+06, + 1.248846e+05, + 1.153453e+04, + 4.098636e+02, + -1.138530e+06, + 1.048019e+05, + 1.506125e+04, + 7.058108e+02, + -7.560038e+05, + 7.458648e+04, + 1.812017e+04, + 1.110256e+03, + -7.365586e+05, + 5.736215e+04, + 2.047117e+04, + 1.622284e+03, + -2.829319e+05, + 2.385083e+04, + 2.194529e+04, + 2.236639e+03, + -3.746521e+05, + 1.866296e+04, + 2.260812e+04, + 2.932459e+03, + -2.109677e+05, + 1.572390e+03, + 2.259219e+04, + 3.699650e+03, + -4.422227e+04, + -1.078135e+04, + 2.187151e+04, + 4.512166e+03, + -1.480152e+05, + -6.663066e+03, + 2.082518e+04, + 5.348479e+03, + -3.470247e+04, + -1.527565e+04, + 1.948176e+04, + 6.200584e+03, + -1.374575e+04, + -1.543198e+04, + 1.789581e+04, + 7.043310e+03, + -4.756536e+04, + -1.215076e+04, + 1.631547e+04, + 7.867040e+03, + -2.328940e+03, + -1.445670e+04, + 1.469261e+04, + 8.665875e+03, + -2.943259e+04, + -1.086144e+04, + 1.309232e+04, + 9.424964e+03, + 2.219356e+04, + -1.335516e+04, + 1.153409e+04, + 1.014250e+04, + -3.753978e+04, + -6.601135e+03, + 1.014219e+04, + 1.080706e+04, + 6.462929e+03, + -9.897952e+03, + 8.803313e+03, + 1.142966e+04, + -1.185789e+04, + -6.587254e+03, + 7.531425e+03, + 1.199133e+04, + -5.585795e+03, + -6.310054e+03, + 6.385138e+03, + 1.249966e+04, + -1.095521e+04, + -4.847504e+03, + 5.319253e+03, + 1.294953e+04, + -1.433834e+04, + -3.906517e+03, + 4.322975e+03, + 1.334142e+04, + -3.995946e+03, + -4.280124e+03, + 3.350694e+03, + 1.367127e+04, + -2.687799e+04, + -1.046360e+03, + 2.493151e+03, + 1.393293e+04, + -3.083327e+04, + -4.093439e+02, + 1.594075e+03, + 1.413478e+04, + -1.950779e+04, + -7.012349e+01, + 6.281431e+02, + 1.425796e+04, +}; + +double solarDataset600[] = +{ + 1.454828e+13, + -1.753873e+07, + 4.108891e+04, + 1.618972e+03, + -1.384284e+12, + 3.644504e+08, + 5.345299e+04, + 1.619749e+03, + -5.626237e+10, + 3.552050e+07, + 8.094015e+04, + 1.629074e+03, + 3.728997e+09, + -3.217893e+06, + 8.610187e+04, + 1.657417e+03, + -1.341046e+09, + 2.537266e+06, + 8.654787e+04, + 1.711991e+03, + 1.037406e+09, + -1.842154e+06, + 8.743552e+04, + 1.804243e+03, + -2.281591e+08, + 1.692114e+06, + 8.931420e+04, + 1.940869e+03, + 4.381924e+07, + 4.651551e+05, + 9.344253e+04, + 2.142112e+03, + -4.759171e+07, + 8.163875e+05, + 9.726835e+04, + 2.419359e+03, + -1.821050e+07, + 4.964279e+05, + 1.013782e+05, + 2.792134e+03, + -2.368294e+07, + 4.294862e+05, + 1.048241e+05, + 3.274694e+03, + -1.941022e+07, + 2.763683e+05, + 1.074121e+05, + 3.882373e+03, + -1.590314e+07, + 1.381601e+05, + 1.084676e+05, + 4.624161e+03, + -1.691643e+07, + 5.407009e+04, + 1.075833e+05, + 5.501698e+03, + -9.692053e+06, + -1.241486e+05, + 1.040909e+05, + 6.506736e+03, + -4.836417e+06, + -2.247011e+05, + 9.795019e+04, + 7.611780e+03, + -5.822942e+06, + -2.072205e+05, + 9.012361e+04, + 8.785157e+03, + -4.934677e+05, + -2.953874e+05, + 8.082216e+04, + 9.997030e+03, + -1.972241e+06, + -2.181519e+05, + 7.109185e+04, + 1.120129e+04, + -2.891157e+05, + -2.240168e+05, + 6.151353e+04, + 1.238053e+04, + -4.966324e+05, + -1.758467e+05, + 5.236592e+04, + 1.350154e+04, + 1.641487e+05, + -1.585700e+05, + 4.401724e+04, + 1.455163e+04, + 8.034773e+04, + -1.203842e+05, + 3.671628e+04, + 1.551563e+04, + -1.271137e+04, + -9.085232e+04, + 3.057720e+04, + 1.639592e+04, + 3.823284e+04, + -7.282635e+04, + 2.535605e+04, + 1.719488e+04, + 4.041914e+04, + -5.648343e+04, + 2.094476e+04, + 1.791302e+04, + 9.493516e+04, + -4.559175e+04, + 1.728272e+04, + 1.855507e+04, + -5.146686e+04, + -2.872101e+04, + 1.434663e+04, + 1.912718e+04, + 7.274758e+04, + -2.868041e+04, + 1.186372e+04, + 1.964130e+04, + -1.137111e+04, + -1.752581e+04, + 9.839214e+03, + 2.009446e+04, + -1.008472e+04, + -1.422576e+04, + 8.192508e+03, + 2.050076e+04, + 2.515788e+04, + -1.323360e+04, + 6.753657e+03, + 2.086086e+04, + 1.584386e+04, + -9.397442e+03, + 5.594194e+03, + 2.117599e+04, + -1.982323e+04, + -5.090890e+03, + 4.709331e+03, + 2.145612e+04, + 9.160687e+03, + -6.384271e+03, + 3.918052e+03, + 2.170842e+04, + 6.487543e+03, + -4.632844e+03, + 3.236203e+03, + 2.192755e+04, + -1.558850e+04, + -2.009499e+03, + 2.714977e+03, + 2.212059e+04, + 1.214568e+04, + -4.063965e+03, + 2.216067e+03, + 2.229301e+04, + -9.387616e+03, + -1.151481e+03, + 1.817672e+03, + 2.243736e+04, + 1.549500e+03, + -2.094099e+03, + 1.475644e+03, + 2.256570e+04, + -4.531227e+03, + -1.034617e+03, + 1.167963e+03, + 2.267195e+04, + -2.936346e+03, + -1.036553e+03, + 8.946197e+02, + 2.276081e+04, + -4.991516e+03, + -5.847746e+02, + 6.400900e+02, + 2.283020e+04, + -8.686370e+03, + -8.226384e+00, + 4.001762e+02, + 2.288082e+04, + -4.282608e+03, + -6.966287e+01, + 1.490135e+02, + 2.291176e+04, + -8.258616e+13, + 9.904778e+08, + 1.318286e+05, + 7.747884e+02, + 2.062665e+12, + -4.786463e+08, + 9.235644e+04, + 7.769322e+02, + -3.538830e+10, + 2.205724e+07, + 6.694206e+04, + 7.847311e+02, + 4.058662e+09, + -3.295631e+06, + 7.000223e+04, + 8.077786e+02, + -1.994471e+07, + 1.416720e+06, + 7.075137e+04, + 8.521384e+02, + -1.187269e+08, + 1.283696e+06, + 7.366460e+04, + 9.280772e+02, + 2.540619e+08, + 2.026807e+05, + 7.681548e+04, + 1.046331e+03, + -1.391960e+08, + 1.579054e+06, + 8.135576e+04, + 1.218133e+03, + 2.530622e+07, + 5.920718e+05, + 8.701200e+04, + 1.465097e+03, + -3.251666e+07, + 8.728196e+05, + 9.250368e+04, + 1.800184e+03, + -4.349050e+07, + 7.754678e+05, + 9.852956e+04, + 2.248042e+03, + -2.011892e+07, + 3.930905e+05, + 1.031312e+05, + 2.827391e+03, + -1.799797e+07, + 2.525175e+05, + 1.056848e+05, + 3.545122e+03, + -1.574729e+07, + 1.139525e+05, + 1.062387e+05, + 4.406529e+03, + -1.205118e+07, + -2.983359e+04, + 1.041875e+05, + 5.405193e+03, + -6.697812e+06, + -1.674924e+05, + 9.926112e+04, + 6.519409e+03, + -4.384345e+06, + -2.195876e+05, + 9.199400e+04, + 7.714342e+03, + -1.862072e+06, + -2.540928e+05, + 8.320020e+04, + 8.954122e+03, + -1.908592e+06, + -2.218975e+05, + 7.374786e+04, + 1.020097e+04, + -6.595484e+05, + -2.191046e+05, + 6.409677e+04, + 1.142642e+04, + 5.591668e+05, + -2.065625e+05, + 5.471249e+04, + 1.259732e+04, + -8.093373e+05, + -1.264564e+05, + 4.652504e+04, + 1.369474e+04, + 1.688527e+05, + -1.334041e+05, + 3.909025e+04, + 1.472375e+04, + 2.419749e+05, + -1.045422e+05, + 3.245138e+04, + 1.565887e+04, + -1.230208e+05, + -6.804517e+04, + 2.707154e+04, + 1.650613e+04, + 1.126806e+05, + -6.300250e+04, + 2.249086e+04, + 1.727731e+04, + -7.142991e+04, + -4.118624e+04, + 1.863553e+04, + 1.796673e+04, + 1.675606e+05, + -4.267365e+04, + 1.536107e+04, + 1.858582e+04, + -6.485362e+04, + -2.110609e+04, + 1.279192e+04, + 1.913137e+04, + 2.637560e+04, + -2.212235e+04, + 1.067530e+04, + 1.962669e+04, + 7.981750e+03, + -1.608272e+04, + 8.844225e+03, + 2.006475e+04, + 1.871909e+04, + -1.315898e+04, + 7.352146e+03, + 2.045392e+04, + -1.840475e+04, + -8.056233e+03, + 6.149474e+03, + 2.079909e+04, + 1.957039e+04, + -9.075917e+03, + 5.104541e+03, + 2.110797e+04, + -8.536233e+03, + -4.982923e+03, + 4.248788e+03, + 2.137749e+04, + 3.499200e+03, + -5.020523e+03, + 3.538293e+03, + 2.161816e+04, + -2.000849e+03, + -3.512066e+03, + 2.928448e+03, + 2.182841e+04, + 3.638545e+03, + -3.264362e+03, + 2.415994e+03, + 2.201285e+04, + -1.015257e+04, + -1.420977e+03, + 1.998918e+03, + 2.217269e+04, + 4.403337e+03, + -2.590383e+03, + 1.602086e+03, + 2.231300e+04, + -7.875874e+03, + -7.971346e+02, + 1.270059e+03, + 2.242772e+04, + 2.108760e+03, + -1.686184e+03, + 9.648043e+02, + 2.252491e+04, + -9.024057e+03, + -1.121285e+02, + 7.146217e+02, + 2.259896e+04, + -1.078560e+04, + 5.370255e+01, + 4.574484e+02, + 2.265738e+04, + -4.144847e+03, + -1.351749e+02, + 1.580973e+02, + 2.269255e+04, + -7.925848e+12, + 7.954113e+07, + 4.342033e+04, + 2.306639e+02, + 2.269955e+11, + -6.495581e+07, + 3.909724e+04, + 2.313954e+02, + 3.302993e+10, + -1.552044e+07, + 3.333664e+04, + 2.355661e+02, + -4.784910e+09, + 7.541830e+06, + 3.379938e+04, + 2.459800e+02, + 3.613537e+08, + 7.051546e+05, + 3.758040e+04, + 2.693637e+02, + 2.012123e+08, + 9.047518e+05, + 4.026196e+04, + 3.100796e+02, + -3.247217e+07, + 1.458624e+06, + 4.458575e+04, + 3.762391e+02, + 3.509220e+07, + 1.133284e+06, + 5.050532e+04, + 4.804963e+02, + -6.375528e+07, + 1.554986e+06, + 5.800171e+04, + 6.381134e+02, + -2.892941e+07, + 1.197304e+06, + 6.695868e+04, + 8.734957e+02, + -5.164969e+07, + 1.213830e+06, + 7.625104e+04, + 1.209469e+03, + -2.739672e+07, + 7.928510e+05, + 8.505819e+04, + 1.674458e+03, + -2.787464e+07, + 6.247649e+05, + 9.206065e+04, + 2.284897e+03, + -1.871019e+07, + 3.383328e+05, + 9.669688e+04, + 3.055270e+03, + -1.379705e+07, + 1.369205e+05, + 9.808678e+04, + 3.981429e+03, + -8.704135e+06, + -3.571846e+04, + 9.616835e+04, + 5.046769e+03, + -4.155272e+06, + -1.581929e+05, + 9.124700e+04, + 6.219767e+03, + -4.104771e+06, + -1.676177e+05, + 8.431879e+04, + 7.461843e+03, + -1.265230e+06, + -2.229547e+05, + 7.591780e+04, + 8.739201e+03, + -9.083431e+05, + -2.002438e+05, + 6.683417e+04, + 1.000630e+04, + -5.255757e+05, + -1.783831e+05, + 5.790308e+04, + 1.123644e+04, + 4.993118e+05, + -1.719879e+05, + 4.940310e+04, + 1.240539e+04, + -7.487545e+05, + -9.942973e+04, + 4.203530e+04, + 1.349507e+04, + 3.978438e+05, + -1.195978e+05, + 3.528825e+04, + 1.451412e+04, + -2.047206e+04, + -7.632391e+04, + 2.942983e+04, + 1.543376e+04, + 6.154258e+04, + -6.346317e+04, + 2.463164e+04, + 1.627325e+04, + -2.863798e+04, + -4.606248e+04, + 2.057180e+04, + 1.703219e+04, + 7.388099e+04, + -4.085648e+04, + 1.711248e+04, + 1.771723e+04, + -2.064163e+04, + -2.712556e+04, + 1.425554e+04, + 1.832846e+04, + 3.328744e+04, + -2.433972e+04, + 1.186725e+04, + 1.887791e+04, + 1.002028e+04, + -1.754222e+04, + 9.878580e+03, + 1.936576e+04, + 8.911729e+03, + -1.374369e+04, + 8.260222e+03, + 1.980154e+04, + -2.085488e+04, + -9.181720e+03, + 6.920058e+03, + 2.019044e+04, + 2.914076e+04, + -1.070749e+04, + 5.730227e+03, + 2.053766e+04, + -1.293038e+04, + -5.174966e+03, + 4.781798e+03, + 2.083987e+04, + 5.221232e+03, + -5.721930e+03, + 3.997709e+03, + 2.111160e+04, + 2.329131e+03, + -4.209210e+03, + 3.318380e+03, + 2.134929e+04, + -1.120600e+04, + -2.323414e+03, + 2.771525e+03, + 2.155871e+04, + 4.077728e+03, + -3.348798e+03, + 2.255768e+03, + 2.174367e+04, + -4.397494e+03, + -1.781340e+03, + 1.814239e+03, + 2.189875e+04, + -2.371566e+03, + -1.679149e+03, + 1.440870e+03, + 2.203123e+04, + -3.509356e+03, + -1.211255e+03, + 1.104800e+03, + 2.213993e+04, + -6.401342e+03, + -6.643209e+02, + 8.055120e+02, + 2.222624e+04, + -9.121022e+03, + -1.798506e+02, + 5.138316e+02, + 2.229047e+04, + -6.114652e+03, + -5.727757e+01, + 2.165918e+02, + 2.233048e+04, + 9.465569e+11, + 2.157107e+07, + 2.323822e+03, + 3.141042e+01, + -3.198079e+11, + 7.414625e+07, + 3.911285e+03, + 3.146173e+01, + 9.476628e+09, + -4.475969e+06, + 7.835770e+03, + 3.245139e+01, + -8.928972e+08, + 1.881666e+06, + 7.953473e+03, + 3.487056e+01, + 3.171872e+08, + 2.635279e+05, + 9.264064e+03, + 4.047706e+01, + -5.849106e+07, + 9.732834e+05, + 1.087038e+04, + 5.087843e+01, + 8.242971e+07, + 6.037953e+05, + 1.349207e+04, + 7.009928e+01, + -3.032662e+07, + 1.159453e+06, + 1.732089e+04, + 1.033948e+02, + -3.561716e+07, + 1.251423e+06, + 2.330419e+04, + 1.629440e+02, + -3.448639e+07, + 1.286417e+06, + 3.117127e+04, + 2.657617e+02, + -3.649510e+07, + 1.300592e+06, + 4.093241e+04, + 4.359338e+02, + -4.363745e+07, + 1.276591e+06, + 5.220971e+04, + 7.050447e+02, + -2.840810e+07, + 9.451539e+05, + 6.355126e+04, + 1.108138e+03, + -2.581926e+07, + 7.360833e+05, + 7.326328e+04, + 1.668684e+03, + -1.354418e+07, + 3.883004e+05, + 8.025788e+04, + 2.403289e+03, + -1.377454e+07, + 2.590663e+05, + 8.389776e+04, + 3.304769e+03, + -6.998331e+06, + 2.378317e+04, + 8.395422e+04, + 4.361063e+03, + -3.017568e+06, + -1.031107e+05, + 8.045998e+04, + 5.528584e+03, + -3.053944e+06, + -1.159054e+05, + 7.492129e+04, + 6.765323e+03, + -9.988790e+05, + -1.670190e+05, + 6.794613e+04, + 8.038403e+03, + -7.984465e+05, + -1.523819e+05, + 6.021692e+04, + 9.302581e+03, + -9.338634e+04, + -1.494507e+05, + 5.246052e+04, + 1.053131e+04, + -1.035431e+05, + -1.215806e+05, + 4.515398e+04, + 1.169887e+04, + -7.357601e+04, + -9.990059e+04, + 3.857402e+04, + 1.279598e+04, + 1.792570e+03, + -8.319324e+04, + 3.268700e+04, + 1.381455e+04, + 3.874347e+04, + -6.749650e+04, + 2.752666e+04, + 1.474920e+04, + 4.244814e+04, + -5.329079e+04, + 2.311818e+04, + 1.560008e+04, + -7.930994e+03, + -3.984100e+04, + 1.941511e+04, + 1.637147e+04, + 8.733277e+04, + -3.589956e+04, + 1.626214e+04, + 1.706943e+04, + -7.640893e+04, + -1.973546e+04, + 1.370832e+04, + 1.769570e+04, + 6.465562e+04, + -2.412718e+04, + 1.146747e+04, + 1.826574e+04, + -1.257959e+04, + -1.387134e+04, + 9.594876e+03, + 1.876880e+04, + -3.216704e+03, + -1.199645e+04, + 8.071823e+03, + 1.922295e+04, + 1.185898e+04, + -1.055074e+04, + 6.732374e+03, + 1.962756e+04, + -8.043290e+02, + -7.356438e+03, + 5.627495e+03, + 1.998509e+04, + -1.628058e+03, + -5.891328e+03, + 4.712682e+03, + 2.030343e+04, + -3.439586e+03, + -4.645427e+03, + 3.923985e+03, + 2.058511e+04, + 3.075924e+03, + -4.271196e+03, + 3.234865e+03, + 2.083229e+04, + -1.635081e+03, + -2.923961e+03, + 2.662415e+03, + 2.104614e+04, + -7.090127e+03, + -1.933064e+03, + 2.185308e+03, + 2.123232e+04, + -4.437563e+03, + -1.933243e+03, + 1.734860e+03, + 2.139234e+04, + -3.653738e+02, + -1.892874e+03, + 1.311083e+03, + 2.152288e+04, + -1.354368e+04, + -1.252045e+02, + 9.651989e+02, + 2.162438e+04, + -6.525776e+03, + -7.519351e+02, + 5.872714e+02, + 2.170241e+04, + -6.046958e+03, + -1.425454e+02, + 2.526236e+02, + 2.174657e+04, + 7.685478e+11, + -3.587368e+06, + -5.614277e+02, + 2.176726e+00, + -6.325697e+10, + 1.540102e+07, + 0, + 2.169919e+00, + 6.037976e+08, + -1.269417e+05, + 9.536601e+02, + 2.283023e+00, + -1.231879e+08, + 2.884108e+05, + 1.064814e+03, + 2.602961e+00, + 1.338161e+08, + -3.138454e+04, + 1.282376e+03, + 3.367459e+00, + -8.742091e+06, + 3.029956e+05, + 1.660242e+03, + 4.836763e+00, + 4.214728e+05, + 3.431726e+05, + 2.546292e+03, + 8.152906e+00, + -8.769409e+06, + 4.935859e+05, + 4.054901e+03, + 1.537637e+01, + -2.118875e+07, + 7.043190e+05, + 6.707452e+03, + 3.116117e+01, + -1.956295e+07, + 8.532277e+05, + 1.108718e+04, + 6.499704e+01, + -3.731153e+07, + 1.135945e+06, + 1.777807e+04, + 1.334155e+02, + -3.091261e+07, + 1.121036e+06, + 2.709678e+04, + 2.649024e+02, + -3.270901e+07, + 1.105922e+06, + 3.809708e+04, + 4.929304e+02, + -2.200409e+07, + 8.529194e+05, + 4.956525e+04, + 8.559269e+02, + -2.038642e+07, + 6.855276e+05, + 5.978076e+04, + 1.380667e+03, + -1.117204e+07, + 3.795010e+05, + 6.745803e+04, + 2.085776e+03, + -9.901093e+06, + 2.365954e+05, + 7.171413e+04, + 2.961349e+03, + -4.354972e+06, + 3.054048e+04, + 7.248689e+04, + 3.990590e+03, + -3.140714e+06, + -3.946535e+04, + 7.017581e+04, + 5.129246e+03, + -1.994865e+06, + -9.051388e+04, + 6.582553e+04, + 6.341791e+03, + -5.803806e+05, + -1.294484e+05, + 5.994991e+04, + 7.586278e+03, + -8.405790e+05, + -1.086236e+05, + 5.349962e+04, + 8.822279e+03, + 2.303613e+05, + -1.273856e+05, + 4.686398e+04, + 1.002781e+04, + -4.101851e+05, + -8.285763e+04, + 4.066681e+04, + 1.117171e+04, + 2.025071e+05, + -9.176353e+04, + 3.492952e+04, + 1.225612e+04, + -1.241871e+05, + -6.014883e+04, + 2.981741e+04, + 1.325813e+04, + 7.450568e+04, + -5.766421e+04, + 2.535029e+04, + 1.418817e+04, + -3.498195e+04, + -4.081103e+04, + 2.145641e+04, + 1.503639e+04, + 5.737509e+04, + -3.728994e+04, + 1.810341e+04, + 1.581109e+04, + 1.553564e+04, + -2.696393e+04, + 1.527417e+04, + 1.651003e+04, + -3.264956e+04, + -1.915601e+04, + 1.294140e+04, + 1.714428e+04, + 2.039836e+04, + -1.885321e+04, + 1.087146e+04, + 1.771893e+04, + 3.616331e+04, + -1.547233e+04, + 9.097636e+03, + 1.822993e+04, + -4.400956e+04, + -6.947860e+03, + 7.730975e+03, + 1.868663e+04, + 2.524433e+04, + -1.107087e+04, + 6.479718e+03, + 1.910332e+04, + -1.159559e+04, + -5.722883e+03, + 5.403721e+03, + 1.946613e+04, + 8.803311e+03, + -6.362971e+03, + 4.509957e+03, + 1.979080e+04, + -7.832658e+03, + -3.602953e+03, + 3.758517e+03, + 2.007421e+04, + -6.382527e+03, + -3.252304e+03, + 3.110174e+03, + 2.032548e+04, + 1.111503e+03, + -3.330009e+03, + 2.499038e+03, + 2.054191e+04, + -6.645172e+03, + -1.857684e+03, + 1.983350e+03, + 2.072246e+04, + -4.647336e+02, + -2.123280e+03, + 1.524736e+03, + 2.087328e+04, + -1.619462e+04, + -7.161461e+01, + 1.135444e+03, + 2.099191e+04, + -1.145722e+04, + -5.148367e+02, + 6.981336e+02, + 2.108415e+04, + -8.317955e+03, + -3.174918e+01, + 2.682136e+02, + 2.113680e+04, + 6.686770e+09, + -5.232905e+04, + 9.004540e+01, + 8.220978e-02, + -1.221062e+09, + 1.938090e+05, + 9.420210e+01, + 8.378067e-02, + 9.327238e+07, + -6.870038e+04, + 8.763799e+01, + 9.582414e-02, + 5.996937e+07, + -4.274478e+04, + 7.265223e+01, + 1.204347e-01, + -1.133786e+07, + 6.147611e+04, + 9.131150e+01, + 1.649432e-01, + 3.386784e+05, + 5.305621e+04, + 1.829889e+02, + 3.157484e-01, + 3.484062e+06, + 8.082698e+04, + 3.519414e+02, + 7.346517e-01, + -8.136297e+06, + 2.145670e+05, + 7.559280e+02, + 1.929050e+00, + -1.422495e+07, + 3.782352e+05, + 1.798927e+03, + 5.751019e+00, + -1.921481e+07, + 5.817554e+05, + 4.031473e+03, + 1.702790e+01, + -2.466374e+07, + 8.092501e+05, + 8.208813e+03, + 4.659724e+01, + -2.957367e+07, + 9.988951e+05, + 1.503472e+04, + 1.151984e+02, + -2.934849e+07, + 1.043498e+06, + 2.455141e+04, + 2.553897e+02, + -2.437625e+07, + 9.281228e+05, + 3.566919e+04, + 5.065714e+02, + -1.808598e+07, + 7.249953e+05, + 4.667018e+04, + 9.049815e+02, + -1.413967e+07, + 5.250627e+05, + 5.602253e+04, + 1.475116e+03, + -9.253251e+06, + 3.021326e+05, + 6.252165e+04, + 2.225350e+03, + -4.436136e+06, + 1.093543e+05, + 6.552585e+04, + 3.139939e+03, + -4.814005e+06, + 5.669314e+04, + 6.565072e+04, + 4.187778e+03, + -1.840489e+06, + -6.337635e+04, + 6.313183e+04, + 5.341067e+03, + -6.904183e+05, + -1.012176e+05, + 5.850287e+04, + 6.544246e+03, + -7.497582e+05, + -9.311380e+04, + 5.312391e+04, + 7.761001e+03, + -4.210654e+05, + -9.618680e+04, + 4.738566e+04, + 8.967658e+03, + 8.995083e+04, + -9.946898e+04, + 4.148243e+04, + 1.013491e+04, + -2.075976e+05, + -7.103257e+04, + 3.602031e+04, + 1.124072e+04, + 8.338291e+04, + -7.078879e+04, + 3.100960e+04, + 1.228431e+04, + -2.730415e+04, + -5.205078e+04, + 2.653114e+04, + 1.325030e+04, + 2.150946e+04, + -4.459231e+04, + 2.264211e+04, + 1.414394e+04, + -1.423980e+04, + -3.417936e+04, + 1.925258e+04, + 1.496260e+04, + 1.473821e+04, + -2.918906e+04, + 1.630554e+04, + 1.571000e+04, + 3.220392e+04, + -2.405451e+04, + 1.376762e+04, + 1.638610e+04, + -2.684524e+04, + -1.571254e+04, + 1.167668e+04, + 1.699638e+04, + 3.088042e+04, + -1.651758e+04, + 9.851958e+03, + 1.755058e+04, + -1.721349e+04, + -9.750730e+03, + 8.323807e+03, + 1.804451e+04, + 1.345637e+04, + -1.027197e+04, + 7.017991e+03, + 1.849141e+04, + -2.174811e+04, + -5.602956e+03, + 5.906349e+03, + 1.888762e+04, + 1.177125e+04, + -7.439854e+03, + 4.898836e+03, + 1.924275e+04, + 1.647970e+03, + -4.795697e+03, + 4.041270e+03, + 1.954881e+04, + -5.843917e+03, + -3.222697e+03, + 3.369872e+03, + 1.981799e+04, + -9.789821e+03, + -2.446804e+03, + 2.772770e+03, + 2.005474e+04, + -1.378097e+03, + -2.879752e+03, + 2.186681e+03, + 2.025740e+04, + -6.290251e+03, + -1.724383e+03, + 1.668369e+03, + 2.042133e+04, + -1.101343e+04, + -9.097999e+02, + 1.211492e+03, + 2.055181e+04, + -1.111452e+04, + -5.639870e+02, + 7.532181e+02, + 2.064806e+04, + -8.320836e+03, + -1.432660e+02, + 3.235242e+02, + 2.070595e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.472727e+07, + 9.704940e+03, + 0, + 0, + -2.351848e+05, + 1.879504e+02, + 1.617783e+00, + 5.236292e-04, + 8.699198e+05, + -9.875575e+02, + 1.570521e+00, + 1.570887e-03, + -6.250379e+05, + 4.145386e+03, + 2.379199e+00, + 3.141775e-03, + 4.286236e+05, + 4.412056e+03, + 1.077048e+01, + 1.466162e-02, + -2.043447e+06, + 3.157819e+04, + 3.625093e+01, + 6.388276e-02, + -1.085061e+06, + 6.162908e+04, + 1.682113e+02, + 3.869620e-01, + -6.697354e+06, + 1.915110e+05, + 5.837246e+02, + 1.821706e+00, + -1.347910e+07, + 3.939200e+05, + 1.934535e+03, + 8.045039e+00, + -1.740487e+07, + 5.943821e+05, + 5.113283e+03, + 2.940335e+01, + -2.005659e+07, + 7.567963e+05, + 1.080316e+04, + 8.665382e+01, + -1.933757e+07, + 8.074300e+05, + 1.910717e+04, + 2.128584e+02, + -1.922524e+07, + 7.785521e+05, + 2.917605e+04, + 4.485973e+02, + -1.197210e+07, + 5.629568e+05, + 3.928913e+04, + 8.333176e+02, + -9.951533e+06, + 4.244022e+05, + 4.773463e+04, + 1.385596e+03, + -6.709627e+06, + 2.506304e+05, + 5.376726e+04, + 2.114235e+03, + -3.571100e+06, + 9.933375e+04, + 5.665657e+04, + 3.002215e+03, + -2.574425e+06, + 2.579319e+04, + 5.681603e+04, + 4.016538e+03, + -1.456834e+06, + -3.525546e+04, + 5.484294e+04, + 5.124406e+03, + -8.939211e+05, + -6.390266e+04, + 5.124523e+04, + 6.284900e+03, + -1.101180e+05, + -8.746416e+04, + 4.665656e+04, + 7.461369e+03, + -4.681458e+05, + -6.529437e+04, + 4.184970e+04, + 8.621092e+03, + -4.045757e+03, + -7.596463e+04, + 3.697388e+04, + 9.752269e+03, + -1.734660e+04, + -6.231731e+04, + 3.224549e+04, + 1.082680e+04, + -9.987665e+04, + -4.861101e+04, + 2.799504e+04, + 1.184010e+04, + 7.265535e+04, + -4.826171e+04, + 2.406867e+04, + 1.278797e+04, + -1.134999e+04, + -3.441852e+04, + 2.062683e+04, + 1.365988e+04, + 6.090832e+03, + -2.914563e+04, + 1.767500e+04, + 1.446480e+04, + -6.974627e+02, + -2.329559e+04, + 1.508844e+04, + 1.520183e+04, + -1.472800e+04, + -1.825859e+04, + 1.284207e+04, + 1.587375e+04, + 3.206836e+04, + -1.770135e+04, + 1.085176e+04, + 1.648269e+04, + -2.032028e+03, + -1.153400e+04, + 9.204911e+03, + 1.702789e+04, + -2.968679e+04, + -7.797147e+03, + 7.845514e+03, + 1.752289e+04, + 3.245165e+04, + -1.117046e+04, + 6.548123e+03, + 1.796936e+04, + -1.709462e+04, + -4.558688e+03, + 5.505584e+03, + 1.835768e+04, + -9.796017e+03, + -4.811111e+03, + 4.633948e+03, + 1.870978e+04, + 3.674447e+03, + -5.128812e+03, + 3.778722e+03, + 1.901758e+04, + 1.967537e+02, + -3.600181e+03, + 3.057183e+03, + 1.927876e+04, + -1.317163e+04, + -1.679278e+03, + 2.480028e+03, + 1.950210e+04, + -2.183190e+03, + -2.611229e+03, + 1.910794e+03, + 1.969236e+04, + -1.531156e+04, + -6.658682e+02, + 1.393683e+03, + 1.984029e+04, + -1.371122e+04, + -5.957229e+02, + 8.684685e+02, + 1.995218e+04, + -1.023819e+04, + -8.502304e+01, + 3.579622e+02, + 2.001862e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.585623e+03, + 2.130250e+02, + 0, + 0, + -1.935079e+05, + 3.900197e+03, + 9.971148e-01, + 1.570887e-03, + -6.527066e+05, + 1.858015e+04, + 2.205255e+01, + 4.974477e-02, + -1.500053e+06, + 6.028248e+04, + 1.529140e+02, + 4.916878e-01, + -4.974313e+06, + 1.764505e+05, + 6.943200e+02, + 3.048045e+00, + -8.678217e+06, + 3.342531e+05, + 2.410493e+03, + 1.446892e+01, + -1.052839e+07, + 4.688102e+05, + 6.113438e+03, + 5.121774e+01, + -1.280428e+07, + 5.701865e+05, + 1.214618e+04, + 1.417166e+02, + -9.465653e+06, + 5.125406e+05, + 2.000545e+04, + 3.248129e+02, + -9.176467e+06, + 4.685079e+05, + 2.835925e+04, + 6.344485e+02, + -6.639283e+06, + 3.383421e+05, + 3.609536e+04, + 1.101131e+03, + -3.945560e+06, + 2.017257e+05, + 4.181661e+04, + 1.731452e+03, + -3.291661e+06, + 1.255684e+05, + 4.524933e+04, + 2.513072e+03, + -1.322687e+06, + 2.510134e+04, + 4.636870e+04, + 3.426583e+03, + -1.300582e+06, + 1.614129e+03, + 4.558508e+04, + 4.432770e+03, + -4.698930e+05, + -4.109357e+04, + 4.343189e+04, + 5.505804e+03, + -4.863562e+05, + -4.316647e+04, + 4.031339e+04, + 6.606426e+03, + -1.901139e+05, + -5.444630e+04, + 3.665707e+04, + 7.711348e+03, + 5.980810e+04, + -5.772322e+04, + 3.272677e+04, + 8.791214e+03, + -1.495518e+05, + -3.987647e+04, + 2.904712e+04, + 9.828835e+03, + -6.078588e+04, + -3.976407e+04, + 2.555865e+04, + 1.082406e+04, + 5.486112e+04, + -3.893029e+04, + 2.216912e+04, + 1.175926e+04, + 1.144987e+04, + -2.896840e+04, + 1.918876e+04, + 1.262592e+04, + -5.371250e+04, + -2.059823e+04, + 1.665072e+04, + 1.343193e+04, + 5.297801e+04, + -2.371871e+04, + 1.429575e+04, + 1.417935e+04, + -5.458191e+04, + -1.220823e+04, + 1.227995e+04, + 1.485766e+04, + 2.920703e+04, + -1.633866e+04, + 1.045753e+04, + 1.548314e+04, + -2.082029e+03, + -1.050044e+04, + 8.856110e+03, + 1.604077e+04, + -2.664664e+03, + -8.621342e+03, + 7.539708e+03, + 1.654564e+04, + -1.404636e+04, + -6.326128e+03, + 6.381937e+03, + 1.699969e+04, + 1.024075e+04, + -7.296601e+03, + 5.310162e+03, + 1.740478e+04, + -1.510660e+04, + -3.541083e+03, + 4.411345e+03, + 1.775632e+04, + 3.804952e+03, + -4.830017e+03, + 3.602141e+03, + 1.806686e+04, + -1.490810e+04, + -2.032319e+03, + 2.896991e+03, + 1.832807e+04, + -1.242364e+03, + -3.160581e+03, + 2.230378e+03, + 1.855009e+04, + -1.894988e+04, + -6.198991e+02, + 1.637798e+03, + 1.872279e+04, + -1.737924e+04, + -5.863084e+02, + 1.025930e+03, + 1.885493e+04, + -1.268231e+04, + -3.096204e+01, + 4.118873e+02, + 1.893342e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -5.049934e+03, + 5.631291e+01, + 0, + 0, + 6.967623e+03, + 1.862467e+01, + 2.093108e-01, + 5.236292e-04, + -7.322636e+04, + 2.442067e+03, + 8.394707e-01, + 2.618146e-03, + -3.181040e+05, + 1.374125e+04, + 2.155526e+01, + 7.330808e-02, + -1.148779e+06, + 5.153572e+04, + 1.649367e+02, + 7.624041e-01, + -2.733073e+06, + 1.274952e+05, + 7.729699e+02, + 4.857184e+00, + -4.098947e+06, + 2.168990e+05, + 2.448323e+03, + 2.118970e+01, + -5.332313e+06, + 2.988307e+05, + 5.711927e+03, + 6.820689e+01, + -5.635984e+06, + 3.325101e+05, + 1.066895e+04, + 1.751199e+02, + -4.580008e+06, + 3.018134e+05, + 1.668111e+04, + 3.755809e+02, + -3.996023e+06, + 2.577529e+05, + 2.279537e+04, + 6.973693e+02, + -2.766915e+06, + 1.817487e+05, + 2.816438e+04, + 1.159531e+03, + -1.990806e+06, + 1.182930e+05, + 3.210268e+04, + 1.762734e+03, + -1.289423e+06, + 6.188542e+04, + 3.442340e+04, + 2.495993e+03, + -8.057612e+05, + 2.131305e+04, + 3.517139e+04, + 3.336770e+03, + -4.410684e+05, + -6.496765e+03, + 3.463019e+04, + 4.257853e+03, + -4.309360e+05, + -1.502963e+04, + 3.317952e+04, + 5.231419e+03, + -1.311448e+05, + -3.210778e+04, + 3.100030e+04, + 6.234108e+03, + -4.415939e+04, + -3.380143e+04, + 2.839568e+04, + 7.235375e+03, + -1.499349e+05, + -2.599550e+04, + 2.576558e+04, + 8.220003e+03, + 1.383474e+04, + -3.242390e+04, + 2.304396e+04, + 9.179023e+03, + -2.218020e+04, + -2.541662e+04, + 2.039304e+04, + 1.009087e+04, + -1.073837e+04, + -2.250757e+04, + 1.797035e+04, + 1.095521e+04, + -2.943186e+03, + -1.953326e+04, + 1.573007e+04, + 1.176649e+04, + -1.123711e+04, + -1.592828e+04, + 1.370204e+04, + 1.252187e+04, + 2.490499e+03, + -1.435292e+04, + 1.186123e+04, + 1.322100e+04, + -1.794959e+04, + -1.053958e+04, + 1.022032e+04, + 1.386157e+04, + 7.179634e+03, + -1.085313e+04, + 8.718724e+03, + 1.444657e+04, + 8.523870e+02, + -8.182112e+03, + 7.395488e+03, + 1.497070e+04, + -1.097305e+04, + -5.802531e+03, + 6.280139e+03, + 1.544169e+04, + -8.647890e+03, + -5.258780e+03, + 5.262032e+03, + 1.586351e+04, + -5.795295e+03, + -4.678129e+03, + 4.303340e+03, + 1.623208e+04, + -6.554213e+03, + -3.732850e+03, + 3.435184e+03, + 1.654581e+04, + -7.571927e+03, + -2.901504e+03, + 2.660403e+03, + 1.680635e+04, + -2.053198e+04, + -1.047036e+03, + 1.963335e+03, + 1.701494e+04, + -2.185000e+04, + -5.709901e+02, + 1.230253e+03, + 1.717247e+04, + -1.551733e+04, + -6.146695e+00, + 4.907671e+02, + 1.726691e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -7.205704e+02, + 2.019571e+01, + 0, + 0, + 5.648551e+02, + 8.455095e+01, + 1.600871e-01, + 5.236292e-04, + -2.062497e+04, + 1.347926e+03, + 1.396682e+00, + 5.759921e-03, + -1.861333e+05, + 9.330316e+03, + 1.914727e+01, + 9.425325e-02, + -4.557963e+05, + 2.826252e+04, + 1.454540e+02, + 9.482924e-01, + -9.818830e+05, + 6.498886e+04, + 5.985040e+02, + 5.287607e+00, + -1.707438e+06, + 1.141619e+05, + 1.758923e+03, + 2.087971e+01, + -2.036629e+06, + 1.496179e+05, + 3.958518e+03, + 6.352460e+01, + -2.012618e+06, + 1.637584e+05, + 7.165573e+03, + 1.556844e+02, + -1.950650e+06, + 1.617404e+05, + 1.107139e+04, + 3.226943e+02, + -1.667168e+06, + 1.387401e+05, + 1.516993e+04, + 5.881769e+02, + -1.142383e+06, + 1.009370e+05, + 1.883831e+04, + 9.663550e+02, + -7.952061e+05, + 6.944554e+04, + 2.170582e+04, + 1.458843e+03, + -7.726009e+05, + 5.004691e+04, + 2.370696e+04, + 2.060531e+03, + -2.850905e+05, + 1.452110e+04, + 2.467497e+04, + 2.760501e+03, + -3.098623e+05, + 7.430022e+03, + 2.475227e+04, + 3.532009e+03, + -2.339934e+05, + -3.779062e+03, + 2.420063e+04, + 4.361069e+03, + 9.185211e+03, + -1.890242e+04, + 2.300010e+04, + 5.223842e+03, + -1.739850e+05, + -8.944235e+03, + 2.156361e+04, + 6.095069e+03, + -2.235243e+04, + -1.943860e+04, + 1.989104e+04, + 6.972243e+03, + 1.198136e+04, + -1.908709e+04, + 1.800541e+04, + 7.826082e+03, + -5.284415e+04, + -1.280211e+04, + 1.625202e+04, + 8.649491e+03, + 7.936083e+03, + -1.590172e+04, + 1.452061e+04, + 9.442641e+03, + -3.481822e+04, + -1.076757e+04, + 1.285434e+04, + 1.018969e+04, + 2.668691e+04, + -1.397913e+04, + 1.125258e+04, + 1.089268e+04, + -4.318571e+04, + -6.253629e+03, + 9.834934e+03, + 1.153860e+04, + 1.098736e+04, + -1.042348e+04, + 8.469408e+03, + 1.214108e+04, + -2.425142e+02, + -7.313199e+03, + 7.189537e+03, + 1.267873e+04, + -2.017386e+04, + -4.486061e+03, + 6.121964e+03, + 1.316283e+04, + -2.992189e+03, + -5.709493e+03, + 5.078553e+03, + 1.359667e+04, + -9.666249e+03, + -3.987421e+03, + 4.098707e+03, + 1.396771e+04, + -1.813279e+04, + -2.576703e+03, + 3.213557e+03, + 1.428080e+04, + -1.133652e+04, + -2.823670e+03, + 2.323008e+03, + 1.453377e+04, + -3.741587e+04, + 7.057299e+02, + 1.498721e+03, + 1.471689e+04, + -1.584264e+04, + -3.098032e+02, + 5.619166e+02, + 1.483525e+04, +}; + +double solarDataset640[] = +{ + -4.439940e+13, + 4.727269e+08, + 1.531960e+05, + 2.789585e+03, + 1.591240e+12, + -3.752929e+08, + 1.299147e+05, + 2.792139e+03, + -1.520825e+10, + 9.464386e+06, + 1.088507e+05, + 2.805146e+03, + 4.968166e+09, + -3.484485e+06, + 1.101562e+05, + 2.841278e+03, + -1.879797e+09, + 4.089612e+06, + 1.117743e+05, + 2.911407e+03, + 3.175884e+08, + -3.936103e+05, + 1.141396e+05, + 3.031274e+03, + -1.247720e+08, + 7.638848e+05, + 1.152491e+05, + 3.210576e+03, + -5.488648e+07, + 3.411906e+05, + 1.167998e+05, + 3.465231e+03, + 7.500485e+07, + -2.624350e+05, + 1.173902e+05, + 3.807030e+03, + -7.626345e+07, + 6.188938e+05, + 1.185754e+05, + 4.246394e+03, + -3.559987e+07, + 1.218147e+05, + 1.193649e+05, + 4.806045e+03, + -5.712451e+04, + -2.445439e+05, + 1.172780e+05, + 5.484460e+03, + -2.917238e+07, + 2.280130e+04, + 1.139230e+05, + 6.275571e+03, + -5.538333e+06, + -3.268659e+05, + 1.085716e+05, + 7.182661e+03, + -1.121999e+07, + -2.401591e+05, + 1.009303e+05, + 8.172688e+03, + -2.076868e+06, + -3.706500e+05, + 9.172349e+04, + 9.227661e+03, + -3.291261e+06, + -2.970064e+05, + 8.154785e+04, + 1.030640e+04, + -1.434784e+06, + -2.886252e+05, + 7.122383e+04, + 1.138676e+04, + -1.028562e+06, + -2.454059e+05, + 6.099909e+04, + 1.243693e+04, + 5.490447e+05, + -2.301291e+05, + 5.134306e+04, + 1.343419e+04, + -3.430376e+05, + -1.558810e+05, + 4.292772e+04, + 1.435918e+04, + 1.571421e+03, + -1.323344e+05, + 3.566474e+04, + 1.521511e+04, + 9.796970e+04, + -1.046920e+05, + 2.933950e+04, + 1.599219e+04, + 3.387552e+04, + -7.798390e+04, + 2.405845e+04, + 1.669041e+04, + 8.586974e+04, + -6.144906e+04, + 1.968644e+04, + 1.731476e+04, + 2.430737e+04, + -4.445872e+04, + 1.611932e+04, + 1.786927e+04, + 8.554925e+04, + -3.643019e+04, + 1.321141e+04, + 1.836202e+04, + -4.184780e+04, + -2.225372e+04, + 1.090368e+04, + 1.879790e+04, + 1.450911e+04, + -2.047436e+04, + 8.970817e+03, + 1.918782e+04, + 5.758854e+04, + -1.762438e+04, + 7.327434e+03, + 1.952962e+04, + -2.647884e+04, + -8.760163e+03, + 6.090933e+03, + 1.982896e+04, + 9.619644e+03, + -9.392713e+03, + 5.064150e+03, + 2.009878e+04, + 1.331023e+04, + -7.397082e+03, + 4.176136e+03, + 2.033522e+04, + -1.686056e+04, + -3.825364e+03, + 3.487137e+03, + 2.054344e+04, + 1.693753e+04, + -5.541195e+03, + 2.872701e+03, + 2.072965e+04, + -8.264414e+03, + -2.280044e+03, + 2.383048e+03, + 2.088944e+04, + 4.622434e+03, + -2.963743e+03, + 1.980519e+03, + 2.103278e+04, + -5.561131e+03, + -1.469762e+03, + 1.637947e+03, + 2.115668e+04, + -5.453383e+02, + -1.717846e+03, + 1.335926e+03, + 2.126589e+04, + -4.010140e+02, + -1.347042e+03, + 1.062944e+03, + 2.135796e+04, + 1.078165e+02, + -1.080735e+03, + 8.377248e+02, + 2.143475e+04, + -4.695232e+03, + -3.873397e+02, + 6.567006e+02, + 2.149810e+04, + -3.120412e+03, + -5.195693e+02, + 4.759587e+02, + 2.155020e+04, + -6.441655e+03, + 1.058743e+00, + 2.972071e+02, + 2.158758e+04, + -3.280148e+03, + -4.465469e+01, + 1.123506e+02, + 2.161064e+04, + -2.992526e+13, + 3.093632e+08, + 1.285107e+05, + 1.370598e+03, + 1.480405e+12, + -3.114235e+08, + 1.125000e+05, + 1.372752e+03, + -1.218458e+11, + 6.632321e+07, + 1.020083e+05, + 1.384393e+03, + 1.665317e+10, + -1.847940e+07, + 1.062419e+05, + 1.420637e+03, + -9.113149e+08, + 3.008784e+06, + 1.029925e+05, + 1.485201e+03, + 1.490734e+08, + 6.212466e+05, + 1.062972e+05, + 1.595766e+03, + -1.105384e+08, + 1.142941e+06, + 1.093467e+05, + 1.764612e+03, + -5.228906e+06, + 5.746185e+05, + 1.127616e+05, + 2.008312e+03, + -4.552848e+07, + 6.442601e+05, + 1.159764e+05, + 2.341555e+03, + -3.742689e+07, + 4.419059e+05, + 1.188852e+05, + 2.782009e+03, + -3.101838e+07, + 2.582848e+05, + 1.205636e+05, + 3.343203e+03, + -2.861615e+07, + 1.118720e+05, + 1.204816e+05, + 4.033752e+03, + -1.284625e+07, + -1.383981e+05, + 1.179923e+05, + 4.854326e+03, + -1.827905e+07, + -1.249114e+05, + 1.132356e+05, + 5.792405e+03, + -3.759817e+06, + -3.523765e+05, + 1.060046e+05, + 6.833684e+03, + -8.330140e+06, + -2.577154e+05, + 9.700446e+04, + 7.940175e+03, + -1.445189e+06, + -3.560434e+05, + 8.673825e+04, + 9.089991e+03, + -2.022213e+06, + -2.868506e+05, + 7.584981e+04, + 1.023690e+04, + -2.065185e+05, + -2.739897e+05, + 6.523903e+04, + 1.135845e+04, + -2.118780e+05, + -2.174656e+05, + 5.534385e+04, + 1.242638e+04, + -3.909280e+05, + -1.684039e+05, + 4.654358e+04, + 1.342916e+04, + 1.510131e+05, + -1.471904e+05, + 3.866829e+04, + 1.435729e+04, + 1.105359e+05, + -1.114876e+05, + 3.188896e+04, + 1.519973e+04, + 2.486681e+04, + -8.288938e+04, + 2.627788e+04, + 1.596027e+04, + 8.548810e+04, + -6.590200e+04, + 2.160359e+04, + 1.664380e+04, + 1.020428e+04, + -4.763506e+04, + 1.775888e+04, + 1.725353e+04, + 9.132896e+04, + -3.989775e+04, + 1.458947e+04, + 1.779729e+04, + -5.893551e+04, + -2.401330e+04, + 1.205272e+04, + 1.827892e+04, + 8.786788e+04, + -2.590156e+04, + 9.903800e+03, + 1.871007e+04, + -4.375724e+04, + -1.286701e+04, + 8.192812e+03, + 1.908692e+04, + 3.806013e+04, + -1.494288e+04, + 6.768657e+03, + 1.942561e+04, + -2.022679e+04, + -7.996085e+03, + 5.595118e+03, + 1.972091e+04, + 4.406976e+04, + -1.028506e+04, + 4.614651e+03, + 1.998424e+04, + -3.557882e+04, + -2.482117e+03, + 3.885495e+03, + 2.021282e+04, + 1.494002e+04, + -6.049385e+03, + 3.237819e+03, + 2.042301e+04, + -4.199329e+03, + -3.113389e+03, + 2.662895e+03, + 2.060288e+04, + 3.034471e+03, + -3.103970e+03, + 2.203542e+03, + 2.076205e+04, + 1.633791e+03, + -2.268264e+03, + 1.819033e+03, + 2.090013e+04, + -1.012340e+04, + -8.623465e+02, + 1.515031e+03, + 2.102106e+04, + 2.750467e+03, + -2.003038e+03, + 1.204360e+03, + 2.112756e+04, + -6.190024e-03, + -1.186111e+03, + 9.348330e+02, + 2.121315e+04, + -5.805871e+03, + -3.823047e+02, + 7.336037e+02, + 2.128391e+04, + -3.542666e+03, + -5.948154e+02, + 5.273264e+02, + 2.134212e+04, + -5.934580e+03, + -1.228610e+02, + 3.234636e+02, + 2.138330e+04, + -4.084604e+03, + -1.983933e+00, + 1.289217e+02, + 2.140821e+04, + -3.727579e+12, + 5.679231e+08, + -1.625664e+04, + 4.250653e+02, + -4.419365e+12, + 1.046109e+09, + 0, + 4.249347e+02, + 3.326869e+10, + -2.023689e+07, + 5.941925e+04, + 4.324018e+02, + 3.471040e+09, + -1.203176e+06, + 5.686938e+04, + 4.508607e+02, + -6.372727e+08, + 3.160899e+06, + 5.957054e+04, + 4.875431e+02, + 2.755881e+08, + 1.055176e+06, + 6.410412e+04, + 5.529359e+02, + -1.275647e+08, + 1.970311e+06, + 6.944887e+04, + 6.571524e+02, + 5.075274e+07, + 1.126893e+06, + 7.624159e+04, + 8.172947e+02, + -8.482724e+07, + 1.658999e+06, + 8.409947e+04, + 1.050219e+03, + -6.311669e+07, + 1.260619e+06, + 9.295005e+04, + 1.383576e+03, + -4.552108e+07, + 8.872372e+05, + 1.005958e+05, + 1.838863e+03, + -3.875198e+07, + 6.047687e+05, + 1.062746e+05, + 2.433263e+03, + -1.845368e+07, + 2.163822e+05, + 1.091074e+05, + 3.176447e+03, + -2.407756e+07, + 1.539447e+05, + 1.089878e+05, + 4.062922e+03, + -9.843639e+06, + -1.515457e+05, + 1.054688e+05, + 5.084079e+03, + -6.115161e+06, + -2.330786e+05, + 9.867827e+04, + 6.200673e+03, + -4.041083e+06, + -2.626724e+05, + 9.005089e+04, + 7.379350e+03, + -2.210499e+06, + -2.717189e+05, + 8.024778e+04, + 8.584178e+03, + -7.206211e+05, + -2.613685e+05, + 6.997467e+04, + 9.778451e+03, + -3.314310e+05, + -2.216301e+05, + 6.004300e+04, + 1.093132e+04, + -3.603027e+05, + -1.775358e+05, + 5.094016e+04, + 1.202401e+04, + 1.605319e+04, + -1.514987e+05, + 4.271129e+04, + 1.304370e+04, + 2.002792e+05, + -1.228584e+05, + 3.549450e+04, + 1.397850e+04, + -8.648454e+04, + -8.570485e+04, + 2.947253e+04, + 1.482726e+04, + 1.357791e+05, + -7.475766e+04, + 2.436487e+04, + 1.559714e+04, + -3.989941e+03, + -5.194180e+04, + 2.011571e+04, + 1.628557e+04, + 8.306635e+04, + -4.386703e+04, + 1.660847e+04, + 1.690318e+04, + -2.096461e+04, + -2.912937e+04, + 1.375069e+04, + 1.745251e+04, + 5.301057e+04, + -2.639084e+04, + 1.137582e+04, + 1.794452e+04, + -3.157995e+04, + -1.607394e+04, + 9.439187e+03, + 1.837976e+04, + 5.385344e+04, + -1.741312e+04, + 7.800361e+03, + 1.876916e+04, + -2.015355e+04, + -8.869094e+03, + 6.498800e+03, + 1.911013e+04, + -2.198646e+03, + -8.557864e+03, + 5.429310e+03, + 1.941755e+04, + 2.183501e+04, + -8.210271e+03, + 4.474652e+03, + 1.968824e+04, + -1.617257e+04, + -3.638040e+03, + 3.742270e+03, + 1.992456e+04, + 1.241488e+04, + -5.232775e+03, + 3.110539e+03, + 2.013736e+04, + -1.201730e+04, + -2.114134e+03, + 2.586648e+03, + 2.032131e+04, + 4.745978e+03, + -3.261955e+03, + 2.124178e+03, + 2.048556e+04, + 1.127970e+03, + -2.123757e+03, + 1.725024e+03, + 2.062462e+04, + -7.597785e+03, + -9.417226e+02, + 1.419309e+03, + 2.074488e+04, + 1.883744e+03, + -1.753948e+03, + 1.118928e+03, + 2.084928e+04, + -6.322678e+03, + -5.176974e+02, + 8.620266e+02, + 2.093272e+04, + -1.605836e+03, + -9.285398e+02, + 6.193314e+02, + 2.100093e+04, + -1.097960e+04, + 3.171899e+02, + 4.038220e+02, + 2.104937e+04, + -4.141973e+03, + -9.836002e+01, + 1.504665e+02, + 2.108164e+04, + -2.330422e+13, + 2.884024e+08, + 3.068028e+04, + 6.138150e+01, + 4.881998e+11, + -1.148322e+08, + 1.984912e+04, + 6.187669e+01, + 1.916792e+09, + 9.729664e+05, + 1.346125e+04, + 6.345753e+01, + -6.675440e+08, + 2.022162e+06, + 1.471542e+04, + 6.803805e+01, + 3.159170e+08, + 5.956514e+05, + 1.648024e+04, + 7.807293e+01, + 1.478614e+08, + 9.030786e+05, + 1.878080e+04, + 9.642790e+01, + -3.518216e+07, + 1.443802e+06, + 2.270551e+04, + 1.286811e+02, + 1.119347e+07, + 1.312378e+06, + 2.852122e+04, + 1.849385e+02, + -7.701323e+07, + 1.801352e+06, + 3.645263e+04, + 2.794408e+02, + -4.292657e+07, + 1.527104e+06, + 4.669619e+04, + 4.369697e+02, + -5.878099e+07, + 1.547497e+06, + 5.815348e+04, + 6.840577e+02, + -4.645158e+07, + 1.228475e+06, + 7.007176e+04, + 1.055326e+03, + -3.318499e+07, + 8.600360e+05, + 8.035939e+04, + 1.577501e+03, + -2.625219e+07, + 5.584589e+05, + 8.775849e+04, + 2.265846e+03, + -1.490142e+07, + 2.204949e+05, + 9.128794e+04, + 3.120972e+03, + -9.255229e+06, + 2.252877e+04, + 9.079563e+04, + 4.120827e+03, + -7.977564e+06, + -6.768208e+04, + 8.706674e+04, + 5.234990e+03, + -1.201566e+06, + -2.257152e+05, + 8.041358e+04, + 6.425469e+03, + -2.557683e+06, + -1.738737e+05, + 7.235760e+04, + 7.637924e+03, + -6.451356e+05, + -2.017795e+05, + 6.379658e+04, + 8.850205e+03, + -3.054659e+05, + -1.757830e+05, + 5.511053e+04, + 1.002201e+04, + 4.282739e+03, + -1.507765e+05, + 4.703559e+04, + 1.113375e+04, + -6.875119e+04, + -1.179384e+05, + 3.983315e+04, + 1.217219e+04, + -6.539296e+04, + -9.429366e+04, + 3.351548e+04, + 1.313309e+04, + 1.390880e+05, + -8.139794e+04, + 2.796880e+04, + 1.401195e+04, + 1.433916e+04, + -5.814147e+04, + 2.331691e+04, + 1.480596e+04, + 4.800799e+04, + -4.699949e+04, + 1.945486e+04, + 1.552491e+04, + 3.355324e+04, + -3.590662e+04, + 1.623079e+04, + 1.617181e+04, + -4.753516e+04, + -2.457913e+04, + 1.357598e+04, + 1.675372e+04, + 4.184174e+04, + -2.433031e+04, + 1.125925e+04, + 1.727713e+04, + 1.681958e+04, + -1.719019e+04, + 9.323416e+03, + 1.773841e+04, + 1.359243e+04, + -1.318457e+04, + 7.786144e+03, + 1.814905e+04, + -1.223584e+04, + -8.858780e+03, + 6.540344e+03, + 1.851573e+04, + 6.675612e+03, + -8.506817e+03, + 5.462955e+03, + 1.884458e+04, + 9.691761e+03, + -6.794523e+03, + 4.542950e+03, + 1.913430e+04, + -1.311304e+04, + -3.705444e+03, + 3.816631e+03, + 1.939046e+04, + 3.177047e+03, + -4.478421e+03, + 3.166507e+03, + 1.961984e+04, + 1.744567e+02, + -3.216510e+03, + 2.594630e+03, + 1.981779e+04, + -3.774980e+03, + -2.236340e+03, + 2.129548e+03, + 1.998954e+04, + 7.002038e+02, + -2.227548e+03, + 1.720140e+03, + 2.013795e+04, + -5.785630e+03, + -1.144891e+03, + 1.374334e+03, + 2.026261e+04, + -1.111106e+03, + -1.431800e+03, + 1.055204e+03, + 2.036742e+04, + -9.405081e+03, + -2.669856e+02, + 7.737057e+02, + 2.044926e+04, + -7.953502e+03, + -3.131021e+02, + 4.776272e+02, + 2.051154e+04, + -5.955234e+03, + -2.333631e+00, + 1.878496e+02, + 2.054783e+04, + 5.900736e+12, + -6.184322e+07, + -3.127993e+03, + 4.662247e+00, + -2.586883e+11, + 5.655632e+07, + 0, + 4.620175e+00, + 6.674828e+09, + -3.908526e+06, + 2.349221e+03, + 4.989151e+00, + 1.823458e+08, + 2.419007e+05, + 1.936986e+03, + 5.573806e+00, + -9.320896e+07, + 5.604882e+05, + 2.468082e+03, + 6.954925e+00, + 7.579802e+07, + 2.506737e+05, + 3.337623e+03, + 1.006148e+01, + -1.611317e+07, + 6.330473e+05, + 4.683591e+03, + 1.620640e+01, + -1.376354e+07, + 7.637402e+05, + 7.223657e+03, + 2.932462e+01, + -2.583591e+07, + 1.010277e+06, + 1.132308e+04, + 5.650986e+01, + -4.465643e+07, + 1.303261e+06, + 1.779668e+04, + 1.116488e+02, + -4.722198e+07, + 1.403819e+06, + 2.704938e+04, + 2.186730e+02, + -4.285916e+07, + 1.335126e+06, + 3.845701e+04, + 4.099392e+02, + -3.417982e+07, + 1.121722e+06, + 5.070906e+04, + 7.219074e+02, + -2.901563e+07, + 8.791541e+05, + 6.214431e+04, + 1.187121e+03, + -1.838120e+07, + 5.316987e+05, + 7.098441e+04, + 1.826925e+03, + -1.217421e+07, + 2.767583e+05, + 7.602698e+04, + 2.638278e+03, + -7.803981e+06, + 8.631945e+04, + 7.726482e+04, + 3.602555e+03, + -4.483355e+06, + -4.639403e+04, + 7.505263e+04, + 4.686021e+03, + -2.447868e+06, + -1.176936e+05, + 7.020737e+04, + 5.845505e+03, + -1.057698e+06, + -1.499728e+05, + 6.373873e+04, + 7.037935e+03, + -5.877838e+05, + -1.450739e+05, + 5.661180e+04, + 8.225507e+03, + -3.775252e+05, + -1.299298e+05, + 4.947172e+04, + 9.381489e+03, + -4.735522e+04, + -1.179415e+05, + 4.261136e+04, + 1.048487e+04, + -3.826733e+04, + -9.552913e+04, + 3.633754e+04, + 1.151890e+04, + 7.634655e+04, + -8.044760e+04, + 3.078666e+04, + 1.247799e+04, + -1.166207e+04, + -6.027152e+04, + 2.601237e+04, + 1.335852e+04, + -3.488352e+04, + -4.748362e+04, + 2.191882e+04, + 1.416472e+04, + 1.451432e+05, + -4.532720e+04, + 1.833155e+04, + 1.489651e+04, + -1.018718e+05, + -2.331123e+04, + 1.545194e+04, + 1.555285e+04, + 6.092841e+04, + -2.791611e+04, + 1.295407e+04, + 1.615327e+04, + 9.914125e+03, + -1.852473e+04, + 1.081145e+04, + 1.668531e+04, + -1.018421e+04, + -1.364660e+04, + 9.097815e+03, + 1.716368e+04, + 2.677632e+04, + -1.320567e+04, + 7.616752e+03, + 1.759324e+04, + -3.190707e+04, + -6.537187e+03, + 6.413697e+03, + 1.797428e+04, + 3.224420e+04, + -1.002234e+04, + 5.332416e+03, + 1.831827e+04, + -1.790675e+04, + -3.819177e+03, + 4.465077e+03, + 1.861606e+04, + 5.741706e+03, + -5.269812e+03, + 3.739037e+03, + 1.888589e+04, + -7.215146e+03, + -3.071621e+03, + 3.094632e+03, + 1.912037e+04, + -1.751587e+03, + -3.077939e+03, + 2.533371e+03, + 1.932641e+04, + 1.684196e+03, + -2.713112e+03, + 2.030604e+03, + 1.950173e+04, + -5.727454e+03, + -1.411693e+03, + 1.625658e+03, + 1.964880e+04, + -4.801342e+03, + -1.316339e+03, + 1.262519e+03, + 1.977305e+04, + -6.741413e+03, + -8.448004e+02, + 9.137641e+02, + 1.987167e+04, + -1.490630e+04, + 2.471177e+02, + 5.794638e+02, + 1.994416e+04, + -5.125526e+03, + -1.870754e+02, + 1.995830e+02, + 1.998926e+04, + -2.869444e+12, + 4.196504e+07, + 1.111129e+03, + 1.914998e-01, + 7.156578e+09, + -1.295320e+06, + 0, + 2.084253e-01, + -1.403689e+09, + 9.962077e+05, + 0, + 2.021387e-01, + -8.216375e+07, + 1.203012e+05, + 2.008386e+02, + 2.596854e-01, + 6.555093e+07, + -5.683459e+04, + 2.540250e+02, + 4.153999e-01, + -1.211732e+07, + 1.476175e+05, + 3.519336e+02, + 6.958794e-01, + 6.522379e+05, + 1.744630e+05, + 7.256024e+02, + 1.564399e+00, + -1.052628e+07, + 3.516827e+05, + 1.498850e+03, + 3.995866e+00, + -2.574797e+07, + 6.281950e+05, + 3.279889e+03, + 1.108668e+01, + -3.086743e+07, + 8.810812e+05, + 6.898743e+03, + 3.079762e+01, + -3.884285e+07, + 1.142616e+06, + 1.310979e+04, + 7.910539e+01, + -3.943960e+07, + 1.250215e+06, + 2.235506e+04, + 1.838892e+02, + -3.665357e+07, + 1.197647e+06, + 3.392539e+04, + 3.827845e+02, + -2.694963e+07, + 9.520602e+05, + 4.610324e+04, + 7.159656e+02, + -2.036503e+07, + 6.966329e+05, + 5.686927e+04, + 1.212730e+03, + -1.444636e+07, + 4.337031e+05, + 6.479572e+04, + 1.887513e+03, + -7.699672e+06, + 1.790196e+05, + 6.888180e+04, + 2.732083e+03, + -5.257205e+06, + 4.882563e+04, + 6.934273e+04, + 3.716165e+03, + -3.250320e+06, + -4.591330e+04, + 6.693171e+04, + 4.806015e+03, + -1.348332e+06, + -1.107657e+05, + 6.225009e+04, + 5.958500e+03, + -6.591738e+05, + -1.229398e+05, + 5.632815e+04, + 7.129749e+03, + -5.308371e+05, + -1.127866e+05, + 5.004913e+04, + 8.289289e+03, + -2.262225e+05, + -1.068280e+05, + 4.374560e+04, + 9.414179e+03, + 3.731957e+04, + -9.700161e+04, + 3.768587e+04, + 1.048232e+04, + -1.736652e+04, + -7.613110e+04, + 3.223589e+04, + 1.148048e+04, + -2.414547e+04, + -6.138152e+04, + 2.745864e+04, + 1.240735e+04, + 6.789920e+04, + -5.299159e+04, + 2.324807e+04, + 1.326047e+04, + -1.736037e+04, + -3.809564e+04, + 1.966746e+04, + 1.403819e+04, + 2.647414e+04, + -3.277573e+04, + 1.660775e+04, + 1.474812e+04, + 8.534694e+03, + -2.499570e+04, + 1.399418e+04, + 1.538991e+04, + -7.165778e+03, + -1.917919e+04, + 1.179604e+04, + 1.596990e+04, + 1.820885e+04, + -1.685831e+04, + 9.900832e+03, + 1.649223e+04, + 5.374457e+03, + -1.240641e+04, + 8.314451e+03, + 1.695838e+04, + -6.216827e+03, + -9.208817e+03, + 7.007123e+03, + 1.737642e+04, + 6.178700e+03, + -8.349800e+03, + 5.875342e+03, + 1.775088e+04, + -5.600157e+03, + -5.764635e+03, + 4.917613e+03, + 1.808234e+04, + 6.164147e+03, + -5.602643e+03, + 4.094812e+03, + 1.837682e+04, + -9.844895e+03, + -3.124692e+03, + 3.410559e+03, + 1.863437e+04, + 1.870561e+03, + -3.694799e+03, + 2.799852e+03, + 1.886209e+04, + -1.653556e+03, + -2.538690e+03, + 2.266366e+03, + 1.905585e+04, + -7.849600e+03, + -1.504537e+03, + 1.824372e+03, + 1.922132e+04, + -6.752870e+03, + -1.437372e+03, + 1.399671e+03, + 1.936046e+04, + -3.301713e+03, + -1.417094e+03, + 9.829110e+02, + 1.946895e+04, + -1.406390e+04, + 1.486421e+02, + 6.317347e+02, + 1.954571e+04, + -8.038091e+03, + -1.892693e+01, + 2.567819e+02, + 1.959578e+04, + 8.092438e+10, + -1.162467e+06, + -3.206142e+01, + 9.671708e-04, + -5.505060e+08, + 9.964000e+04, + 0, + 4.835854e-04, + 2.752931e+07, + -1.352454e+04, + 0, + 9.671708e-04, + -1.833317e+07, + 2.120320e+04, + 0, + 4.835854e-04, + 2.571019e+06, + -3.649190e+03, + 4.673637e+00, + 4.352269e-03, + -7.491211e+04, + 4.848017e+03, + 5.527414e+00, + 8.220952e-03, + -7.418260e+05, + 1.692347e+04, + 2.018402e+01, + 2.853154e-02, + -2.336180e+06, + 5.229333e+04, + 8.361598e+01, + 1.460428e-01, + -4.201515e+06, + 1.305820e+05, + 3.288177e+02, + 7.756710e-01, + -1.289169e+07, + 3.289640e+05, + 1.129365e+03, + 3.612867e+00, + -1.762035e+07, + 5.566023e+05, + 3.358858e+03, + 1.475322e+01, + -2.747414e+07, + 8.490401e+05, + 7.989587e+03, + 4.876524e+01, + -2.619987e+07, + 9.449800e+05, + 1.575022e+04, + 1.343985e+02, + -2.483176e+07, + 9.407079e+05, + 2.589242e+04, + 3.096513e+02, + -2.096394e+07, + 7.980703e+05, + 3.700925e+04, + 6.166125e+02, + -1.260854e+07, + 5.301678e+05, + 4.692981e+04, + 1.086607e+03, + -1.011947e+07, + 3.644354e+05, + 5.426536e+04, + 1.727560e+03, + -6.162520e+06, + 1.740138e+05, + 5.850899e+04, + 2.535811e+03, + -3.372106e+06, + 4.020494e+04, + 5.938275e+04, + 3.481855e+03, + -2.254455e+06, + -2.599647e+04, + 5.763576e+04, + 4.527013e+03, + -9.857144e+05, + -7.745357e+04, + 5.399678e+04, + 5.633404e+03, + -5.863116e+05, + -8.788475e+04, + 4.923235e+04, + 6.760406e+03, + -1.620644e+05, + -9.249139e+04, + 4.402444e+04, + 7.879244e+03, + -2.699903e+05, + -7.601326e+04, + 3.884746e+04, + 8.965668e+03, + -1.358876e+05, + -7.057037e+04, + 3.384431e+04, + 1.000696e+04, + 1.675314e+05, + -6.959774e+04, + 2.906964e+04, + 1.098559e+04, + -9.302058e+04, + -4.442220e+04, + 2.495681e+04, + 1.189088e+04, + 7.251168e+03, + -4.169873e+04, + 2.136185e+04, + 1.273426e+04, + 5.481866e+04, + -3.555078e+04, + 1.813324e+04, + 1.350642e+04, + -3.479656e+04, + -2.368568e+04, + 1.543658e+04, + 1.420950e+04, + 1.551094e+04, + -2.236704e+04, + 1.309303e+04, + 1.485312e+04, + 1.826623e+04, + -1.782883e+04, + 1.104855e+04, + 1.543299e+04, + 1.003366e+04, + -1.355278e+04, + 9.363013e+03, + 1.595548e+04, + -3.906669e+04, + -7.936198e+03, + 7.972150e+03, + 1.642815e+04, + 3.712882e+04, + -1.211740e+04, + 6.656119e+03, + 1.685648e+04, + -2.359586e+04, + -4.682025e+03, + 5.586378e+03, + 1.722895e+04, + 1.313605e+04, + -7.041172e+03, + 4.675363e+03, + 1.756662e+04, + -8.595405e+03, + -3.626245e+03, + 3.892172e+03, + 1.785962e+04, + -4.083225e+03, + -3.541047e+03, + 3.228339e+03, + 1.812020e+04, + -2.079108e+03, + -3.062724e+03, + 2.613468e+03, + 1.834503e+04, + -4.585763e+03, + -2.207125e+03, + 2.078593e+03, + 1.853488e+04, + -8.379371e+03, + -1.445921e+03, + 1.605151e+03, + 1.869252e+04, + -3.288252e+03, + -1.643252e+03, + 1.148159e+03, + 1.881809e+04, + -1.880134e+04, + 4.395417e+02, + 7.550833e+02, + 1.890833e+04, + -9.040297e+03, + -8.067476e+01, + 3.009619e+02, + 1.896881e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.709387e+03, + 1.221581e+02, + 0, + 0, + -5.051096e+04, + 1.037139e+03, + 3.952580e-01, + 4.835854e-04, + -1.390577e+05, + 5.605787e+03, + 5.152017e+00, + 9.188123e-03, + -1.185086e+06, + 3.357945e+04, + 4.125296e+01, + 9.961860e-02, + -3.324630e+06, + 1.101904e+05, + 2.773980e+02, + 9.043047e-01, + -7.853728e+06, + 2.688967e+05, + 1.210126e+03, + 5.456778e+00, + -1.227331e+07, + 4.602241e+05, + 3.787044e+03, + 2.381416e+01, + -1.502364e+07, + 6.070524e+05, + 8.821902e+03, + 7.802554e+01, + -1.336220e+07, + 6.235281e+05, + 1.626265e+04, + 2.025851e+02, + -1.337434e+07, + 5.982898e+05, + 2.508429e+04, + 4.360495e+02, + -8.551671e+06, + 4.261216e+05, + 3.375827e+04, + 8.145489e+02, + -6.484517e+06, + 2.997790e+05, + 4.067227e+04, + 1.350606e+03, + -3.892800e+06, + 1.628204e+05, + 4.528823e+04, + 2.044370e+03, + -3.174152e+06, + 8.617744e+04, + 4.739307e+04, + 2.875549e+03, + -7.858401e+05, + -1.795473e+04, + 4.709930e+04, + 3.816879e+03, + -1.506677e+06, + -1.051765e+04, + 4.520483e+04, + 4.824117e+03, + -1.654844e+05, + -6.662056e+04, + 4.211810e+04, + 5.878308e+03, + -3.325870e+05, + -5.482462e+04, + 3.828890e+04, + 6.932492e+03, + -1.669931e+05, + -5.691599e+04, + 3.434296e+04, + 7.973661e+03, + 3.176809e+04, + -5.704259e+04, + 3.032616e+04, + 8.979996e+03, + -1.281974e+05, + -4.107245e+04, + 2.659716e+04, + 9.936586e+03, + 5.251609e+04, + -4.338252e+04, + 2.310631e+04, + 1.084227e+04, + -3.310454e+04, + -3.100850e+04, + 1.995372e+04, + 1.168280e+04, + 1.373580e+04, + -2.826584e+04, + 1.717322e+04, + 1.246385e+04, + 1.486695e+04, + -2.286523e+04, + 1.471232e+04, + 1.318078e+04, + -2.699775e+04, + -1.623475e+04, + 1.261542e+04, + 1.383733e+04, + 3.280403e+04, + -1.719400e+04, + 1.073590e+04, + 1.443831e+04, + -2.669848e+04, + -9.678436e+03, + 9.151064e+03, + 1.497882e+04, + 1.838055e+04, + -1.142924e+04, + 7.757786e+03, + 1.547212e+04, + -1.527434e+04, + -6.522392e+03, + 6.559644e+03, + 1.591064e+04, + 6.134069e+03, + -7.241503e+03, + 5.514782e+03, + 1.630624e+04, + -6.323445e+03, + -4.711065e+03, + 4.604267e+03, + 1.665383e+04, + -4.073073e+03, + -4.157336e+03, + 3.818693e+03, + 1.696133e+04, + -3.689038e+03, + -3.435628e+03, + 3.109516e+03, + 1.722780e+04, + -5.989523e+03, + -2.575961e+03, + 2.483016e+03, + 1.745440e+04, + -7.028686e+03, + -2.007072e+03, + 1.916696e+03, + 1.764283e+04, + -1.237906e+04, + -1.066394e+03, + 1.391888e+03, + 1.779266e+04, + -1.530568e+04, + -3.931004e+02, + 8.686103e+02, + 1.790328e+04, + -1.075759e+04, + -3.241883e+01, + 3.519534e+02, + 1.797018e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -3.054978e+04, + 7.410320e+02, + 0, + 0, + -9.722180e+04, + 4.326381e+03, + 4.923375e+00, + 1.305681e-02, + -3.957187e+05, + 2.108857e+04, + 4.479837e+01, + 1.639355e-01, + -2.217090e+06, + 8.601666e+04, + 2.778367e+02, + 1.331311e+00, + -3.595510e+06, + 1.730620e+05, + 1.233921e+03, + 8.028002e+00, + -5.986757e+06, + 2.900617e+05, + 3.538550e+03, + 3.203512e+01, + -6.769567e+06, + 3.551039e+05, + 7.723701e+03, + 9.713732e+01, + -5.667593e+06, + 3.457250e+05, + 1.341347e+04, + 2.349867e+02, + -5.458172e+06, + 3.222378e+05, + 1.977905e+04, + 4.766324e+02, + -3.782412e+06, + 2.373311e+05, + 2.587928e+04, + 8.491315e+02, + -2.850464e+06, + 1.657680e+05, + 3.072606e+04, + 1.360673e+03, + -2.076195e+06, + 9.869617e+04, + 3.393877e+04, + 2.007443e+03, + -8.459967e+05, + 2.822829e+04, + 3.528651e+04, + 2.770476e+03, + -7.874505e+05, + 9.303483e+03, + 3.518552e+04, + 3.618710e+03, + -4.961071e+05, + -1.453427e+04, + 3.405307e+04, + 4.532258e+03, + -2.021158e+05, + -3.136214e+04, + 3.200853e+04, + 5.481500e+03, + -1.413239e+05, + -3.330948e+04, + 2.947684e+04, + 6.438940e+03, + -1.032936e+05, + -3.292416e+04, + 2.675684e+04, + 7.387225e+03, + -2.743197e+04, + -3.315766e+04, + 2.395645e+04, + 8.310655e+03, + -4.213430e+04, + -2.797667e+04, + 2.123679e+04, + 9.195288e+03, + 1.688152e+04, + -2.708199e+04, + 1.866320e+04, + 1.003492e+04, + -3.945755e+04, + -1.950281e+04, + 1.632798e+04, + 1.082159e+04, + 3.775898e+04, + -2.118019e+04, + 1.417740e+04, + 1.155761e+04, + -3.951332e+04, + -1.232675e+04, + 1.230190e+04, + 1.223448e+04, + 1.628466e+04, + -1.456907e+04, + 1.060143e+04, + 1.286326e+04, + 2.475050e+03, + -1.062776e+04, + 9.074832e+03, + 1.343267e+04, + -2.958304e+04, + -6.604437e+03, + 7.794557e+03, + 1.395159e+04, + 2.382873e+04, + -9.973204e+03, + 6.556652e+03, + 1.442337e+04, + -1.898300e+04, + -4.141927e+03, + 5.521709e+03, + 1.483557e+04, + -6.649303e+02, + -5.415087e+03, + 4.618044e+03, + 1.520793e+04, + -5.006126e+03, + -3.945080e+03, + 3.776118e+03, + 1.552981e+04, + -8.901394e+03, + -2.910036e+03, + 3.041676e+03, + 1.580619e+04, + -1.200711e+04, + -2.169750e+03, + 2.355820e+03, + 1.603784e+04, + -4.968676e+03, + -2.395668e+03, + 1.683550e+03, + 1.622197e+04, + -2.774133e+04, + 6.568597e+02, + 1.105917e+03, + 1.635428e+04, + -1.302099e+04, + -1.357563e+02, + 4.374897e+02, + 1.644280e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -9.717292e+02, + 3.525304e+01, + 0, + 0, + -5.304463e+03, + 3.218125e+02, + 3.073832e-01, + 9.671708e-04, + -1.934360e+04, + 2.085146e+03, + 3.966715e+00, + 1.644190e-02, + -3.180464e+05, + 1.510232e+04, + 3.388872e+01, + 1.745743e-01, + -6.480828e+05, + 4.043076e+04, + 2.338605e+02, + 1.570202e+00, + -1.516090e+06, + 9.036847e+04, + 8.833714e+02, + 8.063303e+00, + -2.034832e+06, + 1.366083e+05, + 2.427098e+03, + 3.009062e+01, + -2.361191e+06, + 1.706568e+05, + 5.064127e+03, + 8.568311e+01, + -2.387942e+06, + 1.804522e+05, + 8.693407e+03, + 1.993470e+02, + -2.155769e+06, + 1.647391e+05, + 1.283741e+04, + 3.965541e+02, + -1.303862e+06, + 1.206826e+05, + 1.681586e+04, + 6.963707e+02, + -1.382930e+06, + 1.028904e+05, + 2.021420e+04, + 1.105526e+03, + -7.363076e+05, + 5.682299e+04, + 2.276260e+04, + 1.628739e+03, + -7.293309e+05, + 3.878596e+04, + 2.422386e+04, + 2.250501e+03, + -1.958146e+05, + 3.375079e+03, + 2.465448e+04, + 2.957056e+03, + -2.527096e+05, + 3.571719e+02, + 2.429786e+04, + 3.719856e+03, + -1.824193e+05, + -8.454398e+03, + 2.346440e+04, + 4.527808e+03, + -1.207450e+05, + -1.454655e+04, + 2.212836e+04, + 5.360145e+03, + -1.873828e+04, + -2.014348e+04, + 2.043631e+04, + 6.196165e+03, + -6.547356e+04, + -1.592640e+04, + 1.864471e+04, + 7.017728e+03, + 1.538025e+04, + -1.940620e+04, + 1.681319e+04, + 7.818656e+03, + -3.081477e+04, + -1.380759e+04, + 1.505269e+04, + 8.584346e+03, + -3.688264e+04, + -1.237202e+04, + 1.339212e+04, + 9.316279e+03, + 3.700757e+04, + -1.579093e+04, + 1.171025e+04, + 1.000491e+04, + -3.096457e+04, + -7.862788e+03, + 1.025124e+04, + 1.063862e+04, + -3.624742e+03, + -9.431423e+03, + 8.931243e+03, + 1.123263e+04, + -7.771562e+02, + -8.102068e+03, + 7.655642e+03, + 1.177367e+04, + -9.869735e+03, + -6.022230e+03, + 6.528116e+03, + 1.226242e+04, + -4.868512e+03, + -5.631664e+03, + 5.495559e+03, + 1.270154e+04, + -9.937763e+03, + -4.263030e+03, + 4.546326e+03, + 1.308752e+04, + -4.005424e+03, + -4.161767e+03, + 3.664244e+03, + 1.342139e+04, + -1.613158e+04, + -2.200682e+03, + 2.871716e+03, + 1.369982e+04, + -1.400113e+04, + -2.118312e+03, + 2.095777e+03, + 1.392675e+04, + -2.681191e+04, + -1.270264e+02, + 1.333515e+03, + 1.409262e+04, + -1.703298e+04, + -1.198066e+01, + 5.383685e+02, + 1.419677e+04, +}; + +double solarDataset680[] = +{ + -352468042275216, + 4.565228e+09, + 3.493754e+05, + 4.079590e+03, + 5.683662e+12, + -1.328402e+09, + 1.925649e+05, + 4.085164e+03, + -7.764229e+10, + 4.963131e+07, + 1.202445e+05, + 4.099044e+03, + 5.563528e+09, + -4.324424e+06, + 1.277691e+05, + 4.141022e+03, + -3.769498e+09, + 6.005153e+06, + 1.290424e+05, + 4.222198e+03, + 9.852032e+08, + -2.967738e+06, + 1.291679e+05, + 4.360144e+03, + -3.875109e+07, + 1.836524e+05, + 1.271300e+05, + 4.559262e+03, + -1.192922e+08, + 3.590793e+05, + 1.273769e+05, + 4.838049e+03, + 5.235498e+06, + -2.993428e+05, + 1.264319e+05, + 5.209221e+03, + -3.536095e+07, + -5.551723e+04, + 1.244122e+05, + 5.678238e+03, + -3.682262e+07, + -1.175068e+05, + 1.215785e+05, + 6.254607e+03, + -1.683494e+07, + -3.365406e+05, + 1.166413e+05, + 6.937634e+03, + -6.725039e+06, + -4.184973e+05, + 1.096698e+05, + 7.714702e+03, + -1.347547e+07, + -3.110082e+05, + 1.015845e+05, + 8.570426e+03, + -5.796493e+06, + -3.962767e+05, + 9.212522e+04, + 9.489327e+03, + -1.470687e+06, + -3.999603e+05, + 8.144721e+04, + 1.043704e+04, + -3.891564e+06, + -2.924573e+05, + 7.082390e+04, + 1.138470e+04, + 1.268637e+06, + -3.320372e+05, + 6.027083e+04, + 1.231325e+04, + -1.553830e+06, + -2.010288e+05, + 5.070597e+04, + 1.318976e+04, + 6.401092e+05, + -2.083886e+05, + 4.212731e+04, + 1.401579e+04, + -4.089157e+05, + -1.325947e+05, + 3.467286e+04, + 1.476862e+04, + 4.689382e+05, + -1.255255e+05, + 2.832884e+04, + 1.545545e+04, + -2.414026e+05, + -7.345191e+04, + 2.313068e+04, + 1.606742e+04, + 2.093406e+05, + -7.131366e+04, + 1.878759e+04, + 1.661838e+04, + 8.730097e+04, + -4.851327e+04, + 1.522608e+04, + 1.710171e+04, + -2.825615e+04, + -3.260464e+04, + 1.246629e+04, + 1.753026e+04, + 9.246158e+03, + -2.696444e+04, + 1.017736e+04, + 1.791157e+04, + 5.845154e+04, + -2.256224e+04, + 8.255250e+03, + 1.824608e+04, + -1.623206e+03, + -1.409944e+04, + 6.758571e+03, + 1.853795e+04, + 1.397299e+04, + -1.179690e+04, + 5.565383e+03, + 1.879686e+04, + 9.810044e+03, + -8.809613e+03, + 4.588390e+03, + 1.902473e+04, + -1.056924e+04, + -5.731825e+03, + 3.808836e+03, + 1.922618e+04, + 1.867460e+04, + -6.355988e+03, + 3.137056e+03, + 1.940511e+04, + -2.207924e+04, + -2.223620e+03, + 2.609823e+03, + 1.956056e+04, + 2.317944e+04, + -5.069146e+03, + 2.128577e+03, + 1.970022e+04, + -1.315186e+04, + -9.880525e+02, + 1.767994e+03, + 1.981745e+04, + 4.416039e+03, + -2.401660e+03, + 1.471594e+03, + 1.992484e+04, + 2.469023e+02, + -1.450777e+03, + 1.203539e+03, + 2.001628e+04, + -7.126793e+03, + -5.842061e+02, + 9.964367e+02, + 2.009623e+04, + 5.680761e+03, + -1.675038e+03, + 7.812342e+02, + 2.016597e+04, + -3.303117e+03, + -3.317838e+02, + 6.218765e+02, + 2.022109e+04, + -3.628281e+03, + -3.367296e+02, + 4.942834e+02, + 2.026943e+04, + -1.932363e+03, + -4.513063e+02, + 3.479496e+02, + 2.030822e+04, + -2.905107e+03, + -1.741303e+02, + 2.130510e+02, + 2.033521e+04, + -2.186812e+03, + -6.044464e+01, + 9.550916e+01, + 2.035167e+04, + 2.566491e+12, + -2.160143e+07, + 1.253489e+05, + 2.094745e+03, + 1.072830e+11, + 3.373914e+06, + 1.268921e+05, + 2.096912e+03, + -6.278151e+10, + 3.625360e+07, + 1.323924e+05, + 2.112461e+03, + 5.355040e+09, + -6.437409e+06, + 1.359364e+05, + 2.157505e+03, + 6.328454e+08, + -3.831994e+05, + 1.342600e+05, + 2.242976e+03, + -3.525021e+08, + 1.289271e+06, + 1.355533e+05, + 2.384464e+03, + 7.237564e+06, + 1.315110e+05, + 1.369959e+05, + 2.598910e+03, + -8.490662e+07, + 3.829063e+05, + 1.376758e+05, + 2.899528e+03, + -3.478052e+07, + 3.597080e+04, + 1.377450e+05, + 3.301754e+03, + -5.179258e+07, + 5.107895e+04, + 1.365542e+05, + 3.815687e+03, + -2.559535e+07, + -2.211796e+05, + 1.336407e+05, + 4.449428e+03, + -2.591427e+07, + -2.568699e+05, + 1.286169e+05, + 5.199989e+03, + -1.373490e+07, + -3.999240e+05, + 1.214603e+05, + 6.059833e+03, + -1.260242e+07, + -3.952445e+05, + 1.123008e+05, + 7.008387e+03, + -2.957989e+06, + -4.813305e+05, + 1.014858e+05, + 8.021575e+03, + -5.251237e+06, + -3.746148e+05, + 8.996501e+04, + 9.064690e+03, + -4.198038e+05, + -3.933644e+05, + 7.821981e+04, + 1.011487e+04, + -1.996456e+06, + -2.874528e+05, + 6.689029e+04, + 1.113727e+04, + 4.266078e+05, + -2.786719e+05, + 5.627982e+04, + 1.211684e+04, + -3.919704e+05, + -1.965459e+05, + 4.681414e+04, + 1.302821e+04, + 1.091816e+05, + -1.649710e+05, + 3.862777e+04, + 1.386995e+04, + 3.750077e+05, + -1.318222e+05, + 3.161062e+04, + 1.463277e+04, + -2.406655e+05, + -8.206026e+04, + 2.595029e+04, + 1.531832e+04, + 2.170257e+05, + -7.837065e+04, + 2.115790e+04, + 1.593722e+04, + -7.134165e+04, + -4.885270e+04, + 1.721207e+04, + 1.648268e+04, + 1.378171e+05, + -4.537327e+04, + 1.397250e+04, + 1.696781e+04, + 3.258145e+04, + -2.938905e+04, + 1.138823e+04, + 1.739164e+04, + 1.146137e+03, + -2.126903e+04, + 9.382346e+03, + 1.776806e+04, + 1.883121e+04, + -1.738343e+04, + 7.723831e+03, + 1.810256e+04, + -1.217855e+04, + -1.191290e+04, + 6.363021e+03, + 1.839774e+04, + 1.663010e+04, + -1.094152e+04, + 5.216659e+03, + 1.865889e+04, + 1.933224e+04, + -8.372961e+03, + 4.279327e+03, + 1.888639e+04, + -6.277107e+03, + -4.826426e+03, + 3.572708e+03, + 1.908656e+04, + -1.213908e+04, + -3.694135e+03, + 2.989211e+03, + 1.926630e+04, + 1.843629e+04, + -5.074897e+03, + 2.437722e+03, + 1.942497e+04, + -3.720726e+03, + -2.060727e+03, + 2.022513e+03, + 1.956010e+04, + -7.571230e+03, + -1.529007e+03, + 1.706477e+03, + 1.968213e+04, + 3.388922e+03, + -2.219310e+03, + 1.387955e+03, + 1.978997e+04, + -8.136688e+02, + -1.296765e+03, + 1.118924e+03, + 1.988048e+04, + -2.113553e+00, + -1.105284e+03, + 9.057690e+02, + 1.995827e+04, + -5.605613e+03, + -3.817953e+02, + 7.273565e+02, + 2.002416e+04, + 2.555659e+03, + -1.135591e+03, + 5.415747e+02, + 2.007969e+04, + -7.323743e+03, + 1.792085e+02, + 4.001082e+02, + 2.012072e+04, + -1.158262e+03, + -4.852916e+02, + 2.418730e+02, + 2.015369e+04, + -1.923105e+03, + -1.119911e+02, + 1.136166e+02, + 2.017163e+04, + -4.453960e+13, + 4.901918e+08, + 1.224067e+05, + 6.971794e+02, + 1.428199e+12, + -3.402263e+08, + 9.960258e+04, + 6.992069e+02, + 2.850891e+09, + 1.332939e+06, + 7.987958e+04, + 7.087809e+02, + 3.653290e+09, + -2.318826e+05, + 8.167014e+04, + 7.351861e+02, + -1.710126e+09, + 5.205901e+06, + 8.583269e+04, + 7.881288e+02, + 3.500513e+08, + 7.327072e+05, + 9.110828e+04, + 8.821503e+02, + -3.667415e+07, + 1.644077e+06, + 9.599104e+04, + 1.028221e+03, + -6.427903e+07, + 1.499947e+06, + 1.026622e+05, + 1.245859e+03, + -8.902301e+07, + 1.348587e+06, + 1.097649e+05, + 1.556074e+03, + -5.458529e+07, + 8.715855e+05, + 1.161171e+05, + 1.980872e+03, + -7.078158e+07, + 7.296954e+05, + 1.206867e+05, + 2.536762e+03, + -2.407104e+07, + 9.613678e+04, + 1.221006e+05, + 3.235974e+03, + -2.892878e+07, + 3.067619e+04, + 1.200345e+05, + 4.068347e+03, + -1.424189e+07, + -2.367188e+05, + 1.148582e+05, + 5.025490e+03, + -8.468524e+06, + -3.287116e+05, + 1.065955e+05, + 6.075512e+03, + -4.418101e+06, + -3.647176e+05, + 9.643889e+04, + 7.185170e+03, + -3.842678e+06, + -3.284474e+05, + 8.532578e+04, + 8.318939e+03, + -5.278715e+05, + -3.366958e+05, + 7.378807e+04, + 9.444730e+03, + -3.937578e+05, + -2.707005e+05, + 6.272309e+04, + 1.052705e+04, + -4.639425e+05, + -2.130327e+05, + 5.276832e+04, + 1.155043e+04, + 2.817660e+05, + -1.847892e+05, + 4.384989e+04, + 1.250236e+04, + 2.903034e+04, + -1.344634e+05, + 3.621580e+04, + 1.337110e+04, + 4.635096e+03, + -1.030736e+05, + 2.983586e+04, + 1.416051e+04, + 2.047168e+05, + -8.515824e+04, + 2.444758e+04, + 1.487116e+04, + -1.279274e+05, + -5.337031e+04, + 2.008387e+04, + 1.550475e+04, + 1.415452e+05, + -5.181761e+04, + 1.640018e+04, + 1.607299e+04, + 5.602843e+04, + -3.510271e+04, + 1.339511e+04, + 1.657132e+04, + -1.127698e+04, + -2.404607e+04, + 1.106697e+04, + 1.701421e+04, + 1.253660e+04, + -2.007243e+04, + 9.134211e+03, + 1.740961e+04, + 1.780279e+04, + -1.574977e+04, + 7.514154e+03, + 1.775883e+04, + 5.640618e+03, + -1.147763e+04, + 6.204614e+03, + 1.806675e+04, + 2.936546e+03, + -8.829144e+03, + 5.139387e+03, + 1.833932e+04, + 5.299726e+03, + -7.061936e+03, + 4.256417e+03, + 1.858020e+04, + 5.686652e+03, + -5.507486e+03, + 3.532321e+03, + 1.879251e+04, + -7.404946e+03, + -3.452414e+03, + 2.950484e+03, + 1.898008e+04, + 3.770764e+03, + -3.682956e+03, + 2.441272e+03, + 1.914689e+04, + 3.794749e+03, + -2.805228e+03, + 2.009244e+03, + 1.929140e+04, + -9.089152e+03, + -1.190131e+03, + 1.676729e+03, + 1.941776e+04, + 3.011825e+03, + -2.138990e+03, + 1.359400e+03, + 1.952992e+04, + 1.428751e+02, + -1.319583e+03, + 1.084559e+03, + 1.962291e+04, + -4.913817e+03, + -5.934187e+02, + 8.743950e+02, + 1.970191e+04, + -5.071407e+02, + -9.664004e+02, + 6.676441e+02, + 1.976881e+04, + -4.650836e+03, + -3.007170e+02, + 4.834242e+02, + 1.982025e+04, + -5.376321e+03, + -1.327924e+02, + 3.054971e+02, + 1.985899e+04, + -3.742214e+03, + -1.749535e+01, + 1.250497e+02, + 1.988258e+04, + -7.893237e+12, + 8.288681e+07, + 3.010748e+04, + 1.136166e+02, + 3.103597e+11, + -7.118740e+07, + 2.592881e+04, + 1.141198e+02, + 8.428280e+09, + -8.028634e+05, + 2.230568e+04, + 1.167572e+02, + -3.605961e+09, + 5.798521e+06, + 2.449204e+04, + 1.242727e+02, + 8.783630e+08, + -1.200222e+04, + 2.748804e+04, + 1.413170e+02, + 1.044530e+08, + 1.460532e+06, + 3.037633e+04, + 1.712288e+02, + -9.170265e+05, + 1.717708e+06, + 3.572950e+04, + 2.228753e+02, + -4.501713e+07, + 1.862117e+06, + 4.323714e+04, + 3.093172e+02, + -7.396908e+07, + 1.935003e+06, + 5.294040e+04, + 4.499654e+02, + -6.169410e+07, + 1.717830e+06, + 6.431161e+04, + 6.711980e+02, + -7.366754e+07, + 1.587813e+06, + 7.632218e+04, + 1.002824e+03, + -4.663231e+07, + 1.055055e+06, + 8.724662e+04, + 1.476305e+03, + -4.048764e+07, + 7.247687e+05, + 9.513528e+04, + 2.107835e+03, + -1.960904e+07, + 2.489285e+05, + 9.891534e+04, + 2.902937e+03, + -1.894416e+07, + 9.872926e+04, + 9.837949e+04, + 3.841311e+03, + -4.442386e+06, + -2.116653e+05, + 9.380338e+04, + 4.898693e+03, + -5.834290e+06, + -1.885613e+05, + 8.648343e+04, + 6.023302e+03, + -1.719788e+06, + -2.613590e+05, + 7.770079e+04, + 7.187578e+03, + -1.691541e+06, + -2.251616e+05, + 6.812535e+04, + 8.346053e+03, + -5.227803e+05, + -2.157890e+05, + 5.856276e+04, + 9.472141e+03, + 4.814127e+05, + -1.960903e+05, + 4.946763e+04, + 1.053652e+04, + -4.579357e+05, + -1.276666e+05, + 4.162523e+04, + 1.152409e+04, + 1.805291e+05, + -1.211531e+05, + 3.473519e+04, + 1.244006e+04, + 1.359116e+05, + -9.125698e+04, + 2.876191e+04, + 1.326975e+04, + -8.572899e+04, + -6.301636e+04, + 2.388140e+04, + 1.401999e+04, + 1.408473e+05, + -5.792684e+04, + 1.972080e+04, + 1.469810e+04, + -3.746225e+04, + -3.691816e+04, + 1.630243e+04, + 1.530117e+04, + 6.587470e+04, + -3.359362e+04, + 1.347244e+04, + 1.584278e+04, + 1.012335e+04, + -2.298597e+04, + 1.114689e+04, + 1.632227e+04, + 6.639102e+03, + -1.787249e+04, + 9.269274e+03, + 1.675072e+04, + -6.477797e+02, + -1.369067e+04, + 7.700812e+03, + 1.713232e+04, + 2.142191e+04, + -1.198949e+04, + 6.378977e+03, + 1.747105e+04, + -4.414359e+03, + -7.644321e+03, + 5.317687e+03, + 1.776972e+04, + 1.533924e+03, + -6.582866e+03, + 4.443001e+03, + 1.803667e+04, + 1.981630e+03, + -5.240241e+03, + 3.694367e+03, + 1.827267e+04, + -1.052148e+03, + -3.932107e+03, + 3.071754e+03, + 1.848069e+04, + 7.306138e+02, + -3.290251e+03, + 2.545786e+03, + 1.866390e+04, + 4.229719e+02, + -2.571537e+03, + 2.102797e+03, + 1.882392e+04, + -7.944393e+03, + -1.390188e+03, + 1.735472e+03, + 1.896341e+04, + 4.214760e+03, + -2.291285e+03, + 1.382288e+03, + 1.908470e+04, + -5.750642e+03, + -7.694022e+02, + 1.094846e+03, + 1.918353e+04, + 1.100272e+02, + -1.256194e+03, + 8.401738e+02, + 1.926736e+04, + -1.010048e+04, + 6.181541e+01, + 6.190195e+02, + 1.933230e+04, + -3.820373e+03, + -5.389325e+02, + 3.661653e+02, + 1.938243e+04, + -3.917769e+03, + -6.433621e+01, + 1.509301e+02, + 1.940952e+04, + -8.070633e+12, + 1.076138e+08, + 6.631032e+03, + 1.018617e+01, + 1.369399e+11, + -2.815586e+07, + 3.146703e+03, + 1.029111e+01, + -1.827832e+10, + 1.209860e+07, + 2.333390e+03, + 1.050144e+01, + 9.521666e+08, + -5.255783e+05, + 4.376365e+03, + 1.192131e+01, + 1.173580e+07, + 6.003251e+05, + 4.867928e+03, + 1.474579e+01, + 1.090046e+08, + 4.481858e+05, + 6.169347e+03, + 2.054185e+01, + -8.730001e+06, + 9.393270e+05, + 8.380095e+03, + 3.174291e+01, + -3.942600e+07, + 1.234005e+06, + 1.236733e+04, + 5.449888e+01, + -5.058522e+07, + 1.455714e+06, + 1.855333e+04, + 1.000252e+02, + -5.517395e+07, + 1.596469e+06, + 2.732046e+04, + 1.871469e+02, + -5.839261e+07, + 1.629707e+06, + 3.862401e+04, + 3.439872e+02, + -5.114727e+07, + 1.444003e+06, + 5.151836e+04, + 6.065740e+02, + -3.969641e+07, + 1.116577e+06, + 6.409615e+04, + 1.010369e+03, + -3.222007e+07, + 7.829705e+05, + 7.436652e+04, + 1.580560e+03, + -1.492637e+07, + 3.287719e+05, + 8.053808e+04, + 2.324370e+03, + -1.367783e+07, + 1.737145e+05, + 8.239238e+04, + 3.220077e+03, + -5.409060e+06, + -6.916228e+04, + 8.037208e+04, + 4.244663e+03, + -3.749200e+06, + -1.294274e+05, + 7.520553e+04, + 5.347740e+03, + -1.438150e+06, + -1.808190e+05, + 6.828222e+04, + 6.491727e+03, + -1.031219e+06, + -1.695525e+05, + 6.052789e+04, + 7.635895e+03, + -5.897295e+05, + -1.566876e+05, + 5.266149e+04, + 8.752942e+03, + 2.142786e+05, + -1.502598e+05, + 4.501376e+04, + 9.817549e+03, + -3.080940e+05, + -1.038003e+05, + 3.819615e+04, + 1.081081e+04, + 2.489975e+05, + -1.015549e+05, + 3.212658e+04, + 1.173425e+04, + -1.029353e+05, + -6.635146e+04, + 2.693457e+04, + 1.257483e+04, + 1.251409e+05, + -6.152113e+04, + 2.251714e+04, + 1.334400e+04, + -3.664596e+04, + -4.097680e+04, + 1.880373e+04, + 1.403645e+04, + 5.410562e+04, + -3.659535e+04, + 1.568214e+04, + 1.466359e+04, + -8.388199e+03, + -2.544703e+04, + 1.306777e+04, + 1.522421e+04, + 3.381060e+04, + -2.226293e+04, + 1.088538e+04, + 1.572764e+04, + 8.123732e+03, + -1.580665e+04, + 9.086832e+03, + 1.617555e+04, + -5.569137e+02, + -1.204825e+04, + 7.622303e+03, + 1.657705e+04, + -3.528642e+03, + -9.509650e+03, + 6.381344e+03, + 1.693640e+04, + 1.153206e+04, + -8.551674e+03, + 5.310794e+03, + 1.725604e+04, + -7.248790e+03, + -5.378741e+03, + 4.434661e+03, + 1.753772e+04, + 3.681099e+03, + -5.223851e+03, + 3.690070e+03, + 1.778863e+04, + 1.885868e+03, + -3.926101e+03, + 3.056040e+03, + 1.800796e+04, + -4.915319e+03, + -2.588201e+03, + 2.541884e+03, + 1.820050e+04, + 4.294262e+02, + -2.621170e+03, + 2.087430e+03, + 1.836978e+04, + -5.053803e+03, + -1.594382e+03, + 1.693140e+03, + 1.851459e+04, + -1.007074e+02, + -1.793775e+03, + 1.337123e+03, + 1.863817e+04, + -7.506678e+03, + -6.792374e+02, + 1.030627e+03, + 1.873863e+04, + 8.309197e+02, + -1.383974e+03, + 7.309777e+02, + 1.881973e+04, + -1.813795e+04, + 9.635944e+02, + 4.941701e+02, + 1.887662e+04, + -3.621577e+03, + -2.330195e+02, + 1.616740e+02, + 1.891720e+04, + 6.535480e+11, + -5.929338e+06, + -3.781728e+02, + 5.184347e-01, + -3.304103e+10, + 7.713900e+06, + 0, + 5.135015e-01, + 1.605064e+08, + -1.634788e+05, + 4.183612e+02, + 5.677667e-01, + 3.242006e+08, + -2.400051e+05, + 3.629284e+02, + 6.928907e-01, + -1.079961e+08, + 3.789254e+05, + 4.524209e+02, + 9.108485e-01, + 1.466292e+07, + 1.653131e+05, + 8.910833e+02, + 1.679980e+00, + 5.139923e+06, + 3.030831e+05, + 1.517958e+03, + 3.541142e+00, + -2.137928e+07, + 6.141632e+05, + 2.918879e+03, + 8.370747e+00, + -4.382682e+07, + 9.923543e+05, + 5.952912e+03, + 2.155764e+01, + -4.591369e+07, + 1.251039e+06, + 1.153723e+04, + 5.541645e+01, + -5.599871e+07, + 1.504362e+06, + 2.021971e+04, + 1.319322e+02, + -4.905457e+07, + 1.461205e+06, + 3.191749e+04, + 2.858732e+02, + -4.156802e+07, + 1.274441e+06, + 4.502474e+04, + 5.570078e+02, + -3.338034e+07, + 9.727163e+05, + 5.748065e+04, + 9.823445e+02, + -1.872780e+07, + 5.500384e+05, + 6.692099e+04, + 1.582833e+03, + -1.333256e+07, + 3.021913e+05, + 7.223951e+04, + 2.351712e+03, + -6.921961e+06, + 7.087433e+04, + 7.357275e+04, + 3.270621e+03, + -5.394556e+06, + -2.381757e+04, + 7.145035e+04, + 4.301491e+03, + -2.089262e+06, + -1.282498e+05, + 6.663436e+04, + 5.405952e+03, + -6.847307e+05, + -1.546674e+05, + 6.012913e+04, + 6.533810e+03, + -7.349015e+05, + -1.335175e+05, + 5.325038e+04, + 7.651409e+03, + -2.879821e+05, + -1.272674e+05, + 4.640416e+04, + 8.738273e+03, + -8.462746e+03, + -1.130442e+05, + 3.982467e+04, + 9.771057e+03, + -1.063739e+05, + -8.787637e+04, + 3.388731e+04, + 1.073618e+04, + 1.343560e+05, + -7.883937e+04, + 2.860691e+04, + 1.162993e+04, + 1.389387e+04, + -5.691194e+04, + 2.410021e+04, + 1.244608e+04, + -5.177439e+04, + -4.289378e+04, + 2.031934e+04, + 1.319275e+04, + 8.139572e+04, + -4.013155e+04, + 1.699864e+04, + 1.387169e+04, + 2.468899e+04, + -2.814082e+04, + 1.423289e+04, + 1.448002e+04, + -6.571990e+04, + -1.805698e+04, + 1.199929e+04, + 1.503010e+04, + 8.726906e+04, + -2.301298e+04, + 9.974486e+03, + 1.552759e+04, + -3.911454e+04, + -9.959665e+03, + 8.366133e+03, + 1.596392e+04, + 2.754859e+04, + -1.261897e+04, + 7.034917e+03, + 1.636173e+04, + -2.143616e+04, + -6.578940e+03, + 5.902874e+03, + 1.671286e+04, + 1.445855e+04, + -8.060233e+03, + 4.922564e+03, + 1.702911e+04, + -1.068146e+03, + -5.007837e+03, + 4.094606e+03, + 1.730495e+04, + -1.446239e+03, + -4.042107e+03, + 3.428210e+03, + 1.755026e+04, + -7.646742e+03, + -2.833790e+03, + 2.850615e+03, + 1.776680e+04, + 6.036580e+03, + -3.510960e+03, + 2.317098e+03, + 1.795618e+04, + -5.012745e+03, + -1.656924e+03, + 1.885239e+03, + 1.811589e+04, + -4.810884e+03, + -1.478773e+03, + 1.519931e+03, + 1.825459e+04, + -6.234266e+03, + -1.106439e+03, + 1.165198e+03, + 1.836994e+04, + -2.823139e+03, + -1.181941e+03, + 8.197310e+02, + 1.846054e+04, + -1.258697e+04, + 2.043762e+02, + 5.250146e+02, + 1.852450e+04, + -5.978057e+03, + -7.475415e+01, + 2.034009e+02, + 1.856604e+04, + -8.418277e+10, + 1.154661e+06, + 5.714404e+01, + 4.036256e-03, + -2.687024e+07, + -8.592069e+04, + 2.190888e+01, + 4.933202e-03, + 1.021218e+08, + -5.017017e+04, + 0, + 6.278621e-03, + -1.255189e+07, + 1.903032e+04, + 0, + 4.484729e-03, + 1.558282e+06, + 2.417039e+03, + 8.957179e+00, + 8.969458e-03, + -3.914997e+05, + 1.370244e+04, + 1.920907e+01, + 2.287212e-02, + -6.741212e+05, + 3.455420e+04, + 5.930749e+01, + 8.520985e-02, + -4.870917e+06, + 1.084084e+05, + 2.009074e+02, + 3.735779e-01, + -9.230984e+06, + 2.505707e+05, + 7.085224e+02, + 1.758462e+00, + -2.106645e+07, + 5.356899e+05, + 2.195612e+03, + 7.431645e+00, + -2.950385e+07, + 8.461586e+05, + 5.821344e+03, + 2.723083e+01, + -3.782577e+07, + 1.119956e+06, + 1.259572e+04, + 8.251229e+01, + -3.282215e+07, + 1.127447e+06, + 2.260996e+04, + 2.090373e+02, + -3.131878e+07, + 1.051472e+06, + 3.440400e+04, + 4.481747e+02, + -2.053329e+07, + 7.431721e+05, + 4.587941e+04, + 8.398019e+02, + -1.369182e+07, + 4.785742e+05, + 5.475855e+04, + 1.400337e+03, + -9.066544e+06, + 2.627224e+05, + 6.030965e+04, + 2.128540e+03, + -6.437927e+06, + 1.088040e+05, + 6.231489e+04, + 3.004682e+03, + -2.053492e+06, + -4.777547e+04, + 6.091525e+04, + 3.993557e+03, + -1.949825e+06, + -6.605211e+04, + 5.729296e+04, + 5.045588e+03, + -9.414086e+05, + -9.996283e+04, + 5.243186e+04, + 6.132059e+03, + -1.890967e+05, + -1.121647e+05, + 4.675167e+04, + 7.214864e+03, + -3.045963e+05, + -9.180211e+04, + 4.106393e+04, + 8.265942e+03, + -5.330101e+04, + -8.608205e+04, + 3.562988e+04, + 9.272761e+03, + -3.028050e+04, + -7.119125e+04, + 3.058189e+04, + 1.021899e+04, + 3.389382e+04, + -6.002974e+04, + 2.607403e+04, + 1.109889e+04, + 2.504837e+04, + -4.749684e+04, + 2.215132e+04, + 1.190918e+04, + 3.155848e+04, + -3.811928e+04, + 1.880026e+04, + 1.265226e+04, + -7.201400e+04, + -2.586018e+04, + 1.596321e+04, + 1.333116e+04, + 7.110271e+04, + -2.854939e+04, + 1.340926e+04, + 1.395078e+04, + 4.710820e+03, + -1.819806e+04, + 1.127146e+04, + 1.450295e+04, + -1.716947e+04, + -1.351549e+04, + 9.553127e+03, + 1.500363e+04, + 1.705228e+04, + -1.317062e+04, + 8.030335e+03, + 1.545596e+04, + -7.296253e+03, + -8.740504e+03, + 6.744056e+03, + 1.585811e+04, + 1.124590e+04, + -8.382692e+03, + 5.655728e+03, + 1.621866e+04, + -6.404979e+03, + -5.276710e+03, + 4.751552e+03, + 1.653766e+04, + -4.078801e+03, + -4.618901e+03, + 3.982096e+03, + 1.682316e+04, + 5.784536e+03, + -4.519947e+03, + 3.287528e+03, + 1.707427e+04, + -1.229816e+04, + -2.021194e+03, + 2.721875e+03, + 1.729168e+04, + 1.842108e+03, + -3.109246e+03, + 2.195199e+03, + 1.748291e+04, + 1.022085e+03, + -2.237389e+03, + 1.729408e+03, + 1.764076e+04, + -1.355747e+04, + -3.814936e+02, + 1.371889e+03, + 1.777199e+04, + -4.135917e+03, + -1.405750e+03, + 9.812738e+02, + 1.788158e+04, + -1.176006e+04, + -1.122970e+02, + 6.103796e+02, + 1.795760e+04, + -7.664940e+03, + -2.255428e+01, + 2.505438e+02, + 1.800524e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.756796e+04, + 3.410796e+02, + 0, + 0, + -1.318358e+05, + 2.755397e+03, + 1.097018e+00, + 1.345419e-03, + -5.608807e+05, + 1.562207e+04, + 1.379447e+01, + 2.466601e-02, + -2.514261e+06, + 6.918882e+04, + 1.071228e+02, + 2.654960e-01, + -6.065589e+06, + 1.944641e+05, + 5.889450e+02, + 2.019474e+00, + -1.283506e+07, + 4.191455e+05, + 2.215660e+03, + 1.058396e+01, + -1.846805e+07, + 6.414717e+05, + 6.149145e+03, + 4.126265e+01, + -1.742585e+07, + 7.178521e+05, + 1.289995e+04, + 1.231435e+02, + -1.832815e+07, + 7.396414e+05, + 2.178945e+04, + 2.939924e+02, + -1.255612e+07, + 5.674151e+05, + 3.137447e+04, + 5.949191e+02, + -9.863656e+06, + 4.196776e+05, + 3.966016e+04, + 1.048397e+03, + -6.077376e+06, + 2.402884e+05, + 4.561200e+04, + 1.662630e+03, + -3.971539e+06, + 1.160875e+05, + 4.864964e+04, + 2.421336e+03, + -1.807408e+06, + 1.308620e+04, + 4.902579e+04, + 3.296939e+03, + -1.659778e+06, + -1.565950e+04, + 4.744301e+04, + 4.252506e+03, + -6.733442e+05, + -5.969285e+04, + 4.440953e+04, + 5.259324e+03, + -2.473511e+05, + -7.140758e+04, + 4.040044e+04, + 6.277780e+03, + -2.042537e+05, + -6.499188e+04, + 3.615217e+04, + 7.282236e+03, + -1.170966e+05, + -6.002899e+04, + 3.193951e+04, + 8.257070e+03, + -2.352214e+04, + -5.459684e+04, + 2.787370e+04, + 9.187282e+03, + 4.937715e+04, + -4.785421e+04, + 2.412159e+04, + 1.006206e+04, + -1.156724e+05, + -3.191696e+04, + 2.084086e+04, + 1.087739e+04, + 1.297973e+05, + -3.849662e+04, + 1.781328e+04, + 1.163679e+04, + -9.774888e+04, + -1.844295e+04, + 1.526608e+04, + 1.232678e+04, + 5.200490e+04, + -2.438844e+04, + 1.301188e+04, + 1.296761e+04, + -8.135849e+03, + -1.543929e+04, + 1.102631e+04, + 1.354296e+04, + 1.028947e+04, + -1.379101e+04, + 9.377438e+03, + 1.406704e+04, + -8.156883e+03, + -9.874940e+03, + 7.962838e+03, + 1.453982e+04, + -9.036508e+01, + -8.750479e+03, + 6.734128e+03, + 1.496712e+04, + 1.570054e+03, + -7.174620e+03, + 5.655807e+03, + 1.534847e+04, + -1.278293e+03, + -5.539760e+03, + 4.740587e+03, + 1.568705e+04, + -2.566299e+03, + -4.405104e+03, + 3.959008e+03, + 1.598696e+04, + -1.910568e+03, + -3.654087e+03, + 3.277553e+03, + 1.625060e+04, + -8.951905e+03, + -2.385243e+03, + 2.683652e+03, + 1.647951e+04, + -2.863973e+03, + -2.620958e+03, + 2.123866e+03, + 1.667582e+04, + -5.366473e+03, + -1.785690e+03, + 1.617383e+03, + 1.683538e+04, + -4.998538e+03, + -1.403221e+03, + 1.171570e+03, + 1.696147e+04, + -1.930573e+04, + 4.416717e+02, + 7.785677e+02, + 1.705459e+04, + -9.332163e+03, + -8.178539e+01, + 3.103724e+02, + 1.711692e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -8.909025e+02, + 3.538429e+01, + 0, + 0, + -6.422168e+04, + 1.628264e+03, + 2.273205e-01, + 4.484729e-04, + -1.684485e+05, + 8.745175e+03, + 1.123560e+01, + 3.049616e-02, + -1.396076e+06, + 4.954183e+04, + 9.457898e+01, + 3.480150e-01, + -3.153636e+06, + 1.315038e+05, + 5.765050e+02, + 2.867984e+00, + -5.753237e+06, + 2.566029e+05, + 2.084437e+03, + 1.445742e+01, + -8.015029e+06, + 3.742078e+05, + 5.388979e+03, + 5.210269e+01, + -8.074433e+06, + 4.135002e+05, + 1.068476e+04, + 1.446774e+02, + -6.661386e+06, + 3.790568e+05, + 1.722141e+04, + 3.258434e+02, + -6.077928e+06, + 3.260624e+05, + 2.393450e+04, + 6.249524e+02, + -3.712201e+06, + 2.107243e+05, + 2.968932e+04, + 1.061776e+03, + -2.467015e+06, + 1.292915e+05, + 3.366006e+04, + 1.632819e+03, + -1.882443e+06, + 7.221017e+04, + 3.588291e+04, + 2.326102e+03, + -1.086002e+06, + 1.703520e+04, + 3.635384e+04, + 3.120870e+03, + -4.605255e+05, + -1.927992e+04, + 3.530604e+04, + 3.984944e+03, + -4.341743e+05, + -2.590209e+04, + 3.334915e+04, + 4.887920e+03, + -1.327876e+05, + -3.966641e+04, + 3.080680e+04, + 5.809224e+03, + -1.434539e+05, + -3.617659e+04, + 2.795994e+04, + 6.723427e+03, + -3.317195e+04, + -3.750287e+04, + 2.503988e+04, + 7.617373e+03, + -7.415801e+04, + -3.064914e+04, + 2.218438e+04, + 8.475763e+03, + 5.703238e+04, + -3.265980e+04, + 1.944651e+04, + 9.292128e+03, + -6.193252e+04, + -2.057404e+04, + 1.700446e+04, + 1.005564e+04, + 1.215735e+04, + -2.212679e+04, + 1.477610e+04, + 1.077365e+04, + 1.341243e+04, + -1.799234e+04, + 1.273145e+04, + 1.143468e+04, + -3.132178e+04, + -1.206636e+04, + 1.099078e+04, + 1.204245e+04, + 3.848496e+04, + -1.481817e+04, + 9.392096e+03, + 1.260173e+04, + -3.404114e+04, + -6.555128e+03, + 8.060933e+03, + 1.310445e+04, + 4.790791e+03, + -8.972117e+03, + 6.866951e+03, + 1.356787e+04, + 2.423192e+03, + -6.922553e+03, + 5.758467e+03, + 1.397865e+04, + 1.399033e+03, + -5.445455e+03, + 4.839055e+03, + 1.434333e+04, + -1.893961e+04, + -2.804734e+03, + 4.069198e+03, + 1.466700e+04, + 1.877066e+03, + -4.505274e+03, + 3.305315e+03, + 1.495392e+04, + -2.115025e+03, + -3.042529e+03, + 2.614916e+03, + 1.519227e+04, + -1.104184e+04, + -1.582042e+03, + 2.053080e+03, + 1.539091e+04, + -1.188713e+04, + -1.306613e+03, + 1.508474e+03, + 1.555342e+04, + -2.215601e+04, + 1.527387e+02, + 9.531955e+02, + 1.567324e+04, + -9.598320e+03, + -2.176024e+02, + 3.465646e+02, + 1.574722e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.644955e+03, + 6.448869e+01, + 0, + 0, + -1.029582e+04, + 6.950336e+02, + 5.752530e-01, + 1.793892e-03, + -1.273869e+05, + 6.122692e+03, + 8.641528e+00, + 3.498089e-02, + -4.160031e+05, + 2.380720e+04, + 8.266186e+01, + 4.377096e-01, + -1.255311e+06, + 6.800200e+04, + 4.206646e+02, + 2.985036e+00, + -2.081254e+06, + 1.244833e+05, + 1.454439e+03, + 1.399056e+01, + -2.900617e+06, + 1.789184e+05, + 3.584258e+03, + 4.729999e+01, + -2.756955e+06, + 1.947111e+05, + 6.897862e+03, + 1.251625e+02, + -2.672126e+06, + 1.929093e+05, + 1.099130e+04, + 2.723388e+02, + -2.086269e+06, + 1.602556e+05, + 1.530917e+04, + 5.125534e+02, + -1.573510e+06, + 1.215890e+05, + 1.919192e+04, + 8.597800e+02, + -1.355439e+06, + 8.820952e+04, + 2.224744e+04, + 1.318242e+03, + -5.451509e+05, + 3.738095e+04, + 2.414097e+04, + 1.882051e+03, + -6.036619e+05, + 2.573667e+04, + 2.497727e+04, + 2.530007e+03, + -3.048824e+05, + 1.354461e+03, + 2.497001e+04, + 3.250364e+03, + -2.405107e+05, + -7.845169e+03, + 2.417257e+04, + 4.017749e+03, + -7.981406e+04, + -1.839566e+04, + 2.282880e+04, + 4.812674e+03, + -5.359818e+04, + -1.914615e+04, + 2.117668e+04, + 5.613727e+03, + -9.539372e+04, + -1.631387e+04, + 1.943298e+04, + 6.409506e+03, + -4.737571e+03, + -2.057378e+04, + 1.755731e+04, + 7.189996e+03, + -1.608912e+04, + -1.712993e+04, + 1.567655e+04, + 7.938106e+03, + -2.088100e+03, + -1.571847e+04, + 1.391656e+04, + 8.650875e+03, + -3.661972e+04, + -1.147036e+04, + 1.228681e+04, + 9.323355e+03, + 1.657977e+04, + -1.377689e+04, + 1.070581e+04, + 9.954345e+03, + -3.463596e+03, + -9.698335e+03, + 9.274149e+03, + 1.053254e+04, + -5.891139e+03, + -8.043333e+03, + 8.040790e+03, + 1.106587e+04, + -1.191734e+04, + -6.450980e+03, + 6.917247e+03, + 1.155414e+04, + 3.491650e+02, + -6.574146e+03, + 5.858587e+03, + 1.199621e+04, + -7.578241e+03, + -4.689544e+03, + 4.907900e+03, + 1.238765e+04, + -1.092448e+04, + -3.741680e+03, + 4.055337e+03, + 1.273290e+04, + 4.106714e+03, + -4.518819e+03, + 3.238118e+03, + 1.303002e+04, + -2.102369e+04, + -1.074664e+03, + 2.560131e+03, + 1.327469e+04, + -1.056000e+04, + -2.204585e+03, + 1.868347e+03, + 1.347934e+04, + -2.377808e+04, + -1.032248e+02, + 1.180047e+03, + 1.362602e+04, + -1.508705e+04, + -9.908849e+00, + 4.767186e+02, + 1.371823e+04, +}; + +double solarDataset720[] = +{ + 2.525918e+14, + -2.554558e+09, + -1.370972e+05, + 5.293898e+03, + -9.815726e+12, + 2.361968e+09, + 0, + 5.292070e+03, + -2.161284e+10, + 3.681165e+06, + 1.412622e+05, + 5.309215e+03, + 5.368037e+09, + -9.739389e+06, + 1.367183e+05, + 5.355116e+03, + 1.822593e+09, + -3.920899e+06, + 1.308458e+05, + 5.439746e+03, + 7.141674e+07, + -1.791913e+05, + 1.286456e+05, + 5.575115e+03, + -2.827977e+08, + 6.550345e+05, + 1.286106e+05, + 5.776749e+03, + -4.278581e+07, + -3.471843e+05, + 1.274126e+05, + 6.058476e+03, + -4.678445e+07, + -3.154022e+05, + 1.243004e+05, + 6.425649e+03, + -1.705526e+06, + -5.419689e+05, + 1.199770e+05, + 6.883746e+03, + -4.511176e+07, + -2.088734e+05, + 1.148018e+05, + 7.432212e+03, + -9.899075e+06, + -5.263774e+05, + 1.080124e+05, + 8.072059e+03, + -1.136389e+07, + -4.495800e+05, + 9.941715e+04, + 8.783408e+03, + -4.432855e+06, + -4.699310e+05, + 8.991963e+04, + 9.551761e+03, + -6.678983e+06, + -3.711487e+05, + 7.987525e+04, + 1.035412e+04, + -1.048795e+06, + -3.923684e+05, + 6.943065e+04, + 1.117043e+04, + -1.487792e+06, + -3.054383e+05, + 5.919156e+04, + 1.197072e+04, + -5.138917e+05, + -2.592954e+05, + 4.970314e+04, + 1.273960e+04, + 4.638959e+05, + -2.185755e+05, + 4.110096e+04, + 1.345986e+04, + -3.133674e+05, + -1.488658e+05, + 3.379813e+04, + 1.412155e+04, + 7.701003e+02, + -1.222341e+05, + 2.757857e+04, + 1.472633e+04, + 1.443326e+05, + -9.575337e+04, + 2.226568e+04, + 1.526806e+04, + 1.586498e+05, + -7.156428e+04, + 1.793449e+04, + 1.574764e+04, + 1.756484e+04, + -4.896879e+04, + 1.451310e+04, + 1.617102e+04, + 8.828851e+04, + -3.944113e+04, + 1.175869e+04, + 1.654602e+04, + -6.323419e+04, + -2.418904e+04, + 9.565046e+03, + 1.687570e+04, + 9.171615e+04, + -2.493151e+04, + 7.723482e+03, + 1.716762e+04, + -1.428085e+04, + -1.376363e+04, + 6.275414e+03, + 1.741964e+04, + 2.437380e+04, + -1.256407e+04, + 5.133211e+03, + 1.764318e+04, + 1.709855e+03, + -8.360511e+03, + 4.206652e+03, + 1.783845e+04, + -1.602339e+03, + -6.380326e+03, + 3.464464e+03, + 1.801101e+04, + 1.086892e+04, + -5.672266e+03, + 2.839413e+03, + 1.816274e+04, + 1.947834e+03, + -3.743557e+03, + 2.343114e+03, + 1.829498e+04, + -4.914126e+03, + -2.541311e+03, + 1.951555e+03, + 1.841212e+04, + 7.500891e+03, + -2.900219e+03, + 1.606900e+03, + 1.851587e+04, + -6.683859e+03, + -1.171479e+03, + 1.335113e+03, + 1.860554e+04, + 2.524698e+03, + -1.755106e+03, + 1.097230e+03, + 1.868573e+04, + 1.413303e+02, + -1.123324e+03, + 8.913331e+02, + 1.875383e+04, + -5.972485e+02, + -8.258019e+02, + 7.301851e+02, + 1.881276e+04, + -1.374811e+03, + -6.044738e+02, + 5.930501e+02, + 1.886362e+04, + -2.464199e+02, + -6.001397e+02, + 4.686460e+02, + 1.890681e+04, + -3.386839e+03, + -1.749768e+02, + 3.615101e+02, + 1.894210e+04, + 1.115795e+03, + -5.876697e+02, + 2.497363e+02, + 1.897051e+04, + -5.909912e+03, + 3.198230e+02, + 1.691543e+02, + 1.898962e+04, + -1.580136e+03, + -5.978889e+01, + 6.196234e+01, + 1.900370e+04, + 2.989518e+13, + -1.289421e+08, + 1.099829e+05, + 2.834177e+03, + -3.090365e+12, + 6.856653e+08, + 1.321869e+05, + 2.836187e+03, + 9.682967e+10, + -5.904165e+07, + 1.626712e+05, + 2.856692e+03, + -5.436058e+09, + 6.318661e+06, + 1.551570e+05, + 2.907038e+03, + 6.591801e+08, + -1.130499e+06, + 1.565831e+05, + 3.007157e+03, + -7.138774e+08, + 1.316135e+06, + 1.563922e+05, + 3.171322e+03, + 3.237601e+07, + -7.953836e+05, + 1.552515e+05, + 3.417128e+03, + -4.655197e+07, + -3.938954e+05, + 1.522345e+05, + 3.753533e+03, + -2.305480e+07, + -4.616706e+05, + 1.487543e+05, + 4.192527e+03, + -8.350406e+07, + -1.385543e+05, + 1.443327e+05, + 4.741292e+03, + -2.273311e+07, + -6.254407e+05, + 1.375714e+05, + 5.403999e+03, + -2.274408e+07, + -5.692192e+05, + 1.282140e+05, + 6.164358e+03, + -6.189259e+06, + -6.624563e+05, + 1.172277e+05, + 7.007832e+03, + -1.040898e+07, + -5.161737e+05, + 1.053028e+05, + 7.908995e+03, + -2.699482e+06, + -5.346775e+05, + 9.279238e+04, + 8.847287e+03, + -2.235491e+06, + -4.383825e+05, + 8.020280e+04, + 9.789863e+03, + -1.374288e+06, + -3.645659e+05, + 6.827003e+04, + 1.071465e+04, + -1.221563e+04, + -3.098323e+05, + 5.718372e+04, + 1.159997e+04, + -3.432144e+05, + -2.317054e+05, + 4.735807e+04, + 1.242805e+04, + 1.796722e+05, + -1.889060e+05, + 3.883150e+04, + 1.319192e+04, + 5.940359e+04, + -1.395754e+05, + 3.160908e+04, + 1.388396e+04, + 1.898772e+05, + -1.085417e+05, + 2.562541e+04, + 1.450571e+04, + 6.259607e+04, + -7.758476e+04, + 2.076082e+04, + 1.505893e+04, + 9.493680e+03, + -5.706448e+04, + 1.682657e+04, + 1.555047e+04, + 1.154325e+05, + -4.666948e+04, + 1.358994e+04, + 1.598475e+04, + -6.600032e+03, + -3.033826e+04, + 1.102596e+04, + 1.636513e+04, + 5.150180e+04, + -2.556832e+04, + 8.962958e+03, + 1.670138e+04, + -5.043216e+03, + -1.683693e+04, + 7.309487e+03, + 1.699565e+04, + 4.630010e+04, + -1.531867e+04, + 5.969269e+03, + 1.725549e+04, + -3.176222e+04, + -7.688050e+03, + 4.927359e+03, + 1.748265e+04, + 1.990387e+04, + -9.109929e+03, + 4.042288e+03, + 1.768595e+04, + 1.136736e+04, + -6.270534e+03, + 3.303928e+03, + 1.786155e+04, + -1.921046e+03, + -4.000413e+03, + 2.750164e+03, + 1.801613e+04, + -8.295624e+03, + -2.881436e+03, + 2.295908e+03, + 1.815411e+04, + 1.158890e+04, + -3.694378e+03, + 1.877598e+03, + 1.827603e+04, + -7.985865e+03, + -1.327338e+03, + 1.554511e+03, + 1.838032e+04, + 6.287924e+03, + -2.268548e+03, + 1.279719e+03, + 1.847378e+04, + -5.841113e+03, + -7.169778e+02, + 1.056665e+03, + 1.855324e+04, + 2.331521e+03, + -1.372167e+03, + 8.596951e+02, + 1.862405e+04, + -6.715950e+02, + -7.448262e+02, + 6.904255e+02, + 1.868294e+04, + -2.277589e+03, + -4.673925e+02, + 5.571070e+02, + 1.873345e+04, + -2.143745e+03, + -4.255135e+02, + 4.286454e+02, + 1.877595e+04, + -2.342452e+03, + -3.095573e+02, + 3.018268e+02, + 1.880924e+04, + -2.141651e+03, + -1.996398e+02, + 1.826752e+02, + 1.883282e+04, + -1.800736e+03, + -5.698464e+01, + 8.207416e+01, + 1.884678e+04, + 1.447401e+13, + -8.993067e+07, + 7.803754e+04, + 1.013116e+03, + -8.727215e+11, + 2.292335e+08, + 8.783964e+04, + 1.014508e+03, + -2.637424e+10, + 1.849076e+07, + 1.050400e+05, + 1.026912e+03, + 2.501031e+09, + -8.153203e+05, + 1.086648e+05, + 1.062371e+03, + 6.350316e+08, + 1.081054e+06, + 1.106769e+05, + 1.131995e+03, + -5.067515e+08, + 2.734648e+06, + 1.150568e+05, + 1.250306e+03, + 8.471154e+07, + 7.604123e+05, + 1.198954e+05, + 1.435562e+03, + -5.169626e+07, + 1.125922e+06, + 1.244427e+05, + 1.702570e+03, + -1.420182e+08, + 1.257137e+06, + 1.296866e+05, + 2.073373e+03, + -6.016236e+07, + 4.507910e+05, + 1.331301e+05, + 2.568637e+03, + -6.181395e+07, + 2.560844e+05, + 1.334031e+05, + 3.194251e+03, + -2.944661e+07, + -1.809190e+05, + 1.302883e+05, + 3.952267e+03, + -1.974673e+07, + -3.302753e+05, + 1.236749e+05, + 4.825974e+03, + -1.831211e+07, + -3.630744e+05, + 1.144628e+05, + 5.793807e+03, + -1.063314e+05, + -5.671483e+05, + 1.027316e+05, + 6.825455e+03, + -7.428135e+06, + -3.646082e+05, + 9.035604e+04, + 7.875637e+03, + -4.224498e+05, + -4.226070e+05, + 7.785079e+04, + 8.928044e+03, + -5.225200e+05, + -3.292931e+05, + 6.569603e+04, + 9.939440e+03, + 1.351084e+05, + -2.692418e+05, + 5.486961e+04, + 1.089545e+04, + -6.986607e+05, + -1.900635e+05, + 4.546374e+04, + 1.178319e+04, + 8.151561e+05, + -1.826275e+05, + 3.717645e+04, + 1.259855e+04, + -2.097157e+05, + -1.087743e+05, + 3.039241e+04, + 1.332873e+04, + 8.873651e+04, + -9.305999e+04, + 2.483143e+04, + 1.399033e+04, + 8.394321e+04, + -7.004892e+04, + 2.014053e+04, + 1.457831e+04, + 2.568894e+04, + -5.092930e+04, + 1.634436e+04, + 1.509840e+04, + 1.280322e+05, + -4.220220e+04, + 1.325641e+04, + 1.555749e+04, + -3.361001e+04, + -2.513248e+04, + 1.085224e+04, + 1.596046e+04, + 2.979468e+04, + -2.253703e+04, + 8.893598e+03, + 1.631985e+04, + 3.723816e+04, + -1.735501e+04, + 7.267372e+03, + 1.663501e+04, + -1.726087e+04, + -1.053326e+04, + 6.006399e+03, + 1.691243e+04, + 1.578262e+04, + -1.021949e+04, + 4.953342e+03, + 1.715986e+04, + 1.743296e+03, + -6.992042e+03, + 4.079600e+03, + 1.737627e+04, + 1.170557e+03, + -5.467831e+03, + 3.375752e+03, + 1.756744e+04, + 7.317985e+03, + -4.658490e+03, + 2.788852e+03, + 1.773572e+04, + -2.944508e+03, + -2.890565e+03, + 2.322051e+03, + 1.788333e+04, + -1.384627e+03, + -2.499429e+03, + 1.932715e+03, + 1.801462e+04, + 3.870094e+03, + -2.380198e+03, + 1.589263e+03, + 1.812959e+04, + -7.589419e+03, + -9.387526e+02, + 1.316390e+03, + 1.822906e+04, + 6.765004e+03, + -2.055863e+03, + 1.059421e+03, + 1.831691e+04, + -7.908487e+03, + -1.944332e+02, + 8.634886e+02, + 1.838909e+04, + 2.402999e+03, + -1.255047e+03, + 6.776365e+02, + 1.845334e+04, + -3.022120e+03, + -3.713633e+02, + 5.165854e+02, + 1.850326e+04, + -2.480041e+03, + -3.839458e+02, + 3.785083e+02, + 1.854419e+04, + -7.542281e+03, + 2.431373e+02, + 2.418575e+02, + 1.857417e+04, + -1.557329e+03, + -1.160108e+02, + 7.276011e+01, + 1.859310e+04, + -4.132444e+13, + 4.983149e+08, + 6.380020e+04, + 1.851747e+02, + 1.098450e+12, + -2.448093e+08, + 4.414219e+04, + 1.862109e+02, + -3.624187e+10, + 2.421969e+07, + 3.304274e+04, + 1.899028e+02, + 3.813707e+09, + -2.123873e+06, + 3.724471e+04, + 2.020496e+02, + -9.762495e+07, + 2.271395e+06, + 3.918961e+04, + 2.259298e+02, + 3.247350e+08, + 1.259102e+06, + 4.364256e+04, + 2.695358e+02, + -7.726482e+07, + 2.316327e+06, + 4.998989e+04, + 3.423470e+02, + -1.019017e+08, + 2.228401e+06, + 5.902081e+04, + 4.620756e+02, + -5.107875e+07, + 1.805353e+06, + 6.940990e+04, + 6.504069e+02, + -9.891926e+07, + 1.883571e+06, + 8.077203e+04, + 9.326294e+02, + -6.594961e+07, + 1.309945e+06, + 9.189406e+04, + 1.340972e+03, + -5.421313e+07, + 8.991718e+05, + 1.004014e+05, + 1.895689e+03, + -3.766459e+07, + 4.481471e+05, + 1.050914e+05, + 2.607513e+03, + -2.032421e+07, + 5.007750e+04, + 1.049523e+05, + 3.466517e+03, + -1.278947e+07, + -1.455609e+05, + 1.004758e+05, + 4.443536e+03, + -6.566446e+06, + -2.703383e+05, + 9.276981e+04, + 5.502737e+03, + -2.497008e+06, + -3.170135e+05, + 8.300714e+04, + 6.601359e+03, + -2.210423e+06, + -2.754951e+05, + 7.259218e+04, + 7.700522e+03, + -8.795482e+05, + -2.564902e+05, + 6.219949e+04, + 8.772571e+03, + 4.875594e+05, + -2.333622e+05, + 5.229111e+04, + 9.788438e+03, + -3.924964e+05, + -1.589745e+05, + 4.367724e+04, + 1.073035e+04, + 2.878946e+05, + -1.428811e+05, + 3.620966e+04, + 1.160062e+04, + -8.617935e+04, + -9.818419e+04, + 2.987112e+04, + 1.238861e+04, + 1.563730e+05, + -8.375478e+04, + 2.455211e+04, + 1.310190e+04, + 3.157587e+04, + -5.922817e+04, + 2.015025e+04, + 1.373849e+04, + 1.956095e+04, + -4.524892e+04, + 1.656404e+04, + 1.430792e+04, + 4.832654e+04, + -3.595669e+04, + 1.358688e+04, + 1.481455e+04, + 4.014487e+04, + -2.701491e+04, + 1.116623e+04, + 1.526291e+04, + -8.957043e+03, + -1.852113e+04, + 9.237221e+03, + 1.566073e+04, + 1.813805e+04, + -1.597159e+04, + 7.633708e+03, + 1.601542e+04, + 7.265770e+03, + -1.171307e+04, + 6.306238e+03, + 1.632830e+04, + 5.845122e+03, + -9.056395e+03, + 5.229642e+03, + 1.660539e+04, + 1.705465e+03, + -6.842519e+03, + 4.346327e+03, + 1.685070e+04, + -3.099670e+03, + -5.132762e+03, + 3.614027e+03, + 1.706799e+04, + 9.091824e+03, + -4.904382e+03, + 2.986894e+03, + 1.725985e+04, + -3.097208e+03, + -2.861985e+03, + 2.486454e+03, + 1.742725e+04, + -5.115305e+03, + -2.254430e+03, + 2.073917e+03, + 1.757629e+04, + 3.305222e+03, + -2.536090e+03, + 1.690410e+03, + 1.770681e+04, + 8.613358e+02, + -1.693291e+03, + 1.373974e+03, + 1.781760e+04, + -5.270481e+03, + -8.177981e+02, + 1.129554e+03, + 1.791337e+04, + 7.202933e+01, + -1.244067e+03, + 8.946304e+02, + 1.799642e+04, + -3.932364e+03, + -5.617175e+02, + 6.851235e+02, + 1.806340e+04, + -2.555341e+03, + -5.981541e+02, + 4.914744e+02, + 1.811718e+04, + -7.312382e+03, + 8.261489e+01, + 3.128333e+02, + 1.815579e+04, + -3.444405e+03, + -5.151392e+01, + 1.189236e+02, + 1.818034e+04, + 8.583418e+11, + -5.864616e+06, + 5.801889e+03, + 1.923411e+01, + -6.597669e+10, + 1.477868e+07, + 6.364852e+03, + 1.933677e+01, + 2.967102e+09, + -1.520837e+06, + 7.049525e+03, + 2.020405e+01, + 1.724924e+09, + -8.185196e+05, + 7.008149e+03, + 2.245400e+01, + -3.378314e+08, + 1.650445e+06, + 8.069082e+03, + 2.703836e+01, + 1.552037e+08, + 6.585714e+05, + 1.041940e+04, + 3.695513e+01, + -3.403201e+07, + 1.345522e+06, + 1.363123e+04, + 5.551902e+01, + -1.703697e+07, + 1.439665e+06, + 1.903317e+04, + 9.145205e+01, + -9.003897e+07, + 1.961474e+06, + 2.698744e+04, + 1.586961e+02, + -6.267348e+07, + 1.801412e+06, + 3.788213e+04, + 2.823781e+02, + -7.470787e+07, + 1.811829e+06, + 5.060948e+04, + 4.922647e+02, + -5.781055e+07, + 1.427287e+06, + 6.398865e+04, + 8.261355e+02, + -4.006817e+07, + 9.697074e+05, + 7.540147e+04, + 1.312352e+03, + -3.092562e+07, + 6.019593e+05, + 8.322421e+04, + 1.964145e+03, + -1.617086e+07, + 1.930166e+05, + 8.632748e+04, + 2.776467e+03, + -7.153255e+06, + -5.054112e+04, + 8.478684e+04, + 3.717483e+03, + -8.315402e+06, + -7.881484e+04, + 8.021572e+04, + 4.749714e+03, + -1.434409e+06, + -2.349591e+05, + 7.304797e+04, + 5.840556e+03, + -1.429239e+06, + -2.030418e+05, + 6.452381e+04, + 6.933083e+03, + -6.545407e+05, + -1.903916e+05, + 5.599103e+04, + 8.003800e+03, + -3.793090e+04, + -1.703670e+05, + 4.774203e+04, + 9.026419e+03, + -9.296898e+04, + -1.335883e+05, + 4.028177e+04, + 9.983296e+03, + 5.681627e+04, + -1.098699e+05, + 3.373445e+04, + 1.086875e+04, + 7.934290e+04, + -8.617558e+04, + 2.809759e+04, + 1.167776e+04, + -1.118900e+05, + -6.075673e+04, + 2.336891e+04, + 1.241185e+04, + 2.127956e+05, + -5.972293e+04, + 1.927296e+04, + 1.307544e+04, + -1.157300e+04, + -3.572063e+04, + 1.597792e+04, + 1.366415e+04, + -1.006642e+04, + -2.856674e+04, + 1.333737e+04, + 1.419680e+04, + 2.851548e+04, + -2.432571e+04, + 1.105653e+04, + 1.467415e+04, + 1.366951e+04, + -1.801951e+04, + 9.163722e+03, + 1.509781e+04, + 2.547955e+03, + -1.350032e+04, + 7.624751e+03, + 1.547499e+04, + 1.201292e+04, + -1.116877e+04, + 6.343424e+03, + 1.581086e+04, + -7.993522e+03, + -7.540323e+03, + 5.292034e+03, + 1.610860e+04, + 1.389183e+04, + -7.477679e+03, + 4.396669e+03, + 1.637388e+04, + -4.384238e+03, + -4.479632e+03, + 3.669053e+03, + 1.660659e+04, + -3.138125e+03, + -3.810639e+03, + 3.067716e+03, + 1.681444e+04, + 2.205661e+03, + -3.486730e+03, + 2.530998e+03, + 1.699733e+04, + 3.541657e+03, + -2.789475e+03, + 2.081942e+03, + 1.715588e+04, + -6.419750e+03, + -1.349094e+03, + 1.732402e+03, + 1.729391e+04, + -3.412184e+03, + -1.520739e+03, + 1.412396e+03, + 1.741589e+04, + -1.601511e+03, + -1.397792e+03, + 1.100329e+03, + 1.751816e+04, + 1.155029e+03, + -1.304754e+03, + 8.286155e+02, + 1.760046e+04, + -1.103308e+04, + 2.218581e+02, + 6.236810e+02, + 1.766473e+04, + -2.654581e+03, + -6.688353e+02, + 3.763136e+02, + 1.771593e+04, + -3.364310e+03, + -1.387471e+02, + 1.691463e+02, + 1.774386e+04, + -3.366371e+12, + 4.551509e+07, + 2.521199e+03, + 1.176103e+00, + 4.269705e+10, + -9.375992e+06, + 1.089486e+03, + 1.215845e+00, + -2.678077e+09, + 1.632330e+06, + 6.917876e+02, + 1.285806e+00, + 5.646428e+08, + -4.307335e+05, + 8.992048e+02, + 1.593390e+00, + -6.281455e+07, + 4.035231e+05, + 1.038831e+03, + 2.138181e+00, + 3.725795e+07, + 2.678653e+05, + 1.679090e+03, + 3.603652e+00, + -1.868599e+07, + 6.078925e+05, + 2.794495e+03, + 7.040473e+00, + -2.585413e+07, + 8.892713e+05, + 5.187431e+03, + 1.587553e+01, + -6.872034e+07, + 1.419539e+06, + 9.710418e+03, + 3.789527e+01, + -5.812931e+07, + 1.579306e+06, + 1.744566e+04, + 9.048376e+01, + -7.327242e+07, + 1.818701e+06, + 2.839538e+04, + 2.005187e+02, + -6.016819e+07, + 1.612661e+06, + 4.199317e+04, + 4.081326e+02, + -4.581463e+07, + 1.252723e+06, + 5.561195e+04, + 7.517504e+02, + -3.153234e+07, + 8.265349e+05, + 6.688402e+04, + 1.259016e+03, + -1.853079e+07, + 4.259439e+05, + 7.406056e+04, + 1.936723e+03, + -1.281312e+07, + 1.802667e+05, + 7.674943e+04, + 2.768831e+03, + -5.976285e+06, + -3.734133e+04, + 7.529271e+04, + 3.725956e+03, + -3.885336e+06, + -1.139315e+05, + 7.068494e+04, + 4.762226e+03, + -1.400809e+06, + -1.718468e+05, + 6.415010e+04, + 5.837947e+03, + -8.976969e+05, + -1.633241e+05, + 5.674855e+04, + 6.911982e+03, + -2.378758e+05, + -1.548497e+05, + 4.928211e+04, + 7.958122e+03, + -4.067629e+05, + -1.224513e+05, + 4.221302e+04, + 8.953753e+03, + 3.647054e+05, + -1.214788e+05, + 3.566013e+04, + 9.887462e+03, + -3.019450e+05, + -7.317725e+04, + 3.004861e+04, + 1.074445e+04, + 2.857755e+05, + -7.965496e+04, + 2.512925e+04, + 1.153600e+04, + -1.459626e+05, + -4.460431e+04, + 2.100972e+04, + 1.224792e+04, + 1.068546e+05, + -4.654852e+04, + 1.751428e+04, + 1.289850e+04, + 1.656740e+04, + -3.151584e+04, + 1.455586e+04, + 1.347833e+04, + 3.276173e+04, + -2.545561e+04, + 1.216656e+04, + 1.400043e+04, + -2.466748e+04, + -1.712349e+04, + 1.020130e+04, + 1.446904e+04, + 1.127833e+04, + -1.587340e+04, + 8.510004e+03, + 1.489124e+04, + 1.967525e+04, + -1.277787e+04, + 7.060958e+03, + 1.526518e+04, + -5.566324e+03, + -8.375268e+03, + 5.904955e+03, + 1.559653e+04, + 6.832170e+03, + -7.582035e+03, + 4.940098e+03, + 1.589320e+04, + -1.505137e+03, + -5.380298e+03, + 4.129024e+03, + 1.615572e+04, + -4.851997e+03, + -4.146360e+03, + 3.449533e+03, + 1.638915e+04, + 6.220823e+03, + -4.200678e+03, + 2.847212e+03, + 1.659502e+04, + -2.257540e+03, + -2.529572e+03, + 2.356955e+03, + 1.677328e+04, + -6.506661e+03, + -1.772864e+03, + 1.953201e+03, + 1.693045e+04, + 1.966362e+03, + -2.261074e+03, + 1.566694e+03, + 1.706682e+04, + -2.160232e+03, + -1.314709e+03, + 1.240209e+03, + 1.717955e+04, + -6.509197e+03, + -6.756691e+02, + 9.705296e+02, + 1.727398e+04, + -3.335667e+03, + -8.945697e+02, + 6.952550e+02, + 1.735046e+04, + -1.024257e+04, + 1.096345e+02, + 4.408097e+02, + 1.740488e+04, + -4.884337e+03, + -6.995646e+01, + 1.680061e+02, + 1.743947e+04, + 5.051346e+10, + -3.482968e+05, + -3.302132e+01, + 1.117732e-02, + -6.399594e+09, + 1.170259e+06, + 0, + 1.076335e-02, + 2.378197e+07, + -1.273564e+04, + 2.884079e+00, + 1.655900e-02, + -4.193101e+07, + 6.299121e+04, + 2.194923e+00, + 1.697297e-02, + 2.186069e+06, + 9.422620e+03, + 3.137534e+01, + 3.311800e-02, + 3.955651e+06, + 1.710432e+04, + 5.844243e+01, + 7.906922e-02, + -5.048300e+06, + 8.807915e+04, + 1.413038e+02, + 2.281002e-01, + -5.834264e+06, + 1.808251e+05, + 4.543665e+02, + 9.066052e-01, + -1.717877e+07, + 4.260059e+05, + 1.359382e+03, + 3.620625e+00, + -3.208799e+07, + 7.976457e+05, + 3.825320e+03, + 1.376715e+01, + -4.503408e+07, + 1.172645e+06, + 9.176929e+03, + 4.577239e+01, + -4.518399e+07, + 1.327171e+06, + 1.816020e+04, + 1.279439e+02, + -4.202028e+07, + 1.290199e+06, + 2.997675e+04, + 2.998951e+02, + -3.158344e+07, + 1.021061e+06, + 4.259877e+04, + 6.043667e+02, + -2.250542e+07, + 7.018793e+05, + 5.343008e+04, + 1.070337e+03, + -1.237124e+07, + 3.643660e+05, + 6.071096e+04, + 1.705578e+03, + -9.254795e+06, + 1.838508e+05, + 6.403515e+04, + 2.492654e+03, + -4.016937e+06, + -5.014300e+03, + 6.370683e+04, + 3.405094e+03, + -3.183145e+06, + -5.838735e+04, + 6.052375e+04, + 4.397082e+03, + -6.326153e+05, + -1.310928e+05, + 5.546362e+04, + 5.432589e+03, + -8.980466e+05, + -1.100814e+05, + 4.957269e+04, + 6.467941e+03, + -1.845464e+05, + -1.171335e+05, + 4.351408e+04, + 7.484261e+03, + -7.330240e+04, + -1.000436e+05, + 3.759655e+04, + 8.455153e+03, + -8.536306e+04, + -8.124805e+04, + 3.220664e+04, + 9.369683e+03, + 6.271460e+04, + -7.084973e+04, + 2.735632e+04, + 1.022133e+04, + -6.549462e+04, + -5.149641e+04, + 2.313856e+04, + 1.100420e+04, + 1.042378e+05, + -4.819678e+04, + 1.945257e+04, + 1.172164e+04, + -6.586040e+03, + -3.243944e+04, + 1.636407e+04, + 1.236958e+04, + 1.937888e+04, + -2.723890e+04, + 1.379626e+04, + 1.295960e+04, + -2.094192e+04, + -1.965536e+04, + 1.161032e+04, + 1.349253e+04, + 2.879330e+04, + -1.852871e+04, + 9.713757e+03, + 1.397336e+04, + 1.432240e+04, + -1.343548e+04, + 8.130835e+03, + 1.440101e+04, + -1.821063e+04, + -8.725253e+03, + 6.865050e+03, + 1.478482e+04, + 1.419588e+04, + -9.358718e+03, + 5.748762e+03, + 1.513083e+04, + 1.055273e+03, + -6.305478e+03, + 4.805868e+03, + 1.543573e+04, + -5.662820e+03, + -4.626779e+03, + 4.041581e+03, + 1.570792e+04, + 3.620958e+02, + -4.298662e+03, + 3.366303e+03, + 1.595011e+04, + 1.279925e+03, + -3.472943e+03, + 2.779108e+03, + 1.616176e+04, + -8.119412e+03, + -1.999793e+03, + 2.294268e+03, + 1.634600e+04, + 2.703808e+03, + -2.683207e+03, + 1.844539e+03, + 1.650646e+04, + -5.608882e+03, + -1.263187e+03, + 1.464334e+03, + 1.663925e+04, + -2.539837e+03, + -1.379024e+03, + 1.128950e+03, + 1.675095e+04, + -6.360200e+03, + -6.734980e+02, + 8.228503e+02, + 1.683877e+04, + -1.233536e+04, + 1.203160e+02, + 5.305324e+02, + 1.690457e+04, + -5.730992e+03, + -9.461582e+01, + 1.996954e+02, + 1.694608e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.824802e+05, + 5.662913e+02, + 0, + 0, + -2.089360e+05, + 7.956041e+02, + 5.856313e-01, + 4.139750e-04, + 2.204465e+05, + -3.219661e+02, + 1.539320e+00, + 2.483850e-03, + -2.076559e+05, + 5.716207e+03, + 3.299164e+00, + 6.623600e-03, + -1.630833e+06, + 3.651570e+04, + 3.131705e+01, + 5.961240e-02, + -4.750601e+06, + 1.270860e+05, + 2.360423e+02, + 6.023336e-01, + -1.059805e+07, + 3.175159e+05, + 1.112384e+03, + 3.994031e+00, + -1.908619e+07, + 5.949891e+05, + 3.700632e+03, + 1.870919e+01, + -2.366093e+07, + 8.041978e+05, + 9.162593e+03, + 6.578187e+01, + -2.229039e+07, + 8.434683e+05, + 1.752631e+04, + 1.799168e+02, + -1.954097e+07, + 7.599747e+05, + 2.748722e+04, + 4.014783e+02, + -1.339870e+07, + 5.499302e+05, + 3.708410e+04, + 7.652249e+02, + -1.029819e+07, + 3.727003e+05, + 4.454472e+04, + 1.285347e+03, + -4.368519e+06, + 1.495000e+05, + 4.891481e+04, + 1.957839e+03, + -4.419116e+06, + 8.860581e+04, + 5.036253e+04, + 2.752876e+03, + -1.481145e+06, + -3.114013e+04, + 4.934483e+04, + 3.647707e+03, + -1.131953e+06, + -5.304541e+04, + 4.640097e+04, + 4.594923e+03, + -4.087520e+05, + -7.696885e+04, + 4.249037e+04, + 5.566846e+03, + -4.277536e+05, + -6.969004e+04, + 3.810892e+04, + 6.533158e+03, + -3.981790e+04, + -7.471184e+04, + 3.357954e+04, + 7.475552e+03, + -5.532513e+04, + -6.146236e+04, + 2.921408e+04, + 8.372805e+03, + 2.297742e+04, + -5.372960e+04, + 2.523788e+04, + 9.218872e+03, + -4.526357e+04, + -4.095211e+04, + 2.170188e+04, + 1.000775e+04, + 2.858501e+04, + -3.694172e+04, + 1.854799e+04, + 1.073977e+04, + -3.310096e+04, + -2.679609e+04, + 1.578940e+04, + 1.141043e+04, + 8.050741e+04, + -2.739862e+04, + 1.336283e+04, + 1.202398e+04, + -6.328003e+04, + -1.355651e+04, + 1.138577e+04, + 1.257725e+04, + 3.556582e+04, + -1.753080e+04, + 9.641932e+03, + 1.308660e+04, + -1.740585e+03, + -1.121468e+04, + 8.123657e+03, + 1.354004e+04, + 4.908269e+03, + -9.544626e+03, + 6.882834e+03, + 1.395006e+04, + -1.374891e+04, + -6.463029e+03, + 5.824501e+03, + 1.431834e+04, + 1.616534e+04, + -7.552350e+03, + 4.872531e+03, + 1.464918e+04, + -1.772732e+04, + -3.244296e+03, + 4.094072e+03, + 1.493915e+04, + 9.689841e+03, + -5.153985e+03, + 3.394548e+03, + 1.520003e+04, + -9.718081e+03, + -2.277143e+03, + 2.798639e+03, + 1.542337e+04, + -6.633543e+02, + -2.845618e+03, + 2.278206e+03, + 1.562014e+04, + -4.278643e+03, + -1.892766e+03, + 1.806022e+03, + 1.578510e+04, + -5.433639e+03, + -1.433992e+03, + 1.392542e+03, + 1.592207e+04, + -7.648617e+03, + -9.150271e+02, + 1.007781e+03, + 1.603088e+04, + -8.612245e+03, + -4.992492e+02, + 6.366121e+02, + 1.611080e+04, + -6.343749e+03, + -2.056231e+02, + 2.914770e+02, + 1.616025e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -1.135457e+04, + 2.791630e+02, + 0, + 0, + -7.955274e+04, + 2.985927e+03, + 1.611854e+00, + 3.311800e-03, + -6.493155e+05, + 2.185150e+04, + 2.430096e+01, + 6.789190e-02, + -2.078383e+06, + 8.094823e+04, + 2.102422e+02, + 7.973158e-01, + -6.000804e+06, + 2.164166e+05, + 1.026160e+03, + 5.360976e+00, + -7.509681e+06, + 3.346173e+05, + 3.348784e+03, + 2.463110e+01, + -9.709505e+06, + 4.476003e+05, + 7.656050e+03, + 7.966162e+01, + -9.777442e+06, + 4.686826e+05, + 1.394700e+04, + 2.033979e+02, + -7.272808e+06, + 3.875450e+05, + 2.106614e+04, + 4.303630e+02, + -6.067236e+06, + 3.045882e+05, + 2.765451e+04, + 7.835942e+02, + -3.743681e+06, + 1.836085e+05, + 3.273701e+04, + 1.274002e+03, + -2.204422e+06, + 9.353882e+04, + 3.571808e+04, + 1.890326e+03, + -1.657859e+06, + 4.246821e+04, + 3.683928e+04, + 2.612254e+03, + -8.290594e+05, + -6.996218e+03, + 3.633556e+04, + 3.416065e+03, + -4.247261e+05, + -3.007731e+04, + 3.457926e+04, + 4.269476e+03, + -4.641352e+05, + -3.218306e+04, + 3.213056e+04, + 5.146662e+03, + 3.361520e+04, + -5.076883e+04, + 2.915608e+04, + 6.027337e+03, + -1.771637e+05, + -3.534656e+04, + 2.610100e+04, + 6.884571e+03, + -4.187517e+04, + -3.789010e+04, + 2.312238e+04, + 7.715656e+03, + 8.157849e+04, + -3.709787e+04, + 2.020432e+04, + 8.503474e+03, + -1.077364e+05, + -2.122007e+04, + 1.767673e+04, + 9.241847e+03, + 3.794355e+04, + -2.646253e+04, + 1.532351e+04, + 9.938986e+03, + -2.130421e+03, + -1.891377e+04, + 1.317205e+04, + 1.057852e+04, + 2.458205e+03, + -1.585926e+04, + 1.133734e+04, + 1.116822e+04, + -1.024932e+04, + -1.227472e+04, + 9.729063e+03, + 1.170859e+04, + 1.302318e+04, + -1.167431e+04, + 8.296256e+03, + 1.220175e+04, + -2.645825e+03, + -8.200160e+03, + 7.072718e+03, + 1.264649e+04, + -1.946731e+04, + -5.712138e+03, + 6.033100e+03, + 1.305017e+04, + 1.908928e+04, + -7.856404e+03, + 5.040421e+03, + 1.341373e+04, + -1.921842e+04, + -2.904171e+03, + 4.229674e+03, + 1.372996e+04, + 7.815975e+03, + -5.041356e+03, + 3.502309e+03, + 1.401481e+04, + -1.222105e+04, + -2.090158e+03, + 2.867188e+03, + 1.425719e+04, + -1.443808e+03, + -2.926865e+03, + 2.291167e+03, + 1.446851e+04, + -8.489031e+03, + -1.591866e+03, + 1.763443e+03, + 1.464092e+04, + -6.705956e+03, + -1.467380e+03, + 1.277843e+03, + 1.477936e+04, + -2.081073e+04, + 4.070825e+02, + 8.281583e+02, + 1.488046e+04, + -8.711751e+03, + -1.750566e+02, + 3.099560e+02, + 1.494590e+04, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -2.563361e+03, + 1.163545e+02, + 0, + 0, + -4.016111e+04, + 1.858785e+03, + 1.077420e+00, + 3.311800e-03, + -2.538882e+05, + 1.204296e+04, + 2.087577e+01, + 8.486487e-02, + -8.568045e+05, + 4.291307e+04, + 1.658171e+02, + 9.066052e-01, + -1.848280e+06, + 9.915324e+04, + 7.465497e+02, + 5.567136e+00, + -2.940953e+06, + 1.660291e+05, + 2.247529e+03, + 2.303978e+01, + -3.370234e+06, + 2.089797e+05, + 5.011666e+03, + 7.097312e+01, + -3.259946e+06, + 2.186080e+05, + 8.892565e+03, + 1.735888e+02, + -3.097047e+06, + 2.032584e+05, + 1.336445e+04, + 3.563617e+02, + -1.821542e+06, + 1.437017e+05, + 1.764923e+04, + 6.394746e+02, + -1.802035e+06, + 1.171823e+05, + 2.118802e+04, + 1.028337e+03, + -1.000732e+06, + 6.321832e+04, + 2.372803e+04, + 1.525758e+03, + -7.690809e+05, + 3.504376e+04, + 2.503483e+04, + 2.115529e+03, + -3.914894e+05, + 6.298728e+03, + 2.528814e+04, + 2.781267e+03, + -3.035803e+05, + -5.220347e+03, + 2.468978e+04, + 3.499590e+03, + -1.135560e+05, + -1.761802e+04, + 2.348786e+04, + 4.251977e+03, + -1.801992e+05, + -1.570171e+04, + 2.191753e+04, + 5.017650e+03, + 1.706318e+04, + -2.545515e+04, + 2.006382e+04, + 5.784350e+03, + -6.797234e+04, + -1.795386e+04, + 1.815090e+04, + 6.531178e+03, + -1.793578e+04, + -1.930896e+04, + 1.628261e+04, + 7.256949e+03, + -2.326593e+04, + -1.656161e+04, + 1.443550e+04, + 7.949046e+03, + 2.835627e+04, + -1.719413e+04, + 1.268036e+04, + 8.602624e+03, + -3.200616e+04, + -1.034425e+04, + 1.113968e+04, + 9.211894e+03, + -1.865985e+04, + -1.040495e+04, + 9.723009e+03, + 9.784332e+03, + 3.642018e+04, + -1.251177e+04, + 8.326634e+03, + 1.030995e+04, + -3.566772e+04, + -4.462584e+03, + 7.200285e+03, + 1.078360e+04, + 1.006844e+04, + -8.044621e+03, + 6.164034e+03, + 1.122405e+04, + -1.216649e+04, + -4.566143e+03, + 5.198882e+03, + 1.161386e+04, + 2.635189e+03, + -5.240412e+03, + 4.341674e+03, + 1.196312e+04, + -9.610371e+03, + -3.091591e+03, + 3.584704e+03, + 1.226633e+04, + -5.856573e+03, + -3.064976e+03, + 2.898065e+03, + 1.253040e+04, + -1.080053e+04, + -2.040908e+03, + 2.251652e+03, + 1.275061e+04, + -1.117498e+04, + -1.629984e+03, + 1.631049e+03, + 1.292734e+04, + -1.961133e+04, + -2.300963e+02, + 1.034000e+03, + 1.305636e+04, + -1.288515e+04, + -4.832654e+01, + 4.255474e+02, + 1.313697e+04, +}; + +double* solarDatasets[] = +{ + solarDataset320, + solarDataset360, + solarDataset400, + solarDataset440, + solarDataset480, + solarDataset520, + solarDataset560, + solarDataset600, + solarDataset640, + solarDataset680, + solarDataset720 +}; + +double limbDarkeningDataset320[] = +{ 0.087657, 0.767174, 0.658123, -1.02953, 0.703297, -0.186735 }; + +double limbDarkeningDataset360[] = +{ 0.122953, 1.01278, 0.238687, -1.12208, 1.17087, -0.424947 }; + +double limbDarkeningDataset400[] = +{ 0.123511, 1.08444, -0.405598, 0.370629, -0.240567, 0.0674778 }; + +double limbDarkeningDataset440[] = +{ 0.158489, 1.23346, -0.875754, 0.857812, -0.484919, 0.110895 }; + +double limbDarkeningDataset480[] = +{ 0.198587, 1.30507, -1.25998, 1.49727, -1.04047, 0.299516 }; + +double limbDarkeningDataset520[] = +{ 0.23695, 1.29927, -1.28034, 1.37760, -0.85054, 0.21706 }; + +double limbDarkeningDataset560[] = +{ 0.26892, 1.34319, -1.58427, 1.91271, -1.31350, 0.37295 }; + +double limbDarkeningDataset600[] = +{ 0.299804, 1.36718, -1.80884, 2.29294, -1.60595, 0.454874 }; + +double limbDarkeningDataset640[] = +{ 0.33551, 1.30791, -1.79382, 2.44646, -1.89082, 0.594769 }; + +double limbDarkeningDataset680[] = +{ 0.364007, 1.27316, -1.73824, 2.28535, -1.70203, 0.517758 }; + +double limbDarkeningDataset720[] = +{ 0.389704, 1.2448, -1.69708, 2.14061, -1.51803, 0.440004 }; + +double * limbDarkeningDatasets[] = +{ + limbDarkeningDataset320, + limbDarkeningDataset360, + limbDarkeningDataset400, + limbDarkeningDataset440, + limbDarkeningDataset480, + limbDarkeningDataset520, + limbDarkeningDataset560, + limbDarkeningDataset600, + limbDarkeningDataset640, + limbDarkeningDataset680, + limbDarkeningDataset720 +}; + + diff --git a/src/ext/stb b/src/ext/stb new file mode 160000 index 00000000..b42009b3 --- /dev/null +++ b/src/ext/stb @@ -0,0 +1 @@ +Subproject commit b42009b3b9d4ca35bc703f5310eedc74f584be58 diff --git a/src/ext/zlib b/src/ext/zlib new file mode 160000 index 00000000..54d591ea --- /dev/null +++ b/src/ext/zlib @@ -0,0 +1 @@ +Subproject commit 54d591eabf9fe0e84c725638f8d5d8d202a093fa diff --git a/src/pbrt/.clang-format b/src/pbrt/.clang-format new file mode 100644 index 00000000..88f32173 --- /dev/null +++ b/src/pbrt/.clang-format @@ -0,0 +1,15 @@ +BasedOnStyle: Google +AccessModifierOffset: -2 +IndentCaseLabels: false +PointerBindsToType: false +Standard: Cpp11 +IndentWidth: 4 +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AllowShortLambdasOnASingleLine: All +AlwaysBreakBeforeMultilineStrings: false +IncludeBlocks: Preserve +AllowAllConstructorInitializersOnNextLine: true +MaxEmptyLinesToKeep: 1 +ColumnLimit: 90 diff --git a/src/pbrt/base/#shape.h# b/src/pbrt/base/#shape.h# new file mode 100644 index 00000000..cc4e1dc0 --- /dev/null +++ b/src/pbrt/base/#shape.h# @@ -0,0 +1,83 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_SHAPE_H +#define PBRT_BASE_SHAPE_H + +#include + +#include +#include +#include +#include + +#include + +namespace pbrt { + +// Shape Declarations +class Triangle; +class BilinearPatch; +class Curve; +class Sphere; +class Cylinder; +class Disk; + +struct ShapeSample; +struct ShapeIntersection; + +class ShapeSampleContext; + +// ShapeHandle Definition +class ShapeHandle + : public TaggedPointer { + public: + // Shape Interface + using TaggedPointer::TaggedPointer; + + static pstd::vector Create(const std::string &name, + const Transform *renderFromObject, + const Transform *objectFromRender, + bool reverseOrientation, + const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc); + std::string ToString() const; + + PBRT_CPU_GPU inline Bounds3f Bounds() const; + + PBRT_CPU_GPU inline DirectionCone NormalBounds() const; + + PBRT_CPU_GPU inline pstd::optional Intersect( + const Ray &ray, Float tMax = Infinity) const; + + PBRT_CPU_GPU inline bool IntersectP(const Ray &ray, Float tMax = Infinity) const; + + PBRT_CPU_GPU inline Float Area() const; + + PBRT_CPU_GPU inline pstd::optional Sample(const Point2f &u) const; + + PBRT_CPU_GPU inline Float PDF(const Interaction &) const; + + PBRT_CPU_GPU inline pstd::optional Sample(const ShapeSampleContext &ctx, + const Point2f &u) const; + + PBRT_CPU_GPU inline Float PDF(const ShapeSampleContext &ctx, + const Vector3f &wi) const; + + private: + // ShapeHandle Private Members + friend class TriangleMesh; + friend class BilinearPatchMesh; + + static BufferCache *indexBufferCache; + static BufferCache *pBufferCache; + static BufferCache *nBufferCache; + static BufferCache *uvBufferCache; + static BufferCache *sBufferCache; + static BufferCache *faceIndexBufferCache; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_SHAPE_H diff --git a/src/pbrt/base/bssrdf.h b/src/pbrt/base/bssrdf.h new file mode 100644 index 00000000..52b0f903 --- /dev/null +++ b/src/pbrt/base/bssrdf.h @@ -0,0 +1,40 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_BSSRDF_H +#define PBRT_BASE_BSSRDF_H + +#include + +#include +#include + +#include + +namespace pbrt { + +struct BSSRDFSample; +struct BSSRDFProbeSegment; +struct SubsurfaceInteraction; +struct BSSRDFTable; + +// BSSRDFHandle Definition +class TabulatedBSSRDF; + +class BSSRDFHandle : public TaggedPointer { + public: + // BSSRDFHandle Public Interface + using TaggedPointer::TaggedPointer; + + PBRT_CPU_GPU inline SampledSpectrum S(const Point3f &p, const Vector3f &wi); + + PBRT_CPU_GPU inline BSSRDFProbeSegment Sample(Float u1, const Point2f &u2) const; + + PBRT_CPU_GPU inline BSSRDFSample ProbeIntersectionToSample( + const SubsurfaceInteraction &si, ScratchBuffer &scratchBuffer) const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_BSSRDF_H diff --git a/src/pbrt/base/bxdf.h b/src/pbrt/base/bxdf.h new file mode 100644 index 00000000..fdc9fb0a --- /dev/null +++ b/src/pbrt/base/bxdf.h @@ -0,0 +1,198 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_BXDF_H +#define PBRT_BASE_BXDF_H + +#include + +#include +#include +#include +#include + +#include + +namespace pbrt { + +class MeasuredBRDF; + +// BxDFReflTransFlags Definition +enum class BxDFReflTransFlags { + Unset = 0, + Reflection = 1 << 0, + Transmission = 1 << 1, + All = Reflection | Transmission +}; + +PBRT_CPU_GPU +inline BxDFReflTransFlags operator|(BxDFReflTransFlags a, BxDFReflTransFlags b) { + return BxDFReflTransFlags((int)a | (int)b); +} + +PBRT_CPU_GPU +inline int operator&(BxDFReflTransFlags a, BxDFReflTransFlags b) { + return ((int)a & (int)b); +} + +PBRT_CPU_GPU +inline BxDFReflTransFlags &operator|=(BxDFReflTransFlags &a, BxDFReflTransFlags b) { + (int &)a |= int(b); + return a; +} + +std::string ToString(BxDFReflTransFlags flags); + +// BxDFFlags Definition +enum class BxDFFlags { + Unset = 0, + Reflection = 1 << 0, + Transmission = 1 << 1, + Diffuse = 1 << 2, + Glossy = 1 << 3, + Specular = 1 << 4, + // Composite _BxDFFlags_ definitions + DiffuseReflection = Diffuse | Reflection, + DiffuseTransmission = Diffuse | Transmission, + GlossyReflection = Glossy | Reflection, + GlossyTransmission = Glossy | Transmission, + SpecularReflection = Specular | Reflection, + SpecularTransmission = Specular | Transmission, + All = Diffuse | Glossy | Specular | Reflection | Transmission + +}; + +PBRT_CPU_GPU +inline BxDFFlags operator|(BxDFFlags a, BxDFFlags b) { + return BxDFFlags((int)a | (int)b); +} + +PBRT_CPU_GPU +inline int operator&(BxDFFlags a, BxDFFlags b) { + return ((int)a & (int)b); +} + +PBRT_CPU_GPU +inline int operator&(BxDFFlags a, BxDFReflTransFlags b) { + return ((int)a & (int)b); +} + +PBRT_CPU_GPU +inline BxDFFlags &operator|=(BxDFFlags &a, BxDFFlags b) { + (int &)a |= int(b); + return a; +} + +PBRT_CPU_GPU +inline bool IsReflective(BxDFFlags flags) { + return (flags & BxDFFlags::Reflection) != 0; +} +PBRT_CPU_GPU +inline bool IsTransmissive(BxDFFlags flags) { + return (flags & BxDFFlags::Transmission) != 0; +} +PBRT_CPU_GPU +inline bool IsDiffuse(BxDFFlags flags) { + return (flags & BxDFFlags::Diffuse) != 0; +} +PBRT_CPU_GPU +inline bool IsGlossy(BxDFFlags flags) { + return (flags & BxDFFlags::Glossy) != 0; +} +PBRT_CPU_GPU +inline bool IsSpecular(BxDFFlags flags) { + return (flags & BxDFFlags::Specular) != 0; +} + +std::string ToString(BxDFFlags flags); + +// TransportMode Definition +enum class TransportMode { Radiance, Importance }; + +PBRT_CPU_GPU +inline TransportMode operator~(TransportMode mode) { + return (mode == TransportMode::Radiance) ? TransportMode::Importance + : TransportMode::Radiance; +} + +std::string ToString(TransportMode mode); + +// BSDFSample Definition +struct BSDFSample { + // BSDFSample Public Methods + BSDFSample() = default; + PBRT_CPU_GPU + BSDFSample(const SampledSpectrum &f, const Vector3f &wi, Float pdf, BxDFFlags flags) + : f(f), wi(wi), pdf(pdf), flags(flags) {} + + PBRT_CPU_GPU + operator bool() const { return pdf > 0; } + + PBRT_CPU_GPU + bool IsReflection() const { return pbrt::IsReflective(flags); } + PBRT_CPU_GPU + bool IsTransmission() const { return pbrt::IsTransmissive(flags); } + PBRT_CPU_GPU + bool IsDiffuse() const { return pbrt::IsDiffuse(flags); } + PBRT_CPU_GPU + bool IsGlossy() const { return pbrt::IsGlossy(flags); } + PBRT_CPU_GPU + bool IsSpecular() const { return pbrt::IsSpecular(flags); } + + std::string ToString() const; + SampledSpectrum f; + Vector3f wi; + Float pdf = 0; + BxDFFlags flags; +}; + +class IdealDiffuseBxDF; +class DiffuseBxDF; +class DielectricInterfaceBxDF; +class ThinDielectricBxDF; +class HairBxDF; +class MeasuredBxDF; +class ConductorBxDF; +class BSSRDFAdapter; +class CoatedDiffuseBxDF; +class CoatedConductorBxDF; + +// BxDFHandle Definition +class BxDFHandle : public TaggedPointer { + public: + // BxDF Interface + using TaggedPointer::TaggedPointer; + + std::string ToString() const; + + PBRT_CPU_GPU inline BxDFFlags Flags() const; + + PBRT_CPU_GPU inline SampledSpectrum f(Vector3f wo, Vector3f wi, + TransportMode mode) const; + + PBRT_CPU_GPU inline BSDFSample Sample_f( + Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const; + + PBRT_CPU_GPU inline bool SampledPDFIsProportional() const; + + PBRT_CPU_GPU inline Float PDF( + Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const; + + PBRT_CPU_GPU + SampledSpectrum rho(Vector3f wo, pstd::span uc, + pstd::span u2) const; + SampledSpectrum rho(pstd::span uc1, pstd::span u1, + pstd::span uc2, pstd::span u2) const; + + PBRT_CPU_GPU inline void Regularize(); +}; + +} // namespace pbrt + +#endif // PBRT_BASE_BXDF_H diff --git a/src/pbrt/base/camera.h b/src/pbrt/base/camera.h new file mode 100644 index 00000000..88ad9db8 --- /dev/null +++ b/src/pbrt/base/camera.h @@ -0,0 +1,79 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_CAMERA_H +#define PBRT_BASE_CAMERA_H + +#include + +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +// Camera Declarations +struct CameraRay; +struct CameraRayDifferential; +struct CameraWiSample; + +struct CameraSample; +class CameraTransform; + +class PerspectiveCamera; +class OrthographicCamera; +class SphericalCamera; +class RealisticCamera; + +// CameraHandle Definition +class CameraHandle : public TaggedPointer { + public: + // Camera Interface + using TaggedPointer::TaggedPointer; + + static CameraHandle Create(const std::string &name, + const ParameterDictionary ¶meters, MediumHandle medium, + const CameraTransform &cameraTransform, FilmHandle film, + const FileLoc *loc, Allocator alloc); + + PBRT_CPU_GPU inline FilmHandle GetFilm() const; + + PBRT_CPU_GPU inline Float SampleTime(Float u) const; + + PBRT_CPU_GPU inline const CameraTransform &GetCameraTransform() const; + + void InitMetadata(ImageMetadata *metadata) const; + + std::string ToString() const; + + PBRT_CPU_GPU inline CameraRay GenerateRay(CameraSample sample, + SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + pstd::optional GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + void ApproximatedPdxy(const SurfaceInteraction &si) const; + + PBRT_CPU_GPU + SampledSpectrum We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2 = nullptr) const; + + PBRT_CPU_GPU + void PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const; + + PBRT_CPU_GPU + pstd::optional SampleWi(const Interaction &ref, const Point2f &u, + SampledWavelengths &lambda) const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_CAMERA_H diff --git a/src/pbrt/base/film.h b/src/pbrt/base/film.h new file mode 100644 index 00000000..6b1070f6 --- /dev/null +++ b/src/pbrt/base/film.h @@ -0,0 +1,65 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_FILM_H +#define PBRT_BASE_FILM_H + +#include + +#include +#include +#include + +#include + +namespace pbrt { + +class VisibleSurface; +class RGBFilm; +class GBufferFilm; + +// FilmHandle Definition +class FilmHandle : public TaggedPointer { + public: + // Film Interface + PBRT_CPU_GPU inline SampledWavelengths SampleWavelengths(Float u) const; + + PBRT_CPU_GPU inline void AddSample(const Point2i &pFilm, SampledSpectrum L, + const SampledWavelengths &lambda, + const VisibleSurface *visibleSurface, + Float weight); + + PBRT_CPU_GPU + bool UsesVisibleSurface() const; + + PBRT_CPU_GPU + void AddSplat(const Point2f &p, SampledSpectrum v, const SampledWavelengths &lambda); + + PBRT_CPU_GPU inline Point2i FullResolution() const; + PBRT_CPU_GPU inline Float Diagonal() const; + PBRT_CPU_GPU inline Bounds2i PixelBounds() const; + + PBRT_CPU_GPU + RGB GetPixelRGB(const Point2i &p, Float splatScale = 1) const; + void WriteImage(ImageMetadata metadata, Float splatScale = 1); + Image GetImage(ImageMetadata *metadata, Float splatScale = 1); + + using TaggedPointer::TaggedPointer; + + static FilmHandle Create(const std::string &name, + const ParameterDictionary ¶meters, const FileLoc *loc, + FilterHandle filter, Allocator alloc); + + PBRT_CPU_GPU inline FilterHandle GetFilter() const; + + std::string GetFilename() const; + + std::string ToString() const; + + PBRT_CPU_GPU inline Bounds2f SampleBounds() const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_FILM_H diff --git a/src/pbrt/base/filter.h b/src/pbrt/base/filter.h new file mode 100644 index 00000000..34bd2e62 --- /dev/null +++ b/src/pbrt/base/filter.h @@ -0,0 +1,48 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_FILTER_H +#define PBRT_BASE_FILTER_H + +#include + +#include + +#include + +namespace pbrt { + +// Filter Declarations +struct FilterSample; +class BoxFilter; +class GaussianFilter; +class MitchellFilter; +class LanczosSincFilter; +class TriangleFilter; + +// FilterHandle Definition +class FilterHandle : public TaggedPointer { + public: + // Filter Interface + using TaggedPointer::TaggedPointer; + + static FilterHandle Create(const std::string &name, + const ParameterDictionary ¶meters, const FileLoc *loc, + Allocator alloc); + + PBRT_CPU_GPU inline Vector2f Radius() const; + + PBRT_CPU_GPU inline Float Evaluate(const Point2f &p) const; + + PBRT_CPU_GPU inline FilterSample Sample(const Point2f &u) const; + + PBRT_CPU_GPU inline Float Integral() const; + + std::string ToString() const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_FILTER_H diff --git a/src/pbrt/base/light.h b/src/pbrt/base/light.h new file mode 100644 index 00000000..da649743 --- /dev/null +++ b/src/pbrt/base/light.h @@ -0,0 +1,102 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_LIGHT_H +#define PBRT_BASE_LIGHT_H + +#include + +#include +#include +#include +#include + +#include + +namespace pbrt { + +// LightType Definition +enum class LightType : int { DeltaPosition, DeltaDirection, Area, Infinite }; + +// LightSamplingMode Definition +enum class LightSamplingMode { WithMIS, WithoutMIS }; + +class PointLight; +class DistantLight; +class ProjectionLight; +class GoniometricLight; +class DiffuseAreaLight; +class UniformInfiniteLight; +class ImageInfiniteLight; +class PortalImageInfiniteLight; +class SpotLight; + +class LightSampleContext; +struct LightBounds; +struct LightLiSample; +struct LightLeSample; + +// LightHandle Definition +class LightHandle + : public TaggedPointer { + public: + // Light Interface + using TaggedPointer::TaggedPointer; + + static LightHandle Create(const std::string &name, + const ParameterDictionary ¶meters, + const Transform &renderFromLight, + const CameraTransform &cameraTransform, + MediumHandle outsideMedium, const FileLoc *loc, + Allocator alloc); + static LightHandle CreateArea(const std::string &name, + const ParameterDictionary ¶meters, + const Transform &renderFromLight, + const MediumInterface &mediumInterface, + const ShapeHandle shape, const FileLoc *loc, + Allocator alloc); + + void Preprocess(const Bounds3f &sceneBounds); + + PBRT_CPU_GPU inline LightType Type() const; + + SampledSpectrum Phi(const SampledWavelengths &lambda) const; + + PBRT_CPU_GPU inline LightLiSample SampleLi( + LightSampleContext ctx, Point2f u, SampledWavelengths lambda, + LightSamplingMode mode = LightSamplingMode::WithoutMIS) const; + + PBRT_CPU_GPU inline Float PDF_Li( + LightSampleContext ctx, Vector3f wi, + LightSamplingMode mode = LightSamplingMode::WithoutMIS) const; + + std::string ToString() const; + + // AreaLights only + PBRT_CPU_GPU inline SampledSpectrum L(const Point3f &p, const Normal3f &n, + const Point2f &uv, const Vector3f &w, + const SampledWavelengths &lambda) const; + PBRT_CPU_GPU + void PDF_Le(const Interaction &intr, Vector3f &w, Float *pdfPos, Float *pdfDir) const; + + // InfiniteAreaLights only + PBRT_CPU_GPU inline SampledSpectrum Le(const Ray &ray, + const SampledWavelengths &lambda) const; + + LightBounds Bounds() const; + + PBRT_CPU_GPU + LightLeSample SampleLe(const Point2f &u1, const Point2f &u2, + SampledWavelengths &lambda, Float time) const; + + // Note shouldn't be called for area lights.. + PBRT_CPU_GPU + void PDF_Le(const Ray &ray, Float *pdfPos, Float *pdfDir) const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_LIGHT_H diff --git a/src/pbrt/base/lightsampler.h b/src/pbrt/base/lightsampler.h new file mode 100644 index 00000000..5afdd34f --- /dev/null +++ b/src/pbrt/base/lightsampler.h @@ -0,0 +1,51 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_LIGHTSAMPLER_H +#define PBRT_BASE_LIGHTSAMPLER_H + +#include + +#include + +#include + +namespace pbrt { + +// SampledLight Definition +struct SampledLight { + LightHandle light; + Float pdf = 0; + std::string ToString() const; +}; + +class UniformLightSampler; +class PowerLightSampler; +class BVHLightSampler; +class ExhaustiveLightSampler; + +// LightSamplerHandle Definition +class LightSamplerHandle : public TaggedPointer { + public: + // LightSampler Interface + using TaggedPointer::TaggedPointer; + + static LightSamplerHandle Create(const std::string &name, + pstd::span lights, + Allocator alloc); + + std::string ToString() const; + + PBRT_CPU_GPU inline pstd::optional Sample(const LightSampleContext &ctx, + Float u) const; + PBRT_CPU_GPU inline Float PDF(const LightSampleContext &ctx, LightHandle light) const; + + PBRT_CPU_GPU inline pstd::optional Sample(Float u) const; + PBRT_CPU_GPU inline Float PDF(LightHandle light) const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_LIGHTSAMPLER_H diff --git a/src/pbrt/base/material.h b/src/pbrt/base/material.h new file mode 100644 index 00000000..8923f896 --- /dev/null +++ b/src/pbrt/base/material.h @@ -0,0 +1,72 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_MATERIAL_H +#define PBRT_BASE_MATERIAL_H + +#include + +#include +#include +#include + +#include +#include + +namespace pbrt { + +struct MaterialEvalContext; + +// Material Declarations +class CoatedDiffuseMaterial; +class CoatedConductorMaterial; +class ConductorMaterial; +class DielectricMaterial; +class DiffuseMaterial; +class DiffuseTransmissionMaterial; +class HairMaterial; +class MeasuredMaterial; +class SubsurfaceMaterial; +class ThinDielectricMaterial; + +// MaterialHandle Definition +class MaterialHandle + : public TaggedPointer { + public: + // Material Interface + using TaggedPointer::TaggedPointer; + + static MaterialHandle Create( + const std::string &name, const TextureParameterDictionary ¶meters, + /*const */ std::map &namedMaterials, + const FileLoc *loc, Allocator alloc); + + std::string ToString() const; + + template + PBRT_CPU_GPU inline bool CanEvaluateTextures(TextureEvaluator texEval) const; + + template + PBRT_CPU_GPU inline BSDF GetBSDF(TextureEvaluator texEval, MaterialEvalContext ctx, + SampledWavelengths &lambda, + ScratchBuffer &scratchBuffer) const; + + template + PBRT_CPU_GPU inline BSSRDFHandle GetBSSRDF(TextureEvaluator texEval, + MaterialEvalContext ctx, + SampledWavelengths &lambda, + ScratchBuffer &scratchBuffer) const; + + PBRT_CPU_GPU inline FloatTextureHandle GetDisplacement() const; + + PBRT_CPU_GPU inline bool IsTransparent() const; + PBRT_CPU_GPU inline bool HasSubsurfaceScattering() const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_MATERIAL_H diff --git a/src/pbrt/base/medium.h b/src/pbrt/base/medium.h new file mode 100644 index 00000000..8dfc7834 --- /dev/null +++ b/src/pbrt/base/medium.h @@ -0,0 +1,90 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_MEDIUM_H +#define PBRT_BASE_MEDIUM_H + +#include + +#include +#include +#include +#include + +#include +#include + +namespace pbrt { + +// PhaseFunctionSample Definition +struct PhaseFunctionSample { + PBRT_CPU_GPU operator bool() const { return pdf > 0; } + Float p; + Vector3f wi; + Float pdf = 0; +}; + +// PhaseFunctionHandle Definition +class HGPhaseFunction; + +class PhaseFunctionHandle : public TaggedPointer { + public: + // PhaseFunctionHandle Interface + using TaggedPointer::TaggedPointer; + + std::string ToString() const; + + PBRT_CPU_GPU inline Float p(const Vector3f &wo, const Vector3f &wi) const; + + PBRT_CPU_GPU inline PhaseFunctionSample Sample_p(const Vector3f &wo, + const Point2f &u) const; + PBRT_CPU_GPU inline Float PDF(const Vector3f &wo, const Vector3f &wi) const; +}; + +class HomogeneousMedium; +class GridDensityMedium; +struct MediumSample; + +// MediumHandle Definition +class MediumHandle : public TaggedPointer { + public: + // MediumHandle Interface + using TaggedPointer::TaggedPointer; + + static MediumHandle Create(const std::string &name, + const ParameterDictionary ¶meters, + const Transform &renderFromMedium, const FileLoc *loc, + Allocator alloc); + + std::string ToString() const; + + template + PBRT_CPU_GPU void SampleTmaj(const Ray &ray, Float tMax, RNG &rng, + const SampledWavelengths &lambda, F callback) const; + + bool IsEmissive() const; +}; + +// MediumInterface Definition +struct MediumInterface { + // MediumInterface Public Methods + std::string ToString() const; + + MediumInterface() = default; + PBRT_CPU_GPU + MediumInterface(MediumHandle medium) : inside(medium), outside(medium) {} + PBRT_CPU_GPU + MediumInterface(MediumHandle inside, MediumHandle outside) + : inside(inside), outside(outside) {} + + PBRT_CPU_GPU + bool IsMediumTransition() const { return inside != outside; } + + // MediumInterface Public Members + MediumHandle inside, outside; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_MEDIUM_H diff --git a/src/pbrt/base/sampler.h b/src/pbrt/base/sampler.h new file mode 100644 index 00000000..fed810fb --- /dev/null +++ b/src/pbrt/base/sampler.h @@ -0,0 +1,66 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_SAMPLER_H +#define PBRT_BASE_SAMPLER_H + +#include + +#include +#include + +#include +#include + +namespace pbrt { + +// CameraSample Definition +struct CameraSample { + Point2f pFilm; + Point2f pLens; + Float time = 0; + Float weight = 1; + std::string ToString() const; +}; + +// Sampler Declarations +class HaltonSampler; +class PaddedSobolSampler; +class PMJ02BNSampler; +class RandomSampler; +class SobolSampler; +class StratifiedSampler; +class MLTSampler; +class DebugMLTSampler; + +// SamplerHandle Definition +class SamplerHandle + : public TaggedPointer { + public: + // Sampler Interface + using TaggedPointer::TaggedPointer; + + static SamplerHandle Create(const std::string &name, + const ParameterDictionary ¶meters, + const Point2i &fullResolution, const FileLoc *loc, + Allocator alloc); + + PBRT_CPU_GPU inline int SamplesPerPixel() const; + + PBRT_CPU_GPU inline void StartPixelSample(const Point2i &p, int sampleIndex, + int dimension = 0); + + PBRT_CPU_GPU inline Float Get1D(); + PBRT_CPU_GPU inline Point2f Get2D(); + + std::vector Clone(int n, Allocator alloc); + + std::string ToString() const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_SAMPLER_H diff --git a/src/pbrt/base/shape.h b/src/pbrt/base/shape.h new file mode 100644 index 00000000..a68c7301 --- /dev/null +++ b/src/pbrt/base/shape.h @@ -0,0 +1,82 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_SHAPE_H +#define PBRT_BASE_SHAPE_H + +#include + +#include +#include +#include +#include + +#include + +namespace pbrt { + +// Shape Declarations +class Triangle; +class BilinearPatch; +class Curve; +class Sphere; +class Cylinder; +class Disk; + +struct ShapeSample; +struct ShapeIntersection; +class ShapeSampleContext; + +// ShapeHandle Definition +class ShapeHandle + : public TaggedPointer { + public: + // Shape Interface + using TaggedPointer::TaggedPointer; + + static pstd::vector Create(const std::string &name, + const Transform *renderFromObject, + const Transform *objectFromRender, + bool reverseOrientation, + const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc); + std::string ToString() const; + + PBRT_CPU_GPU inline Bounds3f Bounds() const; + + PBRT_CPU_GPU inline DirectionCone NormalBounds() const; + + PBRT_CPU_GPU inline pstd::optional Intersect( + const Ray &ray, Float tMax = Infinity) const; + + PBRT_CPU_GPU inline bool IntersectP(const Ray &ray, Float tMax = Infinity) const; + + PBRT_CPU_GPU inline Float Area() const; + + PBRT_CPU_GPU inline pstd::optional Sample(const Point2f &u) const; + + PBRT_CPU_GPU inline Float PDF(const Interaction &) const; + + PBRT_CPU_GPU inline pstd::optional Sample(const ShapeSampleContext &ctx, + const Point2f &u) const; + + PBRT_CPU_GPU inline Float PDF(const ShapeSampleContext &ctx, + const Vector3f &wi) const; + + private: + // ShapeHandle Private Members + friend class TriangleMesh; + friend class BilinearPatchMesh; + + static BufferCache *indexBufferCache; + static BufferCache *pBufferCache; + static BufferCache *nBufferCache; + static BufferCache *uvBufferCache; + static BufferCache *sBufferCache; + static BufferCache *faceIndexBufferCache; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_SHAPE_H diff --git a/src/pbrt/base/texture.h b/src/pbrt/base/texture.h new file mode 100644 index 00000000..ed1c04cd --- /dev/null +++ b/src/pbrt/base/texture.h @@ -0,0 +1,88 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BASE_TEXTURE_H +#define PBRT_BASE_TEXTURE_H + +#include + +#include + +#include + +namespace pbrt { + +struct TextureEvalContext; + +class FloatConstantTexture; +class FloatBilerpTexture; +class FloatCheckerboardTexture; +class FloatDotsTexture; +class FBmTexture; +class GPUFloatImageTexture; +class FloatImageTexture; +class FloatMixTexture; +class FloatPtexTexture; +class FloatScaledTexture; +class WindyTexture; +class WrinkledTexture; + +// FloatTextureHandle Definition +class FloatTextureHandle + : public TaggedPointer { + public: + // FloatTexture Interface + using TaggedPointer::TaggedPointer; + + static FloatTextureHandle Create(const std::string &name, + const Transform &renderFromTexture, + const TextureParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc, bool gpu); + + std::string ToString() const; + + PBRT_CPU_GPU inline Float Evaluate(TextureEvalContext ctx) const; +}; + +class RGBConstantTexture; +class RGBReflectanceConstantTexture; +class SpectrumConstantTexture; +class SpectrumBilerpTexture; +class SpectrumCheckerboardTexture; +class SpectrumImageTexture; +class GPUSpectrumImageTexture; +class MarbleTexture; +class SpectrumMixTexture; +class SpectrumDotsTexture; +class SpectrumPtexTexture; +class SpectrumScaledTexture; + +// SpectrumTextureHandle Definition +class SpectrumTextureHandle + : public TaggedPointer< + RGBConstantTexture, RGBReflectanceConstantTexture, SpectrumImageTexture, + GPUSpectrumImageTexture, SpectrumMixTexture, SpectrumScaledTexture, + SpectrumConstantTexture, SpectrumBilerpTexture, SpectrumCheckerboardTexture, + MarbleTexture, SpectrumDotsTexture, SpectrumPtexTexture> { + public: + // SpectrumTexture Interface + using TaggedPointer::TaggedPointer; + + static SpectrumTextureHandle Create(const std::string &name, + const Transform &renderFromTexture, + const TextureParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc, bool gpu); + + std::string ToString() const; + + PBRT_CPU_GPU inline SampledSpectrum Evaluate(TextureEvalContext ctx, + SampledWavelengths lambda) const; +}; + +} // namespace pbrt + +#endif // PBRT_BASE_TEXTURE_H diff --git a/src/pbrt/bsdf.cpp b/src/pbrt/bsdf.cpp new file mode 100644 index 00000000..a0c5c7c8 --- /dev/null +++ b/src/pbrt/bsdf.cpp @@ -0,0 +1,22 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include + +namespace pbrt { + +std::string BSDFSample::ToString() const { + return StringPrintf("[ BSDFSample f: %s wi: %s pdf: %s flags: %s ]", f, wi, pdf, + flags); +} + +// BSDF Method Definitions +std::string BSDF::ToString() const { + return StringPrintf("[ BSDF eta: %f bxdf: %s shadingFrame: %s ng: %s ]", eta, bxdf, + shadingFrame, ng); +} + +} // namespace pbrt diff --git a/src/pbrt/bsdf.h b/src/pbrt/bsdf.h new file mode 100644 index 00000000..ea65bd81 --- /dev/null +++ b/src/pbrt/bsdf.h @@ -0,0 +1,201 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BSDF_H +#define PBRT_BSDF_H + +#include + +#include +#include +#include +#include +#include + +namespace pbrt { + +// BSDF Definition +class BSDF { + public: + // BSDF Public Methods + BSDF() = default; + PBRT_CPU_GPU + BSDF(const Vector3f &wo, const Normal3f &n, const Normal3f &ns, const Vector3f &dpdus, + BxDFHandle bxdf, Float eta = 1) + : eta(Dot(wo, n) < 0 ? 1 / eta : eta), + bxdf(bxdf), + ng(n), + shadingFrame(Frame::FromXZ(Normalize(dpdus), Vector3f(ns))) {} + + PBRT_CPU_GPU + operator bool() const { return (bool)bxdf; } + + PBRT_CPU_GPU + Vector3f RenderToLocal(const Vector3f &v) const { return shadingFrame.ToLocal(v); } + PBRT_CPU_GPU + Vector3f LocalToRender(const Vector3f &v) const { return shadingFrame.FromLocal(v); } + + PBRT_CPU_GPU + BxDFHandle GetBxDF() const { return bxdf; } + PBRT_CPU_GPU + void SetBxDF(BxDFHandle b) { bxdf = b; } + + PBRT_CPU_GPU + bool IsNonSpecular() const { + return (bxdf.Flags() & (BxDFFlags::Diffuse | BxDFFlags::Glossy)); + } + PBRT_CPU_GPU + bool IsDiffuse() const { return (bxdf.Flags() & BxDFFlags::Diffuse); } + PBRT_CPU_GPU + bool IsGlossy() const { return (bxdf.Flags() & BxDFFlags::Glossy); } + PBRT_CPU_GPU + bool IsSpecular() const { return (bxdf.Flags() & BxDFFlags::Specular); } + PBRT_CPU_GPU + bool HasReflection() const { return (bxdf.Flags() & BxDFFlags::Reflection); } + PBRT_CPU_GPU + bool HasTransmission() const { return (bxdf.Flags() & BxDFFlags::Transmission); } + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f woRender, Vector3f wiRender, + TransportMode mode = TransportMode::Radiance) const { + Vector3f wi = RenderToLocal(wiRender), wo = RenderToLocal(woRender); + if (wo.z == 0) + return {}; + return bxdf.f(wo, wi, mode) * GBump(woRender, wiRender, mode); + } + + template + PBRT_CPU_GPU SampledSpectrum f(Vector3f woW, Vector3f wiW, + TransportMode mode = TransportMode::Radiance) const { + Vector3f wi = RenderToLocal(wiW), wo = RenderToLocal(woW); + if (wo.z == 0) + return {}; + const BxDF *specificBxDF = bxdf.Cast(); + return specificBxDF->f(wo, wi, mode) * GBump(woW, wiW, mode); + } + + PBRT_CPU_GPU + SampledSpectrum rho(pstd::span uc1, pstd::span u1, + pstd::span uc2, pstd::span u2) const { + return bxdf.rho(uc1, u1, uc2, u2); + } + PBRT_CPU_GPU + SampledSpectrum rho(const Vector3f &woRender, pstd::span uc, + pstd::span u) const { + Vector3f wo = RenderToLocal(woRender); + return bxdf.rho(wo, uc, u); + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f woRender, Float u, const Point2f &u2, + TransportMode mode = TransportMode::Radiance, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + Vector3f wo = RenderToLocal(woRender); + if (wo.z == 0 || !(bxdf.Flags() & sampleFlags)) + return {}; + BSDFSample bs = bxdf.Sample_f(wo, u, u2, mode, sampleFlags); + if (!bs || !bs.f) + return {}; + DCHECK_GT(bs.pdf, 0); + VLOG(2, "For wo = %s, sampled f = %s, pdf = %f, ratio = %s, wi = %s", wo, bs.f, + bs.pdf, (bs.pdf > 0) ? (bs.f / bs.pdf) : SampledSpectrum(0.), bs.wi); + bs.wi = LocalToRender(bs.wi); + bs.f *= GBump(woRender, bs.wi, mode); + return bs; + } + + PBRT_CPU_GPU + Float PDF(Vector3f woRender, Vector3f wiRender, + TransportMode mode = TransportMode::Radiance, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + Vector3f wo = RenderToLocal(woRender), wi = RenderToLocal(wiRender); + if (wo.z == 0) + return 0; + return bxdf.PDF(wo, wi, mode, sampleFlags); + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return bxdf.SampledPDFIsProportional(); } + + template + PBRT_CPU_GPU BSDFSample + Sample_f(Vector3f woRender, Float u, const Point2f &u2, + TransportMode mode = TransportMode::Radiance, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + Vector3f wo = RenderToLocal(woRender); + if (wo.z == 0) + return {}; + + const BxDF *specificBxDF = bxdf.Cast(); + if (!(specificBxDF->Flags() & sampleFlags)) + return {}; + + BSDFSample bs = specificBxDF->Sample_f(wo, u, u2, mode, sampleFlags); + if (!bs || !bs.f) + return {}; + CHECK_GT(bs.pdf, 0); + + VLOG(2, "For wo = %s, sampled f = %s, pdf = %f, ratio = %s, wi = %s", wo, bs.f, + bs.pdf, (bs.pdf > 0) ? (bs.f / bs.pdf) : SampledSpectrum(0.), bs.wi); + + bs.wi = LocalToRender(bs.wi); + bs.f *= GBump(woRender, bs.wi, mode); + + return bs; + } + + template + PBRT_CPU_GPU Float + PDF(Vector3f woRender, Vector3f wiRender, + TransportMode mode = TransportMode::Radiance, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + Vector3f wo = RenderToLocal(woRender), wi = RenderToLocal(wiRender); + if (wo.z == 0) + return 0.; + const BxDF *specificBxDF = bxdf.Cast(); + return specificBxDF->PDF(wo, wi, mode, sampleFlags); + } + + std::string ToString() const; + + PBRT_CPU_GPU + void Regularize() { bxdf.Regularize(); } + + // BSDF Public Members + Float eta; + + private: + friend class SOA; + // BSDF Private Methods + PBRT_CPU_GPU + Float GBump(Vector3f wo, Vector3f wi, TransportMode mode) const { + return 1; // disable for now... + + Vector3f w = (mode == TransportMode::Radiance) ? wi : wo; + Normal3f ngf = FaceForward(ng, w); + Normal3f nsf = FaceForward(Normal3f(shadingFrame.z), ngf); + Float cosThetaIs = std::max(0, Dot(nsf, w)), cosThetaIg = Dot(ngf, w); + Float cosThetaN = Dot(ngf, nsf); + CHECK_GE(cosThetaIs, 0); + CHECK_GE(cosThetaIg, 0); + CHECK_GE(cosThetaN, 0); + + if (cosThetaIs == 0 || cosThetaIg == 0 || cosThetaN == 0) + return 0; + Float G = cosThetaIg / (cosThetaIs * cosThetaN); + if (G >= 1) + return 1; + + return -G * G * G + G * G + G; + } + + // BSDF Private Members + BxDFHandle bxdf; + Frame shadingFrame; + Normal3f ng; +}; + +} // namespace pbrt + +#endif // PBRT_BSDF_H diff --git a/src/pbrt/bsdfs_test.cpp b/src/pbrt/bsdfs_test.cpp new file mode 100644 index 00000000..dfe925b5 --- /dev/null +++ b/src/pbrt/bsdfs_test.cpp @@ -0,0 +1,795 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace pbrt; + +/* The null hypothesis will be rejected when the associated + p-value is below the significance level specified here. */ +#define CHI2_SLEVEL 0.01 + +/* Resolution of the frequency table discretization. The azimuthal + resolution is twice this value. */ +#define CHI2_THETA_RES 10 +#define CHI2_PHI_RES (2 * CHI2_THETA_RES) + +/* Number of MC samples to compute the observed frequency table */ +#define CHI2_SAMPLECOUNT 1000000 + +/* Minimum expected bin frequency. The chi^2 test does not + work reliably when the expected frequency in a cell is + low (e.g. less than 5), because normality assumptions + break down in this case. Therefore, the implementation + will merge such low-frequency cells when they fall below + the threshold specified here. */ +#define CHI2_MINFREQ 5 + +/* Each provided BSDF will be tested for a few different + incident directions. The value specified here determines + how many tests will be executed per BSDF */ +#define CHI2_RUNS 5 + +/// Regularized lower incomplete gamma function (based on code from Cephes) +double RLGamma(double a, double x) { + const double epsilon = 0.000000000000001; + const double big = 4503599627370496.0; + const double bigInv = 2.22044604925031308085e-16; + if (a < 0 || x < 0) + throw std::runtime_error("LLGamma: invalid arguments range!"); + + if (x == 0) + return 0.0f; + + double ax = (a * std::log(x)) - x - std::lgamma(a); + if (ax < -709.78271289338399) + return a < x ? 1.0 : 0.0; + + if (x <= 1 || x <= a) { + double r2 = a; + double c2 = 1; + double ans2 = 1; + + do { + r2 = r2 + 1; + c2 = c2 * x / r2; + ans2 += c2; + } while ((c2 / ans2) > epsilon); + + return std::exp(ax) * ans2 / a; + } + + int c = 0; + double y = 1 - a; + double z = x + y + 1; + double p3 = 1; + double q3 = x; + double p2 = x + 1; + double q2 = z * x; + double ans = p2 / q2; + double error; + + do { + c++; + y += 1; + z += 2; + double yc = y * c; + double p = (p2 * z) - (p3 * yc); + double q = (q2 * z) - (q3 * yc); + + if (q != 0) { + double nextans = p / q; + error = std::abs((ans - nextans) / nextans); + ans = nextans; + } else { + // zero div, skip + error = 1; + } + + // shift + p3 = p2; + p2 = p; + q3 = q2; + q2 = q; + + // normalize fraction when the numerator becomes large + if (std::abs(p) > big) { + p3 *= bigInv; + p2 *= bigInv; + q3 *= bigInv; + q2 *= bigInv; + } + } while (error > epsilon); + + return 1.0 - (std::exp(ax) * ans); +} + +/// Chi^2 distribution cumulative distribution function +double Chi2CDF(double x, int dof) { + if (dof < 1 || x < 0) { + return 0.0; + } else if (dof == 2) { + return 1.0 - std::exp(-0.5 * x); + } else { + return (Float)RLGamma(0.5 * dof, 0.5 * x); + } +} + +/// Adaptive Simpson integration over an 1D interval +Float AdaptiveSimpson(const std::function& f, Float x0, Float x1, + Float eps = 1e-6f, int depth = 6) { + int count = 0; + /* Define an recursive lambda function for integration over subintervals */ + std::function + integrate = [&](Float a, Float b, Float c, Float fa, Float fb, Float fc, Float I, + Float eps, int depth) { + /* Evaluate the function at two intermediate points */ + Float d = 0.5f * (a + b), e = 0.5f * (b + c), fd = f(d), fe = f(e); + + /* Simpson integration over each subinterval */ + Float h = c - a, I0 = (Float)(1.0 / 12.0) * h * (fa + 4 * fd + fb), + I1 = (Float)(1.0 / 12.0) * h * (fb + 4 * fe + fc), Ip = I0 + I1; + ++count; + + /* Stopping criterion from J.N. Lyness (1969) + "Notes on the adaptive Simpson quadrature routine" */ + if (depth <= 0 || std::abs(Ip - I) < 15 * eps) { + // Richardson extrapolation + return Ip + (Float)(1.0 / 15.0) * (Ip - I); + } + + return integrate(a, d, b, fa, fd, fb, I0, .5f * eps, depth - 1) + + integrate(b, e, c, fb, fe, fc, I1, .5f * eps, depth - 1); + }; + Float a = x0, b = 0.5f * (x0 + x1), c = x1; + Float fa = f(a), fb = f(b), fc = f(c); + Float I = (c - a) * (Float)(1.0 / 6.0) * (fa + 4 * fb + fc); + return integrate(a, b, c, fa, fb, fc, I, eps, depth); +} + +/// Nested adaptive Simpson integration over a 2D rectangle +Float AdaptiveSimpson2D(const std::function& f, Float x0, Float y0, + Float x1, Float y1, Float eps = 1e-6f, int depth = 6) { + /* Lambda function that integrates over the X axis */ + auto integrate = [&](Float y) { + return AdaptiveSimpson(std::bind(f, std::placeholders::_1, y), x0, x1, eps, + depth); + }; + Float value = AdaptiveSimpson(integrate, y0, y1, eps, depth); + return value; +} + +/// Generate a histogram of the BSDF density function via MC sampling +void FrequencyTable(const BSDF* bsdf, const Vector3f& wo, RNG& rng, int sampleCount, + int thetaRes, int phiRes, Float* target) { + memset(target, 0, thetaRes * phiRes * sizeof(Float)); + + Float factorTheta = thetaRes / Pi, factorPhi = phiRes / (2 * Pi); + + Vector3f wi; + for (int i = 0; i < sampleCount; ++i) { + Float u = rng.Uniform(); + Point2f sample{rng.Uniform(), rng.Uniform()}; + BSDFSample bs = bsdf->Sample_f(wo, u, sample); + + if (!bs || bs.IsSpecular()) + continue; + + Vector3f wiL = bsdf->RenderToLocal(bs.wi); + + Point2f coords(SafeACos(wiL.z) * factorTheta, + std::atan2(wiL.y, wiL.x) * factorPhi); + + if (coords.y < 0) + coords.y += 2 * Pi * factorPhi; + + int thetaBin = std::min(std::max(0, (int)std::floor(coords.x)), thetaRes - 1); + int phiBin = std::min(std::max(0, (int)std::floor(coords.y)), phiRes - 1); + + target[thetaBin * phiRes + phiBin] += 1; + } +} + +// Numerically integrate the probability density function over rectangles in +// spherical coordinates. +void IntegrateFrequencyTable(const BSDF* bsdf, const Vector3f& wo, int sampleCount, + int thetaRes, int phiRes, Float* target) { + memset(target, 0, thetaRes * phiRes * sizeof(Float)); + + Float factorTheta = Pi / thetaRes, factorPhi = (2 * Pi) / phiRes; + + for (int i = 0; i < thetaRes; ++i) { + for (int j = 0; j < phiRes; ++j) { + *target++ = + sampleCount * + AdaptiveSimpson2D( + [&](Float theta, Float phi) -> Float { + Float cosTheta = std::cos(theta), sinTheta = std::sin(theta); + Float cosPhi = std::cos(phi), sinPhi = std::sin(phi); + Vector3f wiL(sinTheta * cosPhi, sinTheta * sinPhi, cosTheta); + return bsdf->PDF(wo, bsdf->LocalToRender(wiL)) * sinTheta; + }, + i* factorTheta, j* factorPhi, (i + 1) * factorTheta, + (j + 1) * factorPhi); + } + } +} + +/// Write the frequency tables to disk in a format that is nicely plottable by +/// Octave and MATLAB +void DumpTables(const Float* frequencies, const Float* expFrequencies, int thetaRes, + int phiRes, const char* filename) { + std::ofstream f(filename); + + f << "frequencies = [ "; + for (int i = 0; i < thetaRes; ++i) { + for (int j = 0; j < phiRes; ++j) { + f << frequencies[i * phiRes + j]; + if (j + 1 < phiRes) + f << ", "; + } + if (i + 1 < thetaRes) + f << "; "; + } + f << " ];" << std::endl << "expFrequencies = [ "; + for (int i = 0; i < thetaRes; ++i) { + for (int j = 0; j < phiRes; ++j) { + f << expFrequencies[i * phiRes + j]; + if (j + 1 < phiRes) + f << ", "; + } + if (i + 1 < thetaRes) + f << "; "; + } + f << " ];" << std::endl + << "colormap(jet);" << std::endl + << "clf; subplot(2,1,1);" << std::endl + << "imagesc(frequencies);" << std::endl + << "title('Observed frequencies');" << std::endl + << "axis equal;" << std::endl + << "subplot(2,1,2);" << std::endl + << "imagesc(expFrequencies);" << std::endl + << "axis equal;" << std::endl + << "title('Expected frequencies');" << std::endl; + f.close(); +} + +/// Run A Chi^2 test based on the given frequency tables +std::pair Chi2Test(const Float* frequencies, + const Float* expFrequencies, int thetaRes, + int phiRes, int sampleCount, Float minExpFrequency, + Float significanceLevel, int numTests) { + struct Cell { + Float expFrequency; + size_t index; + }; + + /* Sort all cells by their expected frequencies */ + std::vector cells(thetaRes * phiRes); + for (size_t i = 0; i < cells.size(); ++i) { + cells[i].expFrequency = expFrequencies[i]; + cells[i].index = i; + } + std::sort(cells.begin(), cells.end(), [](const Cell& a, const Cell& b) { + return a.expFrequency < b.expFrequency; + }); + + /* Compute the Chi^2 statistic and pool cells as necessary */ + Float pooledFrequencies = 0, pooledExpFrequencies = 0, chsq = 0; + int pooledCells = 0, dof = 0; + + for (const Cell& c : cells) { + if (expFrequencies[c.index] == 0) { + if (frequencies[c.index] > sampleCount * 1e-5f) { + /* Uh oh: samples in a c that should be completely empty + according to the probability density function. Ordinarily, + even a single sample requires immediate rejection of the null + hypothesis. But due to finite-precision computations and + rounding + errors, this can occasionally happen without there being an + actual bug. Therefore, the criterion here is a bit more + lenient. */ + + std::string result = + StringPrintf("Encountered %f samples in a c with expected " + "frequency 0. Rejecting the null hypothesis!", + frequencies[c.index]); + return std::make_pair(false, result); + } + } else if (expFrequencies[c.index] < minExpFrequency) { + /* Pool cells with low expected frequencies */ + pooledFrequencies += frequencies[c.index]; + pooledExpFrequencies += expFrequencies[c.index]; + pooledCells++; + } else if (pooledExpFrequencies > 0 && pooledExpFrequencies < minExpFrequency) { + /* Keep on pooling cells until a sufficiently high + expected frequency is achieved. */ + pooledFrequencies += frequencies[c.index]; + pooledExpFrequencies += expFrequencies[c.index]; + pooledCells++; + } else { + Float diff = frequencies[c.index] - expFrequencies[c.index]; + chsq += (diff * diff) / expFrequencies[c.index]; + ++dof; + } + } + + if (pooledExpFrequencies > 0 || pooledFrequencies > 0) { + Float diff = pooledFrequencies - pooledExpFrequencies; + chsq += (diff * diff) / pooledExpFrequencies; + ++dof; + } + + /* All parameters are assumed to be known, so there is no + additional DF reduction due to model parameters */ + dof -= 1; + + if (dof <= 0) { + std::string result = + StringPrintf("The number of degrees of freedom %d is too low!", dof); + return std::make_pair(false, result); + } + + /* Probability of obtaining a test statistic at least + as extreme as the one observed under the assumption + that the distributions match */ + Float pval = 1 - (Float)Chi2CDF(chsq, dof); + + /* Apply the Sidak correction term, since we'll be conducting multiple + independent + hypothesis tests. This accounts for the fact that the probability of a + failure + increases quickly when several hypothesis tests are run in sequence. */ + Float alpha = 1.0f - std::pow(1.0f - significanceLevel, 1.0f / numTests); + + if (pval < alpha || !std::isfinite(pval)) { + std::string result = StringPrintf("Rejected the null hypothesis (p-value = %f, " + "significance level = %f", + pval, alpha); + return std::make_pair(false, result); + } else { + return std::make_pair(true, std::string("")); + } +} + +void TestBSDF(std::function createBSDF, + const char* description) { + const int thetaRes = CHI2_THETA_RES; + const int phiRes = CHI2_PHI_RES; + const int sampleCount = CHI2_SAMPLECOUNT; + Float* frequencies = new Float[thetaRes * phiRes]; + Float* expFrequencies = new Float[thetaRes * phiRes]; + RNG rng; + + int index = 0; + std::cout.precision(3); + + // Create BSDF, which requires creating a Shape, casting a Ray that + // hits the shape to get a SurfaceInteraction object. + BSDF* bsdf = nullptr; + auto t = std::make_shared(RotateX(-90)); + auto tInv = std::make_shared(Inverse(*t)); + { + bool reverseOrientation = false; + + std::shared_ptr disk = std::make_shared( + t.get(), tInv.get(), reverseOrientation, 0., 1., 0, 360.); + Point3f origin(0.1, 1, + 0); // offset slightly so we don't hit center of disk + Vector3f direction(0, -1, 0); + Ray r(origin, direction); + auto si = disk->Intersect(r); + ASSERT_TRUE(si.has_value()); + bsdf = createBSDF(si->intr, Allocator()); + } + + for (int k = 0; k < CHI2_RUNS; ++k) { + /* Randomly pick an outgoing direction on the hemisphere */ + Point2f sample{rng.Uniform(), rng.Uniform()}; + Vector3f woL = SampleCosineHemisphere(sample); + Vector3f wo = bsdf->LocalToRender(woL); + + FrequencyTable(bsdf, wo, rng, sampleCount, thetaRes, phiRes, frequencies); + + IntegrateFrequencyTable(bsdf, wo, sampleCount, thetaRes, phiRes, expFrequencies); + + std::string filename = + StringPrintf("/tmp/chi2test_%s_%03i.m", description, ++index); + DumpTables(frequencies, expFrequencies, thetaRes, phiRes, filename.c_str()); + + auto result = Chi2Test(frequencies, expFrequencies, thetaRes, phiRes, sampleCount, + CHI2_MINFREQ, CHI2_SLEVEL, CHI2_RUNS); + EXPECT_TRUE(result.first) << result.second << ", iteration " << k; + } + + delete[] frequencies; + delete[] expFrequencies; +} + +BSDF* createLambertian(const SurfaceInteraction& si, Allocator alloc) { + SampledSpectrum Kd(1.); + return alloc.new_object( + si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(Kd, SampledSpectrum(0.), 0)); +} + +TEST(BSDFSampling, Lambertian) { + TestBSDF(createLambertian, "Lambertian"); +} + +#if 0 +BSDF* createMicrofacet(const SurfaceInteraction& si, Allocator alloc, float roughx, + float roughy) { + Float alphax = TrowbridgeReitzDistribution::RoughnessToAlpha(roughx); + Float alphay = TrowbridgeReitzDistribution::RoughnessToAlpha(roughy); + TrowbridgeReitzDistribution distrib(alphax, alphay); + FresnelHandle fresnel = alloc.new_object(1.5, true); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + // CO return alloc.new_object(si, + // alloc.new_object(1.5, distrib, + // TransportMode::Radiance)); +} + +TEST(BSDFSampling, TR_VA_0p5) { + TestBSDF( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + return createMicrofacet(si, alloc, 0.5, 0.5); + }, + "Trowbridge-Reitz, visible area sample, alpha = 0.5"); +} + +TEST(BSDFSampling, TR_VA_0p3_0p15) { + TestBSDF( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + return createMicrofacet(si, alloc, 0.3, 0.15); + }, + "Trowbridge-Reitz, visible area sample, alpha = 0.3/0.15"); +} +#endif + +/////////////////////////////////////////////////////////////////////////// +// Energy Conservation Tests + +static void TestEnergyConservation( + std::function createBSDF, + const char* description) { + RNG rng; + + // Create BSDF, which requires creating a Shape, casting a Ray that + // hits the shape to get a SurfaceInteraction object. + auto t = std::make_shared(RotateX(-90)); + auto tInv = std::make_shared(Inverse(*t)); + + bool reverseOrientation = false; + std::shared_ptr disk = + std::make_shared(t.get(), tInv.get(), reverseOrientation, 0., 1., 0, 360.); + Point3f origin(0.1, 1, + 0); // offset slightly so we don't hit center of disk + Vector3f direction(0, -1, 0); + Ray r(origin, direction); + auto si = disk->Intersect(r); + ASSERT_TRUE(si.has_value()); + BSDF* bsdf = createBSDF(si->intr, Allocator()); + + for (int i = 0; i < 10; ++i) { + Point2f uo{rng.Uniform(), rng.Uniform()}; + Vector3f woL = SampleUniformHemisphere(uo); + Vector3f wo = bsdf->LocalToRender(woL); + + const int nSamples = 16384; + SampledSpectrum Lo(0.f); + for (int j = 0; j < nSamples; ++j) { + Float u = rng.Uniform(); + Point2f ui{rng.Uniform(), rng.Uniform()}; + BSDFSample bs = bsdf->Sample_f(wo, u, ui); + if (bs) + Lo += bs.f * AbsDot(bs.wi, si->intr.n) / bs.pdf; + } + Lo /= nSamples; + + EXPECT_LT(Lo.MaxComponentValue(), 1.01) + << description << ": Lo = " << Lo << ", wo = " << wo; + } +} + +TEST(BSDFEnergyConservation, LambertianReflection) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + return alloc.new_object( + si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(SampledSpectrum(1.f), SampledSpectrum(0.), + 0)); + }, + "LambertianReflection"); +} + +TEST(BSDFEnergyConservation, OrenNayar) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + return alloc.new_object( + si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(SampledSpectrum(1.f), SampledSpectrum(0.), + 20)); + }, + "Oren-Nayar sigma 20"); +} + +#if 0 +TEST(BSDFEnergyConservation, + MicrofacetReflectionBxDFTrowbridgeReitz_alpha0_1_dielectric1_5) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + FresnelHandle fresnel = alloc.new_object(1.f, 1.5f); + TrowbridgeReitzDistribution distrib(0.1, 0.1); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + }, + "MicrofacetReflectionBxDF, Fresnel dielectric, TrowbridgeReitz alpha " + "0.1"); +} + +TEST(BSDFEnergyConservation, + MicrofacetReflectionBxDFTrowbridgeReitz_alpha1_5_dielectric1_5) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + FresnelHandle fresnel = alloc.new_object(1.f, 1.5f); + TrowbridgeReitzDistribution distrib(1.5, 1.5); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + }, + "MicrofacetReflectionBxDF, Fresnel dielectric, TrowbridgeReitz alpha " + "1.5"); +} + +TEST(BSDFEnergyConservation, + MicrofacetReflectionBxDFTrowbridgeReitz_alpha0_01_dielectric1_5) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + FresnelHandle fresnel = alloc.new_object(1.f, 1.5f); + TrowbridgeReitzDistribution distrib(0.01, 0.01); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + }, + "MicrofacetReflectionBxDF, Fresnel dielectric, TrowbridgeReitz alpha " + "0.01"); +} + +TEST(BSDFEnergyConservation, MicrofacetReflectionBxDFTrowbridgeReitz_alpha0_1_conductor) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + SampledWavelengths lambda = SampledWavelengths::SampleUniform(0.5); + SampledSpectrum etaT = GetNamedSpectrum("metal-Al-eta").Sample(lambda); + SampledSpectrum K = GetNamedSpectrum("metal-Al-k").Sample(lambda); + FresnelHandle fresnel = alloc.new_object(etaT, K); + TrowbridgeReitzDistribution distrib(0.1, 0.1); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + }, + "MicrofacetReflectionBxDF, Fresnel conductor, TrowbridgeReitz alpha " + "0.1"); +} + +TEST(BSDFEnergyConservation, MicrofacetReflectionBxDFTrowbridgeReitz_alpha1_5_conductor) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + SampledWavelengths lambda = SampledWavelengths::SampleUniform(0.5); + SampledSpectrum etaT = GetNamedSpectrum("metal-Al-eta").Sample(lambda); + SampledSpectrum K = GetNamedSpectrum("metal-Al-k").Sample(lambda); + FresnelHandle fresnel = alloc.new_object(etaT, K); + TrowbridgeReitzDistribution distrib(1.5, 1.5); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + }, + "MicrofacetReflectionBxDF, Fresnel conductor, TrowbridgeReitz alpha " + "1.5"); +} + +TEST(BSDFEnergyConservation, + MicrofacetReflectionBxDFTrowbridgeReitz_alpha0_01_conductor) { + TestEnergyConservation( + [](const SurfaceInteraction& si, Allocator alloc) -> BSDF* { + SampledWavelengths lambda = SampledWavelengths::SampleUniform(0.5); + SampledSpectrum etaT = GetNamedSpectrum("metal-Al-eta").Sample(lambda); + SampledSpectrum K = GetNamedSpectrum("metal-Al-k").Sample(lambda); + FresnelHandle fresnel = alloc.new_object(etaT, K); + + TrowbridgeReitzDistribution distrib(0.01, 0.01); + return alloc.new_object(si.wo, si.n, si.shading.n, si.shading.dpdu, + alloc.new_object(distrib, fresnel)); + }, + "MicrofacetReflectionBxDF, Fresnel conductor, TrowbridgeReitz alpha " + "0.01"); +} +#endif + +// Hair Tests +#if 0 +TEST(Hair, Reciprocity) { + RNG rng; + for (int i = 0; i < 10; ++i) { + Hair h(-1 + 2 * rng.Uniform(), 1.55, + HairBSDF::SigmaAFromConcentration(.3 + 7.7 * rng.Uniform()), + .1 + .9 * rng.Uniform(), + .1 + .9 * rng.Uniform()); + Vector3f wi = SampleUniformSphere({rng.Uniform(), rng.Uniform()}); + Vector3f wo = SampleUniformSphere({rng.Uniform(), rng.Uniform()}); + Spectrum a = h.f(wi, wo) * AbsCosTheta(wo); + Spectrum b = h.f(wo, wi) * AbsCosTheta(wi); + EXPECT_EQ(a.y(), b.y()) << h << ", a = " << a << ", b = " << b << ", wi = " << wi + << ", wo = " << wo; + } +} + +#endif + +TEST(Hair, WhiteFurnace) { + RNG rng; + Vector3f wo = SampleUniformSphere({rng.Uniform(), rng.Uniform()}); + for (Float beta_m = .1; beta_m < 1; beta_m += .2) { + for (Float beta_n = .1; beta_n < 1; beta_n += .2) { + // Estimate reflected uniform incident radiance from hair + Float ySum = 0; + + // More samples for the smooth case, since we're sampling blindly. + int count = (beta_m < .5 || beta_n < .5) ? 100000 : 20000; + + for (int i = 0; i < count; ++i) { + SampledWavelengths lambda = + SampledWavelengths::SampleXYZ(RadicalInverse(0, i)); + + Float h = Clamp(-1 + 2. * RadicalInverse(1, i), -.999999, .999999); + SampledSpectrum sigma_a(0.f); + HairBxDF hair(h, 1.55, sigma_a, beta_m, beta_n, 0.f); + Vector3f wi = + SampleUniformSphere({RadicalInverse(2, i), RadicalInverse(3, i)}); + + SampledSpectrum f = + hair.f(wo, wi, TransportMode::Radiance) * AbsCosTheta(wi); + ySum += f.y(lambda); + } + + Float avg = ySum / (count * UniformSpherePDF()); + EXPECT_TRUE(avg >= .95 && avg <= 1.05) << avg; + } + } +} + +TEST(Hair, HOnTheEdge) { + Vector3f wo(0.54986966, 0.03359017, 0.83457476), + wi(-0.37383357, -0.91920084, 0.12376696); + Float h = -1, beta_m = .1, beta_n = .1; + SampledSpectrum sigma_a(0.f); + HairBxDF hair(h, 1.55, sigma_a, beta_m, beta_n, 0.f); + + SampledSpectrum f = hair.f(wo, wi, TransportMode::Radiance); +} + +TEST(Hair, WhiteFurnaceSampled) { + RNG rng; + SampledWavelengths lambda = SampledWavelengths::SampleXYZ(0.5); + Vector3f wo = SampleUniformSphere({rng.Uniform(), rng.Uniform()}); + for (Float beta_m = .1; beta_m < 1; beta_m += .2) { + for (Float beta_n = .1; beta_n < 1; beta_n += .2) { + Float ySum = 0; + + int count = 10000; + for (int i = 0; i < count; ++i) { + SampledWavelengths lambda = + SampledWavelengths::SampleXYZ(RadicalInverse(0, i)); + Float h = Clamp(-1 + 2. * RadicalInverse(1, i), -.999999, .999999); + + SampledSpectrum sigma_a(0.f); + HairBxDF hair(h, 1.55, sigma_a, beta_m, beta_n, 0.f); + + Float uc = RadicalInverse(2, i); + Point2f u(RadicalInverse(3, i), RadicalInverse(4, i)); + + BSDFSample bs = hair.Sample_f(wo, uc, u, TransportMode::Radiance, + BxDFReflTransFlags::All); + if (bs) { + SampledSpectrum f = bs.f * AbsCosTheta(bs.wi) / bs.pdf; + ySum += f.y(lambda); + } + } + + Float avg = ySum / count; + EXPECT_TRUE(avg >= .99 && avg <= 1.01) << avg; + } + } +} + +TEST(Hair, SamplingWeights) { + RNG rng; + SampledWavelengths lambda = SampledWavelengths::SampleXYZ(0.5); + for (Float beta_m = .1; beta_m < 1; beta_m += .2) + for (Float beta_n = .4; beta_n < 1; beta_n += .2) { + int count = 10000; + for (int i = 0; i < count; ++i) { + Float h = Clamp(-1 + 2. * RadicalInverse(0, i), -.999999, .999999); + + // Check _HairBxDF::Sample\_f()_ sample weight + SampledSpectrum sigma_a(0.); + HairBxDF hair(h, 1.55, sigma_a, beta_m, beta_n, 0.f); + + Vector3f wo = + SampleUniformSphere({RadicalInverse(1, i), RadicalInverse(2, i)}); + Float uc = RadicalInverse(3, i); + Point2f u = {RadicalInverse(4, i), RadicalInverse(5, i)}; + BSDFSample bs = hair.Sample_f(wo, uc, u, TransportMode::Radiance, + BxDFReflTransFlags::All); + if (bs) { + Float sum = 0; + int ny = 20; + for (Float u : Stratified1D(ny)) { + SampledWavelengths lambda = SampledWavelengths::SampleXYZ(u); + sum += bs.f.y(lambda) * AbsCosTheta(bs.wi) / bs.pdf; + } + + // Verify that hair BSDF sample weight is close to 1 for + // _wi_ + Float avg = sum / ny; + EXPECT_GT(avg, 0.99); + EXPECT_LT(avg, 1.01); + } + } + } +} + +TEST(Hair, SamplingConsistency) { + RNG rng; + SampledWavelengths lambda = SampledWavelengths::SampleXYZ(0.5); + for (Float beta_m = .2; beta_m < 1; beta_m += .2) + for (Float beta_n = .4; beta_n < 1; beta_n += .2) { + // Declare variables for hair sampling test + const int count = 64 * 1024; + SampledSpectrum sigma_a(.25); + Vector3f wo = + SampleUniformSphere({rng.Uniform(), rng.Uniform()}); + auto Li = [](const Vector3f& w) { return SampledSpectrum(w.z * w.z); }; + SampledSpectrum fImportance(0.), fUniform(0.); + for (int i = 0; i < count; ++i) { + // Compute estimates of scattered radiance for hair sampling + // test + Float h = -1 + 2 * rng.Uniform(); + HairBxDF hair(h, 1.55, sigma_a, beta_m, beta_n, 0.f); + Vector3f wi; + Float uc = rng.Uniform(); + Point2f u = {rng.Uniform(), rng.Uniform()}; + BSDFSample bs = hair.Sample_f(wo, uc, u, TransportMode::Radiance, + BxDFReflTransFlags::All); + if (bs) + fImportance += + bs.f * Li(bs.wi) * AbsCosTheta(bs.wi) / (count * bs.pdf); + wi = SampleUniformSphere(u); + fUniform += hair.f(wo, wi, TransportMode::Radiance) * Li(wi) * + AbsCosTheta(wi) / (count * UniformSpherePDF()); + } + // Verify consistency of estimated hair reflected radiance values + Float err = + std::abs(fImportance.y(lambda) - fUniform.y(lambda)) / fUniform.y(lambda); + EXPECT_LT(err, 0.05); + } +} diff --git a/src/pbrt/bssrdf.cpp b/src/pbrt/bssrdf.cpp new file mode 100644 index 00000000..9fc3a10a --- /dev/null +++ b/src/pbrt/bssrdf.cpp @@ -0,0 +1,144 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +std::string TabulatedBSSRDF::ToString() const { + return StringPrintf("[ TabulatedBSSRDF po: %s eta: %f ns: %s ss: %s ts: %s " + "sigma_t: %s rho: %s table: %s ]", + po, eta, ns, ss, ts, sigma_t, rho, *table); +} + +// BSSRDF Function Definitions +Float BeamDiffusionMS(Float sigma_s, Float sigma_a, Float g, Float eta, Float r) { + const int nSamples = 100; + Float Ed = 0; + // Precompute information for dipole integrand + // Compute reduced scattering coefficients $\sigmaps, \sigmapt$ and albedo $\rhop$ + Float sigmap_s = sigma_s * (1 - g); + Float sigmap_t = sigma_a + sigmap_s; + Float rhop = sigmap_s / sigmap_t; + + // Compute non-classical diffusion coefficient $D_\roman{G}$ using Equation + // $(\ref{eq:diffusion-coefficient-grosjean})$ + Float D_g = (2 * sigma_a + sigmap_s) / (3 * sigmap_t * sigmap_t); + + // Compute effective transport coefficient $\sigmatr$ based on $D_\roman{G}$ + Float sigma_tr = SafeSqrt(sigma_a / D_g); + + // Determine linear extrapolation distance $\depthextrapolation$ using Equation + // $(\ref{eq:dipole-boundary-condition})$ + Float fm1 = FresnelMoment1(eta), fm2 = FresnelMoment2(eta); + Float ze = -2 * D_g * (1 + 3 * fm2) / (1 - 2 * fm1); + + // Determine exitance scale factors using Equations $(\ref{eq:kp-exitance-phi})$ and + // $(\ref{eq:kp-exitance-e})$ + Float cPhi = .25f * (1 - 2 * fm1), cE = .5f * (1 - 3 * fm2); + + for (int i = 0; i < nSamples; ++i) { + // Sample real point source depth $\depthreal$ + Float zr = -std::log(1 - (i + .5f) / nSamples) / sigmap_t; + + // Evaluate dipole integrand $E_{\roman{d}}$ at $\depthreal$ and add to _Ed_ + Float zv = -zr + 2 * ze; + Float dr = std::sqrt(r * r + zr * zr), dv = std::sqrt(r * r + zv * zv); + // Compute dipole fluence rate $\dipole(r)$ using Equation + // $(\ref{eq:diffusion-dipole})$ + Float phiD = Inv4Pi / D_g * + (std::exp(-sigma_tr * dr) / dr - std::exp(-sigma_tr * dv) / dv); + + // Compute dipole vector irradiance $-\N{}\cdot\dipoleE(r)$ using Equation + // $(\ref{eq:diffusion-dipole-vector-irradiance-normal})$ + Float EDn = + Inv4Pi * + (zr * (1 + sigma_tr * dr) * std::exp(-sigma_tr * dr) / (dr * dr * dr) - + zv * (1 + sigma_tr * dv) * std::exp(-sigma_tr * dv) / (dv * dv * dv)); + + // Add contribution from dipole for depth $\depthreal$ to _Ed_ + Float E = phiD * cPhi + EDn * cE; + Float kappa = 1 - std::exp(-2 * sigmap_t * (dr + zr)); + Ed += kappa * rhop * rhop * E; + } + return Ed / nSamples; +} + +Float BeamDiffusionSS(Float sigma_s, Float sigma_a, Float g, Float eta, Float r) { + // Compute material parameters and minimum $t$ below the critical angle + Float sigma_t = sigma_a + sigma_s, rho = sigma_s / sigma_t; + Float tCrit = r * SafeSqrt(eta * eta - 1); + + Float Ess = 0; + const int nSamples = 100; + for (int i = 0; i < nSamples; ++i) { + // Evaluate single-scattering integrand and add to _Ess_ + Float ti = tCrit - std::log(1 - (i + .5f) / nSamples) / sigma_t; + // Determine length $d$ of connecting segment and $\cos\theta_\roman{o}$ + Float d = std::sqrt(r * r + ti * ti); + Float cosTheta_o = ti / d; + + // Add contribution of single scattering at depth $t$ + Ess += rho * std::exp(-sigma_t * (d + tCrit)) / (d * d) * + HenyeyGreenstein(cosTheta_o, g) * (1 - FrDielectric(-cosTheta_o, eta)) * + std::abs(cosTheta_o); + } + return Ess / nSamples; +} + +void ComputeBeamDiffusionBSSRDF(Float g, Float eta, BSSRDFTable *t) { + // Choose radius values of the diffusion profile discretization + t->radiusSamples[0] = 0; + t->radiusSamples[1] = 2.5e-3f; + for (int i = 2; i < t->radiusSamples.size(); ++i) + t->radiusSamples[i] = t->radiusSamples[i - 1] * 1.2f; + + // Choose albedo values of the diffusion profile discretization + for (int i = 0; i < t->rhoSamples.size(); ++i) + t->rhoSamples[i] = (1 - std::exp(-8 * i / (Float)(t->rhoSamples.size() - 1))) / + (1 - std::exp(-8)); + + ParallelFor(0, t->rhoSamples.size(), [&](int i) { + // Compute the diffusion profile for the _i_th albedo sample + // Compute scattering profile for chosen albedo $\rho$ + size_t nSamples = t->radiusSamples.size(); + for (int j = 0; j < nSamples; ++j) { + Float rho = t->rhoSamples[i], r = t->radiusSamples[j]; + t->profile[i * nSamples + j] = 2 * Pi * r * + (BeamDiffusionSS(rho, 1 - rho, g, eta, r) + + BeamDiffusionMS(rho, 1 - rho, g, eta, r)); + } + + // Compute effective albedo $\rho_{\roman{eff}}$ and CDF for importance sampling + t->rhoEff[i] = + IntegrateCatmullRom(t->radiusSamples, {&t->profile[i * nSamples], nSamples}, + {&t->profileCDF[i * nSamples], nSamples}); + }); +} + +// BSSRDFTable Method Definitions +BSSRDFTable::BSSRDFTable(int nRhoSamples, int nRadiusSamples, Allocator alloc) + : rhoSamples(nRhoSamples, alloc), + radiusSamples(nRadiusSamples, alloc), + profile(nRadiusSamples * nRhoSamples, alloc), + rhoEff(nRhoSamples, alloc), + profileCDF(nRadiusSamples * nRhoSamples, alloc) {} + +std::string BSSRDFTable::ToString() const { + return StringPrintf("[ BSSRDFTable rhoSamples: %s radiusSamples: %s profile: %s " + "rhoEff: %s profileCDF: %s ]", + rhoSamples, radiusSamples, profile, rhoEff, profileCDF); +} + +} // namespace pbrt diff --git a/src/pbrt/bssrdf.h b/src/pbrt/bssrdf.h new file mode 100644 index 00000000..60e241ba --- /dev/null +++ b/src/pbrt/bssrdf.h @@ -0,0 +1,357 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BSSRDF_H +#define PBRT_BSSRDF_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +// BSSRDFSample Definition +struct BSSRDFSample { + SampledSpectrum S; + Float pdf; + BSDF bsdf; + Vector3f wo; +}; + +// SubsurfaceInteraction Definition +struct SubsurfaceInteraction { + SubsurfaceInteraction() = default; + PBRT_CPU_GPU + SubsurfaceInteraction(const SurfaceInteraction &si) + : pi(si.pi), + n(si.n), + dpdu(si.dpdu), + dpdv(si.dpdv), + ns(si.shading.n), + dpdus(si.shading.dpdu), + dpdvs(si.shading.dpdv) {} + + PBRT_CPU_GPU + operator SurfaceInteraction() const { + SurfaceInteraction si; + si.pi = pi; + si.n = n; + si.dpdu = dpdu; + si.dpdv = dpdv; + si.shading.n = ns; + si.shading.dpdu = dpdus; + si.shading.dpdv = dpdvs; + return si; + } + + PBRT_CPU_GPU + Point3f p() const { return Point3f(pi); } + + Point3fi pi; + Normal3f n; + Vector3f dpdu, dpdv; + Normal3f ns; + Vector3f dpdus, dpdvs; +}; + +// BSSRDF Function Declarations +Float BeamDiffusionSS(Float sigma_s, Float sigma_a, Float g, Float eta, Float r); +Float BeamDiffusionMS(Float sigma_s, Float sigma_a, Float g, Float eta, Float r); + +void ComputeBeamDiffusionBSSRDF(Float g, Float eta, BSSRDFTable *t); + +// BSSRDFTable Definition +struct BSSRDFTable { + // BSSRDFTable Public Members + pstd::vector rhoSamples, radiusSamples; + pstd::vector profile; + pstd::vector rhoEff; + pstd::vector profileCDF; + + // BSSRDFTable Public Methods + BSSRDFTable(int nRhoSamples, int nRadiusSamples, Allocator alloc); + + std::string ToString() const; + + PBRT_CPU_GPU + Float EvalProfile(int rhoIndex, int radiusIndex) const { + CHECK(rhoIndex >= 0 && rhoIndex < rhoSamples.size()); + CHECK(radiusIndex >= 0 && radiusIndex < radiusSamples.size()); + return profile[rhoIndex * radiusSamples.size() + radiusIndex]; + } +}; + +// BSSRDFProbeSegment Definition +struct BSSRDFProbeSegment { + BSSRDFProbeSegment() = default; + PBRT_CPU_GPU + BSSRDFProbeSegment(const Point3f &p0, const Point3f &p1, Float time) + : p0(p0), p1(p1), time(time), valid(true) {} + PBRT_CPU_GPU operator bool() const { return valid; } + + Point3f p0, p1; + Float time; + bool valid = false; +}; + +// TabulatedBSSRDF Definition +class TabulatedBSSRDF { + public: + using BxDF = BSSRDFAdapter; + // TabulatedBSSRDF Public Methods + TabulatedBSSRDF() = default; + PBRT_CPU_GPU + TabulatedBSSRDF(const Point3f &po, const Vector3f &dpdu, const Normal3f &ns, + const Vector3f &wo, Float time, Float eta, + const SampledSpectrum &sigma_a, const SampledSpectrum &sigma_s, + const BSSRDFTable *table) + : po(po), + wo(wo), + eta(eta), + ns(ns), + ss(Normalize(dpdu)), + ts(Cross(ns, ss)), + table(table) { + sigma_t = sigma_a + sigma_s; + rho = SafeDiv(sigma_s, sigma_t); + } + + PBRT_CPU_GPU + SampledSpectrum S(const Point3f &p, const Vector3f &wi) { + Float Ft = FrDielectric(CosTheta(wo), eta); + return (1 - Ft) * Sp(p) * Sw(wi); + } + + PBRT_CPU_GPU + SampledSpectrum Sp(const Point3f &pi) const { return Sr(Distance(po, pi)); } + + PBRT_CPU_GPU + SampledSpectrum Sr(Float r) const { + SampledSpectrum Sr(0.f); + for (int ch = 0; ch < NSpectrumSamples; ++ch) { + // Convert $r$ into unitless optical radius $r_{\roman{optical}}$ + Float rOptical = r * sigma_t[ch]; + + // Compute spline weights to interpolate BSSRDF on channel _ch_ + int rhoOffset, radiusOffset; + Float rhoWeights[4], radiusWeights[4]; + if (!CatmullRomWeights(table->rhoSamples, rho[ch], &rhoOffset, rhoWeights) || + !CatmullRomWeights(table->radiusSamples, rOptical, &radiusOffset, + radiusWeights)) + continue; + + // Set BSSRDF value _Sr[ch]_ using tensor spline interpolation + Float sr = 0; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + // Accumulate contribution of $(i,j)$ table sample + Float weight = rhoWeights[i] * radiusWeights[j]; + if (weight != 0) + sr += + weight * table->EvalProfile(rhoOffset + i, radiusOffset + j); + } + } + // Cancel marginal PDF factor from tabulated BSSRDF profile + if (rOptical != 0) + sr /= 2 * Pi * rOptical; + + Sr[ch] = sr; + } + // Transform BSSRDF value into world space units + Sr *= sigma_t * sigma_t; + + return ClampZero(Sr); + } + + PBRT_CPU_GPU + SampledSpectrum Sw(const Vector3f &w) const { + Float c = 1 - 2 * FresnelMoment1(1 / eta); + return SampledSpectrum((1 - FrDielectric(CosTheta(w), eta)) / (c * Pi)); + } + + std::string ToString() const; + + PBRT_CPU_GPU + BSSRDFProbeSegment Sample(Float u1, const Point2f &u2) const { + // Choose projection axis for BSSRDF sampling + Vector3f vx, vy, vz; + switch (SampleDiscrete({0.5, .25, .25}, u1, nullptr, &u1)) { + case 0: + vx = ss; + vy = ts; + vz = Vector3f(ns); + break; + case 1: + // Prepare for sampling rays with respect to _ss_ + vx = ts; + vy = Vector3f(ns); + vz = ss; + break; + + case 2: + // Prepare for sampling rays with respect to _ts_ + vx = Vector3f(ns); + vy = ss; + vz = ts; + break; + + default: + LOG_FATAL("Unexpected value returned from SampleDiscrete"); + } + + // Choose spectral channel for BSSRDF sampling + int ch = std::min(u1 * NSpectrumSamples, NSpectrumSamples - 1); + u1 = std::min(u1 * NSpectrumSamples - ch, OneMinusEpsilon); + + // Sample BSSRDF profile in polar coordinates + Float r = Sample_Sr(ch, u2[0]); + if (r < 0) + return {}; + Float phi = 2 * Pi * u2[1]; + + // Compute BSSRDF profile bounds and intersection height + Float rMax = Sample_Sr(ch, 0.999f); + if (r >= rMax) + return {}; + Float l = 2 * std::sqrt(rMax * rMax - r * r); + + // Return BSSRDF sampling ray segment + Point3f pStart = + po + r * (vx * std::cos(phi) + vy * std::sin(phi)) - l * vz * 0.5f; + Point3f pTarget = pStart + l * vz; + return BSSRDFProbeSegment{pStart, pTarget, time}; + } + + PBRT_CPU_GPU + Float Sample_Sr(int ch, Float u) const { + if (sigma_t[ch] == 0) + return -1; + return SampleCatmullRom2D(table->rhoSamples, table->radiusSamples, table->profile, + table->profileCDF, rho[ch], u) / + sigma_t[ch]; + } + + PBRT_CPU_GPU + Float PDF_Sr(int ch, Float r) const { + // Convert $r$ into unitless optical radius $r_{\roman{optical}}$ + Float rOptical = r * sigma_t[ch]; + + // Compute spline weights to interpolate BSSRDF density on channel _ch_ + int rhoOffset, radiusOffset; + Float rhoWeights[4], radiusWeights[4]; + if (!CatmullRomWeights(table->rhoSamples, rho[ch], &rhoOffset, rhoWeights) || + !CatmullRomWeights(table->radiusSamples, rOptical, &radiusOffset, + radiusWeights)) + return 0.f; + + // Return BSSRDF profile density for channel _ch_ + Float sr = 0, rhoEff = 0; + for (int i = 0; i < 4; ++i) { + if (rhoWeights[i] == 0) + continue; + rhoEff += table->rhoEff[rhoOffset + i] * rhoWeights[i]; + for (int j = 0; j < 4; ++j) { + if (radiusWeights[j] == 0) + continue; + sr += table->EvalProfile(rhoOffset + i, radiusOffset + j) * + rhoWeights[i] * radiusWeights[j]; + } + } + // Cancel marginal PDF factor from tabulated BSSRDF profile + if (rOptical != 0) + sr /= 2 * Pi * rOptical; + + return std::max(0, sr * sigma_t[ch] * sigma_t[ch] / rhoEff); + } + + PBRT_CPU_GPU + Float PDF_Sp(const Point3f &pi, const Normal3f &ni) const { + // Express $\pti-\pto$ and $\bold{n}_i$ with respect to local coordinates at + // $\pto$ + Vector3f d = pi - po; + Vector3f dLocal(Dot(ss, d), Dot(ts, d), Dot(ns, d)); + Normal3f nLocal(Dot(ss, ni), Dot(ts, ni), Dot(ns, ni)); + + // Compute BSSRDF profile radius under projection along each axis + Float rProj[3] = {std::sqrt(dLocal.y * dLocal.y + dLocal.z * dLocal.z), + std::sqrt(dLocal.z * dLocal.z + dLocal.x * dLocal.x), + std::sqrt(dLocal.x * dLocal.x + dLocal.y * dLocal.y)}; + + // Return combined probability from all BSSRDF sampling strategies + Float pdf = 0, axisProb[3] = {.25f, .25f, .5f}; + Float chProb = 1 / (Float)NSpectrumSamples; + for (int axis = 0; axis < 3; ++axis) + for (int ch = 0; ch < NSpectrumSamples; ++ch) + pdf += PDF_Sr(ch, rProj[axis]) * std::abs(nLocal[axis]) * chProb * + axisProb[axis]; + return pdf; + } + + PBRT_CPU_GPU + BSSRDFSample ProbeIntersectionToSample(const SubsurfaceInteraction &si, + BSSRDFAdapter *bxdf) const { + *bxdf = BSSRDFAdapter(eta); + Vector3f wo = Vector3f(si.ns); + BSDF bsdf(wo, si.n, si.ns, si.dpdus, bxdf, eta); + return BSSRDFSample{Sp(si.p()), PDF_Sp(si.p(), si.n), bsdf, wo}; + } + + private: + friend class SOA; + // TabulatedBSSRDF Private Data + Point3f po; + Vector3f wo; + Float time; + Normal3f ns; + Vector3f ss, ts; + Float eta; + const BSSRDFTable *table; + SampledSpectrum sigma_t, rho; +}; + +// BSSRDF Inline Functions +PBRT_CPU_GPU +inline void SubsurfaceFromDiffuse(const BSSRDFTable &t, const SampledSpectrum &rhoEff, + const SampledSpectrum &mfp, SampledSpectrum *sigma_a, + SampledSpectrum *sigma_s) { + for (int c = 0; c < NSpectrumSamples; ++c) { + Float rho = InvertCatmullRom(t.rhoSamples, t.rhoEff, rhoEff[c]); + (*sigma_s)[c] = rho / mfp[c]; + (*sigma_a)[c] = (1 - rho) / mfp[c]; + } +} + +inline SampledSpectrum BSSRDFHandle::S(const Point3f &p, const Vector3f &wi) { + auto s = [&](auto ptr) { return ptr->S(p, wi); }; + return Dispatch(s); +} + +inline BSSRDFProbeSegment BSSRDFHandle::Sample(Float u1, const Point2f &u2) const { + auto sample = [&](auto ptr) { return ptr->Sample(u1, u2); }; + return Dispatch(sample); +} + +inline BSSRDFSample BSSRDFHandle::ProbeIntersectionToSample( + const SubsurfaceInteraction &si, ScratchBuffer &scratchBuffer) const { + auto pits = [&](auto ptr) { + using BxDF = typename std::remove_reference::type::BxDF; + BxDF *bxdf = (BxDF *)scratchBuffer.Alloc(sizeof(BxDF), alignof(BxDF)); + return ptr->ProbeIntersectionToSample(si, bxdf); + }; + return Dispatch(pits); +} + +} // namespace pbrt + +#endif // PBRT_BSSRDF_H diff --git a/src/pbrt/bxdfs.cpp b/src/pbrt/bxdfs.cpp new file mode 100644 index 00000000..5e064a63 --- /dev/null +++ b/src/pbrt/bxdfs.cpp @@ -0,0 +1,997 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +std::string ToString(BxDFReflTransFlags flags) { + if (flags == BxDFReflTransFlags::Unset) + return "Unset"; + std::string s; + if (flags & BxDFReflTransFlags::Reflection) + s += "Reflection,"; + if (flags & BxDFReflTransFlags::Transmission) + s += "Transmission,"; + return s; +} + +std::string ToString(BxDFFlags flags) { + if (flags == BxDFFlags::Unset) + return "Unset"; + std::string s; + if (flags & BxDFFlags::Reflection) + s += "Reflection,"; + if (flags & BxDFFlags::Transmission) + s += "Transmission,"; + if (flags & BxDFFlags::Diffuse) + s += "Diffuse,"; + if (flags & BxDFFlags::Glossy) + s += "Glossy,"; + if (flags & BxDFFlags::Specular) + s += "Specular,"; + return s; +} + +std::string ToString(TransportMode mode) { + return mode == TransportMode::Radiance ? "Radiance" : "Importance"; +} + +// BxDF Method Definitions +std::string IdealDiffuseBxDF::ToString() const { + return StringPrintf("[ IdealDiffuseBxDF R: %s ]", R); +} +std::string DiffuseBxDF::ToString() const { + return StringPrintf("[ DiffuseBxDF R: %s T: %s A: %f B: %f ]", R, T, A, B); +} + +template +std::string LayeredBxDF::ToString() const { + return StringPrintf( + "[ LayeredBxDF top: %s bottom: %s thickness: %f albedo: %s g: %f ]", top, bottom, + thickness, albedo, g); +} + +std::string DielectricInterfaceBxDF::ToString() const { + return StringPrintf("[ DielectricInterfaceBxDF eta: %f mfDistrib: %s ]", eta, + mfDistrib.ToString()); +} + +std::string ThinDielectricBxDF::ToString() const { + return StringPrintf("[ ThinDielectricBxDF eta: %f ]", eta); +} + +std::string ConductorBxDF::ToString() const { + return StringPrintf("[ ConductorBxDF mfDistrib: %s eta: %s k: %s ]", mfDistrib, eta, + k); +} + +// HairBxDF Method Definitions +HairBxDF::HairBxDF(Float h, Float eta, const SampledSpectrum &sigma_a, Float beta_m, + Float beta_n, Float alpha) + : h(h), + gamma_o(SafeASin(h)), + eta(eta), + sigma_a(sigma_a), + beta_m(beta_m), + beta_n(beta_n) { + CHECK(h >= -1 && h <= 1); + CHECK(beta_m >= 0 && beta_m <= 1); + CHECK(beta_n >= 0 && beta_n <= 1); + // Compute longitudinal variance from $\beta_m$ + static_assert(pMax >= 3, + "Longitudinal variance code must be updated to handle low pMax"); + v[0] = Sqr(0.726f * beta_m + 0.812f * Sqr(beta_m) + 3.7f * Pow<20>(beta_m)); + v[1] = .25 * v[0]; + v[2] = 4 * v[0]; + for (int p = 3; p <= pMax; ++p) + // TODO: is there anything better here? + v[p] = v[2]; + + // Compute azimuthal logistic scale factor from $\beta_n$ + static const Float SqrtPiOver8 = 0.626657069f; + s = SqrtPiOver8 * (0.265f * beta_n + 1.194f * Sqr(beta_n) + 5.372f * Pow<22>(beta_n)); + CHECK(!std::isnan(s)); + + // Compute $\alpha$ terms for hair scales + sin2kAlpha[0] = std::sin(Radians(alpha)); + cos2kAlpha[0] = SafeSqrt(1 - Sqr(sin2kAlpha[0])); + for (int i = 1; i < 3; ++i) { + sin2kAlpha[i] = 2 * cos2kAlpha[i - 1] * sin2kAlpha[i - 1]; + cos2kAlpha[i] = Sqr(cos2kAlpha[i - 1]) - Sqr(sin2kAlpha[i - 1]); + } +} + +SampledSpectrum HairBxDF::f(Vector3f wo, Vector3f wi, TransportMode mode) const { + // Compute hair coordinate system terms related to _wo_ + Float sinTheta_o = wo.x; + Float cosTheta_o = SafeSqrt(1 - Sqr(sinTheta_o)); + Float phi_o = std::atan2(wo.z, wo.y); + + // Compute hair coordinate system terms related to _wi_ + Float sinTheta_i = wi.x; + Float cosTheta_i = SafeSqrt(1 - Sqr(sinTheta_i)); + Float phi_i = std::atan2(wi.z, wi.y); + + // Compute $\cos \thetat$ for refracted ray + Float sinTheta_t = sinTheta_o / eta; + Float cosTheta_t = SafeSqrt(1 - Sqr(sinTheta_t)); + + // Compute $\gammat$ for refracted ray + Float etap = SafeSqrt(eta * eta - Sqr(sinTheta_o)) / cosTheta_o; + Float sinGamma_t = h / etap; + Float cosGamma_t = SafeSqrt(1 - Sqr(sinGamma_t)); + Float gamma_t = SafeASin(sinGamma_t); + + // Compute the transmittance _T_ of a single path through the cylinder + SampledSpectrum T = Exp(-sigma_a * (2 * cosGamma_t / cosTheta_t)); + + // Evaluate hair BSDF + Float phi = phi_i - phi_o; + pstd::array ap = Ap(cosTheta_o, eta, h, T); + SampledSpectrum fsum(0.); + for (int p = 0; p < pMax; ++p) { + // Compute $\sin \thetai$ and $\cos \thetai$ terms accounting for scales + Float sinThetap_o, cosThetap_o; + if (p == 0) { + sinThetap_o = sinTheta_o * cos2kAlpha[1] - cosTheta_o * sin2kAlpha[1]; + cosThetap_o = cosTheta_o * cos2kAlpha[1] + sinTheta_o * sin2kAlpha[1]; + } + // Handle remainder of $p$ values for hair scale tilt + else if (p == 1) { + sinThetap_o = sinTheta_o * cos2kAlpha[0] + cosTheta_o * sin2kAlpha[0]; + cosThetap_o = cosTheta_o * cos2kAlpha[0] - sinTheta_o * sin2kAlpha[0]; + } else if (p == 2) { + sinThetap_o = sinTheta_o * cos2kAlpha[2] + cosTheta_o * sin2kAlpha[2]; + cosThetap_o = cosTheta_o * cos2kAlpha[2] - sinTheta_o * sin2kAlpha[2]; + } else { + sinThetap_o = sinTheta_o; + cosThetap_o = cosTheta_o; + } + + // Handle out-of-range $\cos \thetao$ from scale adjustment + cosThetap_o = std::abs(cosThetap_o); + + fsum += Mp(cosTheta_i, cosThetap_o, sinTheta_i, sinThetap_o, v[p]) * ap[p] * + Np(phi, p, s, gamma_o, gamma_t); + } + // Compute contribution of remaining terms after _pMax_ + fsum += Mp(cosTheta_i, cosTheta_o, sinTheta_i, sinTheta_o, v[pMax]) * ap[pMax] / + (2.f * Pi); + + if (AbsCosTheta(wi) > 0) + fsum /= AbsCosTheta(wi); + CHECK(!std::isinf(fsum.Average()) && !std::isnan(fsum.Average())); + return fsum; +} + +pstd::array HairBxDF::ComputeApPDF(Float cosTheta_o) const { + // Compute array of $A_p$ values for _cosThetaO_ + Float sinTheta_o = SafeSqrt(1 - cosTheta_o * cosTheta_o); + // Compute $\cos \thetat$ for refracted ray + Float sinTheta_t = sinTheta_o / eta; + Float cosTheta_t = SafeSqrt(1 - Sqr(sinTheta_t)); + + // Compute $\gammat$ for refracted ray + Float etap = SafeSqrt(eta * eta - Sqr(sinTheta_o)) / cosTheta_o; + Float sinGamma_t = h / etap; + Float cosGamma_t = SafeSqrt(1 - Sqr(sinGamma_t)); + Float gamma_t = SafeASin(sinGamma_t); + + // Compute the transmittance _T_ of a single path through the cylinder + SampledSpectrum T = Exp(-sigma_a * (2 * cosGamma_t / cosTheta_t)); + + pstd::array ap = Ap(cosTheta_o, eta, h, T); + + // Compute $A_p$ PDF from individual $A_p$ terms + pstd::array apPDF; + Float sumY = 0; + for (const SampledSpectrum &as : ap) + sumY += as.Average(); + for (int i = 0; i <= pMax; ++i) + apPDF[i] = ap[i].Average() / sumY; + + return apPDF; +} + +BSDFSample HairBxDF::Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + // Compute hair coordinate system terms related to _wo_ + Float sinTheta_o = wo.x; + Float cosTheta_o = SafeSqrt(1 - Sqr(sinTheta_o)); + Float phi_o = std::atan2(wo.z, wo.y); + + // Determine which term $p$ to sample for hair scattering + pstd::array apPDF = ComputeApPDF(cosTheta_o); + int p = SampleDiscrete(apPDF, uc, nullptr, &uc); + + // Rotate $\sin \thetao$ and $\cos \thetao$ to account for hair scale tilt + Float sinThetap_o, cosThetap_o; + if (p == 0) { + sinThetap_o = sinTheta_o * cos2kAlpha[1] - cosTheta_o * sin2kAlpha[1]; + cosThetap_o = cosTheta_o * cos2kAlpha[1] + sinTheta_o * sin2kAlpha[1]; + } else if (p == 1) { + sinThetap_o = sinTheta_o * cos2kAlpha[0] + cosTheta_o * sin2kAlpha[0]; + cosThetap_o = cosTheta_o * cos2kAlpha[0] - sinTheta_o * sin2kAlpha[0]; + } else if (p == 2) { + sinThetap_o = sinTheta_o * cos2kAlpha[2] + cosTheta_o * sin2kAlpha[2]; + cosThetap_o = cosTheta_o * cos2kAlpha[2] - sinTheta_o * sin2kAlpha[2]; + } else { + sinThetap_o = sinTheta_o; + cosThetap_o = cosTheta_o; + } + + // Sample $M_p$ to compute $\thetai$ + Float cosTheta = 1 + v[p] * std::log(std::max(u[0], 1e-5) + + (1 - u[0]) * std::exp(-2 / v[p])); + Float sinTheta = SafeSqrt(1 - Sqr(cosTheta)); + Float cosPhi = std::cos(2 * Pi * u[1]); + Float sinTheta_i = -cosTheta * sinThetap_o + sinTheta * cosPhi * cosThetap_o; + Float cosTheta_i = SafeSqrt(1 - Sqr(sinTheta_i)); + + // Sample $N_p$ to compute $\Delta\phi$ + // Compute $\gammat$ for refracted ray + Float etap = SafeSqrt(eta * eta - Sqr(sinTheta_o)) / cosTheta_o; + Float sinGamma_t = h / etap; + Float cosGamma_t = SafeSqrt(1 - Sqr(sinGamma_t)); + Float gamma_t = SafeASin(sinGamma_t); + + Float dphi; + if (p < pMax) + dphi = Phi(p, gamma_o, gamma_t) + SampleTrimmedLogistic(uc, s, -Pi, Pi); + else + dphi = 2 * Pi * uc; + + // Compute _wi_ from sampled hair scattering angles + Float phi_i = phi_o + dphi; + Vector3f wi(sinTheta_i, cosTheta_i * std::cos(phi_i), cosTheta_i * std::sin(phi_i)); + + // Compute PDF for sampled hair scattering direction _wi_ + Float pdf = 0; + for (int p = 0; p < pMax; ++p) { + // Rotate $\sin \thetao$ and $\cos \thetao$ to account for hair scale tilt + Float sinThetap_o, cosThetap_o; + if (p == 0) { + sinThetap_o = sinTheta_o * cos2kAlpha[1] - cosTheta_o * sin2kAlpha[1]; + cosThetap_o = cosTheta_o * cos2kAlpha[1] + sinTheta_o * sin2kAlpha[1]; + } else if (p == 1) { + sinThetap_o = sinTheta_o * cos2kAlpha[0] + cosTheta_o * sin2kAlpha[0]; + cosThetap_o = cosTheta_o * cos2kAlpha[0] - sinTheta_o * sin2kAlpha[0]; + } else if (p == 2) { + sinThetap_o = sinTheta_o * cos2kAlpha[2] + cosTheta_o * sin2kAlpha[2]; + cosThetap_o = cosTheta_o * cos2kAlpha[2] - sinTheta_o * sin2kAlpha[2]; + } else { + sinThetap_o = sinTheta_o; + cosThetap_o = cosTheta_o; + } + + // Handle out-of-range $\cos \thetao$ from scale adjustment + cosThetap_o = std::abs(cosThetap_o); + + pdf += Mp(cosTheta_i, cosThetap_o, sinTheta_i, sinThetap_o, v[p]) * apPDF[p] * + Np(dphi, p, s, gamma_o, gamma_t); + } + pdf += Mp(cosTheta_i, cosTheta_o, sinTheta_i, sinTheta_o, v[pMax]) * apPDF[pMax] * + (1 / (2 * Pi)); + // if (std::abs(wi->x) < .9999) CHECK_NEAR(*pdf, PDF(wo, *wi), .01); + + return BSDFSample(f(wo, wi, mode), wi, pdf, Flags()); +} + +Float HairBxDF::PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + // TODO? flags... + + // Compute hair coordinate system terms related to _wo_ + Float sinTheta_o = wo.x; + Float cosTheta_o = SafeSqrt(1 - Sqr(sinTheta_o)); + Float phi_o = std::atan2(wo.z, wo.y); + + // Compute hair coordinate system terms related to _wi_ + Float sinTheta_i = wi.x; + Float cosTheta_i = SafeSqrt(1 - Sqr(sinTheta_i)); + Float phi_i = std::atan2(wi.z, wi.y); + + // Compute $\gammat$ for refracted ray + Float etap = SafeSqrt(eta * eta - Sqr(sinTheta_o)) / cosTheta_o; + Float sinGamma_t = h / etap; + Float gamma_t = SafeASin(sinGamma_t); + + // Compute PDF for $A_p$ terms + pstd::array apPDF = ComputeApPDF(cosTheta_o); + + // Compute PDF sum for hair scattering events + Float phi = phi_i - phi_o; + Float pdf = 0; + for (int p = 0; p < pMax; ++p) { + // Compute $\sin \thetao$ and $\cos \thetao$ terms accounting for scales + Float sinThetap_o, cosThetap_o; + if (p == 0) { + sinThetap_o = sinTheta_o * cos2kAlpha[1] - cosTheta_o * sin2kAlpha[1]; + cosThetap_o = cosTheta_o * cos2kAlpha[1] + sinTheta_o * sin2kAlpha[1]; + } + + // Handle remainder of $p$ values for hair scale tilt + else if (p == 1) { + sinThetap_o = sinTheta_o * cos2kAlpha[0] + cosTheta_o * sin2kAlpha[0]; + cosThetap_o = cosTheta_o * cos2kAlpha[0] - sinTheta_o * sin2kAlpha[0]; + } else if (p == 2) { + sinThetap_o = sinTheta_o * cos2kAlpha[2] + cosTheta_o * sin2kAlpha[2]; + cosThetap_o = cosTheta_o * cos2kAlpha[2] - sinTheta_o * sin2kAlpha[2]; + } else { + sinThetap_o = sinTheta_o; + cosThetap_o = cosTheta_o; + } + + // Handle out-of-range $\cos \thetao$ from scale adjustment + cosThetap_o = std::abs(cosThetap_o); + pdf += Mp(cosTheta_i, cosThetap_o, sinTheta_i, sinThetap_o, v[p]) * apPDF[p] * + Np(phi, p, s, gamma_o, gamma_t); + } + pdf += Mp(cosTheta_i, cosTheta_o, sinTheta_i, sinTheta_o, v[pMax]) * apPDF[pMax] * + (1 / (2 * Pi)); + return pdf; +} + +RGBSpectrum HairBxDF::SigmaAFromConcentration(Float ce, Float cp) { + RGB eumelaninSigmaA(0.419f, 0.697f, 1.37f); + RGB pheomelaninSigmaA(0.187f, 0.4f, 1.05f); + RGB sigma_a = ce * eumelaninSigmaA + cp * pheomelaninSigmaA; +#ifdef PBRT_IS_GPU_CODE + return RGBSpectrum(*RGBColorSpace_sRGB, sigma_a); +#else + return RGBSpectrum(*RGBColorSpace::sRGB, sigma_a); +#endif +} + +SampledSpectrum HairBxDF::SigmaAFromReflectance(const SampledSpectrum &c, Float beta_n, + const SampledWavelengths &lambda) { + SampledSpectrum sigma_a; + for (int i = 0; i < NSpectrumSamples; ++i) + sigma_a[i] = + Sqr(std::log(c[i]) / (5.969f - 0.215f * beta_n + 2.532f * Sqr(beta_n) - + 10.73f * Pow<3>(beta_n) + 5.574f * Pow<4>(beta_n) + + 0.245f * Pow<5>(beta_n))); + return sigma_a; +} + +std::string HairBxDF::ToString() const { + return StringPrintf("[ HairBxDF h: %f gamma_o: %f eta: %f beta_m: %f beta_n: %f " + "v[0]: %f s: %f sigma_a: %s ]", + h, gamma_o, eta, beta_m, beta_n, v[0], s, sigma_a); +} + +// ***************************************************************************** +// Tensor file I/O +// ***************************************************************************** + +class Tensor { + public: + // Data type of the tensor's fields + enum Type { + /* Invalid/unspecified */ + Invalid = 0, + + /* Signed and unsigned integer values */ + UInt8, + Int8, + UInt16, + Int16, + UInt32, + Int32, + UInt64, + Int64, + + /* Floating point values */ + Float16, + Float32, + Float64, + }; + + struct Field { + // Data type of the tensor's fields + Type dtype; + + // Offset in the file + size_t offset; + + /// Specifies both rank and size along each dimension + std::vector shape; + + /// Pointer to the start of the tensor + std::unique_ptr data; + }; + + /// Load a tensor file into memory + Tensor(const std::string &filename); + + /// Does the file contain a field of the specified name? + bool has_field(const std::string &name) const; + + /// Return a data structure with information about the specified field + const Field &field(const std::string &name) const; + + /// Return a human-readable summary + std::string ToString() const; + + /// Return the total size of the tensor's data + size_t size() const { return m_size; } + + std::string filename() const { return m_filename; } + + private: + std::unordered_map m_fields; + std::string m_filename; + size_t m_size; +}; + +static std::ostream &operator<<(std::ostream &os, Tensor::Type value) { + switch (value) { + case Tensor::Invalid: + os << "invalid"; + break; + case Tensor::UInt8: + os << "uint8_t"; + break; + case Tensor::Int8: + os << "int8_t"; + break; + case Tensor::UInt16: + os << "uint16_t"; + break; + case Tensor::Int16: + os << "int16_t"; + break; + case Tensor::UInt32: + os << "uint32_t"; + break; + case Tensor::Int32: + os << "int8_t"; + break; + case Tensor::UInt64: + os << "uint64_t"; + break; + case Tensor::Int64: + os << "int64_t"; + break; + case Tensor::Float16: + os << "float16_t"; + break; + case Tensor::Float32: + os << "float32_t"; + break; + case Tensor::Float64: + os << "float64_t"; + break; + default: + os << "unkown"; + break; + } + return os; +} + +static size_t type_size(Tensor::Type value) { + switch (value) { + case Tensor::Invalid: + return 0; + break; + case Tensor::UInt8: + return 1; + break; + case Tensor::Int8: + return 1; + break; + case Tensor::UInt16: + return 2; + break; + case Tensor::Int16: + return 2; + break; + case Tensor::UInt32: + return 4; + break; + case Tensor::Int32: + return 4; + break; + case Tensor::UInt64: + return 8; + break; + case Tensor::Int64: + return 8; + break; + case Tensor::Float16: + return 2; + break; + case Tensor::Float32: + return 4; + break; + case Tensor::Float64: + return 8; + break; + default: + return 0; + break; + } +} + +Tensor::Tensor(const std::string &filename) : m_filename(filename) { + // Helpful macros to limit error-handling code duplication +#ifdef ASSERT +#undef ASSERT +#endif // ASSERT + +#define ASSERT(cond, msg) \ + do { \ + if (!(cond)) { \ + fclose(file); \ + ErrorExit("%s: Tensor: " msg, filename); \ + } \ + } while (0) + +#define SAFE_READ(vars, size, count) \ + ASSERT(fread(vars, size, count, file) == (count), "Unable to read " #vars ".") + + FILE *file = fopen(filename.c_str(), "rb"); + if (file == NULL) + ErrorExit("%s: unable to open file", filename); + + ASSERT(!fseek(file, 0, SEEK_END), "Unable to seek to end of file."); + + long size = ftell(file); + ASSERT(size != -1, "Unable to tell file cursor position."); + m_size = static_cast(size); + rewind(file); + + ASSERT(m_size >= 12 + 2 + 4, "Invalid tensor file: too small, truncated?"); + + uint8_t header[12], version[2]; + uint32_t n_fields; + SAFE_READ(header, sizeof(*header), 12); + SAFE_READ(version, sizeof(*version), 2); + SAFE_READ(&n_fields, sizeof(n_fields), 1); + + ASSERT(memcmp(header, "tensor_file", 12) == 0, + "Invalid tensor file: invalid header."); + ASSERT(version[0] == 1 && version[1] == 0, + "Invalid tensor file: unknown file version."); + + for (uint32_t i = 0; i < n_fields; ++i) { + uint8_t dtype; + uint16_t name_length, ndim; + uint64_t offset; + + SAFE_READ(&name_length, sizeof(name_length), 1); + std::string name(name_length, '\0'); + SAFE_READ((char *)name.data(), 1, name_length); + SAFE_READ(&ndim, sizeof(ndim), 1); + SAFE_READ(&dtype, sizeof(dtype), 1); + SAFE_READ(&offset, sizeof(offset), 1); + ASSERT(dtype != Invalid && dtype <= Float64, + "Invalid tensor file: unknown type."); + + std::vector shape(ndim); + size_t total_size = type_size((Type)dtype); // no need to check here, line 43 + // already removes invalid types + for (size_t j = 0; j < (size_t)ndim; ++j) { + uint64_t size_value; + SAFE_READ(&size_value, sizeof(size_value), 1); + shape[j] = (size_t)size_value; + total_size *= shape[j]; + } + + auto data = std::unique_ptr(new uint8_t[total_size]); + + long cur_pos = ftell(file); + ASSERT(cur_pos != -1, "Unable to tell current cursor position."); + ASSERT(fseek(file, offset, SEEK_SET) != -1, "Unable to seek to tensor offset."); + SAFE_READ(data.get(), 1, total_size); + ASSERT(fseek(file, cur_pos, SEEK_SET) != -1, + "Unable to seek back to current position"); + + m_fields[name] = + Field{(Type)dtype, static_cast(offset), shape, std::move(data)}; + } + + fclose(file); + +#undef SAFE_READ +#undef ASSERT +} + +/// Does the file contain a field of the specified name? +bool Tensor::has_field(const std::string &name) const { + return m_fields.find(name) != m_fields.end(); +} + +/// Return a data structure with information about the specified field +const Tensor::Field &Tensor::field(const std::string &name) const { + auto it = m_fields.find(name); + CHECK(it != m_fields.end()); + return it->second; +} + +/// Return a human-readable summary +std::string Tensor::ToString() const { + std::ostringstream oss; + oss << "Tensor[" << std::endl + << " filename = \"" << m_filename << "\"," << std::endl + << " size = " << size() << "," << std::endl + << " fields = {" << std::endl; + + size_t ctr = 0; + for (const auto &it : m_fields) { + oss << " \"" << it.first << "\"" + << " => [" << std::endl + << " dtype = " << it.second.dtype << "," << std::endl + << " offset = " << it.second.offset << "," << std::endl + << " shape = ["; + const auto &shape = it.second.shape; + for (size_t j = 0; j < shape.size(); ++j) { + oss << shape[j]; + if (j + 1 < shape.size()) + oss << ", "; + } + + oss << "]" << std::endl; + + oss << " ]"; + if (++ctr < m_fields.size()) + oss << ","; + oss << std::endl; + } + + oss << " }" << std::endl << "]"; + + return oss.str(); +} + +// MeasuredBRDF Definition +class MeasuredBRDF { + public: + MeasuredBRDF(Allocator alloc) + : ndf(alloc), + sigma(alloc), + vndf(alloc), + luminance(alloc), + spectra(alloc), + wavelengths(alloc) {} + + static MeasuredBRDF *Create(const std::string &filename, Allocator alloc); + + std::string ToString() const { + return StringPrintf("[ MeasuredBRDF filename: %s ]", filename); + } + + using Warp2D0 = PiecewiseLinear2D<0>; + using Warp2D2 = PiecewiseLinear2D<2>; + using Warp2D3 = PiecewiseLinear2D<3>; + + Warp2D0 ndf; + Warp2D0 sigma; + Warp2D2 vndf; + Warp2D2 luminance; + Warp2D3 spectra; + pstd::vector wavelengths; + bool isotropic; + bool jacobian; + std::string filename; +}; + +STAT_MEMORY_COUNTER("Memory/Measured BRDF data", measuredBRDFBytes); + +MeasuredBRDF *MeasuredBRDF::Create(const std::string &filename, Allocator alloc) { + Tensor tf = Tensor(filename); + auto &theta_i = tf.field("theta_i"); + auto &phi_i = tf.field("phi_i"); + auto &ndf = tf.field("ndf"); + auto &sigma = tf.field("sigma"); + auto &vndf = tf.field("vndf"); + auto &spectra = tf.field("spectra"); + auto &luminance = tf.field("luminance"); + auto &wavelengths = tf.field("wavelengths"); + auto &description = tf.field("description"); + auto &jacobian = tf.field("jacobian"); + + if (!(description.shape.size() == 1 && description.dtype == Tensor::UInt8 && + + theta_i.shape.size() == 1 && theta_i.dtype == Tensor::Float32 && + + phi_i.shape.size() == 1 && phi_i.dtype == Tensor::Float32 && + + wavelengths.shape.size() == 1 && wavelengths.dtype == Tensor::Float32 && + + ndf.shape.size() == 2 && ndf.dtype == Tensor::Float32 && + + sigma.shape.size() == 2 && sigma.dtype == Tensor::Float32 && + + vndf.shape.size() == 4 && vndf.dtype == Tensor::Float32 && + vndf.shape[0] == phi_i.shape[0] && vndf.shape[1] == theta_i.shape[0] && + + luminance.shape.size() == 4 && luminance.dtype == Tensor::Float32 && + luminance.shape[0] == phi_i.shape[0] && + luminance.shape[1] == theta_i.shape[0] && + luminance.shape[2] == luminance.shape[3] && + + spectra.dtype == Tensor::Float32 && spectra.shape.size() == 5 && + spectra.shape[0] == phi_i.shape[0] && spectra.shape[1] == theta_i.shape[0] && + spectra.shape[2] == wavelengths.shape[0] && + spectra.shape[3] == spectra.shape[4] && + + luminance.shape[2] == spectra.shape[3] && + luminance.shape[3] == spectra.shape[4] && + + jacobian.shape.size() == 1 && jacobian.shape[0] == 1 && + jacobian.dtype == Tensor::UInt8)) { + Error("%s: invalid BRDF file structure: %s", filename, tf); + return nullptr; + } + + MeasuredBRDF *brdf = alloc.new_object(alloc); + brdf->filename = filename; + brdf->isotropic = phi_i.shape[0] <= 2; + brdf->jacobian = ((uint8_t *)jacobian.data.get())[0]; + + if (!brdf->isotropic) { + float *phi_i_data = (float *)phi_i.data.get(); + int reduction = + (int)std::rint((2 * Pi) / (phi_i_data[phi_i.shape[0] - 1] - phi_i_data[0])); + if (reduction != 1) + ErrorExit("%s: reduction %d (!= 1) not supported", filename, reduction); + } + + /* Construct NDF interpolant data structure */ + brdf->ndf = Warp2D0(alloc, (float *)ndf.data.get(), ndf.shape[1], ndf.shape[0], {}, + {}, false, false); + + /* Construct projected surface area interpolant data structure */ + brdf->sigma = Warp2D0(alloc, (float *)sigma.data.get(), sigma.shape[1], + sigma.shape[0], {}, {}, false, false); + + /* Construct VNDF warp data structure */ + brdf->vndf = + Warp2D2(alloc, (float *)vndf.data.get(), vndf.shape[3], vndf.shape[2], + {{(int)phi_i.shape[0], (int)theta_i.shape[0]}}, + {{(const float *)phi_i.data.get(), (const float *)theta_i.data.get()}}); + + /* Construct Luminance warp data structure */ + brdf->luminance = + Warp2D2(alloc, (float *)luminance.data.get(), luminance.shape[3], + luminance.shape[2], {{(int)phi_i.shape[0], (int)theta_i.shape[0]}}, + {{(const float *)phi_i.data.get(), (const float *)theta_i.data.get()}}); + + /* Copy wavelength information */ + size_t size = wavelengths.shape[0]; + brdf->wavelengths.resize(size); + for (size_t i = 0; i < size; ++i) + brdf->wavelengths[i] = ((const float *)wavelengths.data.get())[i]; + + /* Construct spectral interpolant */ + brdf->spectra = + Warp2D3(alloc, (float *)spectra.data.get(), spectra.shape[4], spectra.shape[3], + {{(int)phi_i.shape[0], (int)theta_i.shape[0], (int)wavelengths.shape[0]}}, + {{(const float *)phi_i.data.get(), (const float *)theta_i.data.get(), + (const float *)wavelengths.data.get()}}, + false, false); + + measuredBRDFBytes += sizeof(MeasuredBRDF) + 4 * brdf->wavelengths.size() + + brdf->ndf.BytesUsed() + brdf->sigma.BytesUsed() + + brdf->vndf.BytesUsed() + brdf->luminance.BytesUsed() + + brdf->spectra.BytesUsed(); + + return brdf; +} + +MeasuredBRDF *MeasuredBxDF::BRDFDataFromFile(const std::string &filename, + Allocator alloc) { + static std::map loadedData; + if (loadedData.find(filename) == loadedData.end()) + loadedData[filename] = MeasuredBRDF::Create(filename, alloc); + return loadedData[filename]; +} + +// MeasuredBxDF Method Definitions +SampledSpectrum MeasuredBxDF::f(Vector3f wo, Vector3f wi, TransportMode mode) const { + if (!SameHemisphere(wo, wi)) + return SampledSpectrum(0.); + if (wo.z < 0) { + wo = -wo; + wi = -wi; + } + + Vector3f wm = wi + wo; + if (LengthSquared(wm) == 0) + return SampledSpectrum(0); + wm = Normalize(wm); + + /* Cartesian -> spherical coordinates */ + Float theta_i = SphericalTheta(wi), phi_i = std::atan2(wi.y, wi.x); + Float theta_m = SphericalTheta(wm), phi_m = std::atan2(wm.y, wm.x); + + /* Spherical coordinates -> unit coordinate system */ + Vector2f u_wi(theta2u(theta_i), phi2u(phi_i)); + Vector2f u_wm(theta2u(theta_m), phi2u(brdf->isotropic ? (phi_m - phi_i) : phi_m)); + u_wm.y = u_wm.y - std::floor(u_wm.y); + + Float params[2] = {phi_i, theta_i}; + auto ui = brdf->vndf.Invert(u_wm, params); + Vector2f sample = ui.p; + Float vndfPDF = ui.pdf; + + SampledSpectrum fr(0); + for (int i = 0; i < pbrt::NSpectrumSamples; ++i) { + Float params_fr[3] = {phi_i, theta_i, lambda[i]}; + fr[i] = brdf->spectra.Evaluate(sample, params_fr); + CHECK_RARE(1e-6, fr[i] < 0); + fr[i] = std::max(0, fr[i]); + } + + return fr * brdf->ndf.Evaluate(u_wm, params) / + (4 * brdf->sigma.Evaluate(u_wi, params) * AbsCosTheta(wi)); +} + +BSDFSample MeasuredBxDF::Sample_f(Vector3f wo, Float uc, const Point2f &u, + TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return {}; + + bool flipWi = false; + if (wo.z <= 0) { + wo = -wo; + flipWi = true; + } + + Float theta_i = SphericalTheta(wo), phi_i = std::atan2(wo.y, wo.x); + + Vector2f sample = Vector2f(u.y, u.x); + Float params[2] = {phi_i, theta_i}; + auto s = brdf->luminance.Sample(sample, params); + sample = s.p; + Float lumPDF = s.pdf; + + s = brdf->vndf.Sample(sample, params); + Vector2f u_wm = s.p; + Float ndfPDF = s.pdf; + + Float phi_m = u2phi(u_wm.y), theta_m = u2theta(u_wm.x); + if (brdf->isotropic) + phi_m += phi_i; + + /* Spherical -> Cartesian coordinates */ + Float sinTheta_m = std::sin(theta_m), cosTheta_m = std::cos(theta_m); + Vector3f wm = SphericalDirection(sinTheta_m, cosTheta_m, phi_m); + + Vector3f wi = Reflect(wo, wm); + if (wi.z <= 0) + return {}; + + SampledSpectrum fr(0); + for (int i = 0; i < pbrt::NSpectrumSamples; ++i) { + Float params_fr[3] = {phi_i, theta_i, lambda[i]}; + fr[i] = brdf->spectra.Evaluate(sample, params_fr); + CHECK_RARE(1e-6, fr[i] < 0); + fr[i] = std::max(0, fr[i]); + } + + Vector2f u_wo = Vector2f(theta2u(theta_i), phi2u(phi_i)); + fr *= brdf->ndf.Evaluate(u_wm, params) / + (4 * brdf->sigma.Evaluate(u_wo, params) * AbsCosTheta(wi)); + + Float jacobian = + 4 * Dot(wo, wm) * std::max(2 * Sqr(Pi) * u_wm.x * sinTheta_m, 1e-6f); + Float pdf = ndfPDF * lumPDF / jacobian; + + if (flipWi) + wi = -wi; + return BSDFSample(fr, wi, pdf, BxDFFlags::GlossyReflection); +} + +Float MeasuredBxDF::PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return 0; + if (!SameHemisphere(wo, wi)) + return 0; + if (wo.z < 0) { + wo = -wo; + wi = -wi; + } + + Vector3f wm = wi + wo; + if (LengthSquared(wm) == 0) + return 0; + wm = Normalize(wm); + + /* Cartesian -> spherical coordinates */ + Float theta_i = SphericalTheta(wi), phi_i = std::atan2(wi.y, wi.x); + Float theta_m = SphericalTheta(wm), phi_m = std::atan2(wm.y, wm.x); + + /* Spherical coordinates -> unit coordinate system */ + Vector2f u_wm(theta2u(theta_m), phi2u(brdf->isotropic ? (phi_m - phi_i) : phi_m)); + u_wm.y = u_wm.y - std::floor(u_wm.y); + + Float params[2] = {phi_i, theta_i}; + auto ui = brdf->vndf.Invert(u_wm, params); + Vector2f sample = ui.p; + Float vndfPDF = ui.pdf; + + Float pdf = brdf->luminance.Evaluate(sample, params); + Float sinTheta_m = std::sqrt(Sqr(wm.x) + Sqr(wm.y)); + Float jacobian = + 4.f * Dot(wi, wm) * std::max(2 * Sqr(Pi) * u_wm.x * sinTheta_m, 1e-6f); + return vndfPDF * pdf / jacobian; +} + +std::string MeasuredBxDF::ToString() const { + return StringPrintf("[ MeasuredBxDF brdf: %s ]", *brdf); +} + +std::string BSSRDFAdapter::ToString() const { + return StringPrintf("[ BSSRDFAdapter eta: %f ]", eta); +} + +// BxDFHandle Method Definitions +SampledSpectrum BxDFHandle::rho(Vector3f wo, pstd::span uc, + pstd::span u2) const { + if (wo.z == 0) + return SampledSpectrum(0.f); + SampledSpectrum r(0.); + DCHECK_EQ(uc.size(), u2.size()); + for (size_t i = 0; i < uc.size(); ++i) { + // Estimate one term of $\rho_\roman{hd}$ + auto bs = Sample_f(wo, uc[i], u2[i], TransportMode::Radiance); + if (bs) + r += bs.f * AbsCosTheta(bs.wi) / bs.pdf; + } + return r / uc.size(); +} + +SampledSpectrum BxDFHandle::rho(pstd::span uc1, pstd::span u1, + pstd::span uc2, + pstd::span u2) const { + DCHECK_EQ(uc1.size(), u1.size()); + DCHECK_EQ(uc2.size(), u2.size()); + DCHECK_EQ(u1.size(), u2.size()); + SampledSpectrum r(0.f); + for (size_t i = 0; i < uc1.size(); ++i) { + // Estimate one term of $\rho_\roman{hh}$ + Vector3f wo = SampleUniformHemisphere(u1[i]); + if (wo.z == 0) + continue; + Float pdfo = UniformHemispherePDF(); + auto bs = Sample_f(wo, uc2[i], u2[i], TransportMode::Radiance); + if (bs) + r += bs.f * AbsCosTheta(bs.wi) * AbsCosTheta(wo) / (pdfo * bs.pdf); + } + return r / (Pi * u1.size()); +} + +std::string BxDFHandle::ToString() const { + auto toStr = [](auto ptr) { return ptr->ToString(); }; + return DispatchCPU(toStr); +} + +template class LayeredBxDF; +template class LayeredBxDF; + +} // namespace pbrt diff --git a/src/pbrt/bxdfs.h b/src/pbrt/bxdfs.h new file mode 100644 index 00000000..994ed118 --- /dev/null +++ b/src/pbrt/bxdfs.h @@ -0,0 +1,1457 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_BXDFS_H +#define PBRT_BXDFS_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace pbrt { + +// IdealDiffuseBxDF Definition +class IdealDiffuseBxDF { + public: + // IdealDiffuseBxDF Public Methods + IdealDiffuseBxDF() = default; + PBRT_CPU_GPU + IdealDiffuseBxDF(const SampledSpectrum &R) : R(R) {} + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const { + if (!SameHemisphere(wo, wi)) + return SampledSpectrum(0.f); + return R * InvPi; + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return {}; + Vector3f wi = SampleCosineHemisphere(u); + if (wo.z < 0) + wi.z *= -1; + Float pdf = AbsCosTheta(wi) * InvPi; + return BSDFSample(f(wo, wi, mode), wi, pdf, BxDFFlags::DiffuseReflection); + } + + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return 0; + if (SameHemisphere(wo, wi)) + return AbsCosTheta(wi) * InvPi; + else + return 0; + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + static constexpr const char *Name() { return "IdealDiffuseBxDF"; } + + std::string ToString() const; + + PBRT_CPU_GPU + void Regularize() {} + + PBRT_CPU_GPU + BxDFFlags Flags() const { + return R ? BxDFFlags::DiffuseReflection : BxDFFlags::Unset; + } + + private: + friend class SOA; + SampledSpectrum R; +}; + +// DiffuseBxDF Definition +class DiffuseBxDF { + public: + // DiffuseBxDF Public Methods + DiffuseBxDF() = default; + PBRT_CPU_GPU + DiffuseBxDF(const SampledSpectrum &R, const SampledSpectrum &T, Float sigma) + : R(R), T(T) { + Float sigma2 = Sqr(Radians(sigma)); + A = 1 - sigma2 / (2 * (sigma2 + 0.33f)); + B = 0.45f * sigma2 / (sigma2 + 0.09f); + } + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const { + if (B == 0) + return SameHemisphere(wo, wi) ? (R * InvPi) : (T * InvPi); + + if ((SameHemisphere(wo, wi) && !R) || (!SameHemisphere(wo, wi) && !T)) + return SampledSpectrum(0.); + + Float sinTheta_i = SinTheta(wi), sinTheta_o = SinTheta(wo); + // Compute cosine term of Oren--Nayar model + Float maxCos = 0; + if (sinTheta_i > 0 && sinTheta_o > 0) + maxCos = std::max(0, CosDPhi(wi, wo)); + + // Compute sine and tangent terms of Oren--Nayar model + Float sinAlpha, tanBeta; + if (AbsCosTheta(wi) > AbsCosTheta(wo)) { + sinAlpha = sinTheta_o; + tanBeta = sinTheta_i / AbsCosTheta(wi); + } else { + sinAlpha = sinTheta_i; + tanBeta = sinTheta_o / AbsCosTheta(wo); + } + + if (SameHemisphere(wo, wi)) + return R * InvPi * (A + B * maxCos * sinAlpha * tanBeta); + else + return T * InvPi * (A + B * maxCos * sinAlpha * tanBeta); + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + Float pr = R.MaxComponentValue(), pt = T.MaxComponentValue(); + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + pr = 0; + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + pt = 0; + if (pr == 0 && pt == 0) + return {}; + + Float cpdf; + // TODO: rewrite to a single code path for the GPU. Good chance to + // discuss divergence. + if (SampleDiscrete({pr, pt}, uc, &cpdf) == 0) { + Vector3f wi = SampleCosineHemisphere(u); + if (wo.z < 0) + wi.z *= -1; + Float pdf = AbsCosTheta(wi) * InvPi * cpdf; + return BSDFSample(f(wo, wi, mode), wi, pdf, BxDFFlags::DiffuseReflection); + } else { + Vector3f wi = SampleCosineHemisphere(u); + if (wo.z > 0) + wi.z *= -1; + Float pdf = AbsCosTheta(wi) * InvPi * cpdf; + return BSDFSample(f(wo, wi, mode), wi, pdf, BxDFFlags::DiffuseTransmission); + } + } + + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + Float pr = R.MaxComponentValue(), pt = T.MaxComponentValue(); + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + pr = 0; + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + pt = 0; + if (pr == 0 && pt == 0) + return 0; + + if (SameHemisphere(wo, wi)) + return pr / (pr + pt) * AbsCosTheta(wi) * InvPi; + else + return pt / (pr + pt) * AbsCosTheta(wi) * InvPi; + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + static constexpr const char *Name() { return "DiffuseBxDF"; } + + std::string ToString() const; + + PBRT_CPU_GPU + void Regularize() {} + + PBRT_CPU_GPU + BxDFFlags Flags() const { + return ((R ? BxDFFlags::DiffuseReflection : BxDFFlags::Unset) | + (T ? BxDFFlags::DiffuseTransmission : BxDFFlags::Unset)); + } + + private: + friend class SOA; + // DiffuseBxDF Private Members + SampledSpectrum R, T; + Float A, B; +}; + +// DielectricInterfaceBxDF Definition +class DielectricInterfaceBxDF { + public: + // DielectricInterfaceBxDF Public Methods + DielectricInterfaceBxDF() = default; + PBRT_CPU_GPU + DielectricInterfaceBxDF(Float eta, const TrowbridgeReitzDistribution &mfDistrib) + : eta(eta == 1 ? 1.001 : eta), mfDistrib(mfDistrib) {} + + PBRT_CPU_GPU + BxDFFlags Flags() const { + return BxDFFlags(BxDFFlags::Reflection | BxDFFlags::Transmission | + BxDFFlags(mfDistrib.EffectivelySpecular() ? BxDFFlags::Specular + : BxDFFlags::Glossy)); + } + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const { + if (mfDistrib.EffectivelySpecular()) + return SampledSpectrum(0); + if (SameHemisphere(wo, wi)) { + // Compute reflection at non-delta dielectric interface + Float cosTheta_o = AbsCosTheta(wo), cosTheta_i = AbsCosTheta(wi); + Vector3f wh = wi + wo; + // Handle degenerate cases for microfacet reflection + if (cosTheta_i == 0 || cosTheta_o == 0) + return SampledSpectrum(0.); + if (wh.x == 0 && wh.y == 0 && wh.z == 0) + return SampledSpectrum(0.); + wh = Normalize(wh); + Float F = FrDielectric(Dot(wi, FaceForward(wh, Vector3f(0, 0, 1))), eta); + return SampledSpectrum(mfDistrib.D(wh) * mfDistrib.G(wo, wi) * F / + (4 * cosTheta_i * cosTheta_o)); + + } else { + // Compute transmission at non-delta dielectric interface + Float cosTheta_o = CosTheta(wo), cosTheta_i = CosTheta(wi); + if (cosTheta_i == 0 || cosTheta_o == 0) + return {}; + // Compute $\wh$ from $\wo$ and $\wi$ for microfacet transmission + Float etap = CosTheta(wo) > 0 ? eta : (1 / eta); + Vector3f wh = wo + wi * etap; + CHECK_RARE(1e-6, LengthSquared(wh) == 0); + if (LengthSquared(wh) == 0) + return {}; + wh = FaceForward(Normalize(wh), Normal3f(0, 0, 1)); + + // both on same side? + if (Dot(wi, wh) * Dot(wo, wh) > 0) + return {}; + + Float F = FrDielectric(Dot(wo, wh), eta); + Float sqrtDenom = Dot(wo, wh) + etap * Dot(wi, wh); + Float factor = (mode == TransportMode::Radiance) ? Sqr(1 / etap) : 1; + return SampledSpectrum((1 - F) * factor * + std::abs(mfDistrib.D(wh) * mfDistrib.G(wo, wi) * + AbsDot(wi, wh) * AbsDot(wo, wh) / + (cosTheta_i * cosTheta_o * Sqr(sqrtDenom)))); + } + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + if (wo.z == 0) + return {}; + + if (mfDistrib.EffectivelySpecular()) { + // Sample delta dielectric interface + Float R = FrDielectric(CosTheta(wo), eta), T = 1 - R; + // Compute probabilities _pr_ and _pt_ for sampling reflection and + // transmission + Float pr = R, pt = T; + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + pr = 0; + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + pt = 0; + if (pr == 0 && pt == 0) + return {}; + + if (uc < pr / (pr + pt)) { + // Sample perfect specular reflection at interface + Vector3f wi(-wo.x, -wo.y, wo.z); + SampledSpectrum fr(R / AbsCosTheta(wi)); + return BSDFSample(fr, wi, pr / (pr + pt), BxDFFlags::SpecularReflection); + + } else { + // Sample perfect specular transmission at interface + // Figure out which $\eta$ is incident and which is transmitted + bool entering = CosTheta(wo) > 0; + Float etap = entering ? eta : (1 / eta); + + // Compute ray direction for specular transmission + Vector3f wi; + bool tir = !Refract(wo, FaceForward(Normal3f(0, 0, 1), wo), etap, &wi); + CHECK_RARE(1e-6, tir); + if (tir) + return {}; + + SampledSpectrum ft(T / AbsCosTheta(wi)); + // Account for non-symmetry with transmission to different medium + if (mode == TransportMode::Radiance) + ft /= Sqr(etap); + + return BSDFSample(ft, wi, pt / (pr + pt), + BxDFFlags::SpecularTransmission); + } + + } else { + // Sample non-delta dielectric interface + // Sample half-angle vector for outgoing direction and compute Frensel factor + Vector3f wh = mfDistrib.Sample_wm(wo, u); + Float F = FrDielectric( + Dot(Reflect(wo, wh), FaceForward(wh, Vector3f(0, 0, 1))), eta); + Float R = F, T = 1 - R; + + // Compute probabilities _pr_ and _pt_ for sampling reflection and + // transmission + Float pr = R, pt = T; + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + pr = 0; + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + pt = 0; + if (pr == 0 && pt == 0) + return {}; + + if (uc < pr / (pr + pt)) { + // Sample reflection at non-delta dielectric interface + Vector3f wi = Reflect(wo, wh); + CHECK_RARE(1e-6, Dot(wo, wh) <= 0); + if (!SameHemisphere(wo, wi) || Dot(wo, wh) <= 0) + return {}; + + // Compute PDF of _wi_ for microfacet reflection + Float pdf = mfDistrib.PDF(wo, wh) / (4 * Dot(wo, wh)) * pr / (pr + pt); + CHECK(!std::isnan(pdf)); + + // TODO: reuse fragments from f() + Float cosTheta_o = AbsCosTheta(wo), cosTheta_i = AbsCosTheta(wi); + // Handle degenerate cases for microfacet reflection + if (cosTheta_i == 0 || cosTheta_o == 0) + return {}; + SampledSpectrum f(mfDistrib.D(wh) * mfDistrib.G(wo, wi) * F / + (4 * cosTheta_i * cosTheta_o)); + if (mfDistrib.EffectivelySpecular()) + return BSDFSample(f / pdf, wi, 1, BxDFFlags::SpecularReflection); + else + return BSDFSample(f, wi, pdf, BxDFFlags::GlossyReflection); + + } else { + // Sample transmission at non-delta dielectric interface + // FIXME (make consistent): this etap is 1/etap as used in + // specular... + Float etap = CosTheta(wo) > 0 ? eta : (1 / eta); + Vector3f wi; + bool tir = !Refract(wo, (Normal3f)wh, etap, &wi); + CHECK_RARE(1e-6, tir); + if (SameHemisphere(wo, wi)) + return {}; + if (tir || wi.z == 0) + return {}; + + // Evaluate BSDF + // TODO: share fragments with f(), PDF()... + wh = FaceForward(wh, Normal3f(0, 0, 1)); + + Float sqrtDenom = Dot(wo, wh) + etap * Dot(wi, wh); + Float factor = (mode == TransportMode::Radiance) ? Sqr(1 / etap) : 1; + + SampledSpectrum f( + (1 - F) * factor * + std::abs(mfDistrib.D(wh) * mfDistrib.G(wo, wi) * AbsDot(wi, wh) * + AbsDot(wo, wh) / + (AbsCosTheta(wi) * AbsCosTheta(wo) * Sqr(sqrtDenom)))); + + // Compute PDF + Float dwh_dwi = + /*Sqr(etap) * */ AbsDot(wi, wh) / + Sqr(Dot(wo, wh) + etap * Dot(wi, wh)); + Float pdf = mfDistrib.PDF(wo, wh) * dwh_dwi * pt / (pr + pt); + CHECK(!std::isnan(pdf)); + + if (mfDistrib.EffectivelySpecular()) + return BSDFSample(f / pdf, wi, 1, BxDFFlags::SpecularTransmission); + else + return BSDFSample(f, wi, pdf, BxDFFlags::GlossyTransmission); + } + } + } + + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + if (mfDistrib.EffectivelySpecular()) + return 0; + // Return PDF for non-delta dielectric interface + if (SameHemisphere(wo, wi)) { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return 0; + + Vector3f wh = wo + wi; + CHECK_RARE(1e-6, LengthSquared(wh) == 0); + CHECK_RARE(1e-6, Dot(wo, wh) < 0); + if (LengthSquared(wh) == 0 || Dot(wo, wh) <= 0) + return 0; + + wh = Normalize(wh); + + Float F = FrDielectric(Dot(wi, FaceForward(wh, Vector3f(0, 0, 1))), eta); + CHECK_RARE(1e-6, F == 0); + Float pr = F, pt = 1 - F; + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + pt = 0; + + return mfDistrib.PDF(wo, wh) / (4 * Dot(wo, wh)) * pr / (pr + pt); + } else { + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + return 0; + // Compute $\wh$ from $\wo$ and $\wi$ for microfacet transmission + Float etap = CosTheta(wo) > 0 ? eta : (1 / eta); + Vector3f wh = wo + wi * etap; + CHECK_RARE(1e-6, LengthSquared(wh) == 0); + if (LengthSquared(wh) == 0) + return 0; + wh = Normalize(wh); + + // both on same side? + if (Dot(wi, wh) * Dot(wo, wh) > 0) + return 0.; + + Float F = FrDielectric(Dot(wo, FaceForward(wh, Normal3f(0, 0, 1))), eta); + Float pr = F, pt = 1 - F; + if (pt == 0) + return 0; + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + pr = 0; + + // Compute change of variables _dwh\_dwi_ for microfacet + // transmission + Float dwh_dwi = + /*Sqr(etap) * */ AbsDot(wi, wh) / Sqr(Dot(wo, wh) + etap * Dot(wi, wh)); + CHECK_RARE(1e-6, (1 - F) == 0); + return mfDistrib.PDF(wo, wh) * dwh_dwi * pt / (pr + pt); + } + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + static constexpr const char *Name() { return "DielectricInterfaceBxDF"; } + + std::string ToString() const; + + PBRT_CPU_GPU + void Regularize() { mfDistrib.Regularize(); } + + private: + friend class SOA; + // DielectricInterfaceBxDF Private Members + Float eta; + TrowbridgeReitzDistribution mfDistrib; +}; + +// ThinDielectricBxDF Definition +class ThinDielectricBxDF { + public: + // ThinDielectric Public Methods + ThinDielectricBxDF() = default; + PBRT_CPU_GPU + ThinDielectricBxDF(Float eta) : eta(eta) {} + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const { + return SampledSpectrum(0); + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + Float R = FrDielectric(CosTheta(wo), eta), T = 1 - R; + // Compute _R_ and _T_ accounting for scattering between interfaces + if (R < 1) { + R += T * T * R / (1 - R * R); + T = 1 - R; + } + + // Compute probabilities _pr_ and _pt_ for sampling reflection and transmission + Float pr = R, pt = T; + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + pr = 0; + if (!(sampleFlags & BxDFReflTransFlags::Transmission)) + pt = 0; + if (pr == 0 && pt == 0) + return {}; + + if (uc < pr / (pr + pt)) { + // Sample perfect specular reflection at interface + Vector3f wi(-wo.x, -wo.y, wo.z); + SampledSpectrum fr(R / AbsCosTheta(wi)); + return BSDFSample(fr, wi, pr / (pr + pt), BxDFFlags::SpecularReflection); + + } else { + // Sample perfect specular transmission at thin dielectric interface + Vector3f wi = -wo; + SampledSpectrum ft(T / AbsCosTheta(wi)); + return BSDFSample(ft, wi, pt / (pr + pt), BxDFFlags::SpecularTransmission); + } + } + + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + return 0; + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + static constexpr const char *Name() { return "ThinDielectricBxDF"; } + + std::string ToString() const; + + PBRT_CPU_GPU + void Regularize() { /* TODO */ + } + + PBRT_CPU_GPU + BxDFFlags Flags() const { + return (BxDFFlags::Reflection | BxDFFlags::Transmission | BxDFFlags::Specular); + } + + private: + friend class SOA; + Float eta; +}; + +// ConductorBxDF Definition +class ConductorBxDF { + public: + // ConductorBxDF Public Methods + ConductorBxDF() = default; + PBRT_CPU_GPU + ConductorBxDF(const TrowbridgeReitzDistribution &mfDistrib, + const SampledSpectrum &eta, const SampledSpectrum &k) + : mfDistrib(mfDistrib), eta(eta), k(k) {} + + PBRT_CPU_GPU + BxDFFlags Flags() const { + if (mfDistrib.EffectivelySpecular()) + return (BxDFFlags::Reflection | BxDFFlags::Specular); + else + return (BxDFFlags::Reflection | BxDFFlags::Glossy); + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + static constexpr const char *Name() { return "ConductorBxDF"; } + std::string ToString() const; + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const { + if (!SameHemisphere(wo, wi)) + return {}; + if (mfDistrib.EffectivelySpecular()) + return {}; + Float cosTheta_o = AbsCosTheta(wo), cosTheta_i = AbsCosTheta(wi); + Vector3f wh = wi + wo; + // Handle degenerate cases for microfacet reflection + if (cosTheta_i == 0 || cosTheta_o == 0) + return {}; + if (wh.x == 0 && wh.y == 0 && wh.z == 0) + return {}; + + wh = Normalize(wh); + Float frCosTheta_i = AbsDot(wi, FaceForward(wh, Vector3f(0, 0, 1))); + SampledSpectrum F = FrConductor(frCosTheta_i, eta, k); + return mfDistrib.D(wh) * mfDistrib.G(wo, wi) * F / (4 * cosTheta_i * cosTheta_o); + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return {}; + if (mfDistrib.EffectivelySpecular()) { + // Compute perfect specular reflection direction + Vector3f wi(-wo.x, -wo.y, wo.z); + + SampledSpectrum f = FrConductor(AbsCosTheta(wi), eta, k) / AbsCosTheta(wi); + return BSDFSample(f, wi, 1, BxDFFlags::SpecularReflection); + } + + // Sample microfacet orientation $\wh$ and reflected direction $\wi$ + if (wo.z == 0) + return {}; + Vector3f wh = mfDistrib.Sample_wm(wo, u); + Vector3f wi = Reflect(wo, wh); + CHECK_RARE(1e-6, Dot(wo, wh) <= 0); + if (!SameHemisphere(wo, wi) || Dot(wo, wh) <= 0) + return {}; + + // Compute PDF of _wi_ for microfacet reflection + Float pdf = mfDistrib.PDF(wo, wh) / (4 * Dot(wo, wh)); + + // TODO: reuse fragments from f() + Float cosTheta_o = AbsCosTheta(wo), cosTheta_i = AbsCosTheta(wi); + // Handle degenerate cases for microfacet reflection + if (cosTheta_i == 0 || cosTheta_o == 0) + return {}; + Float frCosTheta_i = AbsDot(wi, FaceForward(wh, Vector3f(0, 0, 1))); + SampledSpectrum F = FrConductor(frCosTheta_i, eta, k); + SampledSpectrum f = + mfDistrib.D(wh) * mfDistrib.G(wo, wi) * F / (4 * cosTheta_i * cosTheta_o); + return BSDFSample(f, wi, pdf, BxDFFlags::GlossyReflection); + } + + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return 0; + if (!SameHemisphere(wo, wi)) + return 0; + if (mfDistrib.EffectivelySpecular()) + return 0; + Vector3f wh = wo + wi; + CHECK_RARE(1e-6, LengthSquared(wh) == 0); + CHECK_RARE(1e-6, Dot(wo, wh) < 0); + if (LengthSquared(wh) == 0 || Dot(wo, wh) <= 0) + return 0; + wh = Normalize(wh); + return mfDistrib.PDF(wo, wh) / (4 * Dot(wo, wh)); + } + + PBRT_CPU_GPU + void Regularize() { mfDistrib.Regularize(); } + + private: + friend class SOA; + // ConductorBxDF Private Members + TrowbridgeReitzDistribution mfDistrib; + SampledSpectrum eta, k; +}; + +// LayeredBxDFConfig Definition +struct LayeredBxDFConfig { + uint8_t maxDepth = 10; + uint8_t nSamples = 1; + uint8_t twoSided = true; +}; + +// TopOrBottomBxDF Definition +template +class TopOrBottomBxDF { + public: + // TopOrBottomBxDF Public Methods + TopOrBottomBxDF() = default; + PBRT_CPU_GPU + TopOrBottomBxDF &operator=(const TopBxDF *t) { + top = t; + bottom = nullptr; + return *this; + } + PBRT_CPU_GPU + TopOrBottomBxDF &operator=(const BottomBxDF *b) { + bottom = b; + top = nullptr; + return *this; + } + + PBRT_CPU_GPU + SampledSpectrum f(const Vector3f &wo, const Vector3f &wi, TransportMode mode) const { + return top ? top->f(wo, wi, mode) : bottom->f(wo, wi, mode); + } + + PBRT_CPU_GPU + BSDFSample Sample_f(const Vector3f &wo, Float uc, const Point2f &u, + TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + return top ? top->Sample_f(wo, uc, u, mode, sampleFlags) + : bottom->Sample_f(wo, uc, u, mode, sampleFlags); + } + + PBRT_CPU_GPU + Float PDF(const Vector3f &wo, const Vector3f &wi, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + return top ? top->PDF(wo, wi, mode, sampleFlags) + : bottom->PDF(wo, wi, mode, sampleFlags); + } + + PBRT_CPU_GPU + BxDFFlags Flags() const { return top ? top->Flags() : bottom->Flags(); } + + private: + const TopBxDF *top = nullptr; + const BottomBxDF *bottom = nullptr; +}; + +// LayeredBxDF Definition +template +class LayeredBxDF { + public: + // LayeredBxDF Public Methods + LayeredBxDF() = default; + PBRT_CPU_GPU + LayeredBxDF(TopBxDF top, BottomBxDF bottom, Float thickness, + const SampledSpectrum &albedo, Float g, LayeredBxDFConfig config) + : top(top), + bottom(bottom), + thickness(std::max(thickness, std::numeric_limits::min())), + g(g), + albedo(albedo), + config(config) {} + + std::string ToString() const; + + PBRT_CPU_GPU + void Regularize() { + top.Regularize(); + bottom.Regularize(); + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return true; } + + PBRT_CPU_GPU + BxDFFlags Flags() const { + BxDFFlags topFlags = top.Flags(), bottomFlags = bottom.Flags(); + CHECK(IsTransmissive(topFlags) || + IsTransmissive(bottomFlags)); // otherwise, why bother? + + BxDFFlags flags = BxDFFlags::Reflection; + if (IsSpecular(topFlags)) + flags = flags | BxDFFlags::Specular; + + if (IsDiffuse(topFlags) || IsDiffuse(bottomFlags) || albedo) + flags = flags | BxDFFlags::Diffuse; + else if (IsGlossy(topFlags) || IsGlossy(bottomFlags)) + flags = flags | BxDFFlags::Glossy; + + if (IsTransmissive(topFlags) && IsTransmissive(bottomFlags)) + flags = flags | BxDFFlags::Transmission; + + return flags; + } + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const { + SampledSpectrum f(0.); + // Set _wi_ and _wi_ for layered BSDF evaluation + if (config.twoSided && wo.z < 0) { + // BIG WIN + wo = -wo; + wi = -wi; + } + + // Determine entrance and exit interfaces for layered BSDF + bool enteredTop = wo.z > 0; + TopOrBottomBxDF enterInterface, exitInterface; + TopOrBottomBxDF nonExitInterface; + if (enteredTop) + enterInterface = ⊤ + else + enterInterface = ⊥ + if (SameHemisphere(wo, wi) ^ enteredTop) { + exitInterface = ⊥ + nonExitInterface = ⊤ + } else { + exitInterface = ⊤ + nonExitInterface = ⊥ + } + Float exitZ = (SameHemisphere(wo, wi) ^ enteredTop) ? 0 : thickness; + + // Account for reflection at the entrance interface + if (SameHemisphere(wo, wi)) + f = config.nSamples * enterInterface.f(wo, wi, mode); + + // Declare _RNG_ for layered BSDF evaluation + RNG rng(Hash(GetOptions().seed, wo), Hash(wi)); + auto r = [&rng]() { + return std::min(rng.Uniform(), OneMinusEpsilon); + }; + + for (int s = 0; s < config.nSamples; ++s) { + // Sample random walk through layers to estimate BSDF value + // Sample transmission direction through entrance interface + Float uc = r(); + Point2f u(r(), r()); + BSDFSample wos = enterInterface.Sample_f(wo, uc, u, mode, + BxDFReflTransFlags::Transmission); + if (!wos || wos.wi.z == 0) + continue; + + // Sample BSDF for NEE in _wi_'s direction + uc = r(); + u = Point2f(r(), r()); + BSDFSample wis = exitInterface.Sample_f(wi, uc, u, ~mode, + BxDFReflTransFlags::Transmission); + if (!wis || wis.wi.z == 0) + continue; + + // Declare state for random walk through BSDF layers + SampledSpectrum beta = wos.f * AbsCosTheta(wos.wi) / wos.pdf; + SampledSpectrum betaExit = wis.f / wis.pdf; + Vector3f w = wos.wi; + Float z = enteredTop ? thickness : 0; + HGPhaseFunction phase(g); + + for (int depth = 0; depth < config.maxDepth; ++depth) { + // Sample next event for layered BSDF evaluation random walk + VLOG(2, "beta: %s, w: %s, f: %s", beta, w, f); + // Possibly terminate layered BSDF random walk with Russian Roulette + if (depth > 3 && beta.MaxComponentValue() < .25) { + Float q = std::max(0, 1 - beta.MaxComponentValue()); + if (r() < q) + break; + beta /= 1 - q; + VLOG(2, "After RR with q = %f, beta: %s", q, beta); + } + + if (SupportAttenuation && albedo) { + // Sample medium scattering for layered BSDF evaluation + Float sigma_t = 1; + Float dz = SampleExponential(r(), sigma_t / AbsCosTheta(w)); + Float zp = w.z > 0 ? (z + dz) : (z - dz); + CHECK_RARE(1e-5, z == zp); + if (z == zp) + continue; + if (0 < zp && zp < thickness) { + // Handle scattering event in layered BSDF medium +#if 0 +// TODO: cancel out and simplify: should be +// f *= AbsCosTheta(w) / sigma_t (!!!) -- that in turn makes the tricky cosine stuff +// more reasonable / palatible... +//beta *= Tr(dz, w) / ExponentialPDF(dz, sigma_t / AbsCosTheta(w)); +beta *= AbsCosTheta(w) / sigma_t; +// Tricky cosines. Always divide here since we always +// include it when we leave a surface. +beta /= AbsCosTheta(w); +#endif + // Account for scattering through _exitInterface_ using _wis_ + Float wt = 1; + if (!IsSpecular(exitInterface.Flags())) + wt = PowerHeuristic(1, wis.pdf, 1, phase.PDF(-w, -wis.wi)); + Float te = Tr(zp - exitZ, wis.wi); + f += beta * albedo * phase.p(-w, -wis.wi) * wt * te * betaExit; + + // Sample phase function and update layered path state + PhaseFunctionSample ps = phase.Sample_p(-w, Point2f(r(), r())); + if (!ps || ps.wi.z == 0) + continue; + beta *= albedo * ps.p / ps.pdf; + w = ps.wi; + z = zp; + + if (!IsSpecular(exitInterface.Flags())) { + // Account for scattering through _exitInterface_ from new _w_ + SampledSpectrum fExit = exitInterface.f(-w, wi, mode); + if (fExit) { + Float exitPDF = exitInterface.PDF( + -w, wi, mode, BxDFReflTransFlags::Transmission); + Float weight = PowerHeuristic(1, ps.pdf, 1, exitPDF); + f += beta * Tr(zp - exitZ, ps.wi) * fExit * weight; + } + } + + continue; + } + z = Clamp(zp, 0, thickness); + + } else { + // Advance to next layer boundary and update _beta_ for transmittance + z = (z == thickness) ? 0 : thickness; + beta *= Tr(thickness, w); + } + if (z == exitZ) { + // Account for reflection at _exitInterface_ + Float uc = r(); + Point2f u(r(), r()); + BSDFSample bs = exitInterface.Sample_f( + -w, uc, u, mode, BxDFReflTransFlags::Reflection); + if (!bs || bs.pdf == 0 || bs.wi.z == 0) + break; + beta *= bs.f * AbsCosTheta(bs.wi) / bs.pdf; + w = bs.wi; + + } else { + // Account for scattering at _nonExitInterface_ + if (!IsSpecular(nonExitInterface.Flags())) { + // Add NEE contribution along pre-sampled _wis_ direction + Float wt = 1; + if (!IsSpecular(exitInterface.Flags())) + wt = PowerHeuristic(1, wis.pdf, 1, + nonExitInterface.PDF(-w, -wis.wi, mode)); + f += beta * nonExitInterface.f(-w, -wis.wi, mode) * + AbsCosTheta(wis.wi) * wt * Tr(thickness, wis.wi) * betaExit; + } + // Sample new direction using BSDF at _nonExitInterface_ + Float uc = r(); + Point2f u(r(), r()); + BSDFSample bs = nonExitInterface.Sample_f( + -w, uc, u, mode, BxDFReflTransFlags::Reflection); + if (!bs || bs.wi.z == 0) + break; + beta *= bs.f * AbsCosTheta(bs.wi) / bs.pdf; + w = bs.wi; + + if (!IsSpecular(exitInterface.Flags())) { + // Add NEE contribution along direction from BSDF sample + SampledSpectrum fExit = exitInterface.f(-w, wi, mode); + if (fExit) { + Float wt = 1; + if (!IsSpecular(nonExitInterface.Flags())) { + Float exitPDF = exitInterface.PDF( + -w, wi, mode, BxDFReflTransFlags::Transmission); + wt = PowerHeuristic(1, bs.pdf, 1, exitPDF); + } + f += beta * Tr(thickness, bs.wi) * fExit * wt; + } + } + } + } + } + return f / config.nSamples; + } + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + CHECK(sampleFlags == BxDFReflTransFlags::All); // for now + // Set _wo_ for layered BSDF sampling + bool flipWi = false; + if (config.twoSided && wo.z < 0) { + wo = -wo; + flipWi = true; + } + + // Sample BSDF at entrance interface to get initial direction _w_ + bool enteredTop = wo.z > 0; + BSDFSample bs = + enteredTop ? top.Sample_f(wo, uc, u, mode) : bottom.Sample_f(wo, uc, u, mode); + if (!bs) + return {}; + if (bs.IsReflection()) { + if (flipWi) + bs.wi = -bs.wi; + return bs; + } + Vector3f w = bs.wi; + + // Declare _RNG_ for layered BSDF sampling + RNG rng(Hash(GetOptions().seed, wo), Hash(uc, u)); + auto r = [&rng]() { + return std::min(rng.Uniform(), OneMinusEpsilon); + }; + + // Declare common variables for layered BSDF sampling + SampledSpectrum f = bs.f * AbsCosTheta(bs.wi); + Float pdf = bs.pdf; + Float z = enteredTop ? thickness : 0; + HGPhaseFunction phase(g); + + for (int depth = 0; depth < config.maxDepth; ++depth) { + // Follow random walk through layeres to sample layered BSDF + // Possibly terminate layered BSDF sampling with Russian Roulette + Float rrBeta = f.MaxComponentValue() / pdf; + if (depth > 3 && rrBeta < 0.25) { + Float q = std::max(0, 1 - rrBeta); + if (r() < q) + return {}; + pdf *= 1 - q; + } + if (w.z == 0) + return {}; + + if (SupportAttenuation && albedo) { + // Sample potential scattering event in layered medium + Float sigma_t = 1; + Float dz = SampleExponential(r(), sigma_t / AbsCosTheta(w)); + Float zp = w.z > 0 ? (z + dz) : (z - dz); + CHECK_RARE(1e-5, zp == z); + if (zp == z) + return {}; + if (0 < zp && zp < thickness) { + // Update path state for valid scattering event between interfaces +#if 0 +// TODO: cancel out and simplify: should be +// f *= AbsCosTheta(w) / sigma_t (!!!) -- that in turn makes the tricky cosine stuff +// more reasonable / palatible... +//f *= Tr(dz, w) / ExponentialPDF(dz, sigma_t / AbsCosTheta(w)); +f *= AbsCosTheta(w) / sigma_t; +// Tricky cosines. Always divide here since we always +// include it when we leave a surface. +f /= AbsCosTheta(w); +#endif + PhaseFunctionSample ps = phase.Sample_p(-w, Point2f(r(), r())); + if (!ps || ps.wi.z == 0) + return {}; + f *= albedo * ps.p; + pdf *= ps.pdf; + w = ps.wi; + z = zp; + + continue; + } + z = Clamp(zp, 0, thickness); + if (z == 0) + DCHECK_LT(w.z, 0); + else + DCHECK_GT(w.z, 0); + + } else { + // Advance to the other layer interface + // Bounce back and forth between the top and bottom + z = (z == thickness) ? 0 : thickness; + f *= Tr(thickness, w); + } + // Initialize _interface_ for current interface surface + TopOrBottomBxDF interface; + if (z == 0) + interface = ⊥ + else + interface = ⊤ + + // Sample interface BSDF to determine new path direction + Float uc = r(); + Point2f u(r(), r()); + BSDFSample bs = interface.Sample_f(-w, uc, u, mode); + if (!bs || bs.wi.z == 0) + return {}; + f *= bs.f; + pdf *= bs.pdf; + w = bs.wi; + + // Return _BSDFSample_ if path has left the layers + if (bs.IsTransmission()) { + BxDFFlags flags = SameHemisphere(wo, w) ? BxDFFlags::GlossyReflection + : BxDFFlags::GlossyTransmission; + if (flipWi) + w = -w; + return BSDFSample(f, w, pdf, flags); + } + + // Scale _f_ by cosine term after scattering at the interface + f *= AbsCosTheta(bs.wi); + } + return {}; + } + + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags = BxDFReflTransFlags::All) const { + CHECK(sampleFlags == BxDFReflTransFlags::All); // for now + // Set _wi_ and _wi_ for layered BSDF evaluation + if (config.twoSided && wo.z < 0) { + // BIG WIN + wo = -wo; + wi = -wi; + } + + // Declare _RNG_ for layered BSDF evaluation + RNG rng(Hash(GetOptions().seed, wo), Hash(wi)); + auto r = [&rng]() { + return std::min(rng.Uniform(), OneMinusEpsilon); + }; + + bool enteredTop = wo.z > 0; + Float pdfSum = 0; + // Update _pdfSum_ for reflection at the entrance layer + if (SameHemisphere(wo, wi)) { + if (enteredTop) + pdfSum += config.nSamples * + top.PDF(wo, wi, mode, BxDFReflTransFlags::Reflection); + else + pdfSum += config.nSamples * + bottom.PDF(wo, wi, mode, BxDFReflTransFlags::Reflection); + } + + for (int s = 0; s < config.nSamples; ++s) { + // Evaluate layered BSDF PDF sample + if (SameHemisphere(wo, wi)) { + // Evaluate TRT term for PDF estimate + TopOrBottomBxDF rInterface, tInterface; + if (enteredTop) { + rInterface = ⊥ + tInterface = ⊤ + } else { + rInterface = ⊤ + tInterface = ⊥ + } + // Sample _tInterface_ to get direction into the layers + Float uc = r(); + Point2f u(r(), r()); + BSDFSample wos = tInterface.Sample_f(wo, uc, u, mode); + + // Update _pdfSum_ accounting for TRT scattering events + if (!wos || wos.wi.z == 0 || wos.IsReflection()) { + pdfSum += tInterface.PDF(wo, wi, mode); + } else { + uc = r(); + u = Point2f(r(), r()); + BSDFSample wis = tInterface.Sample_f(wi, uc, u, ~mode); + if (!wis || wis.wi.z == 0 || wis.IsReflection()) + continue; + // if (IsSpecular(tInterface.Flags())) + pdfSum += rInterface.PDF(-wos.wi, -wis.wi, mode); + } + + } else { + // Evaluate TT term for PDF estimate + TopOrBottomBxDF toInterface, tiInterface; + if (enteredTop) { + toInterface = ⊤ + tiInterface = ⊥ + } else { + toInterface = ⊥ + tiInterface = ⊤ + } + + Float uc = r(); + Point2f u(r(), r()); + BSDFSample wos = toInterface.Sample_f(wo, uc, u, mode); + if (!wos || wos.wi.z == 0 || wos.IsReflection()) + continue; + + uc = r(); + u = Point2f(r(), r()); + BSDFSample wis = tiInterface.Sample_f(wi, uc, u, ~mode); + if (!wis || wis.wi.z == 0 || wis.IsReflection()) + continue; + + if (IsSpecular(toInterface.Flags())) + pdfSum += tiInterface.PDF(-wos.wi, wi, mode); + else if (IsSpecular(tiInterface.Flags())) + pdfSum += toInterface.PDF(wo, -wis.wi, mode); + else + pdfSum += (toInterface.PDF(wo, -wis.wi, mode) + + tiInterface.PDF(-wos.wi, wi, mode)) / + 2; + } + } + // Return mixture of PDF estimate and constant PDF + return Lerp(.9, 1 / (4 * Pi), pdfSum / config.nSamples); + } + + protected: + // LayeredBxDF Protected Methods + PBRT_CPU_GPU + static Float Tr(Float dz, const Vector3f &w) { + if (std::abs(dz) <= std::numeric_limits::min()) + return 1; + return std::exp(-std::abs(dz) / AbsCosTheta(w)); + } + + // LayeredBxDF Protected Members + TopBxDF top; + BottomBxDF bottom; + Float thickness, g; + SampledSpectrum albedo; + LayeredBxDFConfig config; +}; + +// CoatedDiffuseBxDF Definition +class CoatedDiffuseBxDF + : public LayeredBxDF { + public: + // CoatedDiffuseBxDF Public Methods + using LayeredBxDF::LayeredBxDF; + PBRT_CPU_GPU + static constexpr const char *Name() { return "CoatedDiffuseBxDF"; } + + friend class SOA; +}; + +// CoatedConductorBxDF Definition +class CoatedConductorBxDF + : public LayeredBxDF { + public: + // CoatedConductorBxDF Public Methods + PBRT_CPU_GPU + static constexpr const char *Name() { return "CoatedConductorBxDF"; } + using LayeredBxDF::LayeredBxDF; + + friend class SOA; +}; + +// HairBxDF Definition +class HairBxDF { + public: + // HairBSDF Public Methods + HairBxDF() = default; + PBRT_CPU_GPU + HairBxDF(Float h, Float eta, const SampledSpectrum &sigma_a, Float beta_m, + Float beta_n, Float alpha); + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const; + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags) const; + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const; + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + void Regularize() {} + + PBRT_CPU_GPU + static constexpr const char *Name() { return "HairBxDF"; } + std::string ToString() const; + + PBRT_CPU_GPU + BxDFFlags Flags() const { return BxDFFlags::GlossyReflection; } + + PBRT_CPU_GPU + static RGBSpectrum SigmaAFromConcentration(Float ce, Float cp); + PBRT_CPU_GPU + static SampledSpectrum SigmaAFromReflectance(const SampledSpectrum &c, Float beta_n, + const SampledWavelengths &lambda); + + private: + friend class SOA; + // HairBSDF Constants + static constexpr int pMax = 3; + + // HairBSDF Private Methods + PBRT_CPU_GPU + static Float Mp(Float cosTheta_i, Float cosTheta_o, Float sinTheta_i, + Float sinTheta_o, Float v) { + Float a = cosTheta_i * cosTheta_o / v; + Float b = sinTheta_i * sinTheta_o / v; + Float mp = + (v <= .1) ? (std::exp(LogI0(a) - b - 1 / v + 0.6931f + std::log(1 / (2 * v)))) + : (std::exp(-b) * I0(a)) / (std::sinh(1 / v) * 2 * v); + CHECK(!std::isinf(mp) && !std::isnan(mp)); + return mp; + } + + PBRT_CPU_GPU + static pstd::array Ap(Float cosTheta_o, Float eta, Float h, + const SampledSpectrum &T) { + pstd::array ap; + // Compute $p=0$ attenuation at initial cylinder intersection + Float cosGamma_o = SafeSqrt(1 - h * h); + Float cosTheta = cosTheta_o * cosGamma_o; + Float f = FrDielectric(cosTheta, eta); + ap[0] = SampledSpectrum(f); + + // Compute $p=1$ attenuation term + ap[1] = Sqr(1 - f) * T; + + // Compute attenuation terms up to $p=_pMax_$ + for (int p = 2; p < pMax; ++p) + ap[p] = ap[p - 1] * T * f; + + // Compute attenuation term accounting for remaining orders of scattering + if (1.f - T * f) + ap[pMax] = ap[pMax - 1] * f * T / (1.f - T * f); + + return ap; + } + + PBRT_CPU_GPU + static inline Float Phi(int p, Float gamma_o, Float gamma_t) { + return 2 * p * gamma_t - 2 * gamma_o + p * Pi; + } + + PBRT_CPU_GPU + static inline Float Np(Float phi, int p, Float s, Float gamma_o, Float gamma_t) { + Float dphi = phi - Phi(p, gamma_o, gamma_t); + // Remap _dphi_ to $[-\pi,\pi]$ + while (dphi > Pi) + dphi -= 2 * Pi; + while (dphi < -Pi) + dphi += 2 * Pi; + + return TrimmedLogistic(dphi, s, -Pi, Pi); + } + + PBRT_CPU_GPU + pstd::array ComputeApPDF(Float cosThetaO) const; + + // HairBSDF Private Members + Float h, gamma_o, eta; + SampledSpectrum sigma_a; + Float beta_m, beta_n; + Float v[pMax + 1]; + Float s; + Float sin2kAlpha[3], cos2kAlpha[3]; +}; + +// MeasuredBxDF Definition +class MeasuredBxDF { + public: + // MeasuredBxDF Public Methods + MeasuredBxDF() = default; + PBRT_CPU_GPU + MeasuredBxDF(const MeasuredBRDF *brdf, const SampledWavelengths &lambda) + : brdf(brdf), lambda(lambda) {} + + static MeasuredBRDF *BRDFDataFromFile(const std::string &filename, Allocator alloc); + + PBRT_CPU_GPU + SampledSpectrum f(Vector3f wo, Vector3f wi, TransportMode mode) const; + + PBRT_CPU_GPU + BSDFSample Sample_f(Vector3f wo, Float uc, const Point2f &u, TransportMode mode, + BxDFReflTransFlags sampleFlags) const; + PBRT_CPU_GPU + Float PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const; + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + void Regularize() {} + + PBRT_CPU_GPU + static constexpr const char *Name() { return "MeasuredBxDF"; } + + std::string ToString() const; + + PBRT_CPU_GPU + BxDFFlags Flags() const { return (BxDFFlags::Reflection | BxDFFlags::Glossy); } + + private: + friend class SOA; + // MeasuredBxDF Private Methods + PBRT_CPU_GPU + static Float u2theta(Float u) { return Sqr(u) * (Pi / 2.f); } + PBRT_CPU_GPU + static Float u2phi(Float u) { return (2.f * u - 1.f) * Pi; } + PBRT_CPU_GPU + static Float theta2u(Float theta) { return std::sqrt(theta * (2.f / Pi)); } + PBRT_CPU_GPU + static Float phi2u(Float phi) { return (phi + Pi) / (2.f * Pi); } + + // MeasuredBxDF Private Members + const MeasuredBRDF *brdf; + SampledWavelengths lambda; +}; + +// BSSRDFAdapter Definition +class BSSRDFAdapter { + public: + // BSSRDFAdapter Public Methods + BSSRDFAdapter() = default; + PBRT_CPU_GPU + BSSRDFAdapter(Float eta) : eta(eta) {} + + PBRT_CPU_GPU + BSDFSample Sample_f(const Vector3f &wo, Float uc, const Point2f &u, + TransportMode mode, BxDFReflTransFlags sampleFlags) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return {}; + + // Cosine-sample the hemisphere, flipping the direction if necessary + Vector3f wi = SampleCosineHemisphere(u); + if (wo.z < 0) + wi.z *= -1; + return BSDFSample(f(wo, wi, mode), wi, PDF(wo, wi, mode, sampleFlags), + BxDFFlags::DiffuseReflection); + } + + PBRT_CPU_GPU + Float PDF(const Vector3f &wo, const Vector3f &wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + if (!(sampleFlags & BxDFReflTransFlags::Reflection)) + return 0; + return SameHemisphere(wo, wi) ? AbsCosTheta(wi) * InvPi : 0; + } + + PBRT_CPU_GPU + bool SampledPDFIsProportional() const { return false; } + + PBRT_CPU_GPU + void Regularize() {} + + PBRT_CPU_GPU + static constexpr const char *Name() { return "BSSRDFAdapter"; } + + std::string ToString() const; + + PBRT_CPU_GPU + BxDFFlags Flags() const { + return BxDFFlags(BxDFFlags::Reflection | BxDFFlags::Diffuse); + } + + PBRT_CPU_GPU + SampledSpectrum f(const Vector3f &wo, const Vector3f &wi, TransportMode mode) const { + if (!SameHemisphere(wo, wi)) + return SampledSpectrum(0.f); + // Compute $\Sw$ factor for BSSRDF value + Float c = 1 - 2 * FresnelMoment1(1 / eta); + SampledSpectrum f((1 - FrDielectric(CosTheta(wi), eta)) / (c * Pi)); + + // Update BSSRDF transmission term to account for adjoint light transport + if (mode == TransportMode::Radiance) + f *= Sqr(eta); + + return f; + } + + private: + friend class SOA; + // BSSRDFAdapter Private Members + Float eta; +}; + +inline SampledSpectrum BxDFHandle::f(Vector3f wo, Vector3f wi, TransportMode mode) const { + auto f = [&](auto ptr) -> SampledSpectrum { return ptr->f(wo, wi, mode); }; + return Dispatch(f); +} + +inline BSDFSample BxDFHandle::Sample_f(Vector3f wo, Float uc, const Point2f &u, + TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + auto sample_f = [&](auto ptr) -> BSDFSample { + return ptr->Sample_f(wo, uc, u, mode, sampleFlags); + }; + return Dispatch(sample_f); +} + +inline Float BxDFHandle::PDF(Vector3f wo, Vector3f wi, TransportMode mode, + BxDFReflTransFlags sampleFlags) const { + auto pdf = [&](auto ptr) { return ptr->PDF(wo, wi, mode, sampleFlags); }; + return Dispatch(pdf); +} + +inline bool BxDFHandle::SampledPDFIsProportional() const { + auto approx = [&](auto ptr) { return ptr->SampledPDFIsProportional(); }; + return Dispatch(approx); +} + +inline BxDFFlags BxDFHandle::Flags() const { + auto flags = [&](auto ptr) { return ptr->Flags(); }; + return Dispatch(flags); +} + +inline void BxDFHandle::Regularize() { + auto regularize = [&](auto ptr) { ptr->Regularize(); }; + return Dispatch(regularize); +} + +extern template class LayeredBxDF; +extern template class LayeredBxDF; + +} // namespace pbrt + +#endif // PBRT_BXDFS_H diff --git a/src/pbrt/cameras.cpp b/src/pbrt/cameras.cpp new file mode 100644 index 00000000..28f96b5e --- /dev/null +++ b/src/pbrt/cameras.cpp @@ -0,0 +1,1543 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +// CameraTransform Method Definitions +CameraTransform::CameraTransform(const AnimatedTransform &worldFromCamera) { + switch (Options->renderingSpace) { + case RenderingCoordinateSystem::Camera: { + // Compute _worldFromRender_ for camera-space rendering + Float tMid = (worldFromCamera.startTime + worldFromCamera.endTime) / 2; + worldFromRender = worldFromCamera.Interpolate(tMid); + break; + } + case RenderingCoordinateSystem::CameraWorld: { + // Compute _worldFromRender_ for camera-world space rendering + Float tMid = (worldFromCamera.startTime + worldFromCamera.endTime) / 2; + Point3f pCamera = worldFromCamera(Point3f(0, 0, 0), tMid); + worldFromRender = Translate(Vector3f(pCamera)); + break; + } + case RenderingCoordinateSystem::World: { + // Compute _worldFromRender_ for world-space rendering + worldFromRender = Transform(); + break; + } + default: + LOG_FATAL("Unhandled rendering coordinate space"); + } + // Compute _renderFromCamera_ transformation + Transform renderFromWorld = Inverse(worldFromRender); + Transform rfc[2] = {renderFromWorld * worldFromCamera.startTransform, + renderFromWorld * worldFromCamera.endTransform}; + renderFromCamera = AnimatedTransform(rfc[0], worldFromCamera.startTime, rfc[1], + worldFromCamera.endTime); +} + +std::string CameraTransform::ToString() const { + return StringPrintf("[ CameraTransform renderFromCamera: %s worldFromRender: %s ]", + renderFromCamera, worldFromRender); +} + +// Camera Method Definitions +pstd::optional CameraHandle::GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const { + auto gen = [&](auto ptr) { return ptr->GenerateRayDifferential(sample, lambda); }; + return Dispatch(gen); +} + +void CameraHandle::ApproximatedPdxy(const SurfaceInteraction &si) const { + auto approx = [&](auto ptr) { return ptr->ApproximatedPdxy(si); }; + return Dispatch(approx); +} + +SampledSpectrum CameraHandle::We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2) const { + auto we = [&](auto ptr) { return ptr->We(ray, lambda, pRaster2); }; + return Dispatch(we); +} + +void CameraHandle::PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const { + auto pdf = [&](auto ptr) { return ptr->PDF_We(ray, pdfPos, pdfDir); }; + return Dispatch(pdf); +} + +pstd::optional CameraHandle::SampleWi(const Interaction &ref, + const Point2f &u, + SampledWavelengths &lambda) const { + auto sample = [&](auto ptr) { return ptr->SampleWi(ref, u, lambda); }; + return Dispatch(sample); +} + +void CameraHandle::InitMetadata(ImageMetadata *metadata) const { + auto init = [&](auto ptr) { return ptr->InitMetadata(metadata); }; + return DispatchCPU(init); +} + +std::string CameraHandle::ToString() const { + if (ptr() == nullptr) + return "(nullptr)"; + + auto ts = [&](auto ptr) { return ptr->ToString(); }; + return DispatchCPU(ts); +} + +// CameraBase Method Definitions +CameraBase::CameraBase(const CameraTransform &cameraTransform, Float shutterOpen, + Float shutterClose, FilmHandle film, MediumHandle medium) + : cameraTransform(cameraTransform), + shutterOpen(shutterOpen), + shutterClose(shutterClose), + film(film), + medium(medium) { + if (cameraTransform.CameraFromRenderHasScale()) + Warning("Scaling detected in world-to-camera transformation!\n" + "The system has numerous assumptions, implicit and explicit,\n" + "that this transform will have no scale factors in it.\n" + "Proceed at your own risk; your image may have errors or\n" + "the system may crash as a result of this."); +} + +pstd::optional CameraBase::GenerateRayDifferential( + CameraHandle camera, const CameraSample &sample, SampledWavelengths &lambda) { + // Find ray differential using differencing + // Generate regular camera ray _cr_ for ray differential + CameraRay cr = camera.GenerateRay(sample, lambda); + if (!cr.weight) + return {}; + + RayDifferential rd(cr.ray); + // Find camera ray after shifting one pixel in the $x$ direction + CameraRay rx; + for (Float eps : {.05, -.05}) { + CameraSample sshift = sample; + sshift.pFilm.x += eps; + // Try to generate ray with _sshift_ and compute $x$ differential + if (rx = camera.GenerateRay(sshift, lambda); rx.weight) { + rd.rxOrigin = rd.o + (rx.ray.o - rd.o) / eps; + rd.rxDirection = rd.d + (rx.ray.d - rd.d) / eps; + break; + } + } + if (!rx.weight) + return {}; + + // Find camera ray after shifting one pixel in the $y$ direction + CameraRay ry; + for (Float eps : {.05, -.05}) { + CameraSample sshift = sample; + sshift.pFilm.y += eps; + if (ry = camera.GenerateRay(sshift, lambda); ry.weight) { + rd.ryOrigin = rd.o + (ry.ray.o - rd.o) / eps; + rd.ryDirection = rd.d + (ry.ray.d - rd.d) / eps; + break; + } + } + if (!ry.weight) + return {}; + + rd.hasDifferentials = true; + return CameraRayDifferential{rd, cr.weight}; +} + +void CameraBase::ApproximatedPdxy(const SurfaceInteraction &si) const { + Point3f pc = CameraFromRender(si.p(), si.time); + Float dist = Distance(pc, Point3f(0, 0, 0)); + + Frame f = Frame::FromZ(si.n); + // ray plane: + // (0,0,0) + minPosDifferential + ((0,0,1) + minDirDifferantial)) * t = (x, + // x, dist) + Float tx = (dist - minPosDifferentialX.z) / (1 + minDirDifferentialX.z); + // 0.5 factor to sharpen them up slightly (could be / should be based + // on spp?) + si.dpdx = .5f * f.FromLocal(minPosDifferentialX + tx * minDirDifferentialX); + Float ty = (dist - minPosDifferentialY.z) / (1 + minDirDifferentialY.z); + si.dpdy = .5f * f.FromLocal(minPosDifferentialY + ty * minDirDifferentialY); +} + +void CameraBase::InitMetadata(ImageMetadata *metadata) const { + metadata->cameraFromWorld = cameraTransform.CameraFromWorld(shutterOpen).GetMatrix(); +} + +void CameraBase::FindMinimumDifferentials(CameraHandle camera) { + minPosDifferentialX = minPosDifferentialY = minDirDifferentialX = + minDirDifferentialY = Vector3f(Infinity, Infinity, Infinity); + + CameraSample sample; + sample.pLens = Point2f(0.5, 0.5); + sample.time = 0.5; + SampledWavelengths lambda = SampledWavelengths::SampleXYZ(0.5); + + int n = 512; + for (int i = 0; i < n; ++i) { + sample.pFilm.x = Float(i) / (n - 1) * film.FullResolution().x; + sample.pFilm.y = Float(i) / (n - 1) * film.FullResolution().y; + + pstd::optional crd = + camera.GenerateRayDifferential(sample, lambda); + if (!crd) + continue; + + RayDifferential &ray = crd->ray; + Vector3f dox = CameraFromRender(ray.rxOrigin - ray.o, ray.time); + if (Length(dox) < Length(minPosDifferentialX)) + minPosDifferentialX = dox; + Vector3f doy = CameraFromRender(ray.ryOrigin - ray.o, ray.time); + if (Length(doy) < Length(minPosDifferentialY)) + minPosDifferentialY = doy; + + ray.d = Normalize(ray.d); + ray.rxDirection = Normalize(ray.rxDirection); + ray.ryDirection = Normalize(ray.ryDirection); + + Frame f = Frame::FromZ(ray.d); + Vector3f df = f.ToLocal(ray.d); // should be (0, 0, 1); + Vector3f dxf = Normalize(f.ToLocal(ray.rxDirection)); + Vector3f dyf = Normalize(f.ToLocal(ray.ryDirection)); + + if (Length(dxf - df) < Length(minDirDifferentialX)) + minDirDifferentialX = dxf - df; + if (Length(dyf - df) < Length(minDirDifferentialY)) + minDirDifferentialY = dyf - df; + } + + LOG_VERBOSE("Camera min pos differentials: %s, %s", minPosDifferentialX, + minPosDifferentialY); + LOG_VERBOSE("Camera min dir differentials: %s, %s", minDirDifferentialX, + minDirDifferentialY); +} + +std::string CameraBase::ToString() const { + return StringPrintf("cameraTransform: %s shutterOpen: %f shutterClose: %f film: %s " + "medium: %s minPosDifferentialX: %s minPosDifferentialY: %s " + "minDirDifferentialX: %s minDirDifferentialY: %s ", + cameraTransform, shutterOpen, shutterClose, film, + medium ? medium.ToString().c_str() : "(nullptr)", + minPosDifferentialX, minPosDifferentialY, minDirDifferentialX, + minDirDifferentialY); +} + +std::string CameraSample::ToString() const { + return StringPrintf("[ pFilm: %s pLens: %s time: %f weight: %f ]", pFilm, pLens, time, + weight); +} + +// ProjectiveCamera Method Definitions +void ProjectiveCamera::InitMetadata(ImageMetadata *metadata) const { + metadata->cameraFromWorld = cameraTransform.CameraFromWorld(shutterOpen).GetMatrix(); + + // TODO: double check this + Transform NDCFromWorld = Translate(Vector3f(0.5, 0.5, 0.5)) * Scale(0.5, 0.5, 0.5) * + screenFromCamera * *metadata->cameraFromWorld; + metadata->NDCFromWorld = NDCFromWorld.GetMatrix(); + + CameraBase::InitMetadata(metadata); +} + +std::string ProjectiveCamera::BaseToString() const { + return CameraBase::ToString() + + StringPrintf("screenFromCamera: %s cameraFromRaster: %s " + "rasterFromScreen: %s screenFromRaster: %s " + "lensRadius: %f focalDistance: %f", + screenFromCamera, cameraFromRaster, rasterFromScreen, + screenFromRaster, lensRadius, focalDistance); +} + +CameraHandle CameraHandle::Create(const std::string &name, + const ParameterDictionary ¶meters, + MediumHandle medium, + const CameraTransform &cameraTransform, FilmHandle film, + const FileLoc *loc, Allocator alloc) { + CameraHandle camera; + if (name == "perspective") + camera = PerspectiveCamera::Create(parameters, cameraTransform, film, medium, loc, + alloc); + else if (name == "orthographic") + camera = OrthographicCamera::Create(parameters, cameraTransform, film, medium, + loc, alloc); + else if (name == "realistic") + camera = RealisticCamera::Create(parameters, cameraTransform, film, medium, loc, + alloc); + else if (name == "spherical") + camera = SphericalCamera::Create(parameters, cameraTransform, film, medium, loc, + alloc); + else + ErrorExit(loc, "%s: camera type unknown.", name); + + if (!camera) + ErrorExit(loc, "%s: unable to create camera.", name); + + parameters.ReportUnused(); + return camera; +} + +// OrthographicCamera Method Definitions +CameraRay OrthographicCamera::GenerateRay(CameraSample sample, + SampledWavelengths &lambda) const { + // Compute raster and camera sample positions + Point3f pFilm = Point3f(sample.pFilm.x, sample.pFilm.y, 0); + Point3f pCamera = cameraFromRaster(pFilm); + + Ray ray(pCamera, Vector3f(0, 0, 1), SampleTime(sample.time), medium); + // Modify ray for depth of field + if (lensRadius > 0) { + // Sample point on lens + Point2f pLens = lensRadius * SampleUniformDiskConcentric(sample.pLens); + + // Compute point on plane of focus + Float ft = focalDistance / ray.d.z; + Point3f pFocus = ray(ft); + + // Update ray for effect of lens + ray.o = Point3f(pLens.x, pLens.y, 0); + ray.d = Normalize(pFocus - ray.o); + } + + return CameraRay{RenderFromCamera(ray)}; +} + +pstd::optional OrthographicCamera::GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const { + // Compute main orthographic viewing ray + // Compute raster and camera sample positions + Point3f pFilm = Point3f(sample.pFilm.x, sample.pFilm.y, 0); + Point3f pCamera = cameraFromRaster(pFilm); + + RayDifferential ray(pCamera, Vector3f(0, 0, 1), SampleTime(sample.time), medium); + // Modify ray for depth of field + if (lensRadius > 0) { + // Sample point on lens + Point2f pLens = lensRadius * SampleUniformDiskConcentric(sample.pLens); + + // Compute point on plane of focus + Float ft = focalDistance / ray.d.z; + Point3f pFocus = ray(ft); + + // Update ray for effect of lens + ray.o = Point3f(pLens.x, pLens.y, 0); + ray.d = Normalize(pFocus - ray.o); + } + + // Compute ray differentials for _OrthographicCamera_ + if (lensRadius > 0) { + // Compute \use{OrthographicCamera} ray differentials accounting for lens + // Sample point on lens + Point2f pLens = lensRadius * SampleUniformDiskConcentric(sample.pLens); + + Float ft = focalDistance / ray.d.z; + Point3f pFocus = pCamera + dxCamera + (ft * Vector3f(0, 0, 1)); + ray.rxOrigin = Point3f(pLens.x, pLens.y, 0); + ray.rxDirection = Normalize(pFocus - ray.rxOrigin); + + pFocus = pCamera + dyCamera + (ft * Vector3f(0, 0, 1)); + ray.ryOrigin = Point3f(pLens.x, pLens.y, 0); + ray.ryDirection = Normalize(pFocus - ray.ryOrigin); + + } else { + ray.rxOrigin = ray.o + dxCamera; + ray.ryOrigin = ray.o + dyCamera; + ray.rxDirection = ray.ryDirection = ray.d; + } + + ray.hasDifferentials = true; + return CameraRayDifferential{RenderFromCamera(ray)}; +} + +std::string OrthographicCamera::ToString() const { + return StringPrintf("[ OrthographicCamera %s dxCamera: %s dyCamera: %s ]", + BaseToString(), dxCamera, dyCamera); +} + +OrthographicCamera *OrthographicCamera::Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc) { + // Extract common camera parameters from _ParameterDictionary_ + Float shutteropen = parameters.GetOneFloat("shutteropen", 0.f); + Float shutterclose = parameters.GetOneFloat("shutterclose", 1.f); + if (shutterclose < shutteropen) { + Warning(loc, "Shutter close time %f < shutter open %f. Swapping them.", + shutterclose, shutteropen); + pstd::swap(shutterclose, shutteropen); + } + Float lensradius = parameters.GetOneFloat("lensradius", 0.f); + Float focaldistance = parameters.GetOneFloat("focaldistance", 1e6f); + Float frame = + parameters.GetOneFloat("frameaspectratio", Float(film.FullResolution().x) / + Float(film.FullResolution().y)); + Bounds2f screen; + if (frame > 1.f) { + screen.pMin.x = -frame; + screen.pMax.x = frame; + screen.pMin.y = -1.f; + screen.pMax.y = 1.f; + } else { + screen.pMin.x = -1.f; + screen.pMax.x = 1.f; + screen.pMin.y = -1.f / frame; + screen.pMax.y = 1.f / frame; + } + std::vector sw = parameters.GetFloatArray("screenwindow"); + if (!sw.empty()) { + if (sw.size() == 4) { + screen.pMin.x = sw[0]; + screen.pMax.x = sw[1]; + screen.pMin.y = sw[2]; + screen.pMax.y = sw[3]; + } else + Error("\"screenwindow\" should have four values"); + } + return alloc.new_object(cameraTransform, screen, shutteropen, + shutterclose, lensradius, focaldistance, + film, medium); +} + +// PerspectiveCamera Method Definitions +CameraRay PerspectiveCamera::GenerateRay(CameraSample sample, + SampledWavelengths &lambda) const { + // Compute raster and camera sample positions + Point3f pFilm = Point3f(sample.pFilm.x, sample.pFilm.y, 0); + Point3f pCamera = cameraFromRaster(pFilm); + + Ray ray(Point3f(0, 0, 0), Normalize(Vector3f(pCamera)), SampleTime(sample.time), + medium); + // Modify ray for depth of field + if (lensRadius > 0) { + // Sample point on lens + Point2f pLens = lensRadius * SampleUniformDiskConcentric(sample.pLens); + + // Compute point on plane of focus + Float ft = focalDistance / ray.d.z; + Point3f pFocus = ray(ft); + + // Update ray for effect of lens + ray.o = Point3f(pLens.x, pLens.y, 0); + ray.d = Normalize(pFocus - ray.o); + } + + return CameraRay{RenderFromCamera(ray)}; +} + +pstd::optional PerspectiveCamera::GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const { + // Compute raster and camera sample positions + Point3f pFilm = Point3f(sample.pFilm.x, sample.pFilm.y, 0); + Point3f pCamera = cameraFromRaster(pFilm); + Vector3f dir = Normalize(Vector3f(pCamera.x, pCamera.y, pCamera.z)); + RayDifferential ray(Point3f(0, 0, 0), dir, SampleTime(sample.time), medium); + // Modify ray for depth of field + if (lensRadius > 0) { + // Sample point on lens + Point2f pLens = lensRadius * SampleUniformDiskConcentric(sample.pLens); + + // Compute point on plane of focus + Float ft = focalDistance / ray.d.z; + Point3f pFocus = ray(ft); + + // Update ray for effect of lens + ray.o = Point3f(pLens.x, pLens.y, 0); + ray.d = Normalize(pFocus - ray.o); + } + + // Compute offset rays for \use{PerspectiveCamera} ray differentials + if (lensRadius > 0) { + // Compute \use{PerspectiveCamera} ray differentials accounting for lens + // Sample point on lens + Point2f pLens = lensRadius * SampleUniformDiskConcentric(sample.pLens); + + // Compute $x$ ray differential for _PerspectiveCamera_ with lens + Vector3f dx = Normalize(Vector3f(pCamera + dxCamera)); + Float ft = focalDistance / dx.z; + Point3f pFocus = Point3f(0, 0, 0) + (ft * dx); + ray.rxOrigin = Point3f(pLens.x, pLens.y, 0); + ray.rxDirection = Normalize(pFocus - ray.rxOrigin); + + // Compute $y$ ray differential for _PerspectiveCamera_ with lens + Vector3f dy = Normalize(Vector3f(pCamera + dyCamera)); + ft = focalDistance / dy.z; + pFocus = Point3f(0, 0, 0) + (ft * dy); + ray.ryOrigin = Point3f(pLens.x, pLens.y, 0); + ray.ryDirection = Normalize(pFocus - ray.ryOrigin); + + } else { + ray.rxOrigin = ray.ryOrigin = ray.o; + ray.rxDirection = Normalize(Vector3f(pCamera) + dxCamera); + ray.ryDirection = Normalize(Vector3f(pCamera) + dyCamera); + } + + ray.hasDifferentials = true; + return CameraRayDifferential{RenderFromCamera(ray)}; +} + +std::string PerspectiveCamera::ToString() const { + return StringPrintf("[ PerspectiveCamera %s dxCamera: %s dyCamera: %s A: " + "%f cosTotalWidth: %f ]", + BaseToString(), dxCamera, dyCamera, A, cosTotalWidth); +} + +PerspectiveCamera *PerspectiveCamera::Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc) { + // Extract common camera parameters from _ParameterDictionary_ + Float shutteropen = parameters.GetOneFloat("shutteropen", 0.f); + Float shutterclose = parameters.GetOneFloat("shutterclose", 1.f); + if (shutterclose < shutteropen) { + Warning(loc, "Shutter close time %f < shutter open %f. Swapping them.", + shutterclose, shutteropen); + pstd::swap(shutterclose, shutteropen); + } + Float lensradius = parameters.GetOneFloat("lensradius", 0.f); + Float focaldistance = parameters.GetOneFloat("focaldistance", 1e6); + Float frame = + parameters.GetOneFloat("frameaspectratio", Float(film.FullResolution().x) / + Float(film.FullResolution().y)); + Bounds2f screen; + if (frame > 1.f) { + screen.pMin.x = -frame; + screen.pMax.x = frame; + screen.pMin.y = -1.f; + screen.pMax.y = 1.f; + } else { + screen.pMin.x = -1.f; + screen.pMax.x = 1.f; + screen.pMin.y = -1.f / frame; + screen.pMax.y = 1.f / frame; + } + std::vector sw = parameters.GetFloatArray("screenwindow"); + if (!sw.empty()) { + if (sw.size() == 4) { + screen.pMin.x = sw[0]; + screen.pMax.x = sw[1]; + screen.pMin.y = sw[2]; + screen.pMax.y = sw[3]; + } else + Error(loc, "\"screenwindow\" should have four values"); + } + Float fov = parameters.GetOneFloat("fov", 90.); + return alloc.new_object(cameraTransform, screen, shutteropen, + shutterclose, lensradius, focaldistance, + fov, film, medium); +} + +SampledSpectrum PerspectiveCamera::We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2) const { + // Check if ray is forward-facing with respect to the camera + Float cosTheta = Dot(ray.d, RenderFromCamera(Vector3f(0, 0, 1), ray.time)); + if (cosTheta <= cosTotalWidth) + return SampledSpectrum(0.); + + // Map ray $(\p{}, \w{})$ onto the raster grid + Point3f pFocus = ray((lensRadius > 0 ? focalDistance : 1) / cosTheta); + Point3f pCamera = CameraFromRender(pFocus, ray.time); + Point3f pRaster = cameraFromRaster.ApplyInverse(pCamera); + + // Return raster position if requested + if (pRaster2) + *pRaster2 = Point2f(pRaster.x, pRaster.y); + + // Return zero importance for out of bounds points + Bounds2f sampleBounds = film.SampleBounds(); + if (!Inside(Point2f(pRaster.x, pRaster.y), sampleBounds)) + return SampledSpectrum(0.); + + // Compute lens area of perspective camera + Float lensArea = lensRadius != 0 ? (Pi * lensRadius * lensRadius) : 1; + + // Return importance for point on image plane + return SampledSpectrum(1 / (A * lensArea * Pow<4>(cosTheta))); +} + +void PerspectiveCamera::PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const { + // Return zero PDF values if ray direction is not front-facing + Float cosTheta = Dot(ray.d, RenderFromCamera(Vector3f(0, 0, 1), ray.time)); + if (cosTheta <= cosTotalWidth) { + *pdfPos = *pdfDir = 0; + return; + } + + // Map ray $(\p{}, \w{})$ onto the raster grid + Point3f pFocus = ray((lensRadius > 0 ? focalDistance : 1) / cosTheta); + Point3f pCamera = CameraFromRender(pFocus, ray.time); + Point3f pRaster = cameraFromRaster.ApplyInverse(pCamera); + + // Return zero probability for out of bounds points + Bounds2f sampleBounds = film.SampleBounds(); + if (!Inside(Point2f(pRaster.x, pRaster.y), sampleBounds)) { + *pdfPos = *pdfDir = 0; + return; + } + + // Compute lens area and return perspective camera probabilities + Float lensArea = lensRadius != 0 ? (Pi * lensRadius * lensRadius) : 1; + *pdfPos = 1 / lensArea; + *pdfDir = 1 / (A * Pow<3>(cosTheta)); +} + +pstd::optional PerspectiveCamera::SampleWi( + const Interaction &ref, const Point2f &u, SampledWavelengths &lambda) const { + // Uniformly sample a lens interaction _lensIntr_ + Point2f pLens = lensRadius * SampleUniformDiskConcentric(u); + Point3f pLensRender = RenderFromCamera(Point3f(pLens.x, pLens.y, 0), ref.time); + Normal3f n = Normal3f(RenderFromCamera(Vector3f(0, 0, 1), ref.time)); + Interaction lensIntr(pLensRender, n, ref.time, medium); + + // Populate arguments and compute the importance value + // Compute incident direction to camera _wi_ at _ref_ + Vector3f wi = lensIntr.p() - ref.p(); + Float dist = Length(wi); + wi /= dist; + + // Compute PDF for importance arriving at _ref_ + Float lensArea = lensRadius != 0 ? (Pi * lensRadius * lensRadius) : 1; + Float pdf = (dist * dist) / (AbsDot(lensIntr.n, wi) * lensArea); + + Point2f pRaster; + SampledSpectrum Wi = We(lensIntr.SpawnRay(-wi), lambda, &pRaster); + if (!Wi) + return {}; + return CameraWiSample(Wi, wi, pdf, pRaster, ref, lensIntr); +} + +// SphericalCamera Method Definitions +CameraRay SphericalCamera::GenerateRay(CameraSample sample, + SampledWavelengths &lambda) const { + // Compute spherical camera ray direction + Vector3f dir; + if (mapping == EquiRect) { + // Compute ray direction using equi-rectangular mapping + Float theta = Pi * sample.pFilm.y / film.FullResolution().y; + Float phi = 2 * Pi * sample.pFilm.x / film.FullResolution().x; + dir = SphericalDirection(std::sin(theta), std::cos(theta), phi); + + } else { + // Compute ray direction using equi-area mapping + Point2f uv(sample.pFilm.x / film.FullResolution().x, + sample.pFilm.y / film.FullResolution().y); + uv = WrapEquiAreaSquare(uv); + dir = EquiAreaSquareToSphere(uv); + } + pstd::swap(dir.y, dir.z); + + Ray ray(Point3f(0, 0, 0), dir, SampleTime(sample.time), medium); + return CameraRay{RenderFromCamera(ray)}; +} + +SphericalCamera *SphericalCamera::Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc) { + // Extract common camera parameters from _ParameterDictionary_ + Float shutteropen = parameters.GetOneFloat("shutteropen", 0.f); + Float shutterclose = parameters.GetOneFloat("shutterclose", 1.f); + if (shutterclose < shutteropen) { + Warning(loc, "Shutter close time %f < shutter open %f. Swapping them.", + shutterclose, shutteropen); + pstd::swap(shutterclose, shutteropen); + } + Float lensradius = parameters.GetOneFloat("lensradius", 0.f); + Float focaldistance = parameters.GetOneFloat("focaldistance", 1e30f); + Float frame = + parameters.GetOneFloat("frameaspectratio", Float(film.FullResolution().x) / + Float(film.FullResolution().y)); + Bounds2f screen; + if (frame > 1.f) { + screen.pMin.x = -frame; + screen.pMax.x = frame; + screen.pMin.y = -1.f; + screen.pMax.y = 1.f; + } else { + screen.pMin.x = -1.f; + screen.pMax.x = 1.f; + screen.pMin.y = -1.f / frame; + screen.pMax.y = 1.f / frame; + } + std::vector sw = parameters.GetFloatArray("screenwindow"); + if (!sw.empty()) { + if (sw.size() == 4) { + screen.pMin.x = sw[0]; + screen.pMax.x = sw[1]; + screen.pMin.y = sw[2]; + screen.pMax.y = sw[3]; + } else + Error(loc, "\"screenwindow\" should have four values"); + } + (void)lensradius; // don't need this + (void)focaldistance; // don't need this + + std::string m = parameters.GetOneString("mapping", "equiarea"); + Mapping mapping; + if (m == "equiarea") + mapping = EquiArea; + else if (m == "equirect") + mapping = EquiRect; + else + ErrorExit(loc, + "%s: unknown mapping for spherical camera. (Must be " + "\"equiarea\" or \"equirect\".)", + m); + + return alloc.new_object(cameraTransform, shutteropen, shutterclose, + film, medium, mapping); +} + +std::string SphericalCamera::ToString() const { + return StringPrintf("[ SphericalCamera %s mapping: %s ]", CameraBase::ToString(), + mapping == EquiRect ? "EquiRect" : "EquiArea"); +} + +// RealisticCamera Method Definitions +RealisticCamera::RealisticCamera(const CameraTransform &cameraTransform, + Float shutterOpen, Float shutterClose, + Float setApertureDiameter, Float focusDistance, + Float dispersionFactor, std::vector &lensData, + Float scale, FilmHandle film, MediumHandle medium, + Image apertureImage, Allocator alloc) + : CameraBase(cameraTransform, shutterOpen, shutterClose, film, medium), + scale(scale), + dispersionFactor(dispersionFactor), + elementInterfaces(alloc), + exitPupilBounds(alloc), + apertureImage(std::move(apertureImage)) { + // Initialize _elementInterfaces_ for camera + for (int i = 0; i < (int)lensData.size(); i += 4) { + // Extract lens element configuration from _lensData_ + Float curvatureRadius = scale * lensData[i] * 0.001f; + Float thickness = scale * lensData[i + 1] * 0.001f; + Float eta = lensData[i + 2]; + Float apertureDiameter = scale * lensData[i + 3] * 0.001f; + + if (curvatureRadius == 0) { + // Set aperture stop diameter + setApertureDiameter *= 0.001f; + if (setApertureDiameter > apertureDiameter) + Warning("Specified aperture diameter %f is greater than maximum " + "possible %f. Clamping it.", + setApertureDiameter, apertureDiameter); + else + apertureDiameter = setApertureDiameter; + } + // Add element interface to end of _elementInterfaces_ + LensElementInterface interface{curvatureRadius, thickness, eta, + apertureDiameter / 2}; + elementInterfaces.emplace_back(interface); + } + + // Compute lens--film distance for given focus distance + Float fb = FocusBinarySearch(focusDistance); + elementInterfaces.back().thickness = FocusThickLens(focusDistance); + + // Compute exit pupil bounds at sampled points on the film + int nSamples = 64; + exitPupilBounds.resize(nSamples); + ParallelFor(0, nSamples, [&](int i) { + Float r0 = (Float)i / nSamples * FilmDiagonal() / 2; + Float r1 = (Float)(i + 1) / nSamples * FilmDiagonal() / 2; + exitPupilBounds[i] = BoundExitPupil(r0, r1); + }); + + FindMinimumDifferentials(this); +} + +Float RealisticCamera::TraceLensesFromFilm(const Ray &rCamera, Ray *rOut, + Float lambda) const { + Float elementZ = 0; + Float weight = 1; + // Transform _rCamera_ from camera to lens system space + Transform LensFromCamera = Scale(1, 1, -1); + Ray rLens = LensFromCamera(rCamera); + + for (int i = elementInterfaces.size() - 1; i >= 0; --i) { + const LensElementInterface &element = elementInterfaces[i]; + // Update ray from film accounting for interaction with _element_ + elementZ -= element.thickness; + // Compute intersection of ray with lens element + Float t; + Normal3f n; + bool isStop = (element.curvatureRadius == 0); + if (isStop) { + // Compute _t_ at plane of aperture stop + if (rLens.d.z >= 0.0) + return false; + t = (elementZ - rLens.o.z) / rLens.d.z; + + } else { + // Intersect ray with element to compute _t_ and _n_ + Float radius = element.curvatureRadius; + Float zCenter = elementZ + element.curvatureRadius; + if (!IntersectSphericalElement(radius, zCenter, rLens, &t, &n)) + return false; + } + DCHECK_GE(t, 0); + + // Test intersection point against element aperture + Point3f pHit = rLens(t); + if (isStop && apertureImage) { + // Check intersection point against _apertureImage_ + Point2f uv((pHit.x / element.apertureRadius + 1) / 2, + (pHit.y / element.apertureRadius + 1) / 2); + uv.y = 1 - uv.y; + weight = apertureImage.BilerpChannel(uv, 0, WrapMode::Black); + if (weight == 0) + return 0; + + } else { + // Check intersection point against spherical aperture + Float r2 = pHit.x * pHit.x + pHit.y * pHit.y; + if (r2 > element.apertureRadius * element.apertureRadius) + return 0; + } + rLens.o = pHit; + + // Update ray path for element interface interaction + if (!isStop) { + Vector3f w; + Float eta_i = element.eta; + Float eta_t = (i > 0 && elementInterfaces[i - 1].eta != 0) + ? elementInterfaces[i - 1].eta + : 1; + // Optionally apply ad-hoc dispersion approximation + if (dispersionFactor != 0) { + Float offset = + (lambda - 550) / (550 - 400); // [-1,1] for lambda in [400,700] + eta_i -= offset * dispersionFactor * .02; + eta_t -= offset * dispersionFactor * .02; + } + + if (!Refract(Normalize(-rLens.d), n, eta_t / eta_i, &w)) + return 0; + rLens.d = w; + } + } + // Transform _rLens_ from lens system space back to camera space + if (rOut != nullptr) { + const Transform LensToCamera = Scale(1, 1, -1); + *rOut = LensToCamera(rLens); + } + + return weight; +} + +void RealisticCamera::ComputeCardinalPoints(const Ray &rIn, const Ray &rOut, Float *pz, + Float *fz) { + Float tf = -rOut.o.x / rOut.d.x; + *fz = -rOut(tf).z; + Float tp = (rIn.o.x - rOut.o.x) / rOut.d.x; + *pz = -rOut(tp).z; +} + +void RealisticCamera::ComputeThickLensApproximation(Float pz[2], Float fz[2]) const { + // Find height $x$ from optical axis for parallel rays + Float x = .001 * FilmDiagonal(); + + // Compute cardinal points for film side of lens system + Ray rScene(Point3f(x, 0, LensFrontZ() + 1), Vector3f(0, 0, -1)); + Ray rFilm; + if (!TraceLensesFromScene(rScene, &rFilm)) + ErrorExit("Unable to trace ray from scene to film for thick lens " + "approximation. Is aperture stop extremely small?"); + ComputeCardinalPoints(rScene, rFilm, &pz[0], &fz[0]); + + // Compute cardinal points for scene side of lens system + rFilm = Ray(Point3f(x, 0, LensRearZ() - 1), Vector3f(0, 0, 1)); + if (TraceLensesFromFilm(rFilm, &rScene) == 0) + ErrorExit("Unable to trace ray from film to scene for thick lens " + "approximation. Is aperture stop extremely small?"); + ComputeCardinalPoints(rFilm, rScene, &pz[1], &fz[1]); +} + +Float RealisticCamera::FocusThickLens(Float focusDistance) { + Float pz[2], fz[2]; + ComputeThickLensApproximation(pz, fz); + LOG_VERBOSE("Cardinal points: p' = %f f' = %f, p = %f f = %f.\n", pz[0], fz[0], pz[1], + fz[1]); + LOG_VERBOSE("Effective focal length %f\n", fz[0] - pz[0]); + // Compute translation of lens, _delta_, to focus at _focusDistance_ + Float f = fz[0] - pz[0]; + Float z = -focusDistance; + Float c = (pz[1] - z - pz[0]) * (pz[1] - z - 4 * f - pz[0]); + if (c <= 0) + ErrorExit("Coefficient must be positive. It looks focusDistance %f " + " is too short for a given lenses configuration", + focusDistance); + Float delta = 0.5f * (pz[1] - z + pz[0] - std::sqrt(c)); + + return elementInterfaces.back().thickness + delta; +} + +Float RealisticCamera::FocusBinarySearch(Float focusDistance) { + Float filmDistanceLower, filmDistanceUpper; + // Find _filmDistanceLower_, _filmDistanceUpper_ that bound focus distance + filmDistanceLower = filmDistanceUpper = FocusThickLens(focusDistance); + while (FocusDistance(filmDistanceLower) > focusDistance) + filmDistanceLower *= 1.005f; + while (FocusDistance(filmDistanceUpper) < focusDistance) + filmDistanceUpper /= 1.005f; + + // Do binary search on film distances to focus + for (int i = 0; i < 20; ++i) { + Float fmid = 0.5f * (filmDistanceLower + filmDistanceUpper); + Float midFocus = FocusDistance(fmid); + if (midFocus < focusDistance) + filmDistanceLower = fmid; + else + filmDistanceUpper = fmid; + } + + return 0.5f * (filmDistanceLower + filmDistanceUpper); +} + +Float RealisticCamera::FocusDistance(Float filmDistance) { + // Find offset ray from film center through lens + Bounds2f bounds = BoundExitPupil(0, .001 * FilmDiagonal()); + Ray ray; + bool foundFocusRay = false; + for (Float scale : {0.1f, 0.01f, 0.001f}) { + Float lu = scale * bounds.pMax[0]; + if (TraceLensesFromFilm(Ray(Point3f(0, 0, LensRearZ() - filmDistance), + Vector3f(lu, 0, filmDistance)), + &ray)) { + foundFocusRay = true; + break; + } + } + if (!foundFocusRay) { + Error("Couldn't fidn a focus ray that made it through the lenses " + "with film distance %f?!??\n", + filmDistance); + return Infinity; + } + + // Compute distance _zFocus_ where ray intersects the principal axis + Float tFocus = -ray.o.x / ray.d.x; + Float zFocus = ray(tFocus).z; + if (zFocus < 0) + zFocus = Infinity; + + return zFocus; +} + +Bounds2f RealisticCamera::BoundExitPupil(Float filmX0, Float filmX1) const { + Bounds2f pupilBounds; + // Sample a collection of points on the rear lens to find exit pupil + const int nSamples = 1024 * 1024; + int nExitingRays = 0; + // Compute bounding box of projection of rear element on sampling plane + Float rearRadius = RearElementRadius(); + Bounds2f projRearBounds(Point2f(-1.5f * rearRadius, -1.5f * rearRadius), + Point2f(1.5f * rearRadius, 1.5f * rearRadius)); + + for (int i = 0; i < nSamples; ++i) { + // Find location of sample points on $x$ segment and rear lens element + Point3f pFilm(Lerp((i + 0.5f) / nSamples, filmX0, filmX1), 0, 0); + Float u[2] = {RadicalInverse(0, i), RadicalInverse(1, i)}; + Point3f pRear(Lerp(u[0], projRearBounds.pMin.x, projRearBounds.pMax.x), + Lerp(u[1], projRearBounds.pMin.y, projRearBounds.pMax.y), + LensRearZ()); + + // Expand pupil bounds if ray makes it through the lens system + if (Inside(Point2f(pRear.x, pRear.y), pupilBounds) || + TraceLensesFromFilm(Ray(pFilm, pRear - pFilm), nullptr)) { + pupilBounds = Union(pupilBounds, Point2f(pRear.x, pRear.y)); + ++nExitingRays; + } + } + + // Return entire element bounds if no rays made it through the lens system + if (nExitingRays == 0) { + LOG_VERBOSE("Unable to find exit pupil in x = [%f,%f] on film.", filmX0, filmX1); + return projRearBounds; + } + + // Expand bounds to account for sample spacing + pupilBounds = + Expand(pupilBounds, 2 * Length(projRearBounds.Diagonal()) / std::sqrt(nSamples)); + + return pupilBounds; +} + +Point3f RealisticCamera::SampleExitPupil(const Point2f &pFilm, const Point2f &lensSample, + Float *sampleBoundsArea) const { + // Find exit pupil bound for sample distance from film center + Float rFilm = std::sqrt(pFilm.x * pFilm.x + pFilm.y * pFilm.y); + int rIndex = rFilm / (FilmDiagonal() / 2) * exitPupilBounds.size(); + rIndex = std::min(exitPupilBounds.size() - 1, rIndex); + Bounds2f pupilBounds = exitPupilBounds[rIndex]; + if (sampleBoundsArea != nullptr) + *sampleBoundsArea = pupilBounds.Area(); + + // Generate sample point inside exit pupil bound + Point2f pLens = pupilBounds.Lerp(lensSample); + + // Return sample point rotated by angle of _pFilm_ with $+x$ axis + Float sinTheta = (rFilm != 0) ? pFilm.y / rFilm : 0; + Float cosTheta = (rFilm != 0) ? pFilm.x / rFilm : 1; + return {cosTheta * pLens.x - sinTheta * pLens.y, + sinTheta * pLens.x + cosTheta * pLens.y, LensRearZ()}; +} + +CameraRay RealisticCamera::GenerateRay(CameraSample sample, + SampledWavelengths &lambda) const { + // Find point on film, _pFilm_, corresponding to _sample.pFilm_ + // Compute Film's physical extent + Float aspect = (Float)film.FullResolution().y / (Float)film.FullResolution().x; + Float diagonal = FilmDiagonal(); + Float x = std::sqrt(diagonal * diagonal / (1 + aspect * aspect)); + Float y = aspect * x; + Bounds2f physicalExtent(Point2f(-x / 2, -y / 2), Point2f(x / 2, y / 2)); + + Point2f s(sample.pFilm.x / film.FullResolution().x, + sample.pFilm.y / film.FullResolution().y); + Point2f pFilm2 = physicalExtent.Lerp(s); + Point3f pFilm(-pFilm2.x, pFilm2.y, 0); + + // Trace ray from _pFilm_ through lens system + Float exitPupilBoundsArea; + Point3f pRear = + SampleExitPupil(Point2f(pFilm.x, pFilm.y), sample.pLens, &exitPupilBoundsArea); + Ray rFilm(pFilm, pRear - pFilm); + Ray ray; + Float weight = TraceLensesFromFilm(rFilm, &ray, lambda[0]); + if (weight == 0) + return CameraRay{Ray(), SampledSpectrum(0.f)}; + + // Finish initialization of _RealisticCamera_ ray + ray.time = SampleTime(sample.time); + ray.medium = medium; + ray = RenderFromCamera(ray); + ray.d = Normalize(ray.d); + + // Terminate secondary rays if lenses are dispersive + if (dispersionFactor != 0) + lambda.TerminateSecondary(); + + // Compute weighting for _RealisticCamera_ ray + Float cosTheta = Normalize(rFilm.d).z; + Float cos4Theta = (cosTheta * cosTheta) * (cosTheta * cosTheta); + weight *= (shutterClose - shutterOpen) * (cos4Theta * exitPupilBoundsArea) / + (LensRearZ() * LensRearZ()); + + return CameraRay{ray, SampledSpectrum(weight)}; +} + +STAT_PERCENT("Camera/Rays vignetted by lens system", vignettedRays, totalRays); + +std::string RealisticCamera::LensElementInterface::ToString() const { + return StringPrintf("[ LensElementInterface curvatureRadius: %f thickness: %f " + "eta: %f apertureRadius: %f ]", + curvatureRadius, thickness, eta, apertureRadius); +} + +bool RealisticCamera::TraceLensesFromScene(const Ray &rCamera, Ray *rOut) const { + Float elementZ = -LensFrontZ(); + // Transform _rCamera_ from camera to lens system space + const Transform LensFromCamera = Scale(1, 1, -1); + Ray rLens = LensFromCamera(rCamera); + for (size_t i = 0; i < elementInterfaces.size(); ++i) { + const LensElementInterface &element = elementInterfaces[i]; + // Compute intersection of ray with lens element + Float t; + Normal3f n; + bool isStop = (element.curvatureRadius == 0); + if (isStop) + t = (elementZ - rLens.o.z) / rLens.d.z; + else { + Float radius = element.curvatureRadius; + Float zCenter = elementZ + element.curvatureRadius; + if (!IntersectSphericalElement(radius, zCenter, rLens, &t, &n)) + return false; + } + CHECK_GE(t, 0); + + // Test intersection point against element aperture + // Don't worry about the aperture image here. + Point3f pHit = rLens(t); + Float r2 = pHit.x * pHit.x + pHit.y * pHit.y; + if (r2 > element.apertureRadius * element.apertureRadius) + return false; + rLens.o = pHit; + + // Update ray path for from-scene element interface interaction + if (!isStop) { + Vector3f wt; + Float eta_i = (i == 0 || elementInterfaces[i - 1].eta == 0) + ? 1 + : elementInterfaces[i - 1].eta; + Float eta_t = (elementInterfaces[i].eta != 0) ? elementInterfaces[i].eta : 1; + if (!Refract(Normalize(-rLens.d), n, eta_t / eta_i, &wt)) + return false; + rLens.d = wt; + } + elementZ += element.thickness; + } + // Transform _rLens_ from lens system space back to camera space + if (rOut != nullptr) { + const Transform LensToCamera = Scale(1, 1, -1); + *rOut = LensToCamera(rLens); + } + return true; +} + +void RealisticCamera::DrawLensSystem() const { + Float sumz = -LensFrontZ(); + Float z = sumz; + for (size_t i = 0; i < elementInterfaces.size(); ++i) { + const LensElementInterface &element = elementInterfaces[i]; + Float r = element.curvatureRadius; + if (r == 0) { + // stop + printf("{Thick, Line[{{%f, %f}, {%f, %f}}], ", z, element.apertureRadius, z, + 2 * element.apertureRadius); + printf("Line[{{%f, %f}, {%f, %f}}]}, ", z, -element.apertureRadius, z, + -2 * element.apertureRadius); + } else { + Float theta = std::abs(SafeASin(element.apertureRadius / r)); + if (r > 0) { + // convex as seen from front of lens + Float t0 = Pi - theta; + Float t1 = Pi + theta; + printf("Circle[{%f, 0}, %f, {%f, %f}], ", z + r, r, t0, t1); + } else { + // concave as seen from front of lens + Float t0 = -theta; + Float t1 = theta; + printf("Circle[{%f, 0}, %f, {%f, %f}], ", z + r, -r, t0, t1); + } + if (element.eta != 0 && element.eta != 1) { + // connect top/bottom to next element + CHECK_LT(i + 1, elementInterfaces.size()); + Float nextApertureRadius = elementInterfaces[i + 1].apertureRadius; + Float h = std::max(element.apertureRadius, nextApertureRadius); + Float hlow = std::min(element.apertureRadius, nextApertureRadius); + + Float zp0, zp1; + if (r > 0) { + zp0 = z + element.curvatureRadius - + element.apertureRadius / std::tan(theta); + } else { + zp0 = z + element.curvatureRadius + + element.apertureRadius / std::tan(theta); + } + + Float nextCurvatureRadius = elementInterfaces[i + 1].curvatureRadius; + Float nextTheta = + std::abs(SafeASin(nextApertureRadius / nextCurvatureRadius)); + if (nextCurvatureRadius > 0) { + zp1 = z + element.thickness + nextCurvatureRadius - + nextApertureRadius / std::tan(nextTheta); + } else { + zp1 = z + element.thickness + nextCurvatureRadius + + nextApertureRadius / std::tan(nextTheta); + } + + // Connect tops + printf("Line[{{%f, %f}, {%f, %f}}], ", zp0, h, zp1, h); + printf("Line[{{%f, %f}, {%f, %f}}], ", zp0, -h, zp1, -h); + + // vertical lines when needed to close up the element profile + if (element.apertureRadius < nextApertureRadius) { + printf("Line[{{%f, %f}, {%f, %f}}], ", zp0, h, zp0, hlow); + printf("Line[{{%f, %f}, {%f, %f}}], ", zp0, -h, zp0, -hlow); + } else if (element.apertureRadius > nextApertureRadius) { + printf("Line[{{%f, %f}, {%f, %f}}], ", zp1, h, zp1, hlow); + printf("Line[{{%f, %f}, {%f, %f}}], ", zp1, -h, zp1, -hlow); + } + } + } + z += element.thickness; + } + + // 24mm height for 35mm film + printf("Line[{{0, -.012}, {0, .012}}], "); + // optical axis + printf("Line[{{0, 0}, {%f, 0}}] ", 1.2f * sumz); +} + +void RealisticCamera::DrawRayPathFromFilm(const Ray &r, bool arrow, + bool toOpticalIntercept) const { + Float elementZ = 0; + // Transform _ray_ from camera to lens system space + static const Transform LensFromCamera = Scale(1, 1, -1); + Ray ray = LensFromCamera(r); + printf("{ "); + if (TraceLensesFromFilm(r, nullptr) == 0) { + printf("Dashed, RGBColor[.8, .5, .5]"); + } else + printf("RGBColor[.5, .5, .8]"); + + for (int i = elementInterfaces.size() - 1; i >= 0; --i) { + const LensElementInterface &element = elementInterfaces[i]; + elementZ -= element.thickness; + bool isStop = (element.curvatureRadius == 0); + // Compute intersection of ray with lens element + Float t; + Normal3f n; + if (isStop) + t = -(ray.o.z - elementZ) / ray.d.z; + else { + Float radius = element.curvatureRadius; + Float zCenter = elementZ + element.curvatureRadius; + if (!IntersectSphericalElement(radius, zCenter, ray, &t, &n)) + goto done; + } + CHECK_GE(t, 0); + + printf(", Line[{{%f, %f}, {%f, %f}}]", ray.o.z, ray.o.x, ray(t).z, ray(t).x); + + // Test intersection point against element aperture + Point3f pHit = ray(t); + Float r2 = pHit.x * pHit.x + pHit.y * pHit.y; + Float apertureRadius2 = element.apertureRadius * element.apertureRadius; + if (r2 > apertureRadius2) + goto done; + ray.o = pHit; + + // Update ray path for element interface interaction + if (!isStop) { + Vector3f wt; + Float eta_i = element.eta; + Float eta_t = (i > 0 && elementInterfaces[i - 1].eta != 0) + ? elementInterfaces[i - 1].eta + : 1; + if (!Refract(Normalize(-ray.d), n, eta_t / eta_i, &wt)) + goto done; + ray.d = wt; + } + } + + ray.d = Normalize(ray.d); + { + Float ta = std::abs(elementZ / 4); + if (toOpticalIntercept) { + ta = -ray.o.x / ray.d.x; + printf(", Point[{%f, %f}]", ray(ta).z, ray(ta).x); + } + printf(", %s[{{%f, %f}, {%f, %f}}]", arrow ? "Arrow" : "Line", ray.o.z, ray.o.x, + ray(ta).z, ray(ta).x); + + // overdraw the optical axis if needed... + if (toOpticalIntercept) + printf(", Line[{{%f, 0}, {%f, 0}}]", ray.o.z, ray(ta).z * 1.05f); + } + +done: + printf("}"); +} + +void RealisticCamera::DrawRayPathFromScene(const Ray &r, bool arrow, + bool toOpticalIntercept) const { + Float elementZ = LensFrontZ() * -1; + + // Transform _ray_ from camera to lens system space + static const Transform LensFromCamera = Scale(1, 1, -1); + Ray ray = LensFromCamera(r); + for (size_t i = 0; i < elementInterfaces.size(); ++i) { + const LensElementInterface &element = elementInterfaces[i]; + bool isStop = (element.curvatureRadius == 0); + // Compute intersection of ray with lens element + Float t; + Normal3f n; + if (isStop) + t = -(ray.o.z - elementZ) / ray.d.z; + else { + Float radius = element.curvatureRadius; + Float zCenter = elementZ + element.curvatureRadius; + if (!IntersectSphericalElement(radius, zCenter, ray, &t, &n)) + return; + } + CHECK_GE(t, 0.f); + + printf("Line[{{%f, %f}, {%f, %f}}],", ray.o.z, ray.o.x, ray(t).z, ray(t).x); + + // Test intersection point against element aperture + Point3f pHit = ray(t); + Float r2 = pHit.x * pHit.x + pHit.y * pHit.y; + Float apertureRadius2 = element.apertureRadius * element.apertureRadius; + if (r2 > apertureRadius2) + return; + ray.o = pHit; + + // Update ray path for from-scene element interface interaction + if (!isStop) { + Vector3f wt; + Float eta_i = (i == 0 || elementInterfaces[i - 1].eta == 0.f) + ? 1.f + : elementInterfaces[i - 1].eta; + Float eta_t = + (elementInterfaces[i].eta != 0.f) ? elementInterfaces[i].eta : 1.f; + if (!Refract(Normalize(-ray.d), n, eta_t / eta_i, &wt)) + return; + ray.d = wt; + } + elementZ += element.thickness; + } + + // go to the film plane by default + { + Float ta = -ray.o.z / ray.d.z; + if (toOpticalIntercept) { + ta = -ray.o.x / ray.d.x; + printf("Point[{%f, %f}], ", ray(ta).z, ray(ta).x); + } + printf("%s[{{%f, %f}, {%f, %f}}]", arrow ? "Arrow" : "Line", ray.o.z, ray.o.x, + ray(ta).z, ray(ta).x); + } +} + +void RealisticCamera::RenderExitPupil(Float sx, Float sy, const char *filename) const { + Point3f pFilm(sx, sy, 0); + + const int nSamples = 2048; + Image image(PixelFormat::Float, {nSamples, nSamples}, {"Y"}); + + for (int y = 0; y < nSamples; ++y) { + Float fy = (Float)y / (Float)(nSamples - 1); + Float ly = Lerp(fy, -RearElementRadius(), RearElementRadius()); + for (int x = 0; x < nSamples; ++x) { + Float fx = (Float)x / (Float)(nSamples - 1); + Float lx = Lerp(fx, -RearElementRadius(), RearElementRadius()); + + Point3f pRear(lx, ly, LensRearZ()); + + if (lx * lx + ly * ly > RearElementRadius() * RearElementRadius()) + image.SetChannel({x, y}, 0, 1.); + else if (TraceLensesFromFilm(Ray(pFilm, pRear - pFilm), nullptr)) + image.SetChannel({x, y}, 0, 0.5); + else + image.SetChannel({x, y}, 0, 0.); + } + } + + image.Write(filename); +} + +void RealisticCamera::TestExitPupilBounds() const { + Float filmDiagonal = FilmDiagonal(); + + static RNG rng; + + Float u = rng.Uniform(); + Point3f pFilm(u * filmDiagonal / 2, 0, 0); + + Float r = pFilm.x / (filmDiagonal / 2); + int pupilIndex = std::min(exitPupilBounds.size() - 1, + std::floor(r * (exitPupilBounds.size() - 1))); + Bounds2f pupilBounds = exitPupilBounds[pupilIndex]; + if (pupilIndex + 1 < (int)exitPupilBounds.size()) + pupilBounds = Union(pupilBounds, exitPupilBounds[pupilIndex + 1]); + + // Now, randomly pick points on the aperture and see if any are outside + // of pupil bounds... + for (int i = 0; i < 1000; ++i) { + Point2f u2{rng.Uniform(), rng.Uniform()}; + Point2f pd = SampleUniformDiskConcentric(u2); + pd *= RearElementRadius(); + + Ray testRay(pFilm, Point3f(pd.x, pd.y, 0.f) - pFilm); + Ray testOut; + if (!TraceLensesFromFilm(testRay, &testOut)) + continue; + + if (!Inside(pd, pupilBounds)) { + fprintf(stderr, + "Aha! (%f,%f) went through, but outside bounds (%f,%f) - " + "(%f,%f)\n", + pd.x, pd.y, pupilBounds.pMin[0], pupilBounds.pMin[1], + pupilBounds.pMax[0], pupilBounds.pMax[1]); + RenderExitPupil( + (Float)pupilIndex / exitPupilBounds.size() * filmDiagonal / 2.f, 0.f, + "low.exr"); + RenderExitPupil( + (Float)(pupilIndex + 1) / exitPupilBounds.size() * filmDiagonal / 2.f, + 0.f, "high.exr"); + RenderExitPupil(pFilm.x, 0.f, "mid.exr"); + exit(0); + } + } + fprintf(stderr, "."); +} + +std::string RealisticCamera::ToString() const { + return StringPrintf("[ RealisticCamera %s dispersionFactor: %f " + "elementInterfaces: %s exitPupilBounds: %s ]", + CameraBase::ToString(), dispersionFactor, elementInterfaces, + exitPupilBounds); +} + +RealisticCamera *RealisticCamera::Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc) { + Float shutteropen = parameters.GetOneFloat("shutteropen", 0.f); + Float shutterclose = parameters.GetOneFloat("shutterclose", 1.f); + if (shutterclose < shutteropen) { + Warning(loc, "Shutter close time %f < shutter open %f. Swapping them.", + shutterclose, shutteropen); + pstd::swap(shutterclose, shutteropen); + } + + // Realistic camera-specific parameters + std::string lensFile = ResolveFilename(parameters.GetOneString("lensfile", "")); + Float apertureDiameter = parameters.GetOneFloat("aperturediameter", 1.0); + Float focusDistance = parameters.GetOneFloat("focusdistance", 10.0); + Float dispersionFactor = parameters.GetOneFloat("dispersionfactor", 0.); + Float scale = parameters.GetOneFloat("scale", 1.f); + + if (lensFile.empty()) { + Error(loc, "No lens description file supplied!"); + return nullptr; + } + // Load element data from lens description file + std::vector lensData = ReadFloatFile(lensFile); + if (lensData.empty()) { + Error(loc, "Error reading lens specification file \"%s\".", lensFile); + return nullptr; + } + if (lensData.size() % 4 != 0) { + Error(loc, + "%s: excess values in lens specification file; " + "must be multiple-of-four values, read %d.", + lensFile, (int)lensData.size()); + return nullptr; + } + + int builtinRes = 256; + auto rasterize = [&](pstd::span vert) { + Image image(PixelFormat::Float, {builtinRes, builtinRes}, {"Y"}, nullptr, alloc); + + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) { + Point2f p(-1 + 2 * (x + 0.5f) / image.Resolution().x, + -1 + 2 * (y + 0.5f) / image.Resolution().y); + int windingNumber = 0; + // Test against edges + for (int i = 0; i < vert.size(); ++i) { + int i1 = (i + 1) % vert.size(); + Float e = (p[0] - vert[i][0]) * (vert[i1][1] - vert[i][1]) - + (p[1] - vert[i][1]) * (vert[i1][0] - vert[i][0]); + if (vert[i].y <= p.y) { + if (vert[i1].y > p.y && e > 0) + ++windingNumber; + } else if (vert[i1].y <= p.y && e < 0) + --windingNumber; + } + + image.SetChannel({x, y}, 0, windingNumber == 0 ? 0.f : 1.f); + } + + return image; + }; + + std::string apertureName = ResolveFilename(parameters.GetOneString("aperture", "")); + Image apertureImage; + if (!apertureName.empty()) { + // built-in diaphragm shapes + if (apertureName == "gaussian") { + apertureImage = Image(PixelFormat::Float, {builtinRes, builtinRes}, {"Y"}, + nullptr, alloc); + for (int y = 0; y < apertureImage.Resolution().y; ++y) + for (int x = 0; x < apertureImage.Resolution().x; ++x) { + Point2f uv(-1 + 2 * (x + 0.5f) / apertureImage.Resolution().x, + -1 + 2 * (y + 0.5f) / apertureImage.Resolution().y); + Float r2 = Sqr(uv.x) + Sqr(uv.y); + Float sigma2 = 1; + Float v = std::max( + 0, std::exp(-r2 / sigma2) - std::exp(-1 / sigma2)); + apertureImage.SetChannel({x, y}, 0, v); + } + } else if (apertureName == "square") { + apertureImage = Image(PixelFormat::Float, {builtinRes, builtinRes}, {"Y"}, + nullptr, alloc); + for (int y = 0; y < apertureImage.Resolution().y; ++y) + for (int x = 0; x < apertureImage.Resolution().x; ++x) + apertureImage.SetChannel({x, y}, 0, 1.f); + } else if (apertureName == "pentagon") { + // https://mathworld.wolfram.com/RegularPentagon.html + Float c1 = (std::sqrt(5.f) - 1) / 4; + Float c2 = (std::sqrt(5.f) + 1) / 4; + Float s1 = std::sqrt(10.f + 2.f * std::sqrt(5.f)) / 4; + Float s2 = std::sqrt(10.f - 2.f * std::sqrt(5.f)) / 4; + // Vertices in CW order. + Point2f vert[5] = {Point2f(0, 1), {s1, c1}, {s2, -c2}, {-s2, -c2}, {-s1, c1}}; + // Scale down slightly + for (int i = 0; i < 5; ++i) + vert[i] *= .8f; + apertureImage = rasterize(vert); + } else if (apertureName == "star") { + // 5-sided. Vertices are two pentagons--inner and outer radius + pstd::array vert; + for (int i = 0; i < 10; ++i) { + // inner radius: https://math.stackexchange.com/a/2136996 + Float r = + (i & 1) ? 1.f : (std::cos(Radians(72.f)) / std::cos(Radians(36.f))); + vert[i] = Point2f(r * std::cos(Pi * i / 5.f), r * std::sin(Pi * i / 5.f)); + } + std::reverse(vert.begin(), vert.end()); + apertureImage = rasterize(vert); + } else { + ImageAndMetadata im = Image::Read(apertureName, alloc); + apertureImage = std::move(im.image); + if (apertureImage.NChannels() > 1) { + ImageChannelDesc rgbDesc = apertureImage.GetChannelDesc({"R", "G", "B"}); + if (!rgbDesc) + ErrorExit("%s: didn't find R, G, B channels to average for " + "aperture image.", + apertureName); + + Image mono(PixelFormat::Float, apertureImage.Resolution(), {"Y"}, nullptr, + alloc); + for (int y = 0; y < mono.Resolution().y; ++y) + for (int x = 0; x < mono.Resolution().x; ++x) { + Float avg = apertureImage.GetChannels({x, y}, rgbDesc).Average(); + mono.SetChannel({x, y}, 0, avg); + } + + apertureImage = std::move(mono); + } + } + + if (apertureImage) { + // Normalize it so that brightness matches a circular aperture + Float sum = 0; + for (int y = 0; y < apertureImage.Resolution().y; ++y) + for (int x = 0; x < apertureImage.Resolution().x; ++x) + sum += apertureImage.GetChannel({x, y}, 0); + Float avg = + sum / (apertureImage.Resolution().x * apertureImage.Resolution().y); + + Float scale = (Pi / 4) / avg; + for (int y = 0; y < apertureImage.Resolution().y; ++y) + for (int x = 0; x < apertureImage.Resolution().x; ++x) + apertureImage.SetChannel({x, y}, 0, + apertureImage.GetChannel({x, y}, 0) * scale); + } + } + + return alloc.new_object( + cameraTransform, shutteropen, shutterclose, apertureDiameter, focusDistance, + dispersionFactor, lensData, scale, film, medium, std::move(apertureImage), alloc); +} + +} // namespace pbrt diff --git a/src/pbrt/cameras.h b/src/pbrt/cameras.h new file mode 100644 index 00000000..02a7f311 --- /dev/null +++ b/src/pbrt/cameras.h @@ -0,0 +1,547 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_CAMERAS_H +#define PBRT_CAMERAS_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace pbrt { + +// CameraTransform Definition +class CameraTransform { + public: + // CameraTransform Public Methods + CameraTransform() = default; + explicit CameraTransform(const AnimatedTransform &worldFromCamera); + + PBRT_CPU_GPU + Point3f RenderFromCamera(const Point3f &p, Float time) const { + return renderFromCamera(p, time); + } + PBRT_CPU_GPU + Point3f CameraFromRender(const Point3f &p, Float time) const { + return renderFromCamera.ApplyInverse(p, time); + } + PBRT_CPU_GPU + Point3f RenderFromWorld(const Point3f &p) const { + return worldFromRender.ApplyInverse(p); + } + + PBRT_CPU_GPU + Transform RenderFromWorld() const { return Inverse(worldFromRender); } + PBRT_CPU_GPU + Transform CameraFromRender(Float time) const { + return Inverse(renderFromCamera.Interpolate(time)); + } + PBRT_CPU_GPU + Transform CameraFromWorld(Float time) const { + return Inverse(worldFromRender * renderFromCamera.Interpolate(time)); + } + + PBRT_CPU_GPU + bool CameraFromRenderHasScale() const { return renderFromCamera.HasScale(); } + + PBRT_CPU_GPU + Vector3f RenderFromCamera(const Vector3f &v, Float time) const { + return renderFromCamera(v, time); + } + + PBRT_CPU_GPU + Ray RenderFromCamera(const Ray &r) const { return renderFromCamera(r); } + + PBRT_CPU_GPU + RayDifferential RenderFromCamera(const RayDifferential &r) const { + return renderFromCamera(r); + } + + PBRT_CPU_GPU + Vector3f CameraFromRender(const Vector3f &v, Float time) const { + return renderFromCamera.ApplyInverse(v, time); + } + + std::string ToString() const; + + private: + // CameraTransform Private Members + AnimatedTransform renderFromCamera; + Transform worldFromRender; +}; + +// CameraWiSample Definition +struct CameraWiSample { + public: + CameraWiSample() = default; + PBRT_CPU_GPU + CameraWiSample(const SampledSpectrum &Wi, const Vector3f &wi, Float pdf, + Point2f pRaster, const Interaction &pRef, const Interaction &pLens) + : Wi(Wi), wi(wi), pdf(pdf), pRaster(pRaster), pRef(pRef), pLens(pLens) {} + + SampledSpectrum Wi; + Vector3f wi; + Float pdf; + Point2f pRaster; + Interaction pRef, pLens; +}; + +// CameraRay Definition +struct CameraRay { + Ray ray; + SampledSpectrum weight = SampledSpectrum(1); +}; + +// CameraRayDifferential Definition +struct CameraRayDifferential { + RayDifferential ray; + SampledSpectrum weight = SampledSpectrum(1); +}; + +// CameraBase Definition +class CameraBase { + public: + // CameraBase Public Methods + PBRT_CPU_GPU + FilmHandle GetFilm() const { return film; } + PBRT_CPU_GPU + const CameraTransform &GetCameraTransform() const { return cameraTransform; } + + PBRT_CPU_GPU + Float SampleTime(Float u) const { return Lerp(u, shutterOpen, shutterClose); } + + PBRT_CPU_GPU + void ApproximatedPdxy(const SurfaceInteraction &si) const; + void InitMetadata(ImageMetadata *metadata) const; + std::string ToString() const; + + protected: + // CameraBase Protected Members + CameraTransform cameraTransform; + Float shutterOpen, shutterClose; + FilmHandle film; + MediumHandle medium; + Vector3f minPosDifferentialX, minPosDifferentialY; + Vector3f minDirDifferentialX, minDirDifferentialY; + + // CameraBase Protected Methods + CameraBase() = default; + CameraBase(const CameraTransform &cameraTransform, Float shutterOpen, + Float shutterClose, FilmHandle film, MediumHandle medium); + + PBRT_CPU_GPU + static pstd::optional GenerateRayDifferential( + CameraHandle camera, const CameraSample &sample, SampledWavelengths &lambda); + + PBRT_CPU_GPU + Ray RenderFromCamera(const Ray &r) const { + return cameraTransform.RenderFromCamera(r); + } + PBRT_CPU_GPU + RayDifferential RenderFromCamera(const RayDifferential &r) const { + return cameraTransform.RenderFromCamera(r); + } + + PBRT_CPU_GPU + Vector3f RenderFromCamera(const Vector3f &v, Float time) const { + return cameraTransform.RenderFromCamera(v, time); + } + + PBRT_CPU_GPU + Point3f RenderFromCamera(const Point3f &p, Float time) const { + return cameraTransform.RenderFromCamera(p, time); + } + + PBRT_CPU_GPU + Vector3f CameraFromRender(const Vector3f &v, Float time) const { + return cameraTransform.CameraFromRender(v, time); + } + + PBRT_CPU_GPU + Point3f CameraFromRender(const Point3f &p, Float time) const { + return cameraTransform.CameraFromRender(p, time); + } + + void FindMinimumDifferentials(CameraHandle camera); +}; + +// ProjectiveCamera Definition +class ProjectiveCamera : public CameraBase { + public: + // ProjectiveCamera Public Methods + ProjectiveCamera() = default; + void InitMetadata(ImageMetadata *metadata) const; + + std::string BaseToString() const; + + ProjectiveCamera(const CameraTransform &cameraTransform, + const Transform &screenFromCamera, const Bounds2f &screenWindow, + Float shutterOpen, Float shutterClose, Float lensRadius, + Float focalDistance, FilmHandle film, MediumHandle medium) + : CameraBase(cameraTransform, shutterOpen, shutterClose, film, medium), + screenFromCamera(screenFromCamera), + lensRadius(lensRadius), + focalDistance(focalDistance) { + // Compute projective camera transformations + // Compute projective camera screen transformations + rasterFromScreen = + Scale(film.FullResolution().x, film.FullResolution().y, 1) * + Scale(1 / (screenWindow.pMax.x - screenWindow.pMin.x), + 1 / (screenWindow.pMin.y - screenWindow.pMax.y), 1) * + Translate(Vector3f(-screenWindow.pMin.x, -screenWindow.pMax.y, 0)); + screenFromRaster = Inverse(rasterFromScreen); + + cameraFromRaster = Inverse(screenFromCamera) * screenFromRaster; + } + + // ProjectiveCamera Protected Members + Transform screenFromCamera, cameraFromRaster; + Transform rasterFromScreen, screenFromRaster; + Float lensRadius, focalDistance; +}; + +// OrthographicCamera Definition +class OrthographicCamera : public ProjectiveCamera { + public: + // OrthographicCamera Public Methods + OrthographicCamera(const CameraTransform &cameraTransform, + const Bounds2f &screenWindow, Float shutterOpen, + Float shutterClose, Float lensRadius, Float focalDistance, + FilmHandle film, MediumHandle medium) + : ProjectiveCamera(cameraTransform, Orthographic(0, 1), screenWindow, shutterOpen, + shutterClose, lensRadius, focalDistance, film, medium) { + // Compute differential changes in origin for orthographic camera rays + dxCamera = cameraFromRaster(Vector3f(1, 0, 0)); + dyCamera = cameraFromRaster(Vector3f(0, 1, 0)); + minDirDifferentialX = minDirDifferentialY = Vector3f(0, 0, 0); + minPosDifferentialX = dxCamera; + minPosDifferentialY = dyCamera; + } + + PBRT_CPU_GPU + CameraRay GenerateRay(CameraSample sample, SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + pstd::optional GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const; + + static OrthographicCamera *Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc = {}); + + PBRT_CPU_GPU + SampledSpectrum We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2 = nullptr) const { + LOG_FATAL("We() unimplemented for OrthographicCamera"); + return {}; + } + + PBRT_CPU_GPU + void PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const { + LOG_FATAL("PDF_We() unimplemented for OrthographicCamera"); + } + + PBRT_CPU_GPU + pstd::optional SampleWi(const Interaction &ref, const Point2f &sample, + SampledWavelengths &lambda) const { + LOG_FATAL("SampleWi() unimplemented for OrthographicCamera"); + return {}; + } + + std::string ToString() const; + + private: + // OrthographicCamera Private Members + Vector3f dxCamera, dyCamera; +}; + +// PerspectiveCamera Definition +class PerspectiveCamera : public ProjectiveCamera { + public: + // PerspectiveCamera Public Methods + PerspectiveCamera(const CameraTransform &cameraTransform, + const Bounds2f &screenWindow, Float shutterOpen, Float shutterClose, + Float lensRadius, Float focalDistance, Float fov, FilmHandle film, + MediumHandle medium) + : ProjectiveCamera(cameraTransform, Perspective(fov, 1e-2f, 1000.f), screenWindow, + shutterOpen, shutterClose, lensRadius, focalDistance, film, + medium) { + // Compute differential changes in origin for perspective camera rays + dxCamera = + (cameraFromRaster(Point3f(1, 0, 0)) - cameraFromRaster(Point3f(0, 0, 0))); + dyCamera = + (cameraFromRaster(Point3f(0, 1, 0)) - cameraFromRaster(Point3f(0, 0, 0))); + + // Compute _cosTotalWidth_ for perspective camera + Point2f radius = Point2f(film.GetFilter().Radius()); + Point3f pCornerRaster(-radius.x, -radius.y, 0.f); + Vector3f wCornerCamera = Normalize(Vector3f(cameraFromRaster(pCornerRaster))); + cosTotalWidth = wCornerCamera.z; + DCHECK_LT(.9999 * cosTotalWidth, std::cos(Radians(fov / 2))); + + // Compute image plane bounds at $z=1$ for _PerspectiveCamera_ + Point2i res = film.FullResolution(); + Point3f pMin = cameraFromRaster(Point3f(0, 0, 0)); + Point3f pMax = cameraFromRaster(Point3f(res.x, res.y, 0)); + pMin /= pMin.z; + pMax /= pMax.z; + A = std::abs((pMax.x - pMin.x) * (pMax.y - pMin.y)); + + FindMinimumDifferentials(this); + } + + PerspectiveCamera() = default; + + static PerspectiveCamera *Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc = {}); + + PBRT_CPU_GPU + CameraRay GenerateRay(CameraSample sample, SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + pstd::optional GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + SampledSpectrum We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2 = nullptr) const; + PBRT_CPU_GPU + void PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const; + PBRT_CPU_GPU + pstd::optional SampleWi(const Interaction &ref, const Point2f &sample, + SampledWavelengths &lambda) const; + + std::string ToString() const; + + private: + // PerspectiveCamera Private Members + Float cosTotalWidth; + Vector3f dxCamera, dyCamera; + Float A; +}; + +// SphericalCamera Definition +class SphericalCamera : public CameraBase { + public: + // SphericalCamera::Mapping Definition + enum Mapping { EquiRect, EquiArea }; + + // SphericalCamera Public Methods + SphericalCamera(const CameraTransform &cameraTransform, Float shutterOpen, + Float shutterClose, FilmHandle film, MediumHandle medium, + Mapping mapping) + : CameraBase(cameraTransform, shutterOpen, shutterClose, film, medium), + mapping(mapping) { + FindMinimumDifferentials(this); + } + + static SphericalCamera *Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc = {}); + + PBRT_CPU_GPU + CameraRay GenerateRay(CameraSample sample, SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + pstd::optional GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const { + return CameraBase::GenerateRayDifferential(this, sample, lambda); + } + + PBRT_CPU_GPU + SampledSpectrum We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2 = nullptr) const { + LOG_FATAL("We() unimplemented for SphericalCamera"); + return {}; + } + + PBRT_CPU_GPU + void PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const { + LOG_FATAL("PDF_We() unimplemented for SphericalCamera"); + } + + PBRT_CPU_GPU + pstd::optional SampleWi(const Interaction &ref, const Point2f &sample, + SampledWavelengths &lambda) const { + LOG_FATAL("SampleWi() unimplemented for SphericalCamera"); + return {}; + } + + std::string ToString() const; + + private: + // SphericalCamera Private Members + Mapping mapping; +}; + +// RealisticCamera Definition +class RealisticCamera : public CameraBase { + public: + // RealisticCamera Public Methods + RealisticCamera(const CameraTransform &cameraTransform, Float shutterOpen, + Float shutterClose, Float apertureDiameter, Float focusDistance, + Float dispersionFactor, std::vector &lensData, Float scale, + FilmHandle film, MediumHandle medium, Image apertureImage, + Allocator alloc); + + static RealisticCamera *Create(const ParameterDictionary ¶meters, + const CameraTransform &cameraTransform, + FilmHandle film, MediumHandle medium, + const FileLoc *loc, Allocator alloc = {}); + + PBRT_CPU_GPU + CameraRay GenerateRay(CameraSample sample, SampledWavelengths &lambda) const; + + PBRT_CPU_GPU + pstd::optional GenerateRayDifferential( + const CameraSample &sample, SampledWavelengths &lambda) const { + return CameraBase::GenerateRayDifferential(this, sample, lambda); + } + + PBRT_CPU_GPU + SampledSpectrum We(const Ray &ray, SampledWavelengths &lambda, + Point2f *pRaster2 = nullptr) const { + LOG_FATAL("We() unimplemented for RealisticCamera"); + return {}; + } + + PBRT_CPU_GPU + void PDF_We(const Ray &ray, Float *pdfPos, Float *pdfDir) const { + LOG_FATAL("PDF_We() unimplemented for RealisticCamera"); + } + + PBRT_CPU_GPU + pstd::optional SampleWi(const Interaction &ref, const Point2f &sample, + SampledWavelengths &lambda) const { + LOG_FATAL("SampleWi() unimplemented for RealisticCamera"); + return {}; + } + + std::string ToString() const; + + private: + // RealisticCamera Private Declarations + struct LensElementInterface { + Float curvatureRadius; + Float thickness; + Float eta; + Float apertureRadius; + std::string ToString() const; + }; + + // RealisticCamera Private Methods + PBRT_CPU_GPU + Float LensRearZ() const { return elementInterfaces.back().thickness; } + + PBRT_CPU_GPU + Float LensFrontZ() const { + Float zSum = 0; + for (const LensElementInterface &element : elementInterfaces) + zSum += element.thickness; + return zSum; + } + + PBRT_CPU_GPU + Float RearElementRadius() const { return elementInterfaces.back().apertureRadius; } + + PBRT_CPU_GPU + Float TraceLensesFromFilm(const Ray &rCamera, Ray *rOut, Float lambda = 550) const; + + PBRT_CPU_GPU + static bool IntersectSphericalElement(Float radius, Float zCenter, const Ray &ray, + Float *t, Normal3f *n) { + // Compute _t0_ and _t1_ for ray--element intersection + Point3f o = ray.o - Vector3f(0, 0, zCenter); + Float A = ray.d.x * ray.d.x + ray.d.y * ray.d.y + ray.d.z * ray.d.z; + Float B = 2 * (ray.d.x * o.x + ray.d.y * o.y + ray.d.z * o.z); + Float C = o.x * o.x + o.y * o.y + o.z * o.z - radius * radius; + Float t0, t1; + if (!Quadratic(A, B, C, &t0, &t1)) + return false; + + // Select intersection $t$ based on ray direction and element curvature + bool useCloserT = (ray.d.z > 0) ^ (radius < 0); + *t = useCloserT ? std::min(t0, t1) : std::max(t0, t1); + if (*t < 0) + return false; + + // Compute surface normal of element at ray intersection point + *n = Normal3f(Vector3f(o + *t * ray.d)); + *n = FaceForward(Normalize(*n), -ray.d); + + return true; + } + + PBRT_CPU_GPU + bool TraceLensesFromScene(const Ray &rCamera, Ray *rOut) const; + + PBRT_CPU_GPU + Float FilmDiagonal() const { return film.Diagonal() * scale; } + + void DrawLensSystem() const; + void DrawRayPathFromFilm(const Ray &r, bool arrow, bool toOpticalIntercept) const; + void DrawRayPathFromScene(const Ray &r, bool arrow, bool toOpticalIntercept) const; + + static void ComputeCardinalPoints(const Ray &rIn, const Ray &rOut, Float *p, + Float *f); + void ComputeThickLensApproximation(Float pz[2], Float f[2]) const; + Float FocusThickLens(Float focusDistance); + Float FocusBinarySearch(Float focusDistance); + Float FocusDistance(Float filmDist); + Bounds2f BoundExitPupil(Float filmX0, Float filmX1) const; + void RenderExitPupil(Float sx, Float sy, const char *filename) const; + + PBRT_CPU_GPU + Point3f SampleExitPupil(const Point2f &pFilm, const Point2f &lensSample, + Float *sampleBoundsArea) const; + + void TestExitPupilBounds() const; + + // RealisticCamera Private Members + Float scale; + Float dispersionFactor; + Image apertureImage; + pstd::vector elementInterfaces; + pstd::vector exitPupilBounds; +}; + +inline CameraRay CameraHandle::GenerateRay(CameraSample sample, + SampledWavelengths &lambda) const { + auto generate = [&](auto ptr) { return ptr->GenerateRay(sample, lambda); }; + return Dispatch(generate); +} + +inline FilmHandle CameraHandle::GetFilm() const { + auto getfilm = [&](auto ptr) { return ptr->GetFilm(); }; + return Dispatch(getfilm); +} + +inline Float CameraHandle::SampleTime(Float u) const { + auto sample = [&](auto ptr) { return ptr->SampleTime(u); }; + return Dispatch(sample); +} + +inline const CameraTransform &CameraHandle::GetCameraTransform() const { + auto gtc = [&](auto ptr) -> auto && { return ptr->GetCameraTransform(); }; + return DispatchCRef(gtc); +} + +} // namespace pbrt + +#endif // PBRT_CAMERAS_H diff --git a/src/pbrt/cmd/cyhair2pbrt.cpp b/src/pbrt/cmd/cyhair2pbrt.cpp new file mode 100644 index 00000000..0e0803bf --- /dev/null +++ b/src/pbrt/cmd/cyhair2pbrt.cpp @@ -0,0 +1,480 @@ +// +// cyhair2pbrt.cpp +// +// Convert CyHair files to PBRT. +// Hair vertices are interpreted as Catmull-Rom spline points. +// The tool simply converts Catmull-Rom spline points to cubic Bezier points. +// +// MIT license +// + +///////////// start of cyhair_loader + +// clang-format off + +/* +The MIT License (MIT) + +Copyright (c) 2016 Light Transport Entertainment, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +// Simple Cyhair loader. + +#include +#include +#include +#include +#include + +#include + +//#include + +namespace cyhair { + +class real3 { + public: + real3() : x(0.0f), y(0.0f), z(0.0f) {} + real3(float v) : x(v), y(v), z(v) {} + real3(float xx, float yy, float zz) : x(xx), y(yy), z(zz) {} + //~real3() {} + + real3 operator+(const real3 &f2) const { + return {x + f2.x, y + f2.y, z + f2.z}; + } + real3 operator*(const real3 &f2) const { + return {x * f2.x, y * f2.y, z * f2.z}; + } + real3 operator/(const real3 &f2) const { + return {x / f2.x, y / f2.y, z / f2.z}; + } + real3 operator/(const float f) const { return {x / f, y / f, z / f}; } + + float x, y, z; +}; + +inline real3 operator*(float f, const real3 &v) { + return {v.x * f, v.y * f, v.z * f}; +} + +static const float toC2B[4][4] = { + {0.0f, 6.0f / 6.0f, 0.0f, 0.0f}, + {-1.0f / 6.0f, 6.0f / 6.0f, 1.0f / 6.0f, 0.0f}, + {0.0f, 1.0f / 6.0f, 6.0f / 6.0f, -1.0f / 6.0f}, + {0.0f, 0.0, 6.0f / 6.0f, 0.0f}}; + +static const float toC2B0[4][4] = { + {0.0f, 6.0f / 6.0f, 0.0f, 0.0f}, + {0.0f, 3.0f / 6.0f, 4.0f / 6.0f, -1.0f / 6.0f}, + {0.0f, 1.0f / 6.0f, 6.0f / 6.0f, -1.0f / 6.0f}, + {0.0f, 0.0f, 6.0f / 6.0f, 0.0f}}; + +static const float toC2B1[4][4] = { + {0.0f, 6.0f / 6.0f, 0.0f, 0.0f}, + {-1.0f / 6.0f, 6.0f / 6.0f, 1.0f / 6.0f, 0.0f}, + {-1.0f / 6.0f, 4.0f / 6.0f, 3.0f / 6.0f, 0.0f}, + {0.0f, 0.0f, 6.0f / 6.0f, 0.0f}}; + +static void mul_matrix(real3 out[4], const float mat[4][4], const real3 pt[4]) { + for (int i = 0; i < 4; i++) { + out[i] = mat[i][0] * pt[0] + mat[i][1] * pt[1] + mat[i][2] * pt[2] + + mat[i][3] * pt[3]; + } +} + +static void CamullRomToCubicBezier(real3 Q[4], const real3 *cps, int cps_size, + int seg_idx) { + size_t sz = static_cast(cps_size); + if (sz == 2) { + Q[0] = cps[seg_idx]; + Q[1] = cps[seg_idx] * 2.0f / 3.0f + cps[seg_idx + 1] * 1.0f / 3.0f; + Q[2] = cps[seg_idx] * 1.0f / 3.0f + cps[seg_idx + 1] * 2.0f / 3.0f; + Q[3] = cps[seg_idx + 1]; + } else { + real3 P[4]; + if (seg_idx == 0) { + P[0] = real3(0.0f); + P[1] = cps[seg_idx + 0]; + P[2] = cps[seg_idx + 1]; + P[3] = cps[seg_idx + 2]; + mul_matrix(Q, toC2B0, P); + } else if (seg_idx == static_cast(sz - 2)) { + P[0] = cps[seg_idx - 1]; + P[1] = cps[seg_idx + 0]; + P[2] = cps[seg_idx + 1]; + P[3] = real3(0.0f); + mul_matrix(Q, toC2B1, P); + } else { + P[0] = cps[seg_idx - 1]; + P[1] = cps[seg_idx + 0]; + P[2] = cps[seg_idx + 1]; + P[3] = cps[seg_idx + 2]; + mul_matrix(Q, toC2B, P); + } + } +} + +struct CyHairHeader { + char magic[4]; + unsigned int num_strands; + unsigned int total_points; + unsigned int flags; + unsigned int default_segments; + float default_thickness; + float default_transparency; + float default_color[3]; + char infomation[88]; +}; + +class CyHair { + public: + CyHair() + : flags_(0), + num_strands_(0), + total_points_(0), + default_segments_(-1), + default_thickness_(0.01f), + default_transparency_(1.0f) { + default_color_[0] = 0.5f; + default_color_[1] = 0.5f; + default_color_[2] = 0.5f; + } + + ~CyHair() {} + + /// Load CyHair data from a file. + bool Load(const char *filename); + + /// Convert to cubic bezier curves. + /// 4(cubic) * 3(xyz) * num_curves = vertices.size() + /// 4(cubic) * num_curves = radiuss.size() + /// `max_strands` limits the number of strands to convert. -1 = convert all + /// strands. + /// `thickness` overwrites strand thickness if it have positive value. + /// Apply `vertex_translate` after `vertex_scale`. + /// TODO(syoyo) return strand/segment information + bool ToCubicBezierCurves(std::vector *vertices, + std::vector *radiuss, + const float vertex_scale[3], + const float vertex_translate[3], + const int max_strands = -1, + const float thickness = -1.0f); + + CyHairHeader header_; + + // Raw CyHair values + std::vector segments_; + std::vector points_; // xyz + std::vector thicknesses_; + std::vector transparencies_; + std::vector colors_; // rgb + unsigned int flags_; + unsigned int num_strands_; + unsigned int total_points_; + int default_segments_; + float default_thickness_; + float default_transparency_; + float default_color_[3]; + int pad0; + + // Processed CyHair values + std::vector strand_offsets_; +}; + + + +bool CyHair::Load(const char *filename) { + FILE *fp = fopen(filename, "rb"); + if (!fp) { + return false; + } + + assert(sizeof(CyHairHeader) == 128); + CyHairHeader header; + + if (1 != fread(&header, 128, 1, fp)) { + fclose(fp); + return false; + } + if (memcmp(header.magic, "HAIR", 4) != 0) { + fclose(fp); + return false; + } + + flags_ = header.flags; + default_thickness_ = header.default_thickness; + default_transparency_ = header.default_transparency; + default_segments_ = static_cast(header.default_segments); + default_color_[0] = header.default_color[0]; + default_color_[1] = header.default_color[1]; + default_color_[2] = header.default_color[2]; + + const bool has_segments = flags_ & 0x1; + const bool has_points = flags_ & 0x2; + const bool has_thickness = flags_ & 0x4; + const bool has_transparency = flags_ & 0x8; + const bool has_color = flags_ & 0x10; + + num_strands_ = header.num_strands; + total_points_ = header.total_points; + + if (!has_points) { + std::cout << "No point data in CyHair." << std::endl; + return false; + } + + if ((default_segments_ < 1) && (!has_segments)) { + std::cout << "No valid segment information in CyHair." << std::endl; + return false; + } + + // First read all strand data from a file. + if (has_segments) { + segments_.resize(num_strands_); + if (1 != + fread(&segments_[0], sizeof(unsigned short) * num_strands_, 1, fp)) { + std::cout << "Failed to read CyHair segments data." << std::endl; + fclose(fp); + return false; + } + } + + if (has_points) { + std::cout << "[CyHair] Has points." << std::endl; + points_.resize(3 * total_points_); + size_t n = fread(&points_[0], total_points_ * sizeof(float) * 3, 1, fp); + if (1 != n) { + std::cout << "Failed to read CyHair points data." << std::endl; + fclose(fp); + return false; + } + } + if (has_thickness) { + std::cout << "[CyHair] Has thickness." << std::endl; + thicknesses_.resize(total_points_); + if (1 != fread(&thicknesses_[0], total_points_ * sizeof(float), 1, fp)) { + std::cout << "Failed to read CyHair thickness data." << std::endl; + fclose(fp); + return false; + } + } + + if (has_transparency) { + std::cout << "[CyHair] Has transparency." << std::endl; + transparencies_.resize(total_points_); + if (1 != fread(&transparencies_[0], total_points_ * sizeof(float), 1, fp)) { + std::cout << "Failed to read CyHair transparencies data." << std::endl; + fclose(fp); + return false; + } + } + + if (has_color) { + std::cout << "[CyHair] Has color." << std::endl; + colors_.resize(3 * total_points_); + if (1 != fread(&colors_[0], total_points_ * sizeof(float) * 3, 1, fp)) { + std::cout << "Failed to read CyHair colors data." << std::endl; + fclose(fp); + return false; + } + } + + // Build strand offset table. + strand_offsets_.resize(num_strands_); + strand_offsets_[0] = 0; + for (size_t i = 1; i < num_strands_; i++) { + int num_segments = segments_.empty() ? default_segments_ : segments_[i - 1]; + strand_offsets_[i] = + strand_offsets_[i - 1] + static_cast(num_segments + 1); + } + + return true; +} + +bool CyHair::ToCubicBezierCurves(std::vector *vertices, + std::vector *radiuss, + const float vertex_scale[3], + const float vertex_translate[3], + const int max_strands, const float user_thickness) { + if (points_.empty() || strand_offsets_.empty()) { + return false; + } + + vertices->clear(); + radiuss->clear(); + + int num_strands = static_cast(num_strands_); + + if ((max_strands > 0) && (max_strands < num_strands)) { + num_strands = max_strands; + } + + std::cout << "[Hair] Convert first " << num_strands << " strands from " + << max_strands << " strands in the original hair data." + << std::endl; + + // Assume input points are CatmullRom spline. + for (size_t i = 0; i < static_cast(num_strands); i++) { + if ((i % 1000) == 0) { + std::cout << i << " / " << num_strands_ << std::endl; + } + + int num_segments = segments_.empty() ? default_segments_ : segments_[i]; + if (num_segments < 2) { + continue; + } + + std::vector segment_points; + for (size_t k = 0; k < static_cast(num_segments); k++) { + // Zup -> Yup + real3 p(points_[3 * (strand_offsets_[i] + k) + 0], + points_[3 * (strand_offsets_[i] + k) + 2], + points_[3 * (strand_offsets_[i] + k) + 1]); + segment_points.push_back(p); + } + + // Skip both endpoints + for (int s = 1; s < num_segments - 1; s++) { + int seg_idx = s - 1; + real3 q[4]; + CamullRomToCubicBezier(q, segment_points.data(), num_segments, seg_idx); + + vertices->push_back(vertex_scale[0] * q[0].x + vertex_translate[0]); + vertices->push_back(vertex_scale[1] * q[0].y + vertex_translate[1]); + vertices->push_back(vertex_scale[2] * q[0].z + vertex_translate[2]); + vertices->push_back(vertex_scale[0] * q[1].x + vertex_translate[0]); + vertices->push_back(vertex_scale[1] * q[1].y + vertex_translate[1]); + vertices->push_back(vertex_scale[2] * q[1].z + vertex_translate[2]); + vertices->push_back(vertex_scale[0] * q[2].x + vertex_translate[0]); + vertices->push_back(vertex_scale[1] * q[2].y + vertex_translate[1]); + vertices->push_back(vertex_scale[2] * q[2].z + vertex_translate[2]); + vertices->push_back(vertex_scale[0] * q[3].x + vertex_translate[0]); + vertices->push_back(vertex_scale[1] * q[3].y + vertex_translate[1]); + vertices->push_back(vertex_scale[2] * q[3].z + vertex_translate[2]); + + if (user_thickness > 0) { + // Use user supplied thickness. + radiuss->push_back(user_thickness); + radiuss->push_back(user_thickness); + radiuss->push_back(user_thickness); + radiuss->push_back(user_thickness); + } else { + // TODO(syoyo) Support per point/segment thickness + radiuss->push_back(default_thickness_); + radiuss->push_back(default_thickness_); + radiuss->push_back(default_thickness_); + radiuss->push_back(default_thickness_); + } + } + } + + return true; +} + +} // namespace cyhair + +// clang-format on + +/////////////////////////////////////////////////////////////////////////// +// The above is cyhair_loader.{h,cc} basically directly; pbrt specific +// code follows... + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + if (argc <= 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { + fprintf(stderr, "usage: cyhair2pbrt [CyHair filename] [pbrt output filename] " + "(max strands) (thickness)\n"); + return EXIT_FAILURE; + } + + FILE *f = (strcmp(argv[2], "-") == 0) ? stdout : fopen(argv[2], "w"); + if (!f) { + perror(argv[2]); + return EXIT_FAILURE; + } + + int max_strands = -1; // -1 = Convert all strands + float user_thickness = 1.0f; // -1 = Use thickness in CyHair file. + if (argc > 3) { + max_strands = atoi(argv[3]); + } + + if (argc > 4) { + user_thickness = atof(argv[4]); + } + + cyhair::CyHair hair; + bool ret = hair.Load(argv[1]); + if (!ret) { + fprintf(stderr, "Failed to load CyHair file [ %s ]\n", argv[1]); + return EXIT_FAILURE; + } + + std::vector points; + std::vector radiuss; + const float vertex_scale[3] = {1.0f, 1.0f, 1.0f}; + const float vertex_translate[3] = {0.0f, 0.0f, 0.0f}; + ret = hair.ToCubicBezierCurves(&points, &radiuss, vertex_scale, vertex_translate, + max_strands, user_thickness); + if (!ret) { + fprintf(stderr, "Failed to convert CyHair data\n"); + return EXIT_FAILURE; + } + + double bounds[2][3] = {{1e30, 1e30, 1e30}, {-1e30, -1e30, -1e30}}; + for (size_t i = 0; i < points.size() / 3; ++i) { + const double thickness = static_cast(radiuss[i]); + for (size_t c = 0; c < 3; ++c) { + bounds[0][c] = std::min(bounds[0][c], + static_cast(points[3 * i + c]) - thickness); + bounds[1][c] = std::max(bounds[1][c], + static_cast(points[3 * i + c]) + thickness); + } + } + fprintf(f, "# Converted from \"%s\" by cyhair2pbrt\n", argv[1]); + fprintf(f, "# The number of strands = %d. user_thickness = %f\n", + static_cast(radiuss.size() / 4), static_cast(user_thickness)); + fprintf(f, "# Scene bounds: (%f, %f, %f) - (%f, %f, %f)\n\n\n", bounds[0][0], + bounds[0][1], bounds[0][2], bounds[1][0], bounds[1][1], bounds[1][2]); + + const size_t num_curves = radiuss.size() / 4; + for (size_t i = 0; i < num_curves; i++) { + fprintf(f, R"(Shape "curve" "string type" [ "cylinder" ] "point3 P" [ )"); + for (size_t j = 0; j < 12; j++) { + fprintf(f, "%f ", static_cast(points[12 * i + j])); + } + fprintf(f, " ] \"float width0\" [ %f ] \"float width1\" [ %f ]\n", + static_cast(radiuss[4 * i + 0]), + static_cast(radiuss[4 * i + 3])); + } + + if (f != stdout) + fclose(f); + + fprintf(stderr, "Converted %d strands.\n", static_cast(radiuss.size() / 4)); + + return EXIT_SUCCESS; +} diff --git a/src/pbrt/cmd/imgtool.cpp b/src/pbrt/cmd/imgtool.cpp new file mode 100644 index 00000000..2994f14b --- /dev/null +++ b/src/pbrt/cmd/imgtool.cpp @@ -0,0 +1,2374 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#include +} + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef PBRT_BUILD_GPU_RENDERER + +#include +#include + +#include +#include + +#define OPTIX_CHECK(EXPR) \ + do { \ + OptixResult res = EXPR; \ + if (res != OPTIX_SUCCESS) \ + LOG_FATAL("OptiX call " #EXPR " failed with code %d: \"%s\"", int(res), \ + optixGetErrorString(res)); \ + } while (false) /* eat semicolon */ +#endif + +using namespace pbrt; + +struct CommandUsage { + std::string usage; + std::string options; +}; + +static std::map commandUsage = { + {"assemble", {"assemble [options] ", std::string(R"( + --outfile Output image filename. +)")}}, + {"average", {"average [options] ", std::string(R"( + --outfile Output image filename. +)")}}, + {"cat", {"cat [options] ", std::string(R"( + --csv Output pixel values in CSV format. + --list Output pixel values in a brace-delimited list + (Mathematica-compatible). + --sort Sort output by pixel luminance. +)")}}, + {"bloom", {"bloom [options] ", std::string(R"( + --iterations Number of filtering iterations used to generate the bloom + image. Default: 5 + --level Minimum RGB value for a pixel for it to contribute to bloom. + Default: Infinity (i.e., no bloom is applied) + --outfile Output image filename. + --scale Amount by which the bloom image is scaled before being + added to the original image. Default: 0.3 + --width Width of Gaussian used to generate bloom images. + Default: 15 +)")}}, + {"convert", {"convert [options] ", std::string(R"( + --aces-filmic Apply the ACES filmic s-curve to map values to [0,1]. + --bw Convert to black and white (average channels) + --channels Process the provided comma-delineated set of channels. + Default: R,G,B. + --crop Crop image to the given dimensions. Default: no crop. + --colorspace Convert image to given colorspace. + (Options: "ACES2065-1", "Rec2020", "sRGB") + --despike For any pixels with a luminance value greater than , + replace the pixel with the median of the 3x3 neighboring + pixels. Default: infinity (i.e., disabled). + --flipy Flip the image along the y axis + --gamma Apply a gamma curve with exponent v. (Default: 1 (none)). + --maxluminance Luminance value mapped to white by tonemapping. + Default: 1 + --outfile Output image filename. + --preservecolors By default, out-of-gammut colors have each component + clamped to [0,1] when written to non-HDR formats. With + this option enabled, such colors are scaled by their + maximum component, which preserves the relative ratio + between RGB components. + --repeatpix Repeat each pixel value n times in both directions + --scale Scale pixel values by given amount + --tonemap Apply tonemapping to the image (Reinhard et al.'s + photographic tone mapping operator) +)")}}, + {"diff", {"diff [options] ", std::string(R"( + --crop Crop images before performing diff. + --difftol Acceptable image difference percentage before differences + are reported. Default: 0 + --metric Error metric to use. (Options: "L1", "MSE", "MRSE") + --outfile Filename to use for saving an image that encodes the + absolute value of per-pixel differences. + --reference Filename for reference image +)")}}, + {"denoise", {"denoise [options] ", std::string(R"( options: + --outfile Filename to use for the denoised image. +)")}}, +#ifdef PBRT_BUILD_GPU_RENDERER + {"denoise-optix", {"denoise-optix [options] ", std::string(R"( options: + --outfile Filename to use for the denoised image. +)")}}, +#endif // PBRT_BUILD_GPU_RENDERER + {"error", + {"error [options] \nwhere all image files starting with " + " are used to compute error", + std::string(R"( + --crop Crop images before performing diff. + --errorfile Output average error image. + --metric Error metric to use. (Options: "L1", MSE", "MRSE") + --reference Reference image filename. +)")}}, + {"falsecolor", {"falsecolor [options] ", std::string(R"( + --maxvalue Value to map to the last value in the color ramp. + (Default: maximum pixel value in the image.) + --outfile Filename for output image. + --plusminus Visualize green > 0, red < 0. +)")}}, + {"makeenv", {"makeenv [options] ", std::string(R"( + --outfile Filename of environment map image. + --resolution Resolution of environment map. Default: calculated + from resolution of provited lat-long environment map. +)")}}, + {"makeemitters", {"makeemitters [options] ", std::string(R"( + --downsample Downsample the image by a factor of n in both dimensions + (using simple box filtering). Default: 1. +)")}}, + {"makesky", {"makesky [options] ", std::string(R"( + --albedo Albedo of ground-plane (range 0-1). Default: 0.5 + --elevation Elevation of the sun in degrees (range 0-90). Default: 10 + --outfile Filename to store environment map in. + --turbidity Atmospheric turbidity (range 1.7-10). Default: 3 + --resolution Resolution of generated environment map. Default: 2048 +)")}}, + {"whitebalance", {"whitebalance [options] ", std::string(R"( + --illuminant Apply white balance for the given standard illuminant + (e.g. D65, D50, A, F1, F2, ...) + --outfile Filename to store result image + --primaries Apply white balance for the primaries (x,y) + --temperature Apply white balance for a color temperature T +)")}}, + +}; + +static void usage(const char *cmd, const char *msg = nullptr, ...) { + if (msg != nullptr) { + va_list args; + va_start(args, msg); + fprintf(stderr, "imgtool %s: ", cmd); + vfprintf(stderr, msg, args); + fprintf(stderr, "\n\n"); + } + + auto iter = commandUsage.find(cmd); + CHECK(iter != commandUsage.end()); + fprintf(stderr, "usage: imgtool %s\n\n", iter->second.usage.c_str()); + if (!iter->second.options.empty()) + fprintf(stderr, "options:%s\n", iter->second.options.c_str()); + + exit(1); +} + +void help() { + fprintf(stderr, "usage: imgtool [options]\n\n"); + fprintf(stderr, "where is:"); + int count = 0; + for (const auto &cmd : commandUsage) + fprintf(stderr, " %s%c", cmd.first.c_str(), + ++count < commandUsage.size() ? ',' : ' '); + fprintf(stderr, "\n\n"); + fprintf(stderr, "\"imgtool help \" provides detailed information " + "about .\n"); +} + +int help(int argc, char **argv) { + if (argc == 0) { + help(); + return 0; + } + while (*argv != nullptr) { + auto iter = commandUsage.find(*argv); + if (iter == commandUsage.end()) { + fprintf(stderr, "imgtool help: command \"%s\" not known.\n", *argv); + help(); + return 1; + } else { + fprintf(stderr, "usage: imgtool %s\n\n", iter->second.usage.c_str()); + fprintf(stderr, "options:%s\n", iter->second.options.c_str()); + } + ++argv; + } + return 0; +} + +int makesky(int argc, char *argv[]) { + std::string outfile; + Float albedo = 0.5; + Float turbidity = 3.; + Float elevation = 10; + int resolution = 2048; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("makesky", "%s", err.c_str()); + exit(1); + }; + if (ParseArg(&argv, "outfile", &outfile, onError) || + ParseArg(&argv, "albedo", &albedo, onError) || + ParseArg(&argv, "turbidity", &turbidity, onError) || + ParseArg(&argv, "elevation", &elevation, onError) || + ParseArg(&argv, "resolution", &resolution, onError)) { + // success + } else + onError(StringPrintf("argument %s invalid", *argv)); + } + + if (outfile.empty()) + usage("makesky", "--outfile must be specified"); + if (albedo < 0. || albedo > 1.) + usage("makesky", "--albedo must be between 0 and 1"); + if (turbidity < 1.7 || turbidity > 10.) + usage("makesky", "--turbidity must be between 1.7 and 10."); + if (elevation < 0. || elevation > 90.) + usage("makesky", "--elevation must be between 0. and 90."); + elevation = Radians(elevation); + if (resolution < 1) + usage("makesky", "--resolution must be >= 1"); + + // Vector pointing at the sun. Note that elevation is measured from the + // horizon--not the zenith, as it is elsewhere in pbrt. + Vector3f sunDir(0., std::cos(elevation), std::sin(elevation)); + + Image img(PixelFormat::Float, {resolution, resolution}, {"R", "G", "B"}); + + // They assert wavelengths are in this range... + int nLambda = 1 + (720 - 320) / 32; + std::vector lambda(nLambda, Float(0)); + for (int i = 0; i < nLambda; ++i) + lambda[i] = Lerp(i / Float(nLambda - 1), 320, 720); + + // Assume a uniform spectral albedo + ArHosekSkyModelState *skymodel_state = + arhosekskymodelstate_alloc_init(elevation, turbidity, albedo); + + const RGBColorSpace *colorSpace = RGBColorSpace::ACES2065_1; + XYZ illumXYZ = SpectrumToXYZ(&colorSpace->illuminant); + + ParallelFor(0, resolution, [&](int64_t start, int64_t end) { + std::vector skyv(lambda.size()); + for (int64_t iy = start; iy < end; ++iy) { + Float y = (iy + 0.5f) / resolution; + for (int ix = 0; ix < resolution; ++ix) { + Float x = (ix + 0.5f) / resolution; + Vector3f v = EquiAreaSquareToSphere({x, y}); + if (v.z <= 0) + // downward hemisphere + continue; + + Float theta = SphericalTheta(v); + + // Compute the angle between the pixel's direction and the sun + // direction. + Float gamma = SafeACos(Dot(v, sunDir)); + DCHECK(gamma >= 0 && gamma <= Pi); + + for (int i = 0; i < lambda.size(); ++i) + skyv[i] = arhosekskymodel_solar_radiance(skymodel_state, theta, gamma, + lambda[i]); + + PiecewiseLinearSpectrum spec(pstd::MakeConstSpan(lambda), + pstd::MakeConstSpan(skyv)); + XYZ xyz = SpectrumToXYZ(&spec); + RGB rgb = colorSpace->ToRGB(xyz); + + for (int c = 0; c < 3; ++c) + img.SetChannel({ix, int(iy)}, c, rgb[c]); + } + } + }); + + ImageMetadata metadata; + metadata.colorSpace = colorSpace; + CHECK(img.Write(outfile, metadata)); + + return 0; +} + +int assemble(int argc, char *argv[]) { + if (argc == 0) + usage("assemble", "no filenames provided to \"assemble\"?"); + std::string outfile; + std::vector infiles; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("assemble", "%s", err.c_str()); + }; + if (ParseArg(&argv, "outfile", &outfile, onError)) + ; // success + else if (argv[0][0] == '-') + usage("assemble", "%s: unknown command flag", *argv); + else { + infiles.push_back(*argv); + ++argv; + } + } + + if (outfile.empty()) + usage("assemble", "--outfile not provided for \"assemble\""); + + Image fullImage; + std::vector seenPixel; + int seenMultiple = 0; + Bounds2i fullBounds; + for (const std::string &file : infiles) { + if (!HasExtension(file, "exr")) + usage("assemble", "only EXR images include the image bounding boxes that " + "\"assemble\" needs."); + + ImageAndMetadata im = Image::Read(file); + Image &image = im.image; + ImageMetadata &metadata = im.metadata; + + if (!metadata.fullResolution) { + fprintf(stderr, + "%s: doesn't have full resolution in image metadata. " + "Skipping.\n", + file.c_str()); + continue; + } + if (!metadata.pixelBounds) { + fprintf(stderr, + "%s: doesn't have pixel bounds in image metadata. Skipping.\n", + file.c_str()); + continue; + } + + const RGBColorSpace *colorSpace = nullptr; + if (fullImage.Resolution() == Point2i(0, 0)) { + // First image read. + fullImage = Image(image.Format(), *metadata.fullResolution, + image.ChannelNames(), image.Encoding()); + colorSpace = metadata.GetColorSpace(); + seenPixel.resize(fullImage.Resolution().x * fullImage.Resolution().y); + fullBounds = Bounds2i({0, 0}, fullImage.Resolution()); + } else { + // Make sure that this image's info is compatible with the + // first image's. + if (*metadata.fullResolution != fullImage.Resolution()) { + fprintf(stderr, + "%s: full resolution (%d, %d) in EXR file doesn't match " + "the full resolution of first EXR file (%d, %d). " + "Ignoring this file.\n", + file.c_str(), metadata.fullResolution->x, + metadata.fullResolution->y, fullImage.Resolution().x, + fullImage.Resolution().y); + continue; + } + if (Union(*metadata.pixelBounds, fullBounds) != fullBounds) { + fprintf(stderr, + "%s: pixel bounds (%d, %d) - (%d, %d) in EXR file isn't " + "inside the the full image (0, 0) - (%d, %d). Ignoring " + "this file.\n", + file.c_str(), metadata.pixelBounds->pMin.x, + metadata.pixelBounds->pMin.y, metadata.pixelBounds->pMax.x, + metadata.pixelBounds->pMax.y, fullBounds.pMax.x, + fullBounds.pMax.y); + continue; + } + if (fullImage.NChannels() != image.NChannels()) { + fprintf(stderr, "%s: %d channel image; expecting %d channels.\n", + file.c_str(), image.NChannels(), fullImage.NChannels()); + continue; + } + const RGBColorSpace *cs = metadata.GetColorSpace(); + if (*cs != *colorSpace) { + fprintf(stderr, + "%s: color space (%s) doesn't match first image's color " + "space (%s).\n", + file.c_str(), cs->ToString().c_str(), + colorSpace->ToString().c_str()); + continue; + } + } + + // Copy pixels. + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) { + Point2i fullp{x + metadata.pixelBounds->pMin.x, + y + metadata.pixelBounds->pMin.y}; + size_t fullOffset = fullImage.PixelOffset(fullp); + if (seenPixel[fullOffset]) + ++seenMultiple; + seenPixel[fullOffset] = true; + for (int c = 0; c < fullImage.NChannels(); ++c) + fullImage.SetChannel(fullp, c, image.GetChannel({x, y}, c)); + } + } + + int unseenPixels = 0; + for (int y = 0; y < fullImage.Resolution().y; ++y) + for (int x = 0; x < fullImage.Resolution().x; ++x) + if (!seenPixel[y * fullImage.Resolution().x + x]) + ++unseenPixels; + + if (seenMultiple > 0) + fprintf(stderr, "%s: %d pixels present in multiple images.\n", outfile.c_str(), + seenMultiple); + if (unseenPixels > 0) + fprintf(stderr, "%s: %d pixels not present in any images.\n", outfile.c_str(), + unseenPixels); + + fullImage.Write(outfile); + + return 0; +} + +int cat(int argc, char *argv[]) { + if (argc == 0) + usage("cat", "no filenames provided to \"cat\"?"); + bool sort = false; + bool csv = false; + bool list = false; + + for (int i = 0; i < argc; ++i) { + if (strcmp(argv[i], "--sort") == 0 || strcmp(argv[i], "-sort") == 0) { + sort = !sort; + continue; + } + if (strcmp(argv[i], "--csv") == 0 || strcmp(argv[i], "-csv") == 0) { + csv = !csv; + continue; + } + if (strcmp(argv[i], "--list") == 0 || strcmp(argv[i], "-list") == 0) { + list = !list; + continue; + } + + if (sort && csv) { + fprintf(stderr, "imgtool: --sort and --csv don't make sense to use " + "together.\n"); + return 1; + } + if (sort && list) { + fprintf(stderr, "imgtool: --sort and --list don't make sense to " + "use together.\n"); + return 1; + } + + ImageAndMetadata im = Image::Read(argv[i]); + ImageMetadata &metadata = im.metadata; + Image &image = im.image; + + Bounds2i pixelBounds = + metadata.pixelBounds.value_or(Bounds2i({0, 0}, image.Resolution())); + if (sort) { + std::vector> sorted; + sorted.reserve(pixelBounds.Area()); + for (Point2i p : pixelBounds) { + ImageChannelValues v = image.GetChannels( + {p.x - pixelBounds.pMin.x, p.y - pixelBounds.pMin.y}); + sorted.push_back(std::make_pair(p, v)); + } + + std::sort(sorted.begin(), sorted.end(), + [](const std::pair &a, + const std::pair &b) { + return a.second.Average() < b.second.Average(); + }); + for (const auto &v : sorted) { + const ImageChannelValues &values = v.second; + if (!csv) + printf("(%d, %d): ", v.first.x, v.first.y); + for (size_t i = 0; i < values.size(); ++i) + Printf("%f%c", values[i], (i == values.size() - 1) ? '\n' : ','); + } + } else { + if (list) { + CHECK_EQ(image.NChannels(), 1); + for (int y = pixelBounds.pMin.y; y < pixelBounds.pMax.y; ++y) { + for (int x = pixelBounds.pMin.x; x < pixelBounds.pMax.x; ++x) + printf("%f ", + image.GetChannel( + {x - pixelBounds.pMin.x, y - pixelBounds.pMin.y}, 0)); + printf("\n"); + } + } else { + for (Point2i p : pixelBounds) { + ImageChannelValues values = image.GetChannels( + {p.x - pixelBounds.pMin.x, p.y - pixelBounds.pMin.y}); + if (!csv) + printf("(%d, %d): ", p.x, p.y); + for (size_t i = 0; i < values.size(); ++i) + Printf("%f%c", values[i], (i == values.size() - 1) ? '\n' : ','); + } + } + } + } + return 0; +} + +static bool checkImageCompatibility(const std::string &fn1, const Image &im1, + const std::string &fn2, const Image &im2) { + if (im1.Resolution() != im2.Resolution()) { + fprintf(stderr, "%s: image resolution (%d, %d) doesn't match \"%s\" (%d, %d).", + fn1.c_str(), im1.Resolution().x, im1.Resolution().y, fn2.c_str(), + im2.Resolution().x, im2.Resolution().y); + return false; + } + if (im1.NChannels() != im2.NChannels()) { + fprintf(stderr, "%s: image channel count %d doesn't match \"%s\", %d.", + fn1.c_str(), im1.NChannels(), fn2.c_str(), im2.NChannels()); + return false; + } + if (im1.ChannelNames() != im2.ChannelNames()) { + auto print = [](const std::vector &n) { + std::string s = n[0]; + for (size_t i = 1; i < n.size(); ++i) { + s += ", "; + s += n[i]; + } + return s; + }; + fprintf(stderr, + "%s: warning: image channel names \"%s\" don't match \"%s\" " + "with \"%s\".", + fn1.c_str(), print(im1.ChannelNames()).c_str(), fn2.c_str(), + print(im2.ChannelNames()).c_str()); + } + +#if 0 + if (*md1.GetColorSpace() != *md2.GetColorSpace()) + fprintf(stderr, "%s: warning: : computing difference of images with different " + "color spaces!"); +#endif + return true; +} + +int average(int argc, char *argv[]) { + std::string avgFile, filenameBase; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("average", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "outfile", &avgFile, onError)) { + // success + } else if (filenameBase.empty() && argv[0][0] != '-') { + filenameBase = *argv; + ++argv; + } else + usage("average", "%s: unknown argument", *argv); + } + + if (filenameBase.empty()) + usage("average", "must provide base filename."); + if (avgFile.empty()) + usage("average", "must provide --outfile."); + + std::vector filenames = MatchingFilenames(filenameBase); + if (filenames.empty()) { + fprintf(stderr, "%s: no matching filenames!\n", filenameBase.c_str()); + return 1; + } + + // Compute average image + std::vector avgImages(MaxThreadIndex()); + std::atomic failed{false}; + + ParallelFor(0, filenames.size(), [&](size_t i) { + ImageAndMetadata imRead = Image::Read(filenames[i]); + Image &im = imRead.image; + + Image &avg = avgImages[ThreadIndex]; + if (avg.Resolution() == Point2i(0, 0)) + avg = Image(PixelFormat::Float, im.Resolution(), im.ChannelNames()); + else if (!checkImageCompatibility(filenames[i], im, filenames[0], avg)) { + failed = true; + return; + } + + for (int y = 0; y < avg.Resolution().y; ++y) + for (int x = 0; x < avg.Resolution().x; ++x) + for (int c = 0; c < avg.NChannels(); ++c) { + Float v = im.GetChannel({x, y}, c) / filenames.size(); + if (std::isnan(v)) + LOG_FATAL("NAN Pixel at %s in %s", Point2f(x, y), filenames[i]); + if (std::isinf(v)) + v = 0; + avg.SetChannel({x, y}, c, avg.GetChannel({x, y}, c) + v); + } + }); + + if (failed) + return 1; + + // Average per-thread average images + Image avgImage; + for (const Image &im : avgImages) { + if (im.Resolution() == Point2i(0, 0)) + continue; + else if (avgImage.Resolution() == Point2i(0, 0)) { + // First valid one + avgImage = im; + } else { + for (int y = 0; y < avgImage.Resolution().y; ++y) + for (int x = 0; x < avgImage.Resolution().x; ++x) + for (int c = 0; c < avgImage.NChannels(); ++c) { + Float v = im.GetChannel({x, y}, c); + if (!std::isinf(v)) + avgImage.SetChannel({x, y}, c, + avgImage.GetChannel({x, y}, c) + v); + } + } + } + + CHECK(avgImage.Write(avgFile)); + + return 0; +} + +int error(int argc, char *argv[]) { + std::string referenceFile, errorFile, metric = "MSE"; + std::string filenameBase; + std::array cropWindow = {-1, 0, -1, 0}; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("error", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "reference", &referenceFile, onError) || + ParseArg(&argv, "errorfile", &errorFile, onError) || + ParseArg(&argv, "metric", &metric, onError) || + ParseArg(&argv, "crop", pstd::MakeSpan(cropWindow), onError)) { + // success + } else if (filenameBase.empty() && argv[0][0] != '-') { + filenameBase = *argv; + ++argv; + } else + usage("error", "%s: unknown argument", *argv); + } + + if (filenameBase.empty()) + usage("error", "Must provide base filename."); + if (metric != "MSE" && metric != "MRSE" && metric != "L1") + usage("error", "%s: --metric must be \"L1\", \"MSE\" or \"MRSE\".", + metric.c_str()); + + std::vector filenames = MatchingFilenames(filenameBase); + if (filenames.empty()) { + fprintf(stderr, "%s: no matching filenames!\n", filenameBase.c_str()); + return 1; + } + + if (referenceFile.empty()) + usage("error", "must provide --reference file."); + ImageAndMetadata ref = Image::Read(referenceFile); + Image &referenceImage = ref.image; + + // If last 2 are negative, they're taken as deltas + if (cropWindow[1] < 0) + cropWindow[1] = cropWindow[0] - cropWindow[1]; + if (cropWindow[3] < 0) + cropWindow[3] = cropWindow[2] - cropWindow[3]; + auto crop = [&cropWindow](Image &image) { + if (cropWindow[0] >= 0 && cropWindow[2] >= 0) + image = image.Crop( + Bounds2i({cropWindow[0], cropWindow[2]}, {cropWindow[1], cropWindow[3]})); + }; + + crop(referenceImage); + + // Compute error and error image + using MultiChannelVarianceEstimator = std::vector>; + std::vector> pixelVariances(MaxThreadIndex()); + for (auto &amcve : pixelVariances) { + amcve = Array2D(referenceImage.Resolution().x, + referenceImage.Resolution().y); + for (auto &mcve : amcve) + mcve.resize(referenceImage.NChannels()); + } + + std::vector sumErrors(MaxThreadIndex(), 0.); + std::vector spp(filenames.size()); + std::atomic failed{false}; + ParallelFor(0, filenames.size(), [&](size_t i) { + ImageAndMetadata imRead = Image::Read(filenames[i]); + Image &im = imRead.image; + crop(im); + + CHECK(imRead.metadata.samplesPerPixel.has_value()); + spp[i] = *imRead.metadata.samplesPerPixel; + + Image diffImage; + ImageChannelValues error(referenceImage.NChannels()); + if (metric == "L1") + error = im.L1Error(im.AllChannelsDesc(), referenceImage, &diffImage); + else if (metric == "MSE") + error = im.MSE(im.AllChannelsDesc(), referenceImage, &diffImage); + else + error = im.MRSE(im.AllChannelsDesc(), referenceImage, &diffImage); + sumErrors[ThreadIndex] += error.Average(); + + for (int y = 0; y < im.Resolution().y; ++y) + for (int x = 0; x < im.Resolution().x; ++x) { + MultiChannelVarianceEstimator &pixelVariance = + pixelVariances[ThreadIndex](x, y); + for (int c = 0; c < im.NChannels(); ++c) + if (metric == "MRSE") + pixelVariance[c].Add( + im.GetChannel({x, y}, c) / + (0.01f + referenceImage.GetChannel({x, y}, c))); + else + pixelVariance[c].Add(im.GetChannel({x, y}, c)); + } + }); + + for (int i = 1; i < filenames.size(); ++i) { + if (spp[i] != spp[0]) { + printf("%s: spp %d mismatch. %s has %d.\n", filenames[i].c_str(), spp[i], + filenames[0].c_str(), spp[0]); + return 1; + } + } + + if (failed) + return 1; + + double sumError = std::accumulate(sumErrors.begin(), sumErrors.end(), 0.); + + Array2D pixelVariance(referenceImage.Resolution().x, + referenceImage.Resolution().y); + for (auto &mcve : pixelVariance) + mcve.resize(referenceImage.NChannels()); + + for (const auto &pixVar : pixelVariances) + for (int y = 0; y < referenceImage.Resolution().y; ++y) + for (int x = 0; x < referenceImage.Resolution().x; ++x) + for (int c = 0; c < referenceImage.NChannels(); ++c) + pixelVariance(x, y)[c].Merge(pixVar(x, y)[c]); + + Image errorImage(PixelFormat::Float, + {referenceImage.Resolution().x, referenceImage.Resolution().y}, + {metric}); + for (int y = 0; y < referenceImage.Resolution().y; ++y) + for (int x = 0; x < referenceImage.Resolution().x; ++x) { + Float varSum = 0; + for (int c = 0; c < referenceImage.NChannels(); ++c) + varSum += pixelVariance(x, y)[c].Variance(); + errorImage.SetChannel({x, y}, 0, varSum / referenceImage.NChannels()); + } + + // MSE is the average over all of the pixels + double error = sumError / (filenames.size() - 1); + printf("%s estimate = %.9g\n", metric.c_str(), error); + + if (!errorFile.empty() && !errorImage.Write(errorFile)) { + return 1; + } + + return 0; +} + +int diff(int argc, char *argv[]) { + std::string outFile, imageFile, referenceFile, metric = "MSE"; + std::array cropWindow = {-1, 0, -1, 0}; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("diff", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "outfile", &outFile, onError) || + ParseArg(&argv, "reference", &referenceFile, onError) || + ParseArg(&argv, "metric", &metric, onError) || + ParseArg(&argv, "crop", pstd::MakeSpan(cropWindow), onError)) { + // success + } else if (argv[0][0] == '-') { + usage("diff", "%s: unknown command flag", *argv); + } else if (!imageFile.empty()) { + usage("diff", "%s: excess argument", *argv); + } else { + imageFile = *argv; + ++argv; + } + } + + if (imageFile.empty()) + usage("diff", "must specify image to compute difference with."); + + if (referenceFile.empty()) + usage("diff", "must specify --reference image"); + + if (metric != "L1" && metric != "MSE" && metric != "MRSE") + usage("diff", "%s: --metric must be \"L1\", \"MSE\" or \"MRSE\".", + metric.c_str()); + + ImageAndMetadata refRead = Image::Read(referenceFile); + Image &refImage = refRead.image; + const ImageMetadata &refMetadata = refRead.metadata; + + // If last 2 are negative, they're taken as deltas + if (cropWindow[1] < 0) + cropWindow[1] = cropWindow[0] - cropWindow[1]; + if (cropWindow[3] < 0) + cropWindow[3] = cropWindow[2] - cropWindow[3]; + if (cropWindow[0] >= 0 && cropWindow[2] >= 0) + refImage = refImage.Crop( + Bounds2i({cropWindow[0], cropWindow[2]}, {cropWindow[1], cropWindow[3]})); + + ImageAndMetadata im = Image::Read(imageFile); + Image &image = im.image; + + // Crop before comparing resolutions. + if (cropWindow[0] >= 0 && cropWindow[2] >= 0) + image = image.Crop( + Bounds2i({cropWindow[0], cropWindow[2]}, {cropWindow[1], cropWindow[3]})); + + if (image.Resolution() != refImage.Resolution()) { + fprintf(stderr, + "%s: image resolution (%d, %d) doesn't match reference (%d, %d)\n", + imageFile.c_str(), image.Resolution().x, image.Resolution().y, + refImage.Resolution().x, refImage.Resolution().y); + return 1; + } + if (image.NChannels() != refImage.NChannels()) { + fprintf(stderr, "%s: image channel count %d doesn't match reference %d.\n", + imageFile.c_str(), image.NChannels(), refImage.NChannels()); + return 1; + } + + if (image.ChannelNames() != refImage.ChannelNames()) { + auto print = [](const std::vector &n) { + std::string s = n[0]; + for (size_t i = 1; i < n.size(); ++i) { + s += ", "; + s += n[i]; + } + return s; + }; + fprintf(stderr, + "Warning: image channel names don't match: %s has \"%s\" " + "but reference has \"%s\".\n", + imageFile.c_str(), print(image.ChannelNames()).c_str(), + print(refImage.ChannelNames()).c_str()); + } + + if (*im.metadata.GetColorSpace() != *refMetadata.GetColorSpace()) + fprintf(stderr, "Warning: computing difference of images with different " + "color spaces!"); + + // Clamp Infs + int nClamped = 0, nRefClamped = 0; + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) + for (int c = 0; c < image.NChannels(); ++c) { + if (std::isinf(image.GetChannel({x, y}, c))) { + ++nClamped; + image.SetChannel({x, y}, c, 0); + } + if (std::isinf(refImage.GetChannel({x, y}, c))) { + ++nRefClamped; + refImage.SetChannel({x, y}, c, 0); + } + } + if (nClamped > 0) + fprintf(stderr, "%s: clamped %d infinite pixel values.\n", imageFile.c_str(), + nClamped); + if (nRefClamped > 0) + fprintf(stderr, "%s: clamped %d infinite pixel values.\n", referenceFile.c_str(), + nRefClamped); + + Image diffImage; + ImageChannelValues error(refImage.NChannels()); + if (metric == "L1") + error = image.L1Error(image.AllChannelsDesc(), refImage, &diffImage); + else if (metric == "MSE") + error = image.MSE(image.AllChannelsDesc(), refImage, &diffImage); + else + error = image.MRSE(image.AllChannelsDesc(), refImage, &diffImage); + + if (error.MaxValue() == 0) + // Same same. + return 0; + + // Image averages + Float refAverage = refImage.Average(refImage.AllChannelsDesc()).Average(); + Float imageAverage = image.Average(image.AllChannelsDesc()).Average(); + + float delta = 100.f * (imageAverage - refAverage) / refAverage; + std::string deltaString = StringPrintf("%f%% delta", delta); + if (std::abs(delta) > 0.1) + deltaString = Red(deltaString); + else if (std::abs(delta) > 0.001) + deltaString = Yellow(deltaString); + Printf("Images differ:\n\t%s %s\n\tavg = %f / %f (%s), %s = %f\n", imageFile, + referenceFile, imageAverage, refAverage, deltaString, metric, error.Average()); + + if (!outFile.empty()) { + if (!diffImage.Write(outFile)) + return 1; + } + + return 1; +} + +static void printImageStats(const char *name, const Image &image, + const ImageMetadata &metadata) { + printf("%s:\n\tresolution (%d, %d)\n", name, image.Resolution().x, + image.Resolution().y); + Printf("\tpixel format: %s\n", image.Format()); + + printf("\tcolor space : "); + if (metadata.colorSpace && *metadata.colorSpace != nullptr) { + if (**metadata.colorSpace == *RGBColorSpace::sRGB) + printf("sRGB"); + else if (**metadata.colorSpace == *RGBColorSpace::DCI_P3) + printf("DCI-P3"); + else if (**metadata.colorSpace == *RGBColorSpace::Rec2020) + printf("rec2020"); + else if (**metadata.colorSpace == *RGBColorSpace::ACES2065_1) + printf("ACES"); + else { + const RGBColorSpace &cs = **metadata.colorSpace; + printf(" r: %f %f g: %f %f b: %f %f w: %f %f", cs.r.x, cs.r.y, cs.g.x, cs.g.y, + cs.b.x, cs.b.y, cs.w.x, cs.w.y); + } + printf("\n"); + } else + printf(" (unspecified)\n"); + + if (metadata.fullResolution) + printf("\tfull resolution (%d, %d)\n", metadata.fullResolution->x, + metadata.fullResolution->y); + if (metadata.pixelBounds) + printf("\tpixel bounds (%d, %d) - (%d, %d)\n", metadata.pixelBounds->pMin.x, + metadata.pixelBounds->pMin.y, metadata.pixelBounds->pMax.x, + metadata.pixelBounds->pMax.y); + if (metadata.renderTimeSeconds) { + float s = *metadata.renderTimeSeconds; + int h = int(s) / 3600; + s -= h * 3600; + int m = int(s) / 60; + s -= m * 60; + + printf("\trender time: %dh %dm %d.%02ds\n", h, m, int(s), + int(100 * (s - int(s)))); + } + if (metadata.cameraFromWorld) + printf("\tcamera from world: %s\n", metadata.cameraFromWorld->ToString().c_str()); + if (metadata.NDCFromWorld) + printf("\tNDC from world: %s\n", metadata.NDCFromWorld->ToString().c_str()); + if (metadata.samplesPerPixel) + printf("\tsamples per pixel: %d\n", *metadata.samplesPerPixel); + + if (metadata.estimatedVariance) { + printf("\taverage pixel variance: %g\n", *metadata.estimatedVariance); + if (metadata.renderTimeSeconds) + printf("\tMonte Carlo efficiency: %g\n", + 1. / (*metadata.renderTimeSeconds * *metadata.estimatedVariance)); + else + printf("\n"); + } + + if (metadata.MSE) + printf("\tMSE vs. reference image: %g\n", *metadata.MSE); + + for (const auto &iter : metadata.stringVectors) { + printf("\t\"%s\": [ ", iter.first.c_str()); + for (const std::string &str : iter.second) + printf("\"%s\" ", str.c_str()); + printf("]\n"); + } + + printf("\tChannels:\n"); + + std::vector channelNames = image.ChannelNames(); + for (const auto &channel : channelNames) { + Float min = Infinity, max = -Infinity; + double sum = 0.; + int nNaN = 0, nInf = 0, nValid = 0; + ImageChannelDesc desc = image.GetChannelDesc({channel}); + + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) { + Float v = image.GetChannels({x, y}, desc); + + if (std::isnan(v)) + ++nNaN; + else if (std::isinf(v)) + ++nInf; + else { + min = std::min(min, v); + max = std::max(max, v); + sum += v; + ++nValid; + } + } + + printf("\t %20s: min %12g max %12g avg %12g (%d infinite, %d " + "not-a-number)\n", + channel.c_str(), min, max, sum / nValid, nInf, nNaN); + } +} + +// via tev's FalseColor.cpp, which developed by Thomas Müller +// and is published under the BSD 3-Clause License +// within the LICENSE file. + +// "viridis" colormap data generated with scripts/sample-colormap.py +static const std::vector falseColorValues = { + RGB(0.267004f, 0.004874f, 0.329415f), RGB(0.26851f, 0.009605f, 0.335427f), + RGB(0.269944f, 0.014625f, 0.341379f), RGB(0.271305f, 0.019942f, 0.347269f), + RGB(0.272594f, 0.025563f, 0.353093f), RGB(0.273809f, 0.031497f, 0.358853f), + RGB(0.274952f, 0.037752f, 0.364543f), RGB(0.276022f, 0.044167f, 0.370164f), + RGB(0.277018f, 0.050344f, 0.375715f), RGB(0.277941f, 0.056324f, 0.381191f), + RGB(0.278791f, 0.062145f, 0.386592f), RGB(0.279566f, 0.067836f, 0.391917f), + RGB(0.280267f, 0.073417f, 0.397163f), RGB(0.280894f, 0.078907f, 0.402329f), + RGB(0.281446f, 0.08432f, 0.407414f), RGB(0.281924f, 0.089666f, 0.412415f), + RGB(0.282327f, 0.094955f, 0.417331f), RGB(0.282656f, 0.100196f, 0.42216f), + RGB(0.28291f, 0.105393f, 0.426902f), RGB(0.283091f, 0.110553f, 0.431554f), + RGB(0.283197f, 0.11568f, 0.436115f), RGB(0.283229f, 0.120777f, 0.440584f), + RGB(0.283187f, 0.125848f, 0.44496f), RGB(0.283072f, 0.130895f, 0.449241f), + RGB(0.282884f, 0.13592f, 0.453427f), RGB(0.282623f, 0.140926f, 0.457517f), + RGB(0.28229f, 0.145912f, 0.46151f), RGB(0.281887f, 0.150881f, 0.465405f), + RGB(0.281412f, 0.155834f, 0.469201f), RGB(0.280868f, 0.160771f, 0.472899f), + RGB(0.280255f, 0.165693f, 0.476498f), RGB(0.279574f, 0.170599f, 0.479997f), + RGB(0.278826f, 0.17549f, 0.483397f), RGB(0.278012f, 0.180367f, 0.486697f), + RGB(0.277134f, 0.185228f, 0.489898f), RGB(0.276194f, 0.190074f, 0.493001f), + RGB(0.275191f, 0.194905f, 0.496005f), RGB(0.274128f, 0.199721f, 0.498911f), + RGB(0.273006f, 0.20452f, 0.501721f), RGB(0.271828f, 0.209303f, 0.504434f), + RGB(0.270595f, 0.214069f, 0.507052f), RGB(0.269308f, 0.218818f, 0.509577f), + RGB(0.267968f, 0.223549f, 0.512008f), RGB(0.26658f, 0.228262f, 0.514349f), + RGB(0.265145f, 0.232956f, 0.516599f), RGB(0.263663f, 0.237631f, 0.518762f), + RGB(0.262138f, 0.242286f, 0.520837f), RGB(0.260571f, 0.246922f, 0.522828f), + RGB(0.258965f, 0.251537f, 0.524736f), RGB(0.257322f, 0.25613f, 0.526563f), + RGB(0.255645f, 0.260703f, 0.528312f), RGB(0.253935f, 0.265254f, 0.529983f), + RGB(0.252194f, 0.269783f, 0.531579f), RGB(0.250425f, 0.27429f, 0.533103f), + RGB(0.248629f, 0.278775f, 0.534556f), RGB(0.246811f, 0.283237f, 0.535941f), + RGB(0.244972f, 0.287675f, 0.53726f), RGB(0.243113f, 0.292092f, 0.538516f), + RGB(0.241237f, 0.296485f, 0.539709f), RGB(0.239346f, 0.300855f, 0.540844f), + RGB(0.237441f, 0.305202f, 0.541921f), RGB(0.235526f, 0.309527f, 0.542944f), + RGB(0.233603f, 0.313828f, 0.543914f), RGB(0.231674f, 0.318106f, 0.544834f), + RGB(0.229739f, 0.322361f, 0.545706f), RGB(0.227802f, 0.326594f, 0.546532f), + RGB(0.225863f, 0.330805f, 0.547314f), RGB(0.223925f, 0.334994f, 0.548053f), + RGB(0.221989f, 0.339161f, 0.548752f), RGB(0.220057f, 0.343307f, 0.549413f), + RGB(0.21813f, 0.347432f, 0.550038f), RGB(0.21621f, 0.351535f, 0.550627f), + RGB(0.214298f, 0.355619f, 0.551184f), RGB(0.212395f, 0.359683f, 0.55171f), + RGB(0.210503f, 0.363727f, 0.552206f), RGB(0.208623f, 0.367752f, 0.552675f), + RGB(0.206756f, 0.371758f, 0.553117f), RGB(0.204903f, 0.375746f, 0.553533f), + RGB(0.203063f, 0.379716f, 0.553925f), RGB(0.201239f, 0.38367f, 0.554294f), + RGB(0.19943f, 0.387607f, 0.554642f), RGB(0.197636f, 0.391528f, 0.554969f), + RGB(0.19586f, 0.395433f, 0.555276f), RGB(0.1941f, 0.399323f, 0.555565f), + RGB(0.192357f, 0.403199f, 0.555836f), RGB(0.190631f, 0.407061f, 0.556089f), + RGB(0.188923f, 0.41091f, 0.556326f), RGB(0.187231f, 0.414746f, 0.556547f), + RGB(0.185556f, 0.41857f, 0.556753f), RGB(0.183898f, 0.422383f, 0.556944f), + RGB(0.182256f, 0.426184f, 0.55712f), RGB(0.180629f, 0.429975f, 0.557282f), + RGB(0.179019f, 0.433756f, 0.55743f), RGB(0.177423f, 0.437527f, 0.557565f), + RGB(0.175841f, 0.44129f, 0.557685f), RGB(0.174274f, 0.445044f, 0.557792f), + RGB(0.172719f, 0.448791f, 0.557885f), RGB(0.171176f, 0.45253f, 0.557965f), + RGB(0.169646f, 0.456262f, 0.55803f), RGB(0.168126f, 0.459988f, 0.558082f), + RGB(0.166617f, 0.463708f, 0.558119f), RGB(0.165117f, 0.467423f, 0.558141f), + RGB(0.163625f, 0.471133f, 0.558148f), RGB(0.162142f, 0.474838f, 0.55814f), + RGB(0.160665f, 0.47854f, 0.558115f), RGB(0.159194f, 0.482237f, 0.558073f), + RGB(0.157729f, 0.485932f, 0.558013f), RGB(0.15627f, 0.489624f, 0.557936f), + RGB(0.154815f, 0.493313f, 0.55784f), RGB(0.153364f, 0.497f, 0.557724f), + RGB(0.151918f, 0.500685f, 0.557587f), RGB(0.150476f, 0.504369f, 0.55743f), + RGB(0.149039f, 0.508051f, 0.55725f), RGB(0.147607f, 0.511733f, 0.557049f), + RGB(0.14618f, 0.515413f, 0.556823f), RGB(0.144759f, 0.519093f, 0.556572f), + RGB(0.143343f, 0.522773f, 0.556295f), RGB(0.141935f, 0.526453f, 0.555991f), + RGB(0.140536f, 0.530132f, 0.555659f), RGB(0.139147f, 0.533812f, 0.555298f), + RGB(0.13777f, 0.537492f, 0.554906f), RGB(0.136408f, 0.541173f, 0.554483f), + RGB(0.135066f, 0.544853f, 0.554029f), RGB(0.133743f, 0.548535f, 0.553541f), + RGB(0.132444f, 0.552216f, 0.553018f), RGB(0.131172f, 0.555899f, 0.552459f), + RGB(0.129933f, 0.559582f, 0.551864f), RGB(0.128729f, 0.563265f, 0.551229f), + RGB(0.127568f, 0.566949f, 0.550556f), RGB(0.126453f, 0.570633f, 0.549841f), + RGB(0.125394f, 0.574318f, 0.549086f), RGB(0.124395f, 0.578002f, 0.548287f), + RGB(0.123463f, 0.581687f, 0.547445f), RGB(0.122606f, 0.585371f, 0.546557f), + RGB(0.121831f, 0.589055f, 0.545623f), RGB(0.121148f, 0.592739f, 0.544641f), + RGB(0.120565f, 0.596422f, 0.543611f), RGB(0.120092f, 0.600104f, 0.54253f), + RGB(0.119738f, 0.603785f, 0.5414f), RGB(0.119512f, 0.607464f, 0.540218f), + RGB(0.119423f, 0.611141f, 0.538982f), RGB(0.119483f, 0.614817f, 0.537692f), + RGB(0.119699f, 0.61849f, 0.536347f), RGB(0.120081f, 0.622161f, 0.534946f), + RGB(0.120638f, 0.625828f, 0.533488f), RGB(0.12138f, 0.629492f, 0.531973f), + RGB(0.122312f, 0.633153f, 0.530398f), RGB(0.123444f, 0.636809f, 0.528763f), + RGB(0.12478f, 0.640461f, 0.527068f), RGB(0.126326f, 0.644107f, 0.525311f), + RGB(0.128087f, 0.647749f, 0.523491f), RGB(0.130067f, 0.651384f, 0.521608f), + RGB(0.132268f, 0.655014f, 0.519661f), RGB(0.134692f, 0.658636f, 0.517649f), + RGB(0.137339f, 0.662252f, 0.515571f), RGB(0.14021f, 0.665859f, 0.513427f), + RGB(0.143303f, 0.669459f, 0.511215f), RGB(0.146616f, 0.67305f, 0.508936f), + RGB(0.150148f, 0.676631f, 0.506589f), RGB(0.153894f, 0.680203f, 0.504172f), + RGB(0.157851f, 0.683765f, 0.501686f), RGB(0.162016f, 0.687316f, 0.499129f), + RGB(0.166383f, 0.690856f, 0.496502f), RGB(0.170948f, 0.694384f, 0.493803f), + RGB(0.175707f, 0.6979f, 0.491033f), RGB(0.180653f, 0.701402f, 0.488189f), + RGB(0.185783f, 0.704891f, 0.485273f), RGB(0.19109f, 0.708366f, 0.482284f), + RGB(0.196571f, 0.711827f, 0.479221f), RGB(0.202219f, 0.715272f, 0.476084f), + RGB(0.20803f, 0.718701f, 0.472873f), RGB(0.214f, 0.722114f, 0.469588f), + RGB(0.220124f, 0.725509f, 0.466226f), RGB(0.226397f, 0.728888f, 0.462789f), + RGB(0.232815f, 0.732247f, 0.459277f), RGB(0.239374f, 0.735588f, 0.455688f), + RGB(0.24607f, 0.73891f, 0.452024f), RGB(0.252899f, 0.742211f, 0.448284f), + RGB(0.259857f, 0.745492f, 0.444467f), RGB(0.266941f, 0.748751f, 0.440573f), + RGB(0.274149f, 0.751988f, 0.436601f), RGB(0.281477f, 0.755203f, 0.432552f), + RGB(0.288921f, 0.758394f, 0.428426f), RGB(0.296479f, 0.761561f, 0.424223f), + RGB(0.304148f, 0.764704f, 0.419943f), RGB(0.311925f, 0.767822f, 0.415586f), + RGB(0.319809f, 0.770914f, 0.411152f), RGB(0.327796f, 0.77398f, 0.40664f), + RGB(0.335885f, 0.777018f, 0.402049f), RGB(0.344074f, 0.780029f, 0.397381f), + RGB(0.35236f, 0.783011f, 0.392636f), RGB(0.360741f, 0.785964f, 0.387814f), + RGB(0.369214f, 0.788888f, 0.382914f), RGB(0.377779f, 0.791781f, 0.377939f), + RGB(0.386433f, 0.794644f, 0.372886f), RGB(0.395174f, 0.797475f, 0.367757f), + RGB(0.404001f, 0.800275f, 0.362552f), RGB(0.412913f, 0.803041f, 0.357269f), + RGB(0.421908f, 0.805774f, 0.35191f), RGB(0.430983f, 0.808473f, 0.346476f), + RGB(0.440137f, 0.811138f, 0.340967f), RGB(0.449368f, 0.813768f, 0.335384f), + RGB(0.458674f, 0.816363f, 0.329727f), RGB(0.468053f, 0.818921f, 0.323998f), + RGB(0.477504f, 0.821444f, 0.318195f), RGB(0.487026f, 0.823929f, 0.312321f), + RGB(0.496615f, 0.826376f, 0.306377f), RGB(0.506271f, 0.828786f, 0.300362f), + RGB(0.515992f, 0.831158f, 0.294279f), RGB(0.525776f, 0.833491f, 0.288127f), + RGB(0.535621f, 0.835785f, 0.281908f), RGB(0.545524f, 0.838039f, 0.275626f), + RGB(0.555484f, 0.840254f, 0.269281f), RGB(0.565498f, 0.84243f, 0.262877f), + RGB(0.575563f, 0.844566f, 0.256415f), RGB(0.585678f, 0.846661f, 0.249897f), + RGB(0.595839f, 0.848717f, 0.243329f), RGB(0.606045f, 0.850733f, 0.236712f), + RGB(0.616293f, 0.852709f, 0.230052f), RGB(0.626579f, 0.854645f, 0.223353f), + RGB(0.636902f, 0.856542f, 0.21662f), RGB(0.647257f, 0.8584f, 0.209861f), + RGB(0.657642f, 0.860219f, 0.203082f), RGB(0.668054f, 0.861999f, 0.196293f), + RGB(0.678489f, 0.863742f, 0.189503f), RGB(0.688944f, 0.865448f, 0.182725f), + RGB(0.699415f, 0.867117f, 0.175971f), RGB(0.709898f, 0.868751f, 0.169257f), + RGB(0.720391f, 0.87035f, 0.162603f), RGB(0.730889f, 0.871916f, 0.156029f), + RGB(0.741388f, 0.873449f, 0.149561f), RGB(0.751884f, 0.874951f, 0.143228f), + RGB(0.762373f, 0.876424f, 0.137064f), RGB(0.772852f, 0.877868f, 0.131109f), + RGB(0.783315f, 0.879285f, 0.125405f), RGB(0.79376f, 0.880678f, 0.120005f), + RGB(0.804182f, 0.882046f, 0.114965f), RGB(0.814576f, 0.883393f, 0.110347f), + RGB(0.82494f, 0.88472f, 0.106217f), RGB(0.83527f, 0.886029f, 0.102646f), + RGB(0.845561f, 0.887322f, 0.099702f), RGB(0.85581f, 0.888601f, 0.097452f), + RGB(0.866013f, 0.889868f, 0.095953f), RGB(0.876168f, 0.891125f, 0.09525f), + RGB(0.886271f, 0.892374f, 0.095374f), RGB(0.89632f, 0.893616f, 0.096335f), + RGB(0.906311f, 0.894855f, 0.098125f), RGB(0.916242f, 0.896091f, 0.100717f), + RGB(0.926106f, 0.89733f, 0.104071f), RGB(0.935904f, 0.89857f, 0.108131f), + RGB(0.945636f, 0.899815f, 0.112838f), RGB(0.9553f, 0.901065f, 0.118128f), + RGB(0.964894f, 0.902323f, 0.123941f), RGB(0.974417f, 0.90359f, 0.130215f), + RGB(0.983868f, 0.904867f, 0.136897f), RGB(0.993248f, 0.906157f, 0.143936f), +}; + +int falsecolor(int argc, char *argv[]) { + std::string outFile, inFile; + bool plusMinus = false; + Float maxValue = -Infinity; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("falsecolor", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "outfile", &outFile, onError) || + ParseArg(&argv, "plusminus", &plusMinus, onError) || + ParseArg(&argv, "maxValue", &maxValue, onError)) { + // success + } else if (inFile.empty() && argv[0][0] != '-') { + inFile = *argv; + ++argv; + } else { + usage("falsecolor", "%s: unknown command flag", *argv); + } + } + + if (inFile.empty()) + usage("falsecolor", "expecting input image filename."); + if (outFile.empty()) + usage("falsecolor", "expecting --outfile filename."); + + ImageAndMetadata im = Image::Read(inFile); + const Image &image = im.image; + + if (maxValue == -Infinity) + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) + maxValue = + std::max(maxValue, std::abs(image.GetChannels({x, y}).Average())); + + Image outImage(PixelFormat::Half, image.Resolution(), {"R", "G", "B"}); + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) { + Float relativeValue = image.GetChannels({x, y}).Average() / maxValue; + RGB rgb; + if (plusMinus) { + if (relativeValue > 0) + rgb = RGB(0, relativeValue, 0); + else + rgb = RGB(std::abs(relativeValue), 0, 0); + } else { + relativeValue = Clamp(relativeValue, 0, 1); + int index = relativeValue * falseColorValues.size(); + index = std::min(index, falseColorValues.size() - 1); + rgb = falseColorValues[index]; + } + + outImage.SetChannels({x, y}, {SRGBToLinear(rgb[0]), SRGBToLinear(rgb[1]), + SRGBToLinear(rgb[2])}); + } + + if (!outImage.Write(outFile)) + return 1; + + return 0; +} + +int info(int argc, char *argv[]) { + int err = 0; + for (int i = 0; i < argc; ++i) { + ImageAndMetadata im = Image::Read(argv[i]); + printImageStats(argv[i], im.image, im.metadata); + } + return err; +} + +Image bloom(Image image, Float level, int width, Float scale, int iters) { + return image; +} + +int bloom(int argc, char *argv[]) { + std::string inFile, outFile; + Float level = Infinity; + int width = 15; + Float scale = .3; + int iterations = 5; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("bloom", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "outfile", &outFile, onError) || + ParseArg(&argv, "level", &level, onError) || + ParseArg(&argv, "width", &width, onError) || + ParseArg(&argv, "iterations", &iterations, onError) || + ParseArg(&argv, "scale", &scale, onError)) { + // success + } else if (inFile.empty() && *argv[0] != '-') { + inFile = *argv; + ++argv; + } else { + onError(StringPrintf("argument %s invalid", *argv)); + } + } + + if (outFile.empty()) + usage("bloom", "--outfile must be specified"); + if (inFile.empty()) + usage("bloom", "input filename must be specified"); + + ImageAndMetadata imRead = Image::Read(inFile); + Image &image = imRead.image; + + std::vector blurred; + + // First, threshold the source image + int nSurvivors = 0; + Point2i res = image.Resolution(); + int nc = image.NChannels(); + Image thresholdedImage(PixelFormat::Float, image.Resolution(), image.ChannelNames()); + for (int y = 0; y < res.y; ++y) { + for (int x = 0; x < res.x; ++x) { + bool overThreshold = false; + for (int c = 0; c < nc; ++c) + if (image.GetChannel({x, y}, c) > level) + overThreshold = true; + if (overThreshold) { + ++nSurvivors; + for (int c = 0; c < nc; ++c) + thresholdedImage.SetChannel({x, y}, c, image.GetChannel({x, y}, c)); + } else + for (int c = 0; c < nc; ++c) + thresholdedImage.SetChannel({x, y}, c, 0.f); + } + } + if (nSurvivors == 0) { + fprintf(stderr, "imgtool: no pixels were above bloom threshold %f\n", level); + return 1; + } + blurred.push_back(std::move(thresholdedImage)); + + if ((width % 2) == 0) { + ++width; + fprintf(stderr, "imgtool bloom: width must be an odd value. Rounding up to %d.\n", + width); + } + int radius = width / 2; + + // Blur thresholded image. + Float sigma = radius / 2.; // TODO: make a parameter + + for (int iter = 0; iter < iterations; ++iter) { + Image blur = + blurred.back().GaussianFilter(image.AllChannelsDesc(), radius, sigma); + blurred.push_back(blur); + } + + // Finally, add all of the blurred images, scaled, to the original. + for (int y = 0; y < res.y; ++y) { + for (int x = 0; x < res.x; ++x) { + for (int c = 0; c < nc; ++c) { + Float blurredSum = 0.f; + // Skip the thresholded image, since it's already + // present in the original; just add pixels from the + // blurred ones. + for (size_t j = 1; j < blurred.size(); ++j) + blurredSum += blurred[j].GetChannel({x, y}, c); + image.SetChannel( + {x, y}, c, + image.GetChannel({x, y}, c) + (scale / iterations) * blurredSum); + } + } + } + + image.Write(outFile); + + return 0; +} + +int convert(int argc, char *argv[]) { + bool acesFilmic = false; + float scale = 1.f, gamma = 1.f; + int repeat = 1; + bool flipy = false; + bool tonemap = false; + Float maxY = 1.; + Float despikeLimit = Infinity; + bool preserveColors = false; + bool bw = false; + std::string inFile, outFile; + std::string colorspace; + std::string channelNames; + std::array cropWindow = {-1, 0, -1, 0}; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("convert", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "acesfilmic", &acesFilmic, onError) || + ParseArg(&argv, "bw", &bw, onError) || + ParseArg(&argv, "channels", &channelNames, onError) || + ParseArg(&argv, "colorspace", &colorspace, onError) || + ParseArg(&argv, "crop", pstd::MakeSpan(cropWindow), onError) || + ParseArg(&argv, "despike", &despikeLimit, onError) || + ParseArg(&argv, "flipy", &flipy, onError) || + ParseArg(&argv, "gamma", &gamma, onError) || + ParseArg(&argv, "maxluminance", &maxY, onError) || + ParseArg(&argv, "outfile", &outFile, onError) || + ParseArg(&argv, "preservecolors", &preserveColors, onError) || + ParseArg(&argv, "repeatpix", &repeat, onError) || + ParseArg(&argv, "scale", &scale, onError) || + ParseArg(&argv, "tonemap", &tonemap, onError)) { + // success + } else if (argv[0][0] != '-' && inFile.empty()) { + inFile = *argv; + ++argv; + } else + usage("convert", "%s: unknown command flag", *argv); + } + + if (maxY <= 0) + usage("convert", "--maxluminance value must be greater than zero"); + if (repeat <= 0) + usage("convert", "--repeatpix value must be greater than zero"); + if (scale == 0) + usage("convert", "--scale value must be non-zero"); + if (outFile.empty()) + usage("convert", "--outfile filename must be specified"); + if (inFile.empty()) + usage("convert", "input filename not specified"); + + ImageAndMetadata imRead = Image::Read(inFile); + Image image = std::move(imRead.image); + ImageMetadata metadata = std::move(imRead.metadata); + + if (channelNames.empty()) { + // If the input image has AOVs and the target image is a regular + // format, then just grab R,G,B... + bool hasAOVs = false; + for (const std::string &name : image.ChannelNames()) + if (name != "R" && name != "G" && name != "B" && name != "A") { + hasAOVs = true; + break; + } + + if (hasAOVs && !HasExtension(outFile, "exr")) { + fprintf(stderr, + "%s: image has non-RGB channels but converting to an " + "image format that can't store them. Converting RGB only.\n", + inFile.c_str()); + channelNames = "R,G,B"; + } + } + + if (!channelNames.empty()) { + std::vector splitChannelNames = SplitString(channelNames, ','); + ImageChannelDesc desc = image.GetChannelDesc(splitChannelNames); + if (!desc) { + fprintf(stderr, "%s: image doesn't have channels \"%s\".\n", inFile.c_str(), + channelNames.c_str()); + return 1; + } + image = image.SelectChannels(desc); + } + + Point2i res = image.Resolution(); + int nc = image.NChannels(); + + // Crop + // If last 2 are negative, they're taken as deltas + if (cropWindow[1] < 0) + cropWindow[1] = cropWindow[0] - cropWindow[1]; + if (cropWindow[3] < 0) + cropWindow[3] = cropWindow[2] - cropWindow[3]; + if (cropWindow[0] >= 0 && cropWindow[2] >= 0) { + image = image.Crop( + Bounds2i({cropWindow[0], cropWindow[2]}, {cropWindow[1], cropWindow[3]})); + res = image.Resolution(); + } + + // Convert to a 32-bit format for maximum accuracy in the following + // processing. + if (!Is32Bit(image.Format())) + image = image.ConvertToFormat(PixelFormat::Float); + + if (!colorspace.empty()) { + const RGBColorSpace *dest = RGBColorSpace::GetNamed(colorspace); + if (!dest) { + fprintf(stderr, "%s: color space unknown.\n", colorspace.c_str()); + return 1; + } + ImageChannelDesc rgbDesc = image.GetChannelDesc({"R", "G", "B"}); + if (!rgbDesc) { + fprintf(stderr, "%s: doesn't have R, G, B channels.\n", inFile.c_str()); + return 1; + } + + const RGBColorSpace *srcColorSpace = (metadata.colorSpace && *metadata.colorSpace) + ? *metadata.colorSpace + : RGBColorSpace::sRGB; + SquareMatrix<3> m = ConvertRGBColorSpace(*srcColorSpace, *dest); + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) { + ImageChannelValues channels = image.GetChannels({x, y}, rgbDesc); + RGB rgb = Mul(m, channels); + image.SetChannels({x, y}, rgbDesc, {rgb.r, rgb.g, rgb.b}); + } + metadata.colorSpace = dest; + } + + if (bw) { + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) { + Float sum = 0; + for (int c = 0; c < nc; ++c) + sum += image.GetChannel({x, y}, c); + sum /= nc; + for (int c = 0; c < nc; ++c) + image.SetChannel({x, y}, c, sum); + } + } + + if (despikeLimit < Infinity) { + Image filteredImg = image; + int despikeCount = 0; + std::vector neighbors; + for (int i = 0; i < 9; ++i) + neighbors.push_back(ImageChannelValues(image.NChannels())); + + for (int y = 0; y < res.y; ++y) { + for (int x = 0; x < res.x; ++x) { + if (image.GetChannels({x, y}).Average() < despikeLimit) + continue; + + // Copy all of the valid neighbor pixels into neighbors[]. + ++despikeCount; + int validNeighbors = 0; + for (int dy = -1; dy <= 1; ++dy) { + if (y + dy < 0 || y + dy >= res.y) + continue; + for (int dx = -1; dx <= 1; ++dx) { + if (x + dx < 0 || x + dx > res.x) + continue; + neighbors[validNeighbors++] = image.GetChannels({x + dx, y + dy}); + } + } + + // Find the median of the neighbors, sorted by average value. + int mid = validNeighbors / 2; + std::nth_element( + &neighbors[0], &neighbors[mid], &neighbors[validNeighbors], + [](const ImageChannelValues &a, const ImageChannelValues &b) -> bool { + return a.Average() < b.Average(); + }); + filteredImg.SetChannels({x, y}, neighbors[mid]); + } + } + pstd::swap(image, filteredImg); + fprintf(stderr, "%s: despiked %d pixels\n", inFile.c_str(), despikeCount); + } + + if (scale != 1) { + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) + for (int c = 0; c < nc; ++c) + image.SetChannel({x, y}, c, scale * image.GetChannel({x, y}, c)); + } + + if (gamma != 1) { + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) + for (int c = 0; c < nc; ++c) + image.SetChannel( + {x, y}, c, + std::pow(std::max(0, image.GetChannel({x, y}, c)), gamma)); + } + + if (tonemap) { + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) { + Float lum = image.GetChannels({x, y}).Average(); + // Reinhard et al. photographic tone mapping operator. + Float scale = (1 + lum / (maxY * maxY)) / (1 + lum); + for (int c = 0; c < nc; ++c) + image.SetChannel({x, y}, c, scale * image.GetChannel({x, y}, c)); + } + } + + if (preserveColors) { + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) { + Float m = image.GetChannel({x, y}, 0); + for (int c = 1; c < nc; ++c) + m = std::max(m, image.GetChannel({x, y}, c)); + if (m > 1) { + for (int c = 0; c < nc; ++c) + image.SetChannel({x, y}, c, image.GetChannel({x, y}, c) / m); + } + } + } + + if (acesFilmic) { + // Approximation via + // https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/ + auto ACESFilm = [](Float x) -> Float { + if (x <= 0) + return 0; + Float a = 2.51f; + Float b = 0.03f; + Float c = 2.43f; + Float d = 0.59f; + Float e = 0.14f; + return Clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0, 1); + }; + + for (int y = 0; y < res.y; ++y) + for (int x = 0; x < res.x; ++x) { + for (int c = 0; c < nc; ++c) { + Float v = image.GetChannel({x, y}, c); + v = ACESFilm(v); + image.SetChannel({x, y}, c, v); + } + } + } + + if (repeat > 1) { + Image scaledImage(image.Format(), Point2i(res.x * repeat, res.y * repeat), + image.ChannelNames(), image.Encoding()); + for (int y = 0; y < repeat * res.y; ++y) { + int yy = y / repeat; + for (int x = 0; x < repeat * res.x; ++x) { + int xx = x / repeat; + for (int c = 0; c < nc; ++c) + scaledImage.SetChannel({x, y}, c, image.GetChannel({xx, yy}, c)); + } + } + image = std::move(scaledImage); + res = image.Resolution(); + } + + if (flipy) + image.FlipY(); + + if (!image.Write(outFile)) + return 1; + + return 0; +} + +int whitebalance(int argc, char *argv[]) { + std::string inFile, outFile; + Float temperature = 0; + std::array xy = {Float(0), Float(0)}; + std::string illuminant; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("whitebalance", "%s", err.c_str()); + exit(1); + }; + + if (ParseArg(&argv, "outfile", &outFile, onError) || + ParseArg(&argv, "primaries", pstd::MakeSpan(xy), onError) || + ParseArg(&argv, "illuminant", &illuminant, onError) || + ParseArg(&argv, "temperature", &temperature, onError)) { + // success + } else if (inFile.empty() && *argv[0] != '-') { + inFile = *argv; + ++argv; + } else { + onError(StringPrintf("argument %s invalid", *argv)); + } + } + + if (outFile.empty()) + usage("whitebalance", "--outfile must be specified"); + if (inFile.empty()) + usage("whitebalance", "input filename must be specified"); + + if ((!illuminant.empty() + (temperature > 0) + (xy[0] != 0)) > 1) + usage("whitebalance", + "can only provide one of --illuminant, --primaries, --temperature"); + if (illuminant.empty() && temperature == 0 && xy[0] == 0) + usage("whitebalance", + "must provide one of --illuminant, --primaries, or --temperature"); + + ImageAndMetadata imRead = Image::Read(inFile); + Image &image = imRead.image; + + ImageChannelDesc rgbDesc = image.GetChannelDesc({"R", "G", "B"}); + if (!rgbDesc) { + fprintf(stderr, "%s: doesn't have R, G, B channels.\n", inFile.c_str()); + return 1; + } + + const RGBColorSpace *colorSpace = imRead.metadata.GetColorSpace(); + Point2f srcWhite, targetWhite = colorSpace->w; + if (!illuminant.empty()) { + std::string name = "stdillum-" + illuminant; + SpectrumHandle illum = GetNamedSpectrum(name); + if (!illum) { + fprintf(stderr, "%s: illuminant unknown.\n", name.c_str()); + return 1; + } + srcWhite = SpectrumToXYZ(illum).xy(); + } else if (temperature > 0) { + BlackbodySpectrum bb(temperature, 1.f); + srcWhite = SpectrumToXYZ(&bb).xy(); + } else + srcWhite = Point2f(xy[0], xy[1]); + + SquareMatrix<3> ccMatrix = colorSpace->RGBFromXYZ * + WhiteBalance(srcWhite, targetWhite) * + colorSpace->XYZFromRGB; + + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) { + ImageChannelValues channels = image.GetChannels({x, y}, rgbDesc); + RGB rgb = Mul(ccMatrix, channels); + image.SetChannels({x, y}, rgbDesc, {rgb.r, rgb.g, rgb.b}); + } + + image.Write(outFile); + + return 0; +} + +int makeemitters(int argc, char *argv[]) { + const char *filename = nullptr; + int downsampleRate = 1; + + auto onError = [](const std::string &err) { + usage("makeemitters", "%s", err.c_str()); + exit(1); + }; + while (*argv != nullptr) { + if (ParseArg(&argv, "downsample", &downsampleRate, onError)) { + // success + } else if (argv[0][0] == '-') + usage("makeemitters", "%s: unknown command flag", *argv); + else if (!filename) { + filename = *argv; + ++argv; + } else + usage("makeemitters", "multiple input filenames provided."); + } + + if (filename == nullptr) + usage("makeemitters", "missing image filename"); + + ImageAndMetadata im = Image::Read(filename); + const Image &image = im.image; + + ImageChannelDesc rgbDesc = image.GetChannelDesc({"R", "G", "B"}); + if (!rgbDesc) { + fprintf(stderr, "%s: didn't find R, G, and B channels", filename); + return 1; + } + + Point2i res = image.Resolution(); + float aspect = float(res.x) / float(res.y); + printf("AttributeBegin\n"); + printf("Material \"matte\" \"rgb Kd\" [0 0 0]\n"); + for (int y = 0; y < image.Resolution().y; y += downsampleRate) + for (int x = 0; x < image.Resolution().x; x += downsampleRate) { + ImageChannelValues pSum(rgbDesc.size()); + for (int dy = 0; dy < downsampleRate; ++dy) + for (int dx = 0; dx < downsampleRate; ++dx) { + Point2i pp(x + dx, y + dy); + if (pp.x >= res.x && pp.y >= res.y) + continue; + + ImageChannelValues p = image.GetChannels(pp, rgbDesc); + for (int c = 0; c < p.size(); ++c) + pSum[c] += p[c]; + } + for (int c = 0; c < pSum.size(); ++c) + pSum[c] /= downsampleRate * downsampleRate; + + printf("AreaLightSource \"diffuse\" \"rgb L\" [ %f %f %f ]\n", pSum[0], + pSum[1], pSum[2]); + + float x0 = aspect * (1 - float(x) / image.Resolution().x) - aspect / 2; + float x1 = aspect * (1 - float(std::min(x + downsampleRate, res.x)) / + image.Resolution().x) - + aspect / 2; + float y0 = 1 - float(y) / image.Resolution().y; + float y1 = + 1 - float(std::min(y + downsampleRate, res.y)) / image.Resolution().y; + printf("Shape \"bilinear\" \"point3 P\" [ %f %f 0 %f %f 0 %f %f 0 " + "%f %f 0 ]\n", + x0, y0, x1, y0, x0, y1, x1, y1); + } + printf("AttributeEnd\n"); + + return 0; +} + +int makeenv(int argc, char *argv[]) { + std::string inFilename, outFilename; + int resolution = 0; + + auto onError = [](const std::string &err) { + usage("makeenv", "%s", err.c_str()); + exit(1); + }; + while (*argv != nullptr) { + if (ParseArg(&argv, "resolution", &resolution, onError) || + ParseArg(&argv, "outfile", &outFilename, onError)) { + // success + } else if (argv[0][0] == '-') + usage("makeenv", "%s: unknown command flag", *argv); + else if (inFilename.empty()) { + inFilename = *argv; + ++argv; + } else + usage("makeenv", "multiple input filenames provided."); + } + if (inFilename.empty()) + usage("makeenv", "input image filename must be provided."); + if (outFilename.empty()) + usage("makeenv", "output image filename must be provided."); + + ImageAndMetadata latlong = Image::Read(inFilename); + const Image &latlongImage = latlong.image; + + if (2 * latlongImage.Resolution().y != latlongImage.Resolution().x) + fprintf(stderr, + "%s: Warning: resolution (%d, %d) doesn't have a 2:1 aspect ratio. " + "It's doubtful that this is a lat-long environment map.\n", + inFilename.c_str(), latlongImage.Resolution().x, + latlongImage.Resolution().y); + + if (resolution == 0) + // resolution = 1.25f * latlongImage.Resolution().x * std::sqrt(2.f) / + // 4; + resolution = latlongImage.Resolution().x; + + // TODO: should we check that lat-long has RGB here? + // Should we only copy over RGB? + Image equiRectImage(latlongImage.Format(), {resolution, resolution}, + latlongImage.ChannelNames(), latlongImage.Encoding()); + + GaussianFilter filter(Vector2f(1.5, 1.5), 2); + // MitchellFilter filter(Vector2f(2.f, 2.f), 1.f/3.f, 1.f/3.f); + int sqrtSamples = 6; + WrapMode2D latlongWrap(WrapMode::Repeat, WrapMode::Clamp); + + ParallelFor(0, resolution, [&](int64_t v0, int64_t v1) { + RNG rng(v0); + for (int v = v0; v < v1; ++v) + for (int u = 0; u < resolution; ++u) { + Float sumWeight = 0; + ImageChannelValues sumSamples(latlongImage.NChannels(), 0.f); + + for (int dv = 0; dv < sqrtSamples; ++dv) + for (int du = 0; du < sqrtSamples; ++du) { + // Stratified samples + Point2f s2((du + rng.Uniform()) / sqrtSamples, + (dv + rng.Uniform()) / sqrtSamples); + FilterSample fs = filter.Sample(s2); + // Map to a point in the equirect map for the current + // pixel. + Point2f pSquare((u + 0.5f + fs.p.x) / resolution, + (v + 0.5f + fs.p.y) / resolution); + pSquare = WrapEquiAreaSquare(pSquare); + + // Get corresponding pixel values from the lat-long map. + Vector3f dir = EquiAreaSquareToSphere(pSquare); + Float theta = SphericalTheta(dir), phi = SphericalPhi(dir); + Point2f p(phi / (2 * Pi), theta / Pi); + ImageChannelValues values = latlongImage.Bilerp(p, latlongWrap); + + // Accumulate + for (size_t i = 0; i < values.size(); ++i) + sumSamples[i] += fs.weight * values[i]; + sumWeight += fs.weight; + } + for (size_t i = 0; i < sumSamples.size(); ++i) + sumSamples[i] = std::max(0, sumSamples[i] / sumWeight); + equiRectImage.SetChannels({u, v}, sumSamples); + } + }); + + ImageMetadata equiRectMetadata; + equiRectMetadata.cameraFromWorld = latlong.metadata.cameraFromWorld; + equiRectMetadata.NDCFromWorld = latlong.metadata.NDCFromWorld; + equiRectMetadata.colorSpace = latlong.metadata.colorSpace; + equiRectMetadata.stringVectors = latlong.metadata.stringVectors; + equiRectImage.Write(outFilename, equiRectMetadata); + + return 0; +} + +Image denoiseImage(const Image &in, const ImageChannelDesc &Ldesc, + const Image &varianceImage, const ImageChannelDesc &albedoDesc, + const ImageChannelDesc &zDesc, const ImageChannelDesc &deltaZDesc, + const ImageChannelDesc &nDesc, int halfWidth, int nLevels) { + Image illum(PixelFormat::Float, in.Resolution(), {"R", "G", "B"}); + for (int y = 0; y < in.Resolution().y; ++y) + for (int x = 0; x < in.Resolution().x; ++x) { + ImageChannelValues albedo = in.GetChannels({x, y}, albedoDesc); + ImageChannelValues L = in.GetChannels({x, y}, Ldesc); + for (int c = 0; c < 3; ++c) + if (albedo[c] > 0) + illum.SetChannel({x, y}, c, L[c] / albedo[c]); + else + illum.SetChannel({x, y}, c, L[c]); + } + + std::vector f(halfWidth + 1, 0.); + for (int i = 0; i <= halfWidth; ++i) + f[i] = FastExp(-Float(i) / halfWidth * 3.f); + + static int call = -1; + ++call; + + Image currentImage = std::move(illum); + for (int i = 0; i < nLevels; ++i) { + int delta = 1 << i; // A-Trous step between samples. + + Image filtered(PixelFormat::Float, in.Resolution(), {"R", "G", "B"}); + // Image wImage(PixelFormat::Float, in.Resolution(), 3, "Wp,Wn,Wc"); + // Image dzImage(PixelFormat::Float, in.Resolution(), 1, "Y"); + + ParallelFor(0, currentImage.Resolution().y, [&](int64_t start, int64_t end) { + for (int y = start; y < end; ++y) { + for (int x = 0; x < currentImage.Resolution().x; ++x) { + float wsum = 0; + ImageChannelValues c = currentImage.GetChannels({x, y}); + + Float z = in.GetChannels({x, y}, zDesc); + // FIXME: hack multiply to cancel out scaled ray + // differentials... + Float dzdx = 8 * in.GetChannels({x, y}, deltaZDesc)[0]; + Float dzdy = 8 * in.GetChannels({x, y}, deltaZDesc)[1]; + + ImageChannelValues nChan = in.GetChannels({x, y}, nDesc); + Normal3f n = Normal3f(nChan[0], nChan[1], nChan[2]); + if (n == Normal3f(0, 0, 0)) + // background pixel + continue; + + Float pixelVariance = varianceImage.GetChannel({x, y}, 0); + float result[3] = {0.f}; + float wpSum = 0, wnSum = 0, wcSum = 0; + // if (pixelVariance > .001) { + // pixelVariance = std::max(pixelVariance, + // .000001); { + { + // Higher sigma -> more blur + // Float sigma_y = .05; + Float sigma_z = .005; + + // sigma_y = pixelVariance * 50; + // sigma_y = std::sqrt(std::sqrt(pixelVariance)) * + // 10 * sigmaYScale; + + for (int dy = -halfWidth * delta; dy <= halfWidth * delta; + dy += delta) { + if (y + dy < 0 || y + dy >= currentImage.Resolution().y) + continue; + for (int dx = -halfWidth * delta; dx <= halfWidth * delta; + dx += delta) { + if (x + dx < 0 || x + dx >= currentImage.Resolution().x) + continue; + ImageChannelValues co = + currentImage.GetChannels({x + dx, y + dy}); + Float dc2 = (Sqr(c[0] - co[0]) + Sqr(c[1] - co[1]) + + Sqr(c[2] - co[2])); // squared color + // difference + Float otherVariance = + varianceImage.GetChannel({x + dx, y + dy}, 0); + Float d2 = + std::max(0, dc2 - (pixelVariance + + std::min(pixelVariance, + otherVariance))) / + (1e-4 + 0.36f * (pixelVariance + otherVariance)); + + Float zo = in.GetChannels({x + dx, y + dy}, zDesc); + ImageChannelValues noChan = + in.GetChannels({x + dx, y + dy}, nDesc); + Normal3f no = Normal3f(noChan[0], noChan[1], noChan[2]); + if (no == Normal3f(0, 0, 0)) + // background pixel; + continue; + + Float zp = z + dx * dzdx + dy * dzdy; + Float dz = (z - zp) / ((z + zp) * 0.5f); + + // Assume camera space position... + Float wp = Gaussian(dz, 0, sigma_z) * + f[std::abs(dy / delta)] * + f[std::abs(dx / delta)]; + Float wn = Pow<32>(std::max(0, Dot(n, no))); + Float wc = + FastExp(-d2 / 90); // Gaussian(dc, 0, sigma_y); + CHECK(!std::isnan(wc)); + wpSum += wp; + wnSum += wn; + wcSum += wc; + Float w = wp * wn * wc; + + // CO fprintf(stderr, "(%d, %d) dc2 %f var + // %f other var %f -> d2 %f\n", CO x, y, + // dc2, pixelVariance, otherVariance, d2); + + CHECK(!std::isnan(w)); + if (w == 0) + continue; + + for (int c = 0; c < 3; ++c) { + result[c] += + w * currentImage.GetChannel({x + dx, y + dy}, c); + CHECK(!std::isnan(result[c])); + } + wsum += w; + } + } + } + for (int c = 0; c < 3; ++c) + if (wsum > 0) { + filtered.SetChannel({x, y}, c, result[c] / wsum); + // wImage.SetChannels({x, y}, {wpSum, wnSum, + // wcSum}); + } else + filtered.SetChannel({x, y}, c, + currentImage.GetChannel({x, y}, c)); + } + } + }); + + // filtered.Write(StringPrintf("filtered-%d-%d.exr", call, i)); + // wImage.Write(StringPrintf("weights%d.exr", i)); + // if (i == 0) + // dzImage.Write("dz.exr"); + + pstd::swap(filtered, currentImage); + } + + // static int i = 0; + // currentImage.Write(StringPrintf("filteredillum-%d.exr", i++)); + + // reincorporate albedo + for (int y = 0; y < currentImage.Resolution().y; ++y) + for (int x = 0; x < currentImage.Resolution().x; ++x) { + ImageChannelValues albedo = in.GetChannels({x, y}, albedoDesc); + for (int c = 0; c < 3; ++c) + currentImage.SetChannel({x, y}, c, + currentImage.GetChannel({x, y}, c) * albedo[c]); + } + + return currentImage; +} + +int denoise(int argc, char *argv[]) { + std::string inFilename, outFilename; + + auto onError = [](const std::string &err) { + usage("denoise", "%s", err.c_str()); + exit(1); + }; + while (*argv != nullptr) { + if (ParseArg(&argv, "outfile", &outFilename, onError)) { + // success + } else if (argv[0][0] == '-') + usage("denoise", "%s: unknown command flag", *argv); + else if (inFilename.empty()) { + inFilename = *argv; + ++argv; + } else + usage("denoise", "multiple input filenames provided."); + } + if (inFilename.empty()) + usage("denoise", "input image filename must be provided."); + if (outFilename.empty()) + usage("denoise", "output image filename must be provided."); + + ImageAndMetadata im = Image::Read(inFilename); + Image &in = im.image; + + auto checkForChannels = [&inFilename](ImageChannelDesc &desc, const char *names) { + if (!desc) { + fprintf(stderr, "%s: didn't find \"%s\" channels.\n", inFilename.c_str(), + names); + exit(1); + } + }; + ImageChannelDesc rgbDesc = in.GetChannelDesc({"R", "G", "B"}); + checkForChannels(rgbDesc, "R,G,B"); + ImageChannelDesc zDesc = in.GetChannelDesc({"Pz"}); + checkForChannels(zDesc, "Pz"); + ImageChannelDesc deltaZDesc = in.GetChannelDesc({"dzdx", "dzdy"}); + checkForChannels(deltaZDesc, "dzdx,dzdy"); + ImageChannelDesc nDesc = in.GetChannelDesc({"Nx", "Ny", "Nz"}); + checkForChannels(nDesc, "Nx,Ny,Nz"); + ImageChannelDesc nsDesc = in.GetChannelDesc({"Nsx", "Nsy", "Nsz"}); + checkForChannels(nsDesc, "Nsx,Nsy,Nsz"); + ImageChannelDesc albedoDesc = in.GetChannelDesc({"Albedo.R", "Albedo.G", "Albedo.B"}); + checkForChannels(albedoDesc, "Albedo.R,Albedo.G,Albedo.B"); + ImageChannelDesc varianceDesc = in.GetChannelDesc({"rgbVariance"}); + checkForChannels(varianceDesc, "rgbVariance"); + + ImageChannelDesc jointDesc = in.GetChannelDesc({"Pz", "Nx", "Ny", "Nz"}); + ImageChannelValues jointSigmaIndir(4, 1); + Float xySigmaIndir[2] = {2.f, 2.f}; + Image filteredVariance = in.JointBilateralFilter(varianceDesc, 7, xySigmaIndir, + jointDesc, jointSigmaIndir); + + int halfWidth = 3; + int nLevels = 3; + Image denoisedImage = denoiseImage(in, rgbDesc, filteredVariance, albedoDesc, zDesc, + deltaZDesc, nsDesc, halfWidth, nLevels); + + Image result(PixelFormat::Float, in.Resolution(), {"R", "G", "B"}); + for (int y = 0; y < in.Resolution().y; ++y) + for (int x = 0; x < in.Resolution().x; ++x) { + ImageChannelValues Ldenoised = denoisedImage.GetChannels({x, y}); + for (int c = 0; c < 3; ++c) + result.SetChannel({x, y}, c, Ldenoised[c]); + } + + if (!result.Write(outFilename)) { + fprintf(stderr, "%s: couldn't write image.\n", outFilename.c_str()); + return 1; + } + return 0; +} + +#ifdef PBRT_BUILD_GPU_RENDERER +int denoise_optix(int argc, char *argv[]) { + std::string inFilename, outFilename; + + auto onError = [](const std::string &err) { + usage("denoise-optix", "%s", err.c_str()); + exit(1); + }; + while (*argv != nullptr) { + if (ParseArg(&argv, "outfile", &outFilename, onError)) { + // success + } else if (argv[0][0] == '-') + usage("denoise-optix", "%s: unknown command flag", *argv); + else if (inFilename.empty()) { + inFilename = *argv; + ++argv; + } else + usage("denoise-optix", "multiple input filenames provided."); + } + if (inFilename.empty()) + usage("denoise-optix", "input image filename must be provided."); + if (outFilename.empty()) + usage("denoise-optix", "output image filename must be provided."); + + CUDA_CHECK(cudaFree(nullptr)); + + CUcontext cudaContext; + CU_CHECK(cuCtxGetCurrent(&cudaContext)); + CHECK(cudaContext != nullptr); + + OPTIX_CHECK(optixInit()); + OptixDeviceContext optixContext; + OPTIX_CHECK(optixDeviceContextCreate(cudaContext, 0, &optixContext)); + + ImageAndMetadata im = Image::Read(inFilename); + Image &image = im.image; + + OptixDenoiserOptions options = {}; + options.inputKind = OPTIX_DENOISER_INPUT_RGB_ALBEDO_NORMAL; + + OptixDenoiser denoiserHandle; + OPTIX_CHECK(optixDenoiserCreate(optixContext, &options, &denoiserHandle)); + + OPTIX_CHECK( + optixDenoiserSetModel(denoiserHandle, OPTIX_DENOISER_MODEL_KIND_HDR, nullptr, 0)); + + OptixDenoiserSizes memorySizes; + OPTIX_CHECK(optixDenoiserComputeMemoryResources(denoiserHandle, image.Resolution().x, + image.Resolution().y, &memorySizes)); + + void *denoiserState; + CUDA_CHECK(cudaMalloc(&denoiserState, memorySizes.stateSizeInBytes)); + void *scratchBuffer; + CUDA_CHECK(cudaMalloc(&scratchBuffer, memorySizes.withoutOverlapScratchSizeInBytes)); + + OPTIX_CHECK(optixDenoiserSetup( + denoiserHandle, 0 /* stream */, image.Resolution().x, image.Resolution().y, + CUdeviceptr(denoiserState), memorySizes.stateSizeInBytes, + CUdeviceptr(scratchBuffer), memorySizes.withoutOverlapScratchSizeInBytes)); + + CUDAMemoryResource cudaMemoryResource; + Allocator alloc(&cudaMemoryResource); + + ImageChannelDesc desc[3] = { + image.GetChannelDesc({"R", "G", "B"}), + image.GetChannelDesc({"Albedo.R", "Albedo.G", "Albedo.B"}), + image.GetChannelDesc({"Nsx", "Nsy", "Nsz"})}; + if (!desc[0]) { + fprintf(stderr, "%s: image doesn't have R, G, B channels.", inFilename.c_str()); + return 1; + } + if (!desc[1]) { + fprintf(stderr, "%s: image doesn't have Albedo.{R,G,B} channels.", + inFilename.c_str()); + return 1; + } + if (!desc[2]) { + fprintf(stderr, "%s: image doesn't have Nsx, Nsy, Nsz channels.", + inFilename.c_str()); + return 1; + } + + OptixImage2D *inputLayers = alloc.allocate_object(3); + for (int i = 0; i < 3; ++i) { + inputLayers[i].width = image.Resolution().x; + inputLayers[i].height = image.Resolution().y; + inputLayers[i].rowStrideInBytes = image.Resolution().x * 3 * sizeof(float); + inputLayers[i].pixelStrideInBytes = 0; + inputLayers[i].format = OPTIX_PIXEL_FORMAT_FLOAT3; + + size_t sz = 3 * image.Resolution().x * image.Resolution().y; + float *buf = alloc.allocate_object(sz); + int offset = 0; + for (int y = 0; y < image.Resolution().y; ++y) + for (int x = 0; x < image.Resolution().x; ++x) { + ImageChannelValues v = image.GetChannels({x, y}, desc[i]); + if (i == 2) + v[2] *= -1; // flip z--right handed... + for (int c = 0; c < 3; ++c) + buf[offset++] = v[c]; + } + + inputLayers[i].data = CUdeviceptr(buf); + } + + OptixImage2D *outputImage = alloc.allocate_object(); + outputImage->width = image.Resolution().x; + outputImage->height = image.Resolution().y; + outputImage->rowStrideInBytes = image.Resolution().x * 3 * sizeof(float); + outputImage->pixelStrideInBytes = 0; + outputImage->format = OPTIX_PIXEL_FORMAT_FLOAT3; + + float *intensity = alloc.allocate_object(); + OPTIX_CHECK(optixDenoiserComputeIntensity( + denoiserHandle, 0 /* stream */, &inputLayers[0], CUdeviceptr(intensity), + CUdeviceptr(scratchBuffer), memorySizes.withoutOverlapScratchSizeInBytes)); + + size_t sz = 3 * image.Resolution().x * image.Resolution().y; + pstd::vector buf(sz, alloc); + outputImage->data = CUdeviceptr(buf.data()); + + OptixDenoiserParams params = {}; + params.denoiseAlpha = 0; + params.hdrIntensity = CUdeviceptr(intensity); + params.blendFactor = 0; // TODO what should this be?? + + OPTIX_CHECK(optixDenoiserInvoke( + denoiserHandle, 0 /* stream */, ¶ms, CUdeviceptr(denoiserState), + memorySizes.stateSizeInBytes, inputLayers, 3, 0 /* offset x */, 0 /* offset y */, + outputImage, CUdeviceptr(scratchBuffer), + memorySizes.withoutOverlapScratchSizeInBytes)); + + CUDA_CHECK(cudaDeviceSynchronize()); + + Image result(buf, image.Resolution(), {"R", "G", "B"}); + CHECK(result.Write(outFilename)); + + return 0; +} +#endif // PBRT_BUILD_GPU_RENDERER + +int main(int argc, char *argv[]) { + InitPBRT({}); + + if (argc < 2) { + help(); + return 0; + } + + if (strcmp(argv[1], "average") == 0) + return average(argc - 2, argv + 2); + else if (strcmp(argv[1], "assemble") == 0) + return assemble(argc - 2, argv + 2); + else if (strcmp(argv[1], "bloom") == 0) + return bloom(argc - 2, argv + 2); + else if (strcmp(argv[1], "cat") == 0) + return cat(argc - 2, argv + 2); + else if (strcmp(argv[1], "convert") == 0) + return convert(argc - 2, argv + 2); + else if (strcmp(argv[1], "diff") == 0) + return diff(argc - 2, argv + 2); + else if (strcmp(argv[1], "denoise") == 0) + return denoise(argc - 2, argv + 2); +#ifdef PBRT_BUILD_GPU_RENDERER + else if (strcmp(argv[1], "denoise-optix") == 0) + return denoise_optix(argc - 2, argv + 2); +#endif // PBRT_BUILD_GPU_RENDERER + else if (strcmp(argv[1], "error") == 0) + return error(argc - 2, argv + 2); + else if (strcmp(argv[1], "falsecolor") == 0) + return falsecolor(argc - 2, argv + 2); + else if (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "-help") == 0 || + strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) + return help(argc - 2, argv + 2); + else if (strcmp(argv[1], "info") == 0) + return info(argc - 2, argv + 2); + else if (strcmp(argv[1], "makeenv") == 0) + return makeenv(argc - 2, argv + 2); + else if (strcmp(argv[1], "makeemitters") == 0) + return makeemitters(argc - 2, argv + 2); + else if (strcmp(argv[1], "makesky") == 0) + return makesky(argc - 2, argv + 2); + else if (strcmp(argv[1], "whitebalance") == 0) + return whitebalance(argc - 2, argv + 2); + else if (strcmp(argv[1], "noisybit") == 0) { + // hack for brute force comptuation of ideal filter weights. + + argv += 2; + std::string filename; + std::array pixel = {0, 0}; + int width = 10; + Float sigma = 1; + int nInstances = 100; + + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage("%s", err.c_str()); + exit(1); + }; + if (ParseArg(&argv, "pixel", pstd::MakeSpan(pixel), onError) || + ParseArg(&argv, "width", &width, onError) || + ParseArg(&argv, "sigma", &sigma, onError) || + ParseArg(&argv, "n", &nInstances, onError)) + ; // yaay + else if (filename.empty()) { + filename = *argv; + ++argv; + } else + onError(StringPrintf("unexpected argument \"%s\"", *argv)); + } + CHECK(!filename.empty()); + + ImageAndMetadata imRead = Image::Read(filename); + ImageChannelDesc rgbDesc = imRead.image.GetChannelDesc({"R", "G", "B"}); + CHECK((bool)rgbDesc); + Image image = imRead.image.SelectChannels(rgbDesc); + + if (pixel[0] - width < 0 || pixel[0] + width >= image.Resolution().x || + pixel[0] - width < 0 || pixel[0] + width >= image.Resolution().y) { + fprintf(stderr, + "%s: pixel (%d, %d) with width %d doesn't work with " + "resolution (%d, %d).\n", + filename.c_str(), pixel[0], pixel[0], width, image.Resolution().x, + image.Resolution().y); + return 1; + } + + int nPixels = Sqr(2 * width + 1); + CHECK_GE(3 * nInstances, nPixels); // want to be overconstrained + + RNG rng; + // + FILE *f = fopen("m.csv", "w"); + for (int i = 0; i < nInstances; ++i) + for (int c = 0; c < 3; ++c) { + for (int dx = -width; dx <= width; ++dx) + for (int dy = -width; dy <= width; ++dy) { + // Float noise = .1 * std::exp(-rng.Uniform() * + // 3); if (rng.Uniform() < .5) noise = -noise; + Float noise = SampleNormal(rng.Uniform(), 0., .1); + // TODO: use sigma, make this controllable, etc. + fprintf(f, "%c%f ", (dx > -width || dy > -width) ? ',' : ' ', + image.GetChannel({pixel[0] + dx, pixel[1] + dy}, c) + // * (.95 + .05 * rng.Uniform()) + + noise); + } + fprintf(f, "\n"); + } + fclose(f); + + // what it should equal + f = fopen("b.csv", "w"); + for (int i = 0; i < nInstances; ++i) + for (int c = 0; c < 3; ++c) + fprintf(f, "%f\n", image.GetChannel({pixel[0], pixel[1]}, c)); + fclose(f); + + /* + LeastSquares[Import["m.csv"], Import["b.csv"]] + ArrayPlot[ArrayReshape[ %, {21, 21}], ColorFunction -> Function[a, + GrayLevel[4 a]]] + */ + } else { + fprintf(stderr, "imgtool: unknown command \"%s\"", argv[1]); + help(); + CleanupPBRT(); + return 1; + } + + CleanupPBRT(); + + return 0; +} diff --git a/src/pbrt/cmd/obj2pbrt.cpp b/src/pbrt/cmd/obj2pbrt.cpp new file mode 100644 index 00000000..39cd283c --- /dev/null +++ b/src/pbrt/cmd/obj2pbrt.cpp @@ -0,0 +1,1618 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +// +// obj2pbrt.cpp +// +// Convert Wavefront OBJ files to PBRT. +// Based on Syoyo Fujita's tinyobjloader: +// https://github.com/syoyo/tinyobjloader +// +// 2-clause BSD license +// + +///////////// start of tiny_obj_loader.h + +// clang-format off + +// +// Copyright 2012-2016, Syoyo Fujita. +// +// Licensed under 2-clause BSD license. +// + +// +// version 0.9.22: Introduce `load_flags_t`. +// version 0.9.20: Fixes creating per-face material using `usemtl`(#68) +// version 0.9.17: Support n-polygon and crease tag(OpenSubdiv extension) +// version 0.9.16: Make tinyobjloader header-only +// version 0.9.15: Change API to handle no mtl file case correctly(#58) +// version 0.9.14: Support specular highlight, bump, displacement and alpha +// map(#53) +// version 0.9.13: Report "Material file not found message" in `err`(#46) +// version 0.9.12: Fix groups being ignored if they have 'usemtl' just before +// 'g' (#44) +// version 0.9.11: Invert `Tr` parameter(#43) +// version 0.9.10: Fix seg fault on windows. +// version 0.9.9 : Replace atof() with custom parser. +// version 0.9.8 : Fix multi-materials(per-face material ID). +// version 0.9.7 : Support multi-materials(per-face material ID) per +// object/group. +// version 0.9.6 : Support Ni(index of refraction) mtl parameter. +// Parse transmittance material parameter correctly. +// version 0.9.5 : Parse multiple group name. +// Add support of specifying the base path to load material +// file. +// version 0.9.4 : Initial support of group tag(g) +// version 0.9.3 : Fix parsing triple 'x/y/z' +// version 0.9.2 : Add more .mtl load support +// version 0.9.1 : Add initial .mtl load support +// version 0.9.0 : Initial +// + +// +// Use this in *one* .cc +#define TINYOBJLOADER_IMPLEMENTATION +// #include +// + +#ifndef TINY_OBJ_LOADER_H_ +#define TINY_OBJ_LOADER_H_ + +#include +#include +#include +#include + +namespace tinyobj { + +typedef struct { + std::string name; + + float ambient[3]; + float diffuse[3]; + float specular[3]; + float transmittance[3]; + float emission[3]; + float shininess; + float ior; // index of refraction + float dissolve; // 1 == opaque; 0 == fully transparent + // illumination model (see http://www.fileformat.info/format/material/) + int illum; + + int dummy; // Suppress padding warning. + + std::string ambient_texname; // map_Ka + std::string diffuse_texname; // map_Kd + std::string specular_texname; // map_Ks + std::string specular_highlight_texname; // map_Ns + std::string bump_texname; // map_bump, bump + std::string displacement_texname; // disp + std::string alpha_texname; // map_d + std::map unknown_parameter; +} material_t; + +typedef struct { + std::string name; + + std::vector intValues; + std::vector floatValues; + std::vector stringValues; +} tag_t; + +typedef struct { + std::vector positions; + std::vector normals; + std::vector texcoords; + std::vector indices; + std::vector + num_vertices; // The number of vertices per face. Up to 255. + std::vector material_ids; // per-face material ID + std::vector tags; // SubD tag +} mesh_t; + +typedef struct { + std::string name; + mesh_t mesh; +} shape_t; + +typedef enum +{ + triangulation = 1, // used whether triangulate polygon face in .obj + calculate_normals = 2, // used whether calculate the normals if the .obj normals are empty + // Some nice stuff here +} load_flags_t; + +class float3 +{ +public: + float3() + : x( 0.0f ) + , y( 0.0f ) + , z( 0.0f ) + { + } + + float3(float coord_x, float coord_y, float coord_z) + : x( coord_x ) + , y( coord_y ) + , z( coord_z ) + { + } + + float3(const float3& from, const float3& to) + { + coord[0] = to.coord[0] - from.coord[0]; + coord[1] = to.coord[1] - from.coord[1]; + coord[2] = to.coord[2] - from.coord[2]; + } + + float3 crossproduct ( const float3 & vec ) + { + float a = y * vec.z - z * vec.y ; + float b = z * vec.x - x * vec.z ; + float c = x * vec.y - y * vec.x ; + return { a , b , c }; + } + + void normalize() + { + const float length = std::sqrt( ( coord[0] * coord[0] ) + + ( coord[1] * coord[1] ) + + ( coord[2] * coord[2] ) ); + if( length != 1 ) + { + coord[0] = (coord[0] / length); + coord[1] = (coord[1] / length); + coord[2] = (coord[2] / length); + } + } + +private: + union + { + float coord[3]; + struct + { + float x,y,z; + }; + }; +}; + +class MaterialReader { +public: + MaterialReader() {} + virtual ~MaterialReader(); + + virtual bool operator()(const std::string &matId, + std::vector &materials, + std::map &matMap, + std::string &err) = 0; +}; + +class MaterialFileReader : public MaterialReader { +public: + MaterialFileReader(const std::string &mtl_basepath) + : m_mtlBasePath(mtl_basepath) {} + virtual ~MaterialFileReader() {} + virtual bool operator()(const std::string &matId, + std::vector &materials, + std::map &matMap, std::string &err); + +private: + std::string m_mtlBasePath; +}; + +/// Loads .obj from a file. +/// 'shapes' will be filled with parsed shape data +/// The function returns error string. +/// Returns true when loading .obj become success. +/// Returns warning and error message into `err` +/// 'mtl_basepath' is optional, and used for base path for .mtl file. +/// 'optional flags +bool LoadObj(std::vector &shapes, // [output] + std::vector &materials, // [output] + std::string &err, // [output] + const char *filename, const char *mtl_basepath = nullptr, + unsigned int flags = 1 ); + +/// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve +/// std::istream for materials. +/// Returns true when loading .obj become success. +/// Returns warning and error message into `err` +bool LoadObj(std::vector &shapes, // [output] + std::vector &materials, // [output] + std::string &err, // [output] + std::istream &inStream, MaterialReader &readMatFn, + unsigned int flags = 1); + +/// Loads materials into std::map +void LoadMtl(std::map &material_map, // [output] + std::vector &materials, // [output] + std::istream &inStream); +} + +#ifdef TINYOBJLOADER_IMPLEMENTATION +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace tinyobj { + +MaterialReader::~MaterialReader() {} + +#define TINYOBJ_SSCANF_BUFFER_SIZE (4096) + +struct vertex_index { + int v_idx, vt_idx, vn_idx; + vertex_index() : v_idx(-1), vt_idx(-1), vn_idx(-1) {} + explicit vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {} + vertex_index(int vidx, int vtidx, int vnidx) + : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {} +}; + +struct tag_sizes { + tag_sizes() : num_ints(0), num_floats(0), num_strings(0) {} + int num_ints; + int num_floats; + int num_strings; +}; + +// for std::map +static inline bool operator<(const vertex_index &a, const vertex_index &b) { + if (a.v_idx != b.v_idx) + return (a.v_idx < b.v_idx); + if (a.vn_idx != b.vn_idx) + return (a.vn_idx < b.vn_idx); + if (a.vt_idx != b.vt_idx) + return (a.vt_idx < b.vt_idx); + + return false; +} + +struct obj_shape { + std::vector v; + std::vector vn; + std::vector vt; +}; + +//See http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf +std::istream& safeGetline(std::istream& is, std::string& t) +{ + t.clear(); + + // The characters in the stream are read one-by-one using a std::streambuf. + // That is faster than reading them one-by-one using the std::istream. + // Code that uses streambuf this way must be guarded by a sentry object. + // The sentry object performs various tasks, + // such as thread synchronization and updating the stream state. + + std::istream::sentry se(is, true); + std::streambuf* sb = is.rdbuf(); + + for(;;) { + int c = sb->sbumpc(); + switch (c) { + case '\n': + return is; + case '\r': + if(sb->sgetc() == '\n') + sb->sbumpc(); + return is; + case EOF: + // Also handle the case when the last line has no line ending + if(t.empty()) + is.setstate(std::ios::eofbit); + return is; + default: + t += (char)c; + } + } +} + +#define IS_SPACE( x ) ( ( (x) == ' ') || ( (x) == '\t') ) +#define IS_DIGIT( x ) ( (unsigned int)( (x) - '0' ) < (unsigned int)10 ) +#define IS_NEW_LINE( x ) ( ( (x) == '\r') || ( (x) == '\n') || ( (x) == '\0') ) + +// Make index zero-base, and also support relative index. +static inline int fixIndex(int idx, int n) { + if (idx > 0) + return idx - 1; + if (idx == 0) + return 0; + return n + idx; // negative value = relative +} + +static inline std::string parseString(const char *&token) { + std::string s; + token += strspn(token, " \t"); + size_t e = strcspn(token, " \t\r"); + s = std::string(token, &token[e]); + token += e; + return s; +} + +static inline int parseInt(const char *&token) { + token += strspn(token, " \t"); + int i = atoi(token); + token += strcspn(token, " \t\r"); + return i; +} + +// Tries to parse a floating point number located at s. +// +// s_end should be a location in the string where reading should absolutely +// stop. For example at the end of the string, to prevent buffer overflows. +// +// Parses the following EBNF grammar: +// sign = "+" | "-" ; +// END = ? anything not in digit ? +// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; +// integer = [sign] , digit , {digit} ; +// decimal = integer , ["." , integer] ; +// float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; +// +// Valid strings are for example: +// -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 +// +// If the parsing is a success, result is set to the parsed value and true +// is returned. +// +// The function is greedy and will parse until any of the following happens: +// - a non-conforming character is encountered. +// - s_end is reached. +// +// The following situations triggers a failure: +// - s >= s_end. +// - parse failure. +// +static bool tryParseDouble(const char *s, const char *s_end, double *result) { + if (s >= s_end) { + return false; + } + + double mantissa = 0.0; + // This exponent is base 2 rather than 10. + // However the exponent we parse is supposed to be one of ten, + // thus we must take care to convert the exponent/and or the + // mantissa to a * 2^E, where a is the mantissa and E is the + // exponent. + // To get the final double we will use ldexp, it requires the + // exponent to be in base 2. + int exponent = 0; + + // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED + // TO JUMP OVER DEFINITIONS. + char sign = '+'; + char exp_sign = '+'; + char const *curr = s; + + // How many characters were read in a loop. + int read = 0; + // Tells whether a loop terminated due to reaching s_end. + bool end_not_reached = false; + + /* + BEGIN PARSING. + */ + + // Find out what sign we've got. + if (*curr == '+' || *curr == '-') { + sign = *curr; + curr++; + } else if (IS_DIGIT(*curr)) { /* Pass through. */ + } else { + goto fail; + } + + // Read the integer part. + while ((end_not_reached = (curr != s_end)) && IS_DIGIT(*curr)) { + mantissa *= 10; + mantissa += static_cast(*curr - 0x30); + curr++; + read++; + } + + // We must make sure we actually got something. + if (read == 0) + goto fail; + // We allow numbers of form "#", "###" etc. + if (!end_not_reached) + goto assemble; + + // Read the decimal part. + if (*curr == '.') { + curr++; + read = 1; + while ((end_not_reached = (curr != s_end)) && IS_DIGIT(*curr)) { + // NOTE: Don't use powf here, it will absolutely murder precision. + mantissa += static_cast(*curr - 0x30) * pow(10.0, -read); + read++; + curr++; + } + } else if (*curr == 'e' || *curr == 'E') { + } else { + goto assemble; + } + + if (!end_not_reached) + goto assemble; + + // Read the exponent part. + if (*curr == 'e' || *curr == 'E') { + curr++; + // Figure out if a sign is present and if it is. + if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-')) { + exp_sign = *curr; + curr++; + } else if (IS_DIGIT(*curr)) { /* Pass through. */ + } else { + // Empty E is not allowed. + goto fail; + } + + read = 0; + while ((end_not_reached = (curr != s_end)) && IS_DIGIT(*curr)) { + exponent *= 10; + exponent += static_cast(*curr - 0x30); + curr++; + read++; + } + exponent *= (exp_sign == '+' ? 1 : -1); + if (read == 0) + goto fail; + } + +assemble: + *result = + (sign == '+' ? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), exponent); + return true; +fail: + return false; +} +static inline float parseFloat(const char *&token) { + token += strspn(token, " \t"); +#ifdef TINY_OBJ_LOADER_OLD_FLOAT_PARSER + float f = (float)atof(token); + token += strcspn(token, " \t\r"); +#else + const char *end = token + strcspn(token, " \t\r"); + double val = 0.0; + tryParseDouble(token, end, &val); + float f = static_cast(val); + token = end; +#endif + return f; +} + +static inline void parseFloat2(float &x, float &y, const char *&token) { + x = parseFloat(token); + y = parseFloat(token); +} + +static inline void parseFloat3(float &x, float &y, float &z, + const char *&token) { + x = parseFloat(token); + y = parseFloat(token); + z = parseFloat(token); +} + +static tag_sizes parseTagTriple(const char *&token) { + tag_sizes ts; + + ts.num_ints = atoi(token); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return ts; + } + token++; + + ts.num_floats = atoi(token); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return ts; + } + token++; + + ts.num_strings = atoi(token); + token += strcspn(token, "/ \t\r") + 1; + + return ts; +} + +// Parse triples: i, i/j/k, i//k, i/j +static vertex_index parseTriple(const char *&token, int vsize, int vnsize, + int vtsize) { + vertex_index vi(-1); + + vi.v_idx = fixIndex(atoi(token), vsize); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return vi; + } + token++; + + // i//k + if (token[0] == '/') { + token++; + vi.vn_idx = fixIndex(atoi(token), vnsize); + token += strcspn(token, "/ \t\r"); + return vi; + } + + // i/j/k or i/j + vi.vt_idx = fixIndex(atoi(token), vtsize); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return vi; + } + + // i/j/k + token++; // skip '/' + vi.vn_idx = fixIndex(atoi(token), vnsize); + token += strcspn(token, "/ \t\r"); + return vi; +} + +static unsigned int +updateVertex(std::map &vertexCache, + std::vector &positions, std::vector &normals, + std::vector &texcoords, + const std::vector &in_positions, + const std::vector &in_normals, + const std::vector &in_texcoords, const vertex_index &i) { + const std::map::iterator it = vertexCache.find(i); + + if (it != vertexCache.end()) { + // found cache + return it->second; + } + + assert(in_positions.size() > static_cast(3 * i.v_idx + 2)); + + positions.push_back(in_positions[3 * static_cast(i.v_idx) + 0]); + positions.push_back(in_positions[3 * static_cast(i.v_idx) + 1]); + positions.push_back(in_positions[3 * static_cast(i.v_idx) + 2]); + + if ((i.vn_idx >= 0) && + (static_cast(i.vn_idx * 3 + 2) < in_normals.size())) { + normals.push_back(in_normals[3 * static_cast(i.vn_idx) + 0]); + normals.push_back(in_normals[3 * static_cast(i.vn_idx) + 1]); + normals.push_back(in_normals[3 * static_cast(i.vn_idx) + 2]); + } + + if ((i.vt_idx >= 0) && + (static_cast(i.vt_idx * 2 + 1) < in_texcoords.size())) { + texcoords.push_back(in_texcoords[2 * static_cast(i.vt_idx) + 0]); + texcoords.push_back(in_texcoords[2 * static_cast(i.vt_idx) + 1]); + } + + unsigned int idx = static_cast(positions.size() / 3 - 1); + vertexCache[i] = idx; + + return idx; +} + +static void InitMaterial(material_t &material) { + material.name = ""; + material.ambient_texname = ""; + material.diffuse_texname = ""; + material.specular_texname = ""; + material.specular_highlight_texname = ""; + material.bump_texname = ""; + material.displacement_texname = ""; + material.alpha_texname = ""; + for (int i = 0; i < 3; i++) { + material.ambient[i] = 0.f; + material.diffuse[i] = 0.f; + material.specular[i] = 0.f; + material.transmittance[i] = 0.f; + material.emission[i] = 0.f; + } + material.illum = 0; + material.dissolve = 1.f; + material.shininess = 1.f; + material.ior = 1.f; + material.unknown_parameter.clear(); +} + +static bool exportFaceGroupToShape( + shape_t &shape, std::map vertexCache, + const std::vector &in_positions, + const std::vector &in_normals, + const std::vector &in_texcoords, + const std::vector > &faceGroup, + std::vector &tags, const int material_id, const std::string &name, + bool clearCache, unsigned int flags, std::string& err ) { + if (faceGroup.empty()) { + return false; + } + + bool triangulate( ( flags & triangulation ) == triangulation ); + bool normals_calculation( ( flags & calculate_normals ) == calculate_normals ); + + // Flatten vertices and indices + for (size_t i = 0; i < faceGroup.size(); i++) { + const std::vector &face = faceGroup[i]; + + vertex_index i0 = face[0]; + vertex_index i1(-1); + vertex_index i2 = face[1]; + + size_t npolys = face.size(); + + if (triangulate) { + + // Polygon -> triangle fan conversion + for (size_t k = 2; k < npolys; k++) { + i1 = i2; + i2 = face[k]; + + unsigned int v0 = updateVertex( + vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i0); + unsigned int v1 = updateVertex( + vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i1); + unsigned int v2 = updateVertex( + vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i2); + + shape.mesh.indices.push_back(v0); + shape.mesh.indices.push_back(v1); + shape.mesh.indices.push_back(v2); + + shape.mesh.num_vertices.push_back(3); + shape.mesh.material_ids.push_back(material_id); + } + } else { + + for (size_t k = 0; k < npolys; k++) { + unsigned int v = + updateVertex(vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, + in_texcoords, face[k]); + + shape.mesh.indices.push_back(v); + } + + shape.mesh.num_vertices.push_back(static_cast(npolys)); + shape.mesh.material_ids.push_back(material_id); // per face + } + } + + if (normals_calculation && shape.mesh.normals.empty()) { + const size_t nIndexs = shape.mesh.indices.size(); + if (nIndexs % 3 == 0) { + shape.mesh.normals.resize(shape.mesh.positions.size()); + for (size_t iIndices = 0; iIndices < nIndexs; iIndices += 3) { + float3 v1, v2, v3; + memcpy(&v1, &shape.mesh.positions[shape.mesh.indices[iIndices] * 3], sizeof(float3)); + memcpy(&v2, &shape.mesh.positions[shape.mesh.indices[iIndices + 1] * 3], sizeof(float3)); + memcpy(&v3, &shape.mesh.positions[shape.mesh.indices[iIndices + 2] * 3], sizeof(float3)); + + float3 v12(v1, v2); + float3 v13(v1, v3); + + float3 normal = v12.crossproduct(v13); + normal.normalize(); + + memcpy(&shape.mesh.normals[shape.mesh.indices[iIndices] * 3], &normal, sizeof(float3)); + memcpy(&shape.mesh.normals[shape.mesh.indices[iIndices + 1] * 3], &normal, sizeof(float3)); + memcpy(&shape.mesh.normals[shape.mesh.indices[iIndices + 2] * 3], &normal, sizeof(float3)); + } + } else { + + std::stringstream ss; + ss << "WARN: The shape " << name << " does not have a topology of triangles, therfore the normals calculation could not be performed. Select the tinyobj::triangulation flag for this object." << std::endl; + err += ss.str(); + } + } + + shape.name = name; + shape.mesh.tags.swap(tags); + + if (clearCache) + vertexCache.clear(); + + return true; +} + +void LoadMtl(std::map &material_map, + std::vector &materials, std::istream &inStream) { + + // Create a default material anyway. + material_t material; + InitMaterial(material); + + while (inStream.peek() != -1) { + std::string linebuf; + safeGetline(inStream, linebuf); + + // Trim newline '\r\n' or '\n' + if (!linebuf.empty()) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (!linebuf.empty()) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); + } + + // Skip if empty line. + if (linebuf.empty()) { + continue; + } + + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') + continue; // empty line + + if (token[0] == '#') + continue; // comment line + + // new mtl + if ((0 == strncmp(token, "newmtl", 6)) && IS_SPACE((token[6]))) { + // flush previous material. + if (!material.name.empty()) { + material_map.insert(std::pair( + material.name, static_cast(materials.size()))); + materials.push_back(material); + } + + // initial temporary material + InitMaterial(material); + + // set new mtl name + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + material.name = namebuf; + continue; + } + + // ambient + if (token[0] == 'K' && token[1] == 'a' && IS_SPACE((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.ambient[0] = r; + material.ambient[1] = g; + material.ambient[2] = b; + continue; + } + + // diffuse + if (token[0] == 'K' && token[1] == 'd' && IS_SPACE((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.diffuse[0] = r; + material.diffuse[1] = g; + material.diffuse[2] = b; + continue; + } + + // specular + if (token[0] == 'K' && token[1] == 's' && IS_SPACE((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.specular[0] = r; + material.specular[1] = g; + material.specular[2] = b; + continue; + } + + // transmittance + if (token[0] == 'K' && token[1] == 't' && IS_SPACE((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.transmittance[0] = r; + material.transmittance[1] = g; + material.transmittance[2] = b; + continue; + } + + // ior(index of refraction) + if (token[0] == 'N' && token[1] == 'i' && IS_SPACE((token[2]))) { + token += 2; + material.ior = parseFloat(token); + continue; + } + + // emission + if (token[0] == 'K' && token[1] == 'e' && IS_SPACE(token[2])) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.emission[0] = r; + material.emission[1] = g; + material.emission[2] = b; + continue; + } + + // shininess + if (token[0] == 'N' && token[1] == 's' && IS_SPACE(token[2])) { + token += 2; + material.shininess = parseFloat(token); + continue; + } + + // illum model + if (0 == strncmp(token, "illum", 5) && IS_SPACE(token[5])) { + token += 6; + material.illum = parseInt(token); + continue; + } + + // dissolve + if ((token[0] == 'd' && IS_SPACE(token[1]))) { + token += 1; + material.dissolve = parseFloat(token); + continue; + } + if (token[0] == 'T' && token[1] == 'r' && IS_SPACE(token[2])) { + token += 2; + // Invert value of Tr(assume Tr is in range [0, 1]) + material.dissolve = 1.0f - parseFloat(token); + continue; + } + + // ambient texture + if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) { + token += 7; + material.ambient_texname = token; + continue; + } + + // diffuse texture + if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) { + token += 7; + material.diffuse_texname = token; + continue; + } + + // specular texture + if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) { + token += 7; + material.specular_texname = token; + continue; + } + + // specular highlight texture + if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) { + token += 7; + material.specular_highlight_texname = token; + continue; + } + + // bump texture + if ((0 == strncmp(token, "map_bump", 8)) && IS_SPACE(token[8])) { + token += 9; + material.bump_texname = token; + continue; + } + + // alpha texture + if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) { + token += 6; + material.alpha_texname = token; + continue; + } + + // bump texture + if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) { + token += 5; + material.bump_texname = token; + continue; + } + + // displacement texture + if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) { + token += 5; + material.displacement_texname = token; + continue; + } + + // unknown parameter + const char *_space = strchr(token, ' '); + if (_space == nullptr) { + _space = strchr(token, '\t'); + } + if (_space != nullptr) { + std::ptrdiff_t len = _space - token; + std::string key(token, static_cast(len)); + std::string value = _space + 1; + material.unknown_parameter.insert( + std::pair(key, value)); + } + } + // flush last material. + if (!material.name.empty()) { + material_map.insert(std::pair( + material.name, static_cast(materials.size()))); + materials.push_back(material); + } +} + +bool MaterialFileReader::operator()(const std::string &matId, + std::vector &materials, + std::map &matMap, + std::string &err) { + std::string filepath; + + if (!m_mtlBasePath.empty()) { + filepath = std::string(m_mtlBasePath) + matId; + } else { + filepath = matId; + } + + std::ifstream matIStream(filepath.c_str()); + LoadMtl(matMap, materials, matIStream); + if (!matIStream) { + std::stringstream ss; + ss << "WARN: Material file [ " << filepath + << " ] not found. Created a default material."; + err += ss.str(); + } + return true; +} + +bool LoadObj(std::vector &shapes, // [output] + std::vector &materials, // [output] + std::string &err, const char *filename, const char *mtl_basepath, + unsigned int flags) { + + shapes.clear(); + + std::stringstream errss; + + std::ifstream ifs(filename); + if (!ifs) { + errss << "Cannot open file [" << filename << "]" << std::endl; + err = errss.str(); + return false; + } + + std::string basePath; + if (mtl_basepath != nullptr) { + basePath = mtl_basepath; + } + MaterialFileReader matFileReader(basePath); + + return LoadObj(shapes, materials, err, ifs, matFileReader, flags); +} + +bool LoadObj(std::vector &shapes, // [output] + std::vector &materials, // [output] + std::string &err, std::istream &inStream, + MaterialReader &readMatFn, unsigned int flags) { + + std::stringstream errss; + + std::vector v; + std::vector vn; + std::vector vt; + std::vector tags; + std::vector > faceGroup; + std::string name; + + // material + std::map material_map; + std::map vertexCache; + int material = -1; + + shape_t shape; + + while (inStream.peek() != -1) { + std::string linebuf; + safeGetline(inStream, linebuf); + + // Trim newline '\r\n' or '\n' + if (!linebuf.empty()) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (!linebuf.empty()) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); + } + + // Skip if empty line. + if (linebuf.empty()) { + continue; + } + + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') + continue; // empty line + + if (token[0] == '#') + continue; // comment line + + // vertex + if (token[0] == 'v' && IS_SPACE((token[1]))) { + token += 2; + float x, y, z; + parseFloat3(x, y, z, token); + v.push_back(x); + v.push_back(y); + v.push_back(z); + continue; + } + + // normal + if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { + token += 3; + float x, y, z; + parseFloat3(x, y, z, token); + vn.push_back(x); + vn.push_back(y); + vn.push_back(z); + continue; + } + + // texcoord + if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { + token += 3; + float x, y; + parseFloat2(x, y, token); + vt.push_back(x); + vt.push_back(y); + continue; + } + + // face + if (token[0] == 'f' && IS_SPACE((token[1]))) { + token += 2; + token += strspn(token, " \t"); + + std::vector face; + face.reserve(3); + + while (!IS_NEW_LINE(token[0])) { + vertex_index vi = parseTriple(token, static_cast(v.size() / 3), + static_cast(vn.size() / 3), + static_cast(vt.size() / 2)); + face.push_back(vi); + size_t n = strspn(token, " \t\r"); + token += n; + } + + // replace with emplace_back + std::move on C++11 + faceGroup.push_back(std::vector()); + faceGroup[faceGroup.size() - 1].swap(face); + + continue; + } + + // use mtl + if ((0 == strncmp(token, "usemtl", 6)) && IS_SPACE((token[6]))) { + + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + + int newMaterialId = -1; + if (material_map.find(namebuf) != material_map.end()) { + newMaterialId = material_map[namebuf]; + } else { + // { error!! material not found } + } + + if (newMaterialId != material) { + // Create per-face material + exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, + material, name, true, flags, err ); + faceGroup.clear(); + material = newMaterialId; + } + + continue; + } + + // load mtl + if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + + std::string err_mtl; + bool ok = readMatFn(namebuf, materials, material_map, err_mtl); + err += err_mtl; + + if (!ok) { + faceGroup.clear(); // for safety + return false; + } + + continue; + } + + // group name + if (token[0] == 'g' && IS_SPACE((token[1]))) { + + // flush previous face group. + bool ret = + exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, + material, name, true, flags, err ); + if (ret) { + shapes.push_back(shape); + } + + shape = shape_t(); + + // material = -1; + faceGroup.clear(); + + std::vector names; + names.reserve(2); + + while (!IS_NEW_LINE(token[0])) { + std::string str = parseString(token); + names.push_back(str); + token += strspn(token, " \t\r"); // skip tag + } + + assert(names.size() > 0); + + // names[0] must be 'g', so skip the 0th element. + if (names.size() > 1) { + name = names[1]; + } else { + name = ""; + } + + continue; + } + + // object name + if (token[0] == 'o' && IS_SPACE((token[1]))) { + + // flush previous face group. + bool ret = + exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, tags, + material, name, true, flags, err ); + if (ret) { + shapes.push_back(shape); + } + + // material = -1; + faceGroup.clear(); + shape = shape_t(); + + // @todo { multiple object name? } + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 2; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + name = std::string(namebuf); + + continue; + } + + if (token[0] == 't' && IS_SPACE(token[1])) { + tag_t tag; + + char namebuf[4096]; + token += 2; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + tag.name = std::string(namebuf); + + token += tag.name.size() + 1; + + tag_sizes ts = parseTagTriple(token); + + tag.intValues.resize(static_cast(ts.num_ints)); + + for (size_t i = 0; i < static_cast(ts.num_ints); ++i) { + tag.intValues[i] = atoi(token); + token += strcspn(token, "/ \t\r") + 1; + } + + tag.floatValues.resize(static_cast(ts.num_floats)); + for (size_t i = 0; i < static_cast(ts.num_floats); ++i) { + tag.floatValues[i] = parseFloat(token); + token += strcspn(token, "/ \t\r") + 1; + } + + tag.stringValues.resize(static_cast(ts.num_strings)); + for (size_t i = 0; i < static_cast(ts.num_strings); ++i) { + char stringValueBuffer[4096]; + +#ifdef _MSC_VER + sscanf_s(token, "%s", stringValueBuffer, (unsigned)_countof(stringValueBuffer)); +#else + sscanf(token, "%s", stringValueBuffer); +#endif + tag.stringValues[i] = stringValueBuffer; + token += tag.stringValues[i].size() + 1; + } + + tags.push_back(tag); + } + + // Ignore unknown command. + } + + bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, + tags, material, name, true, flags, err ); + if (ret) { + shapes.push_back(shape); + } + faceGroup.clear(); // for safety + + err += errss.str(); + + return true; +} + +} // namespace + +#endif + +#endif // TINY_OBJ_LOADER_H_ + +// clang-format on + +/////////////////////////////////////////////////////////////////////////// +// The above is tiny_obj_loader.{h,cc} basically directly; pbrt specific +// code follows... + +#include +#include +#include +#include + +using namespace tinyobj; + +static void usage() { + fprintf(stderr, "usage: obj2pbrt [--ptexquads] \n"); + exit(1); +} + +int main(int argc, char *argv[]) { + const char *objFilename = nullptr, *pbrtFilename = nullptr; + bool ptexQuads = false; + for (int i = 1; i < argc; ++i) { + if ((strcmp(argv[i], "--help") == 0) || (strcmp(argv[i], "-h") == 0)) + usage(); + else if (strcmp(argv[i], "--ptexquads") == 0) + ptexQuads = true; + else if (objFilename == nullptr) + objFilename = argv[i]; + else if (pbrtFilename == nullptr) + pbrtFilename = argv[i]; + else + usage(); + } + if (pbrtFilename == nullptr) + usage(); + + std::vector shapes; + std::vector materials; + std::string err; + if (!LoadObj(shapes, materials, err, objFilename, + /* mtl_basepath */ nullptr, + ptexQuads ? 0 : load_flags_t(triangulation))) { + fprintf(stderr, "%s: errors loading OBJ file: %s\n", objFilename, err.c_str()); + return 1; + } + + FILE *f = (strcmp(pbrtFilename, "-") == 0) ? stdout : fopen(pbrtFilename, "w"); + if (f == nullptr) { + perror(pbrtFilename); + return 1; + } + + float bounds[2][3] = {{1e30, 1e30, 1e30}, {-1e30, -1e30, -1e30}}; + for (size_t i = 0; i < shapes.size(); ++i) { + const shape_t &shape = shapes[i]; + const mesh_t &mesh = shape.mesh; + for (size_t i = 0; i < mesh.positions.size(); ++i) { + int c = i % 3; + bounds[0][c] = std::min(bounds[0][c], mesh.positions[i]); + bounds[1][c] = std::max(bounds[1][c], mesh.positions[i]); + } + } + fprintf(f, "# Converted from \"%s\" by obj2pbrt\n", objFilename); + fprintf(f, "# Scene bounds: (%f, %f, %f) - (%f, %f, %f)\n\n\n", bounds[0][0], + bounds[0][1], bounds[0][2], bounds[1][0], bounds[1][1], bounds[1][2]); + + int numAreaLights = 0; + int numTriangles = 0; + int numMeshes = shapes.size(); + + // First, make named materials for all of the materials. + for (const material_t &mtl : materials) { + bool hasDiffuseTex = (!mtl.diffuse_texname.empty()); + if (!mtl.diffuse_texname.empty()) { + if (mtl.diffuse[0] != 0 || mtl.diffuse[1] != 0 || mtl.diffuse[2] != 0) { + fprintf(f, + "Texture \"%s-kd-img\" \"spectrum\" \"imagemap\" " + "\"string imagefile\" [\"%s\"]\n", + mtl.name.c_str(), mtl.diffuse_texname.c_str()); + float scale = (mtl.diffuse[0] + mtl.diffuse[1] + mtl.diffuse[2]) / 3; + if (mtl.diffuse[0] != mtl.diffuse[1] || mtl.diffuse[1] != mtl.diffuse[2]) + fprintf(stderr, + "Averaging non-constant RGB scale for \"%s\" (%f " + "%f %f).\n", + mtl.name.c_str(), mtl.diffuse[0], mtl.diffuse[1], + mtl.diffuse[2]); + fprintf(f, + "Texture \"%s-kd\" \"spectrum\" \"scale\" \"texture tex\" " + "\"%s-kd-img\" \"float scale\" [%f]\n", + mtl.name.c_str(), mtl.name.c_str(), scale); + } else { + fprintf(f, + "Texture \"%s-kd\" \"spectrum\" \"imagemap\" " + "\"string imagefile\" [\"%s\"]\n", + mtl.name.c_str(), mtl.diffuse_texname.c_str()); + } + } + + bool hasSpecularTex = (!mtl.specular_texname.empty()); + if (!mtl.specular_texname.empty()) { + if (mtl.specular[0] != 0 || mtl.specular[1] != 0 || mtl.specular[2] != 0) { + fprintf(f, + "Texture \"%s-ks-img\" \"spectrum\" \"imagemap\" " + "\"string imagefile\" [\"%s\"]\n", + mtl.name.c_str(), mtl.specular_texname.c_str()); + float scale = (mtl.specular[0] + mtl.specular[1] + mtl.specular[2]) / 3; + if (mtl.specular[0] != mtl.specular[1] || + mtl.specular[1] != mtl.specular[2]) + fprintf(stderr, + "Averaging non-constant RGB scale for \"%s\" (%f " + "%f %f).\n", + mtl.name.c_str(), mtl.specular[0], mtl.specular[1], + mtl.specular[2]); + fprintf(f, + "Texture \"%s-ks\" \"spectrum\" \"scale\" \"texture tex\" " + "\"%s-ks-img\" \"float scale\" [%f]\n", + mtl.name.c_str(), mtl.name.c_str(), scale); + } else { + fprintf(f, + "Texture \"%s-ks\" \"spectrum\" \"imagemap\" " + "\"string imagefile\" [\"%s\"]\n", + mtl.name.c_str(), mtl.specular_texname.c_str()); + } + } + + if (!mtl.bump_texname.empty()) { + fprintf(f, + "Texture \"%s-bump\" \"float\" \"imagemap\" " + "\"string imagefile\" [\"%s\"]\n", + mtl.name.c_str(), mtl.bump_texname.c_str()); + } + + float roughness = (mtl.shininess == 0) ? 0. : (1.f / mtl.shininess); + fprintf(f, R"(MakeNamedMaterial "%s" "string type" "uber" )", mtl.name.c_str()); + + if (hasDiffuseTex) + fprintf(f, R"("texture reflectance" "%s-kd" )", mtl.name.c_str()); + else + fprintf(f, "\"rgb reflectance\" [%f %f %f] ", mtl.diffuse[0], mtl.diffuse[1], + mtl.diffuse[2]); + if (hasSpecularTex) + fprintf(f, R"("texture Ks" "%s-ks" )", mtl.name.c_str()); + else + fprintf(f, "\"rgb Ks\" [%f %f %f] ", mtl.specular[0], mtl.specular[1], + mtl.specular[2]); + if (mtl.dissolve < 1) + fprintf(stderr, "Warning: ignoring opacity for \"%s\" material/\n", + mtl.name.c_str()); + fprintf(f, + "\"float roughness\" [%f] " + "\"rgb Kt\" [%f %f %f] \"float eta\" [%f] ", + roughness, mtl.transmittance[0], mtl.transmittance[1], + mtl.transmittance[2], mtl.ior); + if (!mtl.bump_texname.empty()) + fprintf(f, R"("texture displacement" "%s-bump" )", mtl.name.c_str()); + fprintf(f, "\n\n"); + } + + for (const shape_t &shape : shapes) { + const mesh_t &mesh = shape.mesh; + + fprintf(f, "AttributeBegin\n"); + if (!shape.name.empty()) + fprintf(f, "Attribute \"shape\" \"string name\" \"%s\"\n", + shape.name.c_str()); + + // Get the set of material ids used for faces in this mesh. + std::set materialIds; + for (int id : mesh.material_ids) + materialIds.insert(id); + + // Now emit the chunks of the mesh for each material + for (int id : materialIds) { + if (id == -1) { + fprintf(f, "# Material unspecified in OBJ file\n"); + } else { + const material_t &mtl = materials[id]; + + std::map::const_iterator iter; + for (iter = mtl.unknown_parameter.begin(); + iter != mtl.unknown_parameter.end(); ++iter) + fprintf(stderr, "Unknown parameter: %s = %s\n", iter->first.c_str(), + iter->second.c_str()); + + if (mtl.emission[0] > 0 || mtl.emission[1] > 0 || mtl.emission[2] > 0) { + fprintf(f, "AreaLightSource \"area\" \"rgb L\" [ %f %f %f ]\n", + mtl.emission[0], mtl.emission[1], mtl.emission[2]); + ++numAreaLights; + } + + fprintf(f, "NamedMaterial \"%s\"\n", mtl.name.c_str()); + } + + // Now emit all the faces that have the matching material id. + struct Point3f { + float x, y, z; + }; + struct Point2f { + float x, y; + }; + struct Normal3f { + float x, y, z; + }; + std::vector P; + std::vector N; + std::vector st; + std::vector indices, faceIndices; + std::map indexRemap; + int nQuadFaces = 0; + + // Loop over all of the triangles' material ids. + for (size_t i = 0; i < mesh.material_ids.size(); ++i) { + // Skip the ones that don't match the current id that we're + // emitting the mesh for. + if (mesh.material_ids[i] != id) + continue; + + if (ptexQuads) { + if (mesh.num_vertices[i] != 4) { + // We assume all quads when indexing into the indices + // array + fprintf(stderr, "%d: Mesh has a non quad face.. Sorry.\n", + mesh.num_vertices[i]); + exit(1); + } + + faceIndices.push_back(nQuadFaces); + faceIndices.push_back(nQuadFaces); + + int index = P.size(); + // Triangulate + indices.push_back(index); + indices.push_back(index + 1); + indices.push_back(index + 2); + + indices.push_back(index); + indices.push_back(index + 2); + indices.push_back(index + 3); + + for (int v = 0; v < 4; ++v) { + int vi = mesh.indices[4 * i + v]; + P.push_back({mesh.positions[3 * vi], mesh.positions[3 * vi + 1], + mesh.positions[3 * vi + 2]}); + if (!mesh.normals.empty()) + N.push_back({mesh.normals[3 * vi], mesh.normals[3 * vi + 1], + mesh.normals[3 * vi + 2]}); + } + + // fixed texture coords over [0,1] + st.push_back({0.f, 0.f}); + st.push_back({1.f, 0.f}); + st.push_back({1.f, 1.f}); + st.push_back({0.f, 1.f}); + ++nQuadFaces; + numTriangles += 2; + } else { + if (mesh.num_vertices[i] != 3) { + // These should have been triangulated by tinyobj. + fprintf(stderr, "Mesh has a non-triangular face. Sorry.\n"); + exit(1); + } + + // Compute remapped vertex indices. + for (int v = 0; v < 3; ++v) { + int objIndex = mesh.indices[3 * i + v]; + if (indexRemap.find(objIndex) == indexRemap.end()) { + // First time we've seen this index. + indexRemap.insert( + std::make_pair(objIndex, (int)indexRemap.size())); + + P.push_back({mesh.positions[3 * objIndex], + mesh.positions[3 * objIndex + 1], + mesh.positions[3 * objIndex + 2]}); + if (!mesh.normals.empty()) + N.push_back({mesh.normals[3 * objIndex], + mesh.normals[3 * objIndex + 1], + mesh.normals[3 * objIndex + 2]}); + if (!mesh.texcoords.empty()) + st.push_back({mesh.texcoords[2 * objIndex], + mesh.texcoords[2 * objIndex + 1]}); + } + + // In any case emit the index (but remapped + // starting from zero for this slice of the mesh). + indices.push_back(indexRemap[objIndex]); + } + ++numTriangles; + } + } + + fprintf(f, "Shape \"trianglemesh\"\n"); + fprintf(f, " \"point3 P\" [ \n"); + for (Point3f p : P) + fprintf(f, "\t%.10g %.10g %.10g\n", p.x, p.y, p.z); + fprintf(f, "]\n"); + if (!N.empty()) { + fprintf(f, " \"normal N\" [ \n"); + for (Normal3f n : N) + fprintf(f, "\t%.10g %.10g %.10g\n", n.x, n.y, n.z); + fprintf(f, "]\n"); + } + if (!st.empty()) { + fprintf(f, " \"point2 st\" [ \n"); + for (Point2f tex : st) + fprintf(f, "\t%.10g %.10g\n", tex.x, tex.y); + fprintf(f, "]\n"); + } + fprintf(f, " \"integer indices\" [ \n\t"); + for (size_t i = 0; i < indices.size(); ++i) + fprintf(f, "%d%s", indices[i], (i % 3) == 2 ? "\n\t" : " "); + if (!faceIndices.empty()) { + fprintf(f, "]\n \"integer faceIndices\" [\n"); + for (int i : faceIndices) + fprintf(f, "\t%d\n", i); + } + fprintf(f, "]\n\n"); + } + fprintf(f, "AttributeEnd\n\n\n"); + } + if (f != stdout) + fclose(f); + + fprintf(stderr, "Converted %d meshes (%d triangles, %d mesh emitters).\n", numMeshes, + numTriangles, numAreaLights); + + return 0; +} diff --git a/src/pbrt/cmd/pbrt.cpp b/src/pbrt/cmd/pbrt.cpp new file mode 100644 index 00000000..43dea7f2 --- /dev/null +++ b/src/pbrt/cmd/pbrt.cpp @@ -0,0 +1,241 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef NVTX +#include +#include "nvtx3/nvToolsExt.h" +#endif + +using namespace pbrt; + +#ifdef PBRT_BUILD_GPU_RENDERER +namespace pbrt { +extern void GPURender(ParsedScene &); +} +#else +namespace pbrt { +void GPURender(ParsedScene &) { + ErrorExit("GPU rendering is not supported on this system."); +} +} // namespace pbrt +#endif + +static void usage(const std::string &msg = {}) { + if (!msg.empty()) + fprintf(stderr, "pbrt: %s\n\n", msg.c_str()); + + fprintf(stderr, + R"(usage: pbrt [] + +Rendering options: + --cropwindow Specify an image crop window w.r.t. [0,1]^2 + --debugstart Inform the Integrator where to start rendering for + faster debugging. ( are Integrator-specific + and come from error message text.) + --disable-pixel-jitter Always sample pixels at their centers. + --disable-wavelength-jitter Always sample the same %d wavelengths of light. + --display-server Connect to display server at given address and port + to display the image as it's being rendered. + --force-diffuse Convert all materials to be diffuse.)" +#ifdef PBRT_BUILD_GPU_RENDERER + R"( + --gpu Use the GPU for rendering. (Default: disabled) + --gpu-device Use specified GPU for rendering.)" +#endif + R"( + --help Print this help text. + --mse-reference-image Filename for reference image to use for MSE computation. + --mse-reference-out File to write MSE error vs spp results. + --nthreads Use specified number of threads for rendering. + --outfile Write the final image to the given filename. + --pixel Render just the specified pixel. + --pixelbounds Specify an image crop window w.r.t. pixel coordinates. + --pixelstats Record per-pixel statistics and write additional images + with their values. + --quick Automatically reduce a number of quality settings + to render more quickly. + --quiet Suppress all text output other than error messages. + --render-coord-sys Coordinate system to use for the scene when rendering, + where name is "camera", "cameraworld", or "world". + --seed Set random number generator seed. Default: 0. + --spp Override number of pixel samples specified in scene + description file. + +Logging options: + --log-level Log messages at or above this level, where + is "verbose", "error", or "fatal". Default: "error". + --vlog-level Set VLOG verbosity. (Default: 0, disabled.) + +Reformatting options: + --format Print a reformatted version of the input file(s) to + standard output. Does not render an image. + --toply Print a reformatted version of the input file(s) to + standard output and convert all triangle meshes to + PLY files. Does not render an image. + --upgrade Upgrade a pbrt-v3 file to pbrt-v4's format. +)", + NSpectrumSamples); + exit(msg.empty() ? 0 : 1); +} + +// main program +int main(int argc, char *argv[]) { +#ifdef NVTX + nvtxNameOsThread(syscall(SYS_gettid), "MAIN_THREAD"); +#endif + // Declare variables for parsed command line + PBRTOptions options; + std::vector filenames; + + std::string logLevel = "error"; + std::string renderCoordSys = "cameraworld"; + bool format = false, toPly = false; + + // Process command-line arguments + ++argv; + while (*argv != nullptr) { + if ((*argv)[0] != '-') { + filenames.push_back(*argv); + ++argv; + continue; + } + + auto onError = [](const std::string &err) { + usage(err); + exit(1); + }; + + std::string cropWindow, pixelBounds, pixel; + if (ParseArg(&argv, "cropwindow", &cropWindow, onError)) { + pstd::optional> c = SplitStringToFloats(cropWindow, ','); + if (!c || c->size() != 4) { + usage("Didn't find four values after --cropwindow"); + return 1; + } + options.cropWindow = + Bounds2f(Point2f((*c)[0], (*c)[2]), Point2f((*c)[1], (*c)[3])); + } else if (ParseArg(&argv, "pixel", &pixel, onError)) { + pstd::optional> p = SplitStringToInts(pixel, ','); + if (!p || p->size() != 2) { + usage("Didn't find two values after --pixel"); + return 1; + } + options.pixelBounds = + Bounds2i(Point2i((*p)[0], (*p)[1]), Point2i((*p)[0] + 1, (*p)[1] + 1)); + } else if (ParseArg(&argv, "pixelbounds", &pixelBounds, onError)) { + pstd::optional> p = SplitStringToInts(pixelBounds, ','); + if (!p || p->size() != 4) { + usage("Didn't find four integer values after --pixelbounds"); + return 1; + } + options.pixelBounds = + Bounds2i(Point2i((*p)[0], (*p)[2]), Point2i((*p)[1], (*p)[3])); + } else if ( +#ifdef PBRT_BUILD_GPU_RENDERER + ParseArg(&argv, "gpu", &options.useGPU, onError) || + ParseArg(&argv, "gpu-device", &options.gpuDevice, onError) || +#endif + ParseArg(&argv, "debugstart", &options.debugStart, onError) || + ParseArg(&argv, "disable-pixel-jitter", &options.disablePixelJitter, + onError) || + ParseArg(&argv, "disable-wavelength-jitter", &options.disableWavelengthJitter, + onError) || + ParseArg(&argv, "display-server", &options.displayServer, onError) || + ParseArg(&argv, "force-diffuse", &options.forceDiffuse, onError) || + ParseArg(&argv, "format", &format, onError) || + ParseArg(&argv, "log-level", &logLevel, onError) || + ParseArg(&argv, "mse-reference-image", &options.mseReferenceImage, onError) || + ParseArg(&argv, "mse-reference-out", &options.mseReferenceOutput, onError) || + ParseArg(&argv, "nthreads", &options.nThreads, onError) || + ParseArg(&argv, "outfile", &options.imageFile, onError) || + ParseArg(&argv, "pixelstats", &options.recordPixelStatistics, onError) || + ParseArg(&argv, "quick", &options.quickRender, onError) || + ParseArg(&argv, "quiet", &options.quiet, onError) || + ParseArg(&argv, "render-coord-sys", &renderCoordSys, onError) || + ParseArg(&argv, "seed", &options.seed, onError) || + ParseArg(&argv, "spp", &options.pixelSamples, onError) || + ParseArg(&argv, "toply", &toPly, onError) || + ParseArg(&argv, "upgrade", &options.upgrade, onError) || + ParseArg(&argv, "vlog-level", &options.logConfig.vlogLevel, onError)) { + // success + } else if ((strcmp(*argv, "--help") == 0) || (strcmp(*argv, "-help") == 0) || + (strcmp(*argv, "-h") == 0)) { + usage(); + return 0; + } else { + usage(StringPrintf("argument \"%s\" unknown", *argv)); + return 1; + } + } + + // Print welcome banner + if (!options.quiet && !format && !toPly && !options.upgrade) { + printf("pbrt version 4 (built %s at %s)\n", __DATE__, __TIME__); +#ifndef NDEBUG + LOG_VERBOSE("Running debug build"); + printf("*** DEBUG BUILD ***\n"); +#endif // !NDEBUG + printf("Copyright (c)1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys.\n"); + printf("The source code to pbrt (but *not* the book contents) is covered " + "by the BSD License.\n"); + printf("See the file LICENSE.txt for the conditions of the license.\n"); + fflush(stdout); + } + + if (renderCoordSys == "camera") + options.renderingSpace = RenderingCoordinateSystem::Camera; + else if (renderCoordSys == "cameraworld") + options.renderingSpace = RenderingCoordinateSystem::CameraWorld; + else if (renderCoordSys == "world") + options.renderingSpace = RenderingCoordinateSystem::World; + else + ErrorExit("%s: unknown rendering coordinate system.", renderCoordSys); + + if (!options.mseReferenceImage.empty() && options.mseReferenceOutput.empty()) + ErrorExit("Must provide MSE reference output filename via " + "--mse-reference-out"); + if (!options.mseReferenceOutput.empty() && options.mseReferenceImage.empty()) + ErrorExit("Must provide MSE reference image via --mse-reference-image"); + + options.logConfig.level = LogLevelFromString(logLevel); + + InitPBRT(options); + + if (format || toPly || options.upgrade) { + FormattingScene formattingScene(toPly, options.upgrade); + ParseFiles(&formattingScene, filenames); + } else { + // Parse provided scene description files + ParsedScene scene; + ParseFiles(&scene, filenames); + + // Render scene + if (options.useGPU) + GPURender(scene); + else + CPURender(scene); + + LOG_VERBOSE("Memory used after post-render cleanup: %s", GetCurrentRSS()); + // Clean up after rendering scene + CleanupPBRT(); + } + + return 0; +} diff --git a/src/pbrt/cmd/pbrt_test.cpp b/src/pbrt/cmd/pbrt_test.cpp new file mode 100644 index 00000000..95e65cc0 --- /dev/null +++ b/src/pbrt/cmd/pbrt_test.cpp @@ -0,0 +1,81 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include + +#include +#include + +using namespace pbrt; + +void usage(const std::string &msg = "") { + if (!msg.empty()) + fprintf(stderr, "pbrt_test: %s\n\n", msg.c_str()); + + fprintf(stderr, R"(pbrt_test arguments: + --log-level Log messages at or above this level, where + is "verbose", "error", or "fatal". Default: "error". + --nthreads Use specified number of threads for rendering. + --test_filter Regular expression of test names to run. + --vlog-level Set VLOG verbosity. (Default: 0, disabled.) +)"); + + exit(msg.empty() ? 0 : 1); +} + +int main(int argc, char **argv) { + PBRTOptions opt; + opt.quiet = true; + std::string logLevel = "error"; + std::string testFilter; + + char **origArgv = argv; + // Process command-line arguments + ++argv; + while (*argv != nullptr) { + auto onError = [](const std::string &err) { + usage(err); + exit(1); + }; + + if (ParseArg(&argv, "log-level", &logLevel, onError) || + ParseArg(&argv, "nthreads", &opt.nThreads, onError) || + ParseArg(&argv, "test-filter", &testFilter, onError) || + ParseArg(&argv, "vlog-level", &opt.logConfig.vlogLevel, onError)) { + // success + } else if ((strcmp(*argv, "--help") == 0) || (strcmp(*argv, "-h") == 0)) { + usage(); + return 0; + } else { + usage(StringPrintf("argument \"%s\" unknown", *argv)); + return 1; + } + } + + opt.logConfig.level = LogLevelFromString(logLevel); + + InitPBRT(opt); + + int googleArgc = 1; + const char *googleArgv[4] = {}; + googleArgv[0] = argv[0]; + std::string filter; + if (!testFilter.empty()) { + filter = StringPrintf("--gtest_filter=%s", testFilter); + googleArgc += 1; + googleArgv[1] = filter.c_str(); + } + testing::InitGoogleTest(&googleArgc, (char **)googleArgv); + + int ret = RUN_ALL_TESTS(); + + CleanupPBRT(); + + return ret; +} diff --git a/src/pbrt/cmd/rgb2spec_opt.cpp b/src/pbrt/cmd/rgb2spec_opt.cpp new file mode 100644 index 00000000..d6306b0c --- /dev/null +++ b/src/pbrt/cmd/rgb2spec_opt.cpp @@ -0,0 +1,902 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#if defined(_MSC_VER) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#define strcasecmp _stricmp +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * This file contains: + * + * 1. CIE 1931 curves at sampled at 5nm intervals + * + * 2. CIE D65 and D50 spectra sampled at 5nm intervals. + * Both are normalized to have unit luminance. + * + * 3. XYZ <-> sRGB conversion matrices + * XYZ <-> ProPhoto RGB conversion matrices + * + * 4. A convenience function "cie_interp" to access the discretized + * data at arbitrary wavelengths (with linear interpolation) +} + */ +#define CIE_LAMBDA_MIN 360.0 +#define CIE_LAMBDA_MAX 830.0 +#define CIE_SAMPLES 95 + +const double cie_x[CIE_SAMPLES] = { + 0.000129900000, 0.000232100000, 0.000414900000, 0.000741600000, 0.001368000000, + 0.002236000000, 0.004243000000, 0.007650000000, 0.014310000000, 0.023190000000, + 0.043510000000, 0.077630000000, 0.134380000000, 0.214770000000, 0.283900000000, + 0.328500000000, 0.348280000000, 0.348060000000, 0.336200000000, 0.318700000000, + 0.290800000000, 0.251100000000, 0.195360000000, 0.142100000000, 0.095640000000, + 0.057950010000, 0.032010000000, 0.014700000000, 0.004900000000, 0.002400000000, + 0.009300000000, 0.029100000000, 0.063270000000, 0.109600000000, 0.165500000000, + 0.225749900000, 0.290400000000, 0.359700000000, 0.433449900000, 0.512050100000, + 0.594500000000, 0.678400000000, 0.762100000000, 0.842500000000, 0.916300000000, + 0.978600000000, 1.026300000000, 1.056700000000, 1.062200000000, 1.045600000000, + 1.002600000000, 0.938400000000, 0.854449900000, 0.751400000000, 0.642400000000, + 0.541900000000, 0.447900000000, 0.360800000000, 0.283500000000, 0.218700000000, + 0.164900000000, 0.121200000000, 0.087400000000, 0.063600000000, 0.046770000000, + 0.032900000000, 0.022700000000, 0.015840000000, 0.011359160000, 0.008110916000, + 0.005790346000, 0.004109457000, 0.002899327000, 0.002049190000, 0.001439971000, + 0.000999949300, 0.000690078600, 0.000476021300, 0.000332301100, 0.000234826100, + 0.000166150500, 0.000117413000, 0.000083075270, 0.000058706520, 0.000041509940, + 0.000029353260, 0.000020673830, 0.000014559770, 0.000010253980, 0.000007221456, + 0.000005085868, 0.000003581652, 0.000002522525, 0.000001776509, 0.000001251141}; + +const double cie_y[CIE_SAMPLES] = { + 0.000003917000, 0.000006965000, 0.000012390000, 0.000022020000, 0.000039000000, + 0.000064000000, 0.000120000000, 0.000217000000, 0.000396000000, 0.000640000000, + 0.001210000000, 0.002180000000, 0.004000000000, 0.007300000000, 0.011600000000, + 0.016840000000, 0.023000000000, 0.029800000000, 0.038000000000, 0.048000000000, + 0.060000000000, 0.073900000000, 0.090980000000, 0.112600000000, 0.139020000000, + 0.169300000000, 0.208020000000, 0.258600000000, 0.323000000000, 0.407300000000, + 0.503000000000, 0.608200000000, 0.710000000000, 0.793200000000, 0.862000000000, + 0.914850100000, 0.954000000000, 0.980300000000, 0.994950100000, 1.000000000000, + 0.995000000000, 0.978600000000, 0.952000000000, 0.915400000000, 0.870000000000, + 0.816300000000, 0.757000000000, 0.694900000000, 0.631000000000, 0.566800000000, + 0.503000000000, 0.441200000000, 0.381000000000, 0.321000000000, 0.265000000000, + 0.217000000000, 0.175000000000, 0.138200000000, 0.107000000000, 0.081600000000, + 0.061000000000, 0.044580000000, 0.032000000000, 0.023200000000, 0.017000000000, + 0.011920000000, 0.008210000000, 0.005723000000, 0.004102000000, 0.002929000000, + 0.002091000000, 0.001484000000, 0.001047000000, 0.000740000000, 0.000520000000, + 0.000361100000, 0.000249200000, 0.000171900000, 0.000120000000, 0.000084800000, + 0.000060000000, 0.000042400000, 0.000030000000, 0.000021200000, 0.000014990000, + 0.000010600000, 0.000007465700, 0.000005257800, 0.000003702900, 0.000002607800, + 0.000001836600, 0.000001293400, 0.000000910930, 0.000000641530, 0.000000451810}; + +const double cie_z[CIE_SAMPLES] = { + 0.000606100000, 0.001086000000, 0.001946000000, 0.003486000000, 0.006450001000, + 0.010549990000, 0.020050010000, 0.036210000000, 0.067850010000, 0.110200000000, + 0.207400000000, 0.371300000000, 0.645600000000, 1.039050100000, 1.385600000000, + 1.622960000000, 1.747060000000, 1.782600000000, 1.772110000000, 1.744100000000, + 1.669200000000, 1.528100000000, 1.287640000000, 1.041900000000, 0.812950100000, + 0.616200000000, 0.465180000000, 0.353300000000, 0.272000000000, 0.212300000000, + 0.158200000000, 0.111700000000, 0.078249990000, 0.057250010000, 0.042160000000, + 0.029840000000, 0.020300000000, 0.013400000000, 0.008749999000, 0.005749999000, + 0.003900000000, 0.002749999000, 0.002100000000, 0.001800000000, 0.001650001000, + 0.001400000000, 0.001100000000, 0.001000000000, 0.000800000000, 0.000600000000, + 0.000340000000, 0.000240000000, 0.000190000000, 0.000100000000, 0.000049999990, + 0.000030000000, 0.000020000000, 0.000010000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, + 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000}; + +#define N(x) (x / 10566.864005283874576) + +const double cie_d65[CIE_SAMPLES] = { + N(46.6383), N(49.3637), N(52.0891), N(51.0323), N(49.9755), N(52.3118), N(54.6482), + N(68.7015), N(82.7549), N(87.1204), N(91.486), N(92.4589), N(93.4318), N(90.057), + N(86.6823), N(95.7736), N(104.865), N(110.936), N(117.008), N(117.41), N(117.812), + N(116.336), N(114.861), N(115.392), N(115.923), N(112.367), N(108.811), N(109.082), + N(109.354), N(108.578), N(107.802), N(106.296), N(104.79), N(106.239), N(107.689), + N(106.047), N(104.405), N(104.225), N(104.046), N(102.023), N(100.0), N(98.1671), + N(96.3342), N(96.0611), N(95.788), N(92.2368), N(88.6856), N(89.3459), N(90.0062), + N(89.8026), N(89.5991), N(88.6489), N(87.6987), N(85.4936), N(83.2886), N(83.4939), + N(83.6992), N(81.863), N(80.0268), N(80.1207), N(80.2146), N(81.2462), N(82.2778), + N(80.281), N(78.2842), N(74.0027), N(69.7213), N(70.6652), N(71.6091), N(72.979), + N(74.349), N(67.9765), N(61.604), N(65.7448), N(69.8856), N(72.4863), N(75.087), + N(69.3398), N(63.5927), N(55.0054), N(46.4182), N(56.6118), N(66.8054), N(65.0941), + N(63.3828), N(63.8434), N(64.304), N(61.8779), N(59.4519), N(55.7054), N(51.959), + N(54.6998), N(57.4406), N(58.8765), N(60.3125)}; + +#undef N + +#define N(x) (x / 106.8) +const double cie_e[CIE_SAMPLES] = { + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), N(1.0), + N(1.0), N(1.0), N(1.0), N(1.0), N(1.0)}; +#undef N + +#define N(x) (x / 10503.2) + +const double cie_d50[CIE_SAMPLES] = { + N(23.942000), N(25.451000), N(26.961000), N(25.724000), N(24.488000), + N(27.179000), N(29.871000), N(39.589000), N(49.308000), N(52.910000), + N(56.513000), N(58.273000), N(60.034000), N(58.926000), N(57.818000), + N(66.321000), N(74.825000), N(81.036000), N(87.247000), N(88.930000), + N(90.612000), N(90.990000), N(91.368000), N(93.238000), N(95.109000), + N(93.536000), N(91.963000), N(93.843000), N(95.724000), N(96.169000), + N(96.613000), N(96.871000), N(97.129000), N(99.614000), N(102.099000), + N(101.427000), N(100.755000), N(101.536000), N(102.317000), N(101.159000), + N(100.000000), N(98.868000), N(97.735000), N(98.327000), N(98.918000), + N(96.208000), N(93.499000), N(95.593000), N(97.688000), N(98.478000), + N(99.269000), N(99.155000), N(99.042000), N(97.382000), N(95.722000), + N(97.290000), N(98.857000), N(97.262000), N(95.667000), N(96.929000), + N(98.190000), N(100.597000), N(103.003000), N(101.068000), N(99.133000), + N(93.257000), N(87.381000), N(89.492000), N(91.604000), N(92.246000), + N(92.889000), N(84.872000), N(76.854000), N(81.683000), N(86.511000), + N(89.546000), N(92.580000), N(85.405000), N(78.230000), N(67.961000), + N(57.692000), N(70.307000), N(82.923000), N(80.599000), N(78.274000), + N(0), N(0), N(0), N(0), N(0), + N(0), N(0), N(0), N(0)}; + +#undef N + +#define N(x) (x / 10536.3) + +const double cie_d60[CIE_SAMPLES] = { + N(38.683115), N(41.014457), N(42.717548), N(42.264182), N(41.454941), + N(41.763698), N(46.605319), N(59.226938), N(72.278594), N(78.231500), + N(80.440600), N(82.739580), N(82.915027), N(79.009168), N(77.676264), + N(85.163609), N(95.681274), N(103.267764), N(107.954821), N(109.777964), + N(109.559187), N(108.418402), N(107.758141), N(109.071548), N(109.671404), + N(106.734741), N(103.707873), N(103.981942), N(105.232199), N(105.235867), + N(104.427667), N(103.052881), N(102.522934), N(104.371416), N(106.052671), + N(104.948900), N(103.315154), N(103.416286), N(103.538599), N(102.099304), + N(100.000000), N(97.992725), N(96.751421), N(97.102402), N(96.712823), + N(93.174457), N(89.921479), N(90.351933), N(91.999793), N(92.384009), + N(92.098710), N(91.722859), N(90.646003), N(88.327552), N(86.526483), + N(87.034239), N(87.579186), N(85.884584), N(83.976140), N(83.743140), + N(84.724074), N(86.450818), N(87.493491), N(86.546330), N(83.483070), + N(78.268785), N(74.172451), N(74.275184), N(76.620385), N(79.423856), + N(79.051849), N(71.763360), N(65.471371), N(67.984085), N(74.106079), + N(78.556612), N(79.527120), N(75.584935), N(67.307163), N(55.275106), + N(49.273538), N(59.008629), N(70.892412), N(70.950115), N(67.163996), + N(67.445480), N(68.171371), N(66.466636), N(62.989809), N(58.067786), + N(54.990892), N(56.915942), N(60.825601), N(62.987850)}; + +#undef N + +const double xyz_to_srgb[3][3] = {{3.240479, -1.537150, -0.498535}, + {-0.969256, 1.875991, 0.041556}, + {0.055648, -0.204043, 1.057311}}; + +const double srgb_to_xyz[3][3] = {{0.412453, 0.357580, 0.180423}, + {0.212671, 0.715160, 0.072169}, + {0.019334, 0.119193, 0.950227}}; + +const double xyz_to_xyz[3][3] = { + {1.0, 0.0, 0.0}, + {0.0, 1.0, 0.0}, + {0.0, 0.0, 1.0}, +}; + +const double xyz_to_ergb[3][3] = { + {2.689989, -1.276020, -0.413844}, + {-1.022095, 1.978261, 0.043821}, + {0.061203, -0.224411, 1.162859}, +}; + +const double ergb_to_xyz[3][3] = { + {0.496859, 0.339094, 0.164047}, + {0.256193, 0.678188, 0.065619}, + {0.023290, 0.113031, 0.863978}, +}; + +const double xyz_to_prophoto_rgb[3][3] = {{1.3459433, -0.2556075, -0.0511118}, + {-0.5445989, 1.5081673, 0.0205351}, + {0.0000000, 0.0000000, 1.2118128}}; + +const double prophoto_rgb_to_xyz[3][3] = {{0.7976749, 0.1351917, 0.0313534}, + {0.2880402, 0.7118741, 0.0000857}, + {0.0000000, 0.0000000, 0.8252100}}; + +const double xyz_to_aces2065_1[3][3] = {{1.0498110175, 0.0000000000, -0.0000974845}, + {-0.4959030231, 1.3733130458, 0.0982400361}, + {0.0000000000, 0.0000000000, 0.9912520182}}; + +const double aces2065_1_to_xyz[3][3] = {{0.9525523959, 0.0000000000, 0.0000936786}, + {0.3439664498, 0.7281660966, -0.0721325464}, + {0.0000000000, 0.0000000000, 1.0088251844}}; + +const double xyz_to_rec2020[3][3] = {{1.7166511880, -0.3556707838, -0.2533662814}, + {-0.6666843518, 1.6164812366, 0.0157685458}, + {0.0176398574, -0.0427706133, 0.9421031212}}; + +const double rec2020_to_xyz[3][3] = {{0.6369580483, 0.1446169036, 0.1688809752}, + {0.2627002120, 0.6779980715, 0.0593017165}, + {0.0000000000, 0.0280726930, 1.0609850577}}; + +const double xyz_to_dcip3[3][3] = {{2.4931748, -0.93126315, -0.40265882}, + {-0.82950425, 1.7626965, 0.023625137}, + {0.035853732, -0.07618918, 0.9570952}}; +const double dcip3_to_xyz[3][3] = {{0.48663378, 0.26566276, 0.19817366}, + {0.22900413, 0.69172573, 0.079269454}, + {0., 0.04511256, 1.0437145}}; + +double cie_interp(const double *data, double x) { + x -= CIE_LAMBDA_MIN; + x *= (CIE_SAMPLES - 1) / (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN); + int offset = (int)x; + if (offset < 0) + offset = 0; + if (offset > CIE_SAMPLES - 2) + offset = CIE_SAMPLES - 2; + double weight = x - offset; + return (1.0 - weight) * data[offset] + weight * data[offset + 1]; +} + +// LU decomposition & triangular solving code lifted from Wikipedia + +/* INPUT: A - array of pointers to rows of a square matrix having dimension N + * Tol - small tolerance number to detect failure when the matrix is near + * degenerate OUTPUT: Matrix A is changed, it contains both matrices L-E and U + * as A=(L-E)+U such that P*A=L*U. The permutation matrix is not stored as a + * matrix, but in an integer vector P of size N+1 containing column indexes + * where the permutation matrix has "1". The last element P[N]=S+N, where S is + * the number of row exchanges needed for determinant computation, det(P)=(-1)^S + */ +int LUPDecompose(double **A, int N, double Tol, int *P) { + int i, j, k, imax; + double maxA, *ptr, absA; + + for (i = 0; i <= N; i++) + P[i] = i; // Unit permutation matrix, P[N] initialized with N + + for (i = 0; i < N; i++) { + maxA = 0.0; + imax = i; + + for (k = i; k < N; k++) + if ((absA = fabs(A[k][i])) > maxA) { + maxA = absA; + imax = k; + } + + if (maxA < Tol) + return 0; // failure, matrix is degenerate + + if (imax != i) { + // pivoting P + j = P[i]; + P[i] = P[imax]; + P[imax] = j; + + // pivoting rows of A + ptr = A[i]; + A[i] = A[imax]; + A[imax] = ptr; + + // counting pivots starting from N (for determinant) + P[N]++; + } + + for (j = i + 1; j < N; j++) { + A[j][i] /= A[i][i]; + + for (k = i + 1; k < N; k++) + A[j][k] -= A[j][i] * A[i][k]; + } + } + + return 1; // decomposition done +} + +/* INPUT: A,P filled in LUPDecompose; b - rhs vector; N - dimension + * OUTPUT: x - solution vector of A*x=b + */ +void LUPSolve(double **A, int *P, double *b, int N, double *x) { + for (int i = 0; i < N; i++) { + x[i] = b[P[i]]; + + for (int k = 0; k < i; k++) + x[i] -= A[i][k] * x[k]; + } + + for (int i = N - 1; i >= 0; i--) { + for (int k = i + 1; k < N; k++) + x[i] -= A[i][k] * x[k]; + + x[i] = x[i] / A[i][i]; + } +} + +#if defined(_OPENMP) +#define RGB2SPEC_USE_OPENMP 1 +#elif defined(__APPLE__) +#define RGB2SPEC_USE_GCD 1 +#include +#endif + +/// Discretization of quadrature scheme +#define CIE_FINE_SAMPLES ((CIE_SAMPLES - 1) * 3 + 1) +#define RGB2SPEC_EPSILON 1e-4 + +/// Precomputed tables for fast spectral -> RGB conversion +double lambda_tbl[CIE_FINE_SAMPLES], rgb_tbl[3][CIE_FINE_SAMPLES], rgb_to_xyz[3][3], + xyz_to_rgb[3][3], xyz_whitepoint[3]; + +/// Currently supported gamuts +enum Gamut { + SRGB, + ProPhotoRGB, + ACES2065_1, + REC2020, + ERGB, + XYZ, + DCI_P3, + NO_GAMUT, +}; + +double sigmoid(double x) { + return 0.5 * x / std::sqrt(1.0 + x * x) + 0.5; +} + +double smoothstep(double x) { + return x * x * (3.0 - 2.0 * x); +} + +double sqr(double x) { + return x * x; +} + +void cie_lab(double *p) { + double X = 0.0, Y = 0.0, Z = 0.0, Xw = xyz_whitepoint[0], Yw = xyz_whitepoint[1], + Zw = xyz_whitepoint[2]; + + for (int j = 0; j < 3; ++j) { + X += p[j] * rgb_to_xyz[0][j]; + Y += p[j] * rgb_to_xyz[1][j]; + Z += p[j] * rgb_to_xyz[2][j]; + } + + auto f = [](double t) -> double { + double delta = 6.0 / 29.0; + if (t > delta * delta * delta) + return cbrt(t); + else + return t / (delta * delta * 3.0) + (4.0 / 29.0); + }; + + p[0] = 116.0 * f(Y / Yw) - 16.0; + p[1] = 500.0 * (f(X / Xw) - f(Y / Yw)); + p[2] = 200.0 * (f(Y / Yw) - f(Z / Zw)); +} + +/** + * This function precomputes tables used to convert arbitrary spectra + * to RGB (either sRGB or ProPhoto RGB) + * + * A composite quadrature rule integrates the CIE curves, reflectance, and + * illuminant spectrum over each 5nm segment in the 360..830nm range using + * Simpson's 3/8 rule (4th-order accurate), which evaluates the integrand at + * four positions per segment. While the CIE curves and illuminant spectrum are + * linear over the segment, the reflectance could have arbitrary behavior, + * hence the extra precations. + */ +void init_tables(Gamut gamut) { + memset(rgb_tbl, 0, sizeof(rgb_tbl)); + memset(xyz_whitepoint, 0, sizeof(xyz_whitepoint)); + + double h = (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) / (CIE_FINE_SAMPLES - 1); + + const double *illuminant = nullptr; + + switch (gamut) { + case SRGB: + illuminant = cie_d65; + memcpy(xyz_to_rgb, xyz_to_srgb, sizeof(double) * 9); + memcpy(rgb_to_xyz, srgb_to_xyz, sizeof(double) * 9); + break; + + case ERGB: + illuminant = cie_e; + memcpy(xyz_to_rgb, xyz_to_ergb, sizeof(double) * 9); + memcpy(rgb_to_xyz, ergb_to_xyz, sizeof(double) * 9); + break; + + case XYZ: + illuminant = cie_e; + memcpy(xyz_to_rgb, xyz_to_xyz, sizeof(double) * 9); + memcpy(rgb_to_xyz, xyz_to_xyz, sizeof(double) * 9); + break; + + case ProPhotoRGB: + illuminant = cie_d50; + memcpy(xyz_to_rgb, xyz_to_prophoto_rgb, sizeof(double) * 9); + memcpy(rgb_to_xyz, prophoto_rgb_to_xyz, sizeof(double) * 9); + break; + + case ACES2065_1: + illuminant = cie_d60; + memcpy(xyz_to_rgb, xyz_to_aces2065_1, sizeof(double) * 9); + memcpy(rgb_to_xyz, aces2065_1_to_xyz, sizeof(double) * 9); + break; + + case REC2020: + illuminant = cie_d65; + memcpy(xyz_to_rgb, xyz_to_rec2020, sizeof(double) * 9); + memcpy(rgb_to_xyz, rec2020_to_xyz, sizeof(double) * 9); + break; + + case DCI_P3: + illuminant = cie_d65; + memcpy(xyz_to_rgb, xyz_to_dcip3, sizeof(double) * 9); + memcpy(rgb_to_xyz, dcip3_to_xyz, sizeof(double) * 9); + break; + + default: + throw std::runtime_error("init_gamut(): invalid/unsupported gamut."); + } + + for (int i = 0; i < CIE_FINE_SAMPLES; ++i) { + double lambda = CIE_LAMBDA_MIN + i * h; + + double xyz[3] = {cie_interp(cie_x, lambda), cie_interp(cie_y, lambda), + cie_interp(cie_z, lambda)}, + I = cie_interp(illuminant, lambda); + + double weight = 3.0 / 8.0 * h; + if (i == 0 || i == CIE_FINE_SAMPLES - 1) + ; + else if ((i - 1) % 3 == 2) + weight *= 2.f; + else + weight *= 3.f; + + lambda_tbl[i] = lambda; + for (int k = 0; k < 3; ++k) + for (int j = 0; j < 3; ++j) + rgb_tbl[k][i] += xyz_to_rgb[k][j] * xyz[j] * I * weight; + + for (int i = 0; i < 3; ++i) + xyz_whitepoint[i] += xyz[i] * I * weight; + } +} + +void eval_residual(const double *coeffs, const double *rgb, double *residual) { + double out[3] = {0.0, 0.0, 0.0}; + + for (int i = 0; i < CIE_FINE_SAMPLES; ++i) { + /* Scale lambda to 0..1 range */ + double lambda = + (lambda_tbl[i] - CIE_LAMBDA_MIN) / (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN); + + /* Polynomial */ + double x = 0.0; + for (int i = 0; i < 3; ++i) + x = x * lambda + coeffs[i]; + + /* Sigmoid */ + double s = sigmoid(x); + + /* Integrate against precomputed curves */ + for (int j = 0; j < 3; ++j) + out[j] += rgb_tbl[j][i] * s; + } + cie_lab(out); + memcpy(residual, rgb, sizeof(double) * 3); + cie_lab(residual); + + for (int j = 0; j < 3; ++j) + residual[j] -= out[j]; +} + +void eval_jacobian(const double *coeffs, const double *rgb, double **jac) { + double r0[3], r1[3], tmp[3]; + + for (int i = 0; i < 3; ++i) { + memcpy(tmp, coeffs, sizeof(double) * 3); + tmp[i] -= RGB2SPEC_EPSILON; + eval_residual(tmp, rgb, r0); + + memcpy(tmp, coeffs, sizeof(double) * 3); + tmp[i] += RGB2SPEC_EPSILON; + eval_residual(tmp, rgb, r1); + + for (int j = 0; j < 3; ++j) + jac[j][i] = (r1[j] - r0[j]) * 1.0 / (2 * RGB2SPEC_EPSILON); + } +} + +double gauss_newton(const double rgb[3], double coeffs[3], int it = 15) { + double r = 0; + for (int i = 0; i < it; ++i) { + double J0[3], J1[3], J2[3], *J[3] = {J0, J1, J2}; + + double residual[3]; + + eval_residual(coeffs, rgb, residual); + eval_jacobian(coeffs, rgb, J); + + int P[4]; + int rv = LUPDecompose(J, 3, 1e-15, P); + if (rv != 1) { + std::cout << "RGB " << rgb[0] << " " << rgb[1] << " " << rgb[2] << std::endl; + std::cout << "-> " << coeffs[0] << " " << coeffs[1] << " " << coeffs[2] + << std::endl; + throw std::runtime_error("LU decomposition failed!"); + } + + double x[3]; + LUPSolve(J, P, residual, 3, x); + + r = 0.0; + for (int j = 0; j < 3; ++j) { + coeffs[j] -= x[j]; + r += residual[j] * residual[j]; + } + double max = std::max(std::max(coeffs[0], coeffs[1]), coeffs[2]); + + if (max > 200) { + for (int j = 0; j < 3; ++j) + coeffs[j] *= 200 / max; + } + + if (r < 1e-6) + break; + } + return std::sqrt(r); +} + +static Gamut parse_gamut(const char *str) { + if (!strcasecmp(str, "sRGB")) + return SRGB; + if (!strcasecmp(str, "eRGB")) + return ERGB; + if (!strcasecmp(str, "XYZ")) + return XYZ; + if (!strcasecmp(str, "ProPhotoRGB")) + return ProPhotoRGB; + if (!strcasecmp(str, "ACES2065_1")) + return ACES2065_1; + if (!strcasecmp(str, "REC2020")) + return REC2020; + if (!strcasecmp(str, "DCI_P3")) + return DCI_P3; + return NO_GAMUT; +} + +/* hack: below is a copy of enough of util/parallel.* to be able to run + ParallelFor to generate the tables. Note that we don't want to #include + , since we'd end up spending lots of time regenerating + these tables whenever that header file changed. + */ + +void ParallelFor(int64_t start, int64_t end, std::function func, + const char *progressName = nullptr); + +inline void ParallelFor(int64_t start, int64_t end, std::function func, + const char *progressName = nullptr) { + ParallelFor( + start, end, + [&func](int64_t start, int64_t end) { + for (int64_t i = start; i < end; ++i) + func(i); + }, + progressName); +} + +class ParallelJob { + public: + virtual ~ParallelJob() { assert(removed); } + + // *lock should be locked going in and and unlocked coming out. + virtual void RunStep(std::unique_lock *lock) = 0; + virtual bool HaveWork() const = 0; + + bool Finished() const { return !HaveWork() && activeWorkers == 0; } + + private: + friend class ThreadPool; + + ParallelJob *prev = nullptr, *next = nullptr; + int activeWorkers = 0; + bool removed = false; +}; + +class ThreadPool { + public: + explicit ThreadPool(int nThreads); + ~ThreadPool(); + + size_t size() const { return threads.size(); } + + std::unique_lock AddToJobList(ParallelJob *job); + void RemoveFromJobList(ParallelJob *job); + + void WorkOrWait(std::unique_lock *lock); + + private: + void workerFunc(int tIndex); + + ParallelJob *jobList = nullptr; + // Protects jobList + mutable std::mutex jobListMutex; + // Signaled both when a new job is added to the list and when a job has + // finished. + std::condition_variable jobListCondition; + + std::vector threads; + bool shutdownThreads = false; +}; + +static std::unique_ptr threadPool; + +int AvailableCores() { + return std::max(1, std::thread::hardware_concurrency()); +} + +int RunningThreads() { + return threadPool ? (1 + threadPool->size()) : 1; +} + +ThreadPool::ThreadPool(int nThreads) { + // Launch one fewer worker thread than the total number we want doing + // work, since the main thread helps out, too. + for (int i = 0; i < nThreads - 1; ++i) + threads.push_back(std::thread(&ThreadPool::workerFunc, this, i + 1)); +} + +ThreadPool::~ThreadPool() { + if (threads.empty()) + return; + + { + std::lock_guard lock(jobListMutex); + shutdownThreads = true; + jobListCondition.notify_all(); + } + + for (std::thread &thread : threads) + thread.join(); +} + +std::unique_lock ThreadPool::AddToJobList(ParallelJob *job) { + std::unique_lock lock(jobListMutex); + if (jobList != nullptr) + jobList->prev = job; + job->next = jobList; + jobList = job; + jobListCondition.notify_all(); + return lock; +} + +void ThreadPool::RemoveFromJobList(ParallelJob *job) { + assert(!job->removed); + + if (job->prev != nullptr) { + job->prev->next = job->next; + } else { + assert(jobList == job); + jobList = job->next; + } + if (job->next != nullptr) + job->next->prev = job->prev; + + job->removed = true; +} + +void ThreadPool::workerFunc(int tIndex) { + std::unique_lock lock(jobListMutex); + while (!shutdownThreads) + WorkOrWait(&lock); +} + +void ThreadPool::WorkOrWait(std::unique_lock *lock) { + assert(lock->owns_lock()); + + ParallelJob *job = jobList; + while ((job != nullptr) && !job->HaveWork()) + job = job->next; + if (job != nullptr) { + // Run a chunk of loop iterations for _loop_ + job->activeWorkers++; + + job->RunStep(lock); + + assert(!lock->owns_lock()); + lock->lock(); + + // Update _loop_ to reflect completion of iterations + job->activeWorkers--; + + if (job->Finished()) + jobListCondition.notify_all(); + } else + // Wait for something to change (new work, or this loop being + // finished). + jobListCondition.wait(*lock); +} + +class ParallelForLoop1D : public ParallelJob { + public: + ParallelForLoop1D(int64_t start, int64_t end, int chunkSize, + std::function func) + : func(std::move(func)), nextIndex(start), maxIndex(end), chunkSize(chunkSize) {} + + bool HaveWork() const { return nextIndex < maxIndex; } + void RunStep(std::unique_lock *lock); + + private: + std::function func; + int64_t nextIndex; + int64_t maxIndex; + int chunkSize; +}; + +void ParallelForLoop1D::RunStep(std::unique_lock *lock) { + // Find the set of loop iterations to run next + int64_t indexStart = nextIndex; + int64_t indexEnd = std::min(indexStart + chunkSize, maxIndex); + + // Update _loop_ to reflect iterations this thread will run + nextIndex = indexEnd; + + if (!HaveWork()) + threadPool->RemoveFromJobList(this); + + lock->unlock(); + + // Run loop indices in _[indexStart, indexEnd)_ + func(indexStart, indexEnd); +} + +void ParallelFor(int64_t start, int64_t end, std::function func, + const char *progressName) { + assert(threadPool); + + int64_t chunkSize = std::max(1, (end - start) / (8 * RunningThreads())); + + // Create and enqueue _ParallelJob_ for this loop + ParallelForLoop1D loop(start, end, chunkSize, std::move(func)); + std::unique_lock lock = threadPool->AddToJobList(&loop); + + // Help out with parallel loop iterations in the current thread + while (!loop.Finished()) + threadPool->WorkOrWait(&lock); +} + +int main(int argc, char **argv) { + if (argc < 3) { + printf("Syntax: rgb2spec_opt []\n" + "where is one of " + "sRGB,eRGB,XYZ,ProPhotoRGB,ACES2065_1,REC2020\n"); + exit(-1); + } + Gamut gamut = SRGB; + if (argc > 3) + gamut = parse_gamut(argv[3]); + if (gamut == NO_GAMUT) { + fprintf(stderr, "Could not parse gamut `%s'!\n", argv[3]); + exit(-1); + } + init_tables(gamut); + + const int res = atoi(argv[1]); + if (res == 0) { + printf("Invalid resolution!\n"); + exit(-1); + } + + int nThreads = AvailableCores(); + threadPool = std::make_unique(nThreads); + + printf("Optimizing %s spectra...\n", argv[3]); + fflush(stdout); + + float *scale = new float[res]; + for (int k = 0; k < res; ++k) + scale[k] = (float)smoothstep(smoothstep(k / double(res - 1))); + + size_t bufsize = 3 * 3 * res * res * res; + float *out = new float[bufsize]; + + for (int l = 0; l < 3; ++l) { + ParallelFor(0, res, [&](size_t j) { + const double y = j / double(res - 1); + fflush(stdout); + for (int i = 0; i < res; ++i) { + const double x = i / double(res - 1); + double coeffs[3], rgb[3]; + memset(coeffs, 0, sizeof(double) * 3); + + int start = res / 5; + + for (int k = start; k < res; ++k) { + double b = (double)scale[k]; + + rgb[l] = b; + rgb[(l + 1) % 3] = x * b; + rgb[(l + 2) % 3] = y * b; + + double resid = gauss_newton(rgb, coeffs); + (void)resid; + + double c0 = 360.0, c1 = 1.0 / (830.0 - 360.0); + double A = coeffs[0], B = coeffs[1], C = coeffs[2]; + + int idx = ((l * res + k) * res + j) * res + i; + + out[3 * idx + 0] = float(A * (sqr(c1))); + out[3 * idx + 1] = float(B * c1 - 2 * A * c0 * (sqr(c1))); + out[3 * idx + 2] = float(C - B * c0 * c1 + A * (sqr(c0 * c1))); + // out[3*idx + 2] = resid; + } + + memset(coeffs, 0, sizeof(double) * 3); + for (int k = start; k >= 0; --k) { + double b = (double)scale[k]; + + rgb[l] = b; + rgb[(l + 1) % 3] = x * b; + rgb[(l + 2) % 3] = y * b; + + double resid = gauss_newton(rgb, coeffs); + (void)resid; + + double c0 = 360.0, c1 = 1.0 / (830.0 - 360.0); + double A = coeffs[0], B = coeffs[1], C = coeffs[2]; + + int idx = ((l * res + k) * res + j) * res + i; + + out[3 * idx + 0] = float(A * (sqr(c1))); + out[3 * idx + 1] = float(B * c1 - 2 * A * c0 * (sqr(c1))); + out[3 * idx + 2] = float(C - B * c0 * c1 + A * (sqr(c0 * c1))); + // out[3*idx + 2] = resid; + } + } + }); + } + + FILE *f = fopen(argv[2], "w"); + if (f == nullptr) + throw std::runtime_error("Could not create file!"); + fprintf(f, "#include \n"); + fprintf(f, "namespace pbrt {\n"); + fprintf(f, "extern PBRT_CONST int %sToSpectrumTable_Res = %d;\n", argv[3], res); + fprintf(f, "extern PBRT_CONST float %sToSpectrumTable_Scale[%d] = {\n", argv[3], res); + for (int i = 0; i < res; ++i) + fprintf(f, "%.9g, ", scale[i]); + fprintf(f, "};\n"); + fprintf(f, "extern PBRT_CONST float %sToSpectrumTable_Data[%d] = {\n", argv[3], + (int)bufsize); + for (int i = 0; i < bufsize; ++i) + fprintf(f, "%.9g,%c", out[i], ((i + 1) % 9) == 8 ? '\n' : ' '); + fprintf(f, "};\n"); + fprintf(f, "} // namespace pbrt\n"); + fclose(f); + + threadPool.reset(); +} diff --git a/src/pbrt/cmd/soac.cpp b/src/pbrt/cmd/soac.cpp new file mode 100644 index 00000000..673be48b --- /dev/null +++ b/src/pbrt/cmd/soac.cpp @@ -0,0 +1,455 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +/* +TODO: +- how to do float4, fancy packing tricks? + flat int:32; + float float:32 + struct Foo { int a, b; float c, d; }; + would be nice to load as a big float4... + +- mechanism to not store fields that are easily recomputed... + maybe the answer is to just do that--recompute only when needed--in the + original struct! +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int line = 1; + +#ifdef __GNUG__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-security" +#endif // __GNUG__ + +const char *filename; + +template +static void error(const char *fmt, Args... args) { + fprintf(stderr, "%s:%d: ", filename, line); + fprintf(stderr, fmt, std::forward(args)...); + exit(1); +} + +#ifdef __GNUG__ +#pragma GCC diagnostic pop +#endif // __GNUG__ + +struct OptionalString { + OptionalString() = default; + OptionalString(std::string s) : s(s), set(true) {} + + operator bool() const { return set; } + operator std::string() const { + assert(set); + return s; + } + bool operator==(const char *str) const { + assert(set); + return s == str; + } + bool operator!=(const char *str) const { + assert(set); + return s != str; + } + + std::string s; + bool set = false; +}; + +struct Member { + std::string type; + bool isConst = false; + int numPointers = 0; + + std::string GetType() const { + std::string s; + if (isConst) + s = "const "; + s += type; + for (int i = 0; i < numPointers; ++i) + s += "*"; + return s; + } + + std::vector names; + std::vector arraySizes; +}; + +struct SOA { + std::string type; + std::string templateType; + std::vector members; +}; + +int main(int argc, char *argv[]) { + if (argc != 2) + error("usage: soac \n"); + + // Read the file + filename = argv[1]; + std::ifstream ifs(filename, std::ios::binary); + if (!ifs) { + error("%s: %s", filename, strerror(errno)); + return {}; + } + std::string fileContents((std::istreambuf_iterator(ifs)), + (std::istreambuf_iterator())); + int pos = 0; + + auto eof = [&]() { return pos == fileContents.size(); }; + auto getc = [&]() { + assert(!eof()); + if (fileContents[pos] == '\n') + ++line; + return fileContents[pos++]; + }; + auto ungetc = [&]() { + assert(pos > 0); + --pos; + if (fileContents[pos] == '\n') + --line; + }; + + std::function getToken; + getToken = [&](bool eofOk) -> OptionalString { + if (eof()) { + if (eofOk) + return OptionalString(); + else + error("Premature end of file.\n"); + } + + // Skip whitespace + while (true) { + if (eof()) { + if (eofOk) + return OptionalString(); + else + error("Premature end of file.\n"); + } + + char c = getc(); + if (!isspace(c)) { + ungetc(); + break; + } + } + + assert(!eof()); + std::string s; + s += getc(); + if (s[0] == '/' && !eof()) { + if (getc() == '/') { + // skip to EOL + while (true) { + if (eof()) { + if (eofOk) + return OptionalString(); + else + error("Premature end of file.\n"); + } + if (getc() == '\n') + return getToken(eofOk); + } + } else + ungetc(); + } + if (!isalpha(s[0]) && s[0] != '_') + return OptionalString(s); + + while (!eof()) { + char c = getc(); + if (!isalnum(c) && c != '_') { + // end of token + ungetc(); + break; + } + s += c; + } + return OptionalString(s); + }; + + std::set flatTypes, externSOA; + auto isFlatType = [&](std::string type) { + return flatTypes.find(type) != flatTypes.end(); + }; + + // keep as a vector so that we can emit them in the order they were + // defined. + std::vector soaTypes; + + auto soaTypeExists = [&](std::string type) { + for (const auto &s : soaTypes) + if (s.type == type) + return true; + return externSOA.find(type) != externSOA.end(); + }; + + auto expect = [&](const char *str) { + OptionalString tok = getToken(true); + if (!tok) + error("Premature end of file; expected \"%s\".\n", str); + if (tok != str) + error("Syntax error: expected \"%s\".\n", str); + }; + + while (true) { + OptionalString os = getToken(true); + if (!os) + break; + std::string tok = os.s; + if (tok == "flat") { + OptionalString typeTok = getToken(false); + + std::string type = typeTok; + if (flatTypes.find(type) != flatTypes.end()) + error("%s flat type redeclared.\n", type.c_str()); + flatTypes.insert(type); + + expect(";"); + } else if (tok == "soa") { + SOA soa; + + OptionalString typeTok = getToken(false); + soa.type = (std::string)typeTok; + if (!isalpha(soa.type[0])) + error("%s: invalid type identifier.\n", soa.type.c_str()); + + if (soaTypeExists(soa.type)) + error("%s: type redefined.\n", soa.type.c_str()); + + OptionalString tok = getToken(false); + if (tok == "<") { + tok = getToken(false); + soa.templateType = (std::string)tok; + if (!isalpha(soa.templateType[0])) + error("%s: invalid type identifier.\n", soa.templateType.c_str()); + expect(">"); + expect("{"); + } else if (tok == ";") { + externSOA.insert(soa.type); + continue; + } else if (tok != "{") + error("Syntax error: expected \"{\".\n"); + + while (true) { + OptionalString tok = getToken(false); + if (tok == "}") + break; + + Member member; + member.type = (std::string)tok; + // Hacks to parse things like const Foo * + if (member.type == "const") { + member.isConst = true; + tok = getToken(false); + member.type = (std::string)tok; + } + while (true) { + tok = getToken(false); + if (tok == "*") + ++member.numPointers; + else + break; + } + + // Don't check the type if it's a pointer; we already know + // how to SOA pointers.. + if (member.numPointers == 0 && member.type != soa.templateType && + flatTypes.find(member.type) == flatTypes.end() && + !soaTypeExists(member.type)) + error("%s: undefined type\n", member.type.c_str()); + + while (true) { + std::string memberName = tok; + member.names.push_back(memberName); + member.arraySizes.push_back(""); // assume no array for starters + + tok = getToken(false); + if (tok == "[") { + tok = getToken(false); + // just pass it through without interpretation + member.arraySizes[member.arraySizes.size() - 1] = + (std::string)tok; + expect("]"); + tok = getToken(false); + } + + if (tok == ";") + break; + else if (tok == ",") + tok = getToken(false); // and go around again... + } + + if (member.names.empty()) + error("No members specified after type declaration.\n"); + soa.members.push_back(member); + } + expect(";"); + + soaTypes.push_back(soa); + } else + error("%s: invalid token", tok.c_str()); + } + + // And now emit them... + printf("// SOA definitions automatically generated by soac\n"); + printf("// DO NOT EDIT THIS FILE MANUALLY\n\n"); + printf("template struct SOA;\n\n"); + for (const auto &soa : soaTypes) { + if (!soa.templateType.empty()) + printf("template struct SOA<%s<%s>> {\n", + soa.templateType.c_str(), soa.type.c_str(), soa.templateType.c_str()); + else + printf("template <> struct SOA<%s> {\n", soa.type.c_str()); + + // Constructor + printf(" SOA() = default;\n"); + printf(" SOA(int n, Allocator alloc) : nAlloc(n) {\n"); + for (const auto &member : soa.members) { + for (int i = 0; i < member.names.size(); ++i) { + std::string name = member.names[i]; + if (!member.arraySizes[i].empty()) { + printf(" for (int i = 0; i < %s; ++i)\n", + member.arraySizes[i].c_str()); + if (isFlatType(member.type) || member.numPointers > 0) + printf( + " this->%s[i] = alloc.allocate_object<%s>(n);\n", + name.c_str(), member.GetType().c_str()); + else { + assert(member.isConst == false && member.numPointers == 0); + printf(" this->%s[i] = SOA<%s>(n, alloc);\n", name.c_str(), + member.type.c_str()); + } + } else { + if (isFlatType(member.type) || member.numPointers > 0) + printf(" this->%s = alloc.allocate_object<%s>(n);\n", + name.c_str(), member.GetType().c_str()); + else + printf(" this->%s = SOA<%s>(n, alloc);\n", name.c_str(), + member.type.c_str()); + } + } + } + printf(" }\n\n"); + + // operator[] madness... + printf(" struct GetSetIndirector {\n"); + if (!soa.templateType.empty()) { + printf(" PBRT_CPU_GPU\n"); + printf(" operator %s<%s>() const {\n", soa.type.c_str(), + soa.templateType.c_str()); + printf(" %s<%s> r;\n", soa.type.c_str(), soa.templateType.c_str()); + } else { + printf(" PBRT_CPU_GPU\n"); + printf(" operator %s() const {\n", soa.type.c_str()); + printf(" %s r;\n", soa.type.c_str()); + } + for (const auto &member : soa.members) + for (int i = 0; i < member.names.size(); ++i) { + std::string name = member.names[i]; + if (!member.arraySizes[i].empty()) { + printf(" for (int c = 0; c < %s; ++c)\n", + member.arraySizes[i].c_str()); + printf(" r.%s[c] = soa->%s[c][i];\n", name.c_str(), + name.c_str()); + } else + printf(" r.%s = soa->%s[i];\n", name.c_str(), + name.c_str()); + } + printf(" return r;\n"); + printf(" }\n"); + + printf(" PBRT_CPU_GPU\n"); + if (!soa.templateType.empty()) + printf(" void operator=(const %s<%s> &a) {\n", soa.type.c_str(), + soa.templateType.c_str()); + else + printf(" void operator=(const %s &a) {\n", soa.type.c_str()); + for (const auto &member : soa.members) + for (int i = 0; i < member.names.size(); ++i) { + std::string name = member.names[i]; + if (!member.arraySizes[i].empty()) { + printf(" for (int c = 0; c < %s; ++c)\n", + member.arraySizes[i].c_str()); + printf(" soa->%s[c][i] = a.%s[c];\n", name.c_str(), + name.c_str()); + } else + printf(" soa->%s[i] = a.%s;\n", name.c_str(), + name.c_str()); + } + printf(" }\n\n"); + printf(" SOA *soa;\n"); + printf(" int i;\n"); + printf(" };\n\n"); + + printf(" PBRT_CPU_GPU\n"); + printf(" GetSetIndirector operator[](int i) {\n"); + printf(" DCHECK_LT(i, nAlloc);\n"); + printf(" return GetSetIndirector{this, i};\n"); + printf(" }\n"); + printf(" PBRT_CPU_GPU\n"); + if (!soa.templateType.empty()) { + printf(" %s<%s> operator[](int i) const {\n", soa.type.c_str(), + soa.templateType.c_str()); + printf(" DCHECK_LT(i, nAlloc);\n"); + printf(" %s<%s> r;\n", soa.type.c_str(), soa.templateType.c_str()); + } else { + printf(" %s operator[](int i) const {\n", soa.type.c_str()); + printf(" DCHECK_LT(i, nAlloc);\n"); + printf(" %s r;\n", soa.type.c_str()); + } + for (const auto &member : soa.members) + for (int i = 0; i < member.names.size(); ++i) { + std::string name = member.names[i]; + if (!member.arraySizes[i].empty()) { + printf(" for (int c = 0; c < %s; ++c)\n", + member.arraySizes[i].c_str()); + printf(" r.%s[c] = this->%s[c][i];\n", name.c_str(), + name.c_str()); + } else + printf(" r.%s = this->%s[i];\n", name.c_str(), name.c_str()); + } + printf(" return r;\n"); + printf(" }\n"); + printf("\n"); + + // Member definitions + printf(" int nAlloc;\n"); + for (const auto &member : soa.members) { + for (int i = 0; i < member.names.size(); ++i) { + std::string name = member.names[i]; + if (!member.arraySizes[i].empty()) { + if (isFlatType(member.type) || member.numPointers > 0) + printf(" %s * /*__restrict__*/ %s[%s];\n", + member.GetType().c_str(), name.c_str(), + member.arraySizes[i].c_str()); + else + printf(" SOA<%s> %s[%s];\n", member.type.c_str(), name.c_str(), + member.arraySizes[i].c_str()); + } else { + if (isFlatType(member.type) || member.numPointers > 0) + printf(" %s * __restrict__ %s;\n", member.GetType().c_str(), + name.c_str()); + else + printf(" SOA<%s> %s;\n", member.type.c_str(), name.c_str()); + } + } + } + + printf("};\n\n"); + } +} diff --git a/src/pbrt/cpu/accelerators.cpp b/src/pbrt/cpu/accelerators.cpp new file mode 100644 index 00000000..ec40f63f --- /dev/null +++ b/src/pbrt/cpu/accelerators.cpp @@ -0,0 +1,1185 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +STAT_MEMORY_COUNTER("Memory/BVH tree", treeBytes); +STAT_RATIO("BVH/Primitives per leaf node", totalPrimitives, totalLeafNodes); +STAT_COUNTER("BVH/Interior nodes", interiorNodes); +STAT_COUNTER("BVH/Leaf nodes", leafNodes); +STAT_PIXEL_COUNTER("BVH/Nodes visited", bvhNodesVisited); + +// MortonPrimitive Definition +struct MortonPrimitive { + int primitiveIndex; + uint32_t mortonCode; +}; + +// LBVHTreelet Definition +struct LBVHTreelet { + int startIndex, nPrimitives; + BVHBuildNode *buildNodes; +}; + +// BVHAccel Utility Functions +static void RadixSort(std::vector *v) { + std::vector tempVector(v->size()); + constexpr int bitsPerPass = 6; + constexpr int nBits = 30; + static_assert((nBits % bitsPerPass) == 0, + "Radix sort bitsPerPass must evenly divide nBits"); + constexpr int nPasses = nBits / bitsPerPass; + for (int pass = 0; pass < nPasses; ++pass) { + // Perform one pass of radix sort, sorting _bitsPerPass_ bits + int lowBit = pass * bitsPerPass; + // Set in and out vector pointers for radix sort pass + std::vector &in = (pass & 1) ? tempVector : *v; + std::vector &out = (pass & 1) ? *v : tempVector; + + // Count number of zero bits in array for current radix sort bit + constexpr int nBuckets = 1 << bitsPerPass; + int bucketCount[nBuckets] = {0}; + constexpr int bitMask = (1 << bitsPerPass) - 1; + for (const MortonPrimitive &mp : in) { + int bucket = (mp.mortonCode >> lowBit) & bitMask; + CHECK_GE(bucket, 0); + CHECK_LT(bucket, nBuckets); + ++bucketCount[bucket]; + } + + // Compute starting index in output array for each bucket + int outIndex[nBuckets]; + outIndex[0] = 0; + for (int i = 1; i < nBuckets; ++i) + outIndex[i] = outIndex[i - 1] + bucketCount[i - 1]; + + // Store sorted values in output array + for (const MortonPrimitive &mp : in) { + int bucket = (mp.mortonCode >> lowBit) & bitMask; + out[outIndex[bucket]++] = mp; + } + } + // Copy final result from _tempVector_, if needed + if (nPasses & 1) + std::swap(*v, tempVector); +} + +// BucketInfo Definition +struct BucketInfo { + int count = 0; + Bounds3f bounds; +}; + +// BVHPrimitiveInfo Definition +struct BVHPrimitiveInfo { + BVHPrimitiveInfo() {} + BVHPrimitiveInfo(size_t primitiveNumber, const Bounds3f &bounds) + : primitiveNumber(primitiveNumber), + bounds(bounds), + centroid(.5f * bounds.pMin + .5f * bounds.pMax) {} + size_t primitiveNumber; + Bounds3f bounds; + Point3f centroid; +}; + +// BVHBuildNode Definition +struct BVHBuildNode { + // BVHBuildNode Public Methods + void InitLeaf(int first, int n, const Bounds3f &b) { + firstPrimOffset = first; + nPrimitives = n; + bounds = b; + children[0] = children[1] = nullptr; + ++leafNodes; + ++totalLeafNodes; + totalPrimitives += n; + } + + void InitInterior(int axis, BVHBuildNode *c0, BVHBuildNode *c1) { + children[0] = c0; + children[1] = c1; + bounds = Union(c0->bounds, c1->bounds); + splitAxis = axis; + nPrimitives = 0; + ++interiorNodes; + } + + Bounds3f bounds; + BVHBuildNode *children[2]; + int splitAxis, firstPrimOffset, nPrimitives; +}; + +// LinearBVHNode Definition +struct alignas(32) LinearBVHNode { + Bounds3f bounds; + union { + int primitivesOffset; // leaf + int secondChildOffset; // interior + }; + uint16_t nPrimitives; // 0 -> interior node + uint8_t axis; // interior node: xyz +}; + +// BVHAccel Method Definitions +BVHAccel::BVHAccel(std::vector p, int maxPrimsInNode, + SplitMethod splitMethod) + : maxPrimsInNode(std::min(255, maxPrimsInNode)), + splitMethod(splitMethod), + primitives(std::move(p)) { + CHECK(!primitives.empty()); + // Build BVH from _primitives_ + // Initialize _primitiveInfo_ array for primitives + std::vector primitiveInfo(primitives.size()); + for (size_t i = 0; i < primitives.size(); ++i) + primitiveInfo[i] = {i, primitives[i].Bounds()}; + + // Build BVH tree for primitives using _primitiveInfo_ + // These need to survive until we've built the compact BVH... + pstd::pmr::monotonic_buffer_resource resource; + Allocator alloc(&resource); + std::vector threadResources(MaxThreadIndex()); + std::vector threadAllocators; + for (size_t i = 0; i < MaxThreadIndex(); ++i) + threadAllocators.push_back(Allocator(&threadResources[i])); + + std::atomic totalNodes{0}; + std::vector orderedPrims(primitives.size()); + BVHBuildNode *root; + if (splitMethod == SplitMethod::HLBVH) { + root = HLBVHBuild(alloc, primitiveInfo, &totalNodes, orderedPrims); + } else { + std::atomic orderedPrimsOffset{0}; + root = recursiveBuild(threadAllocators, primitiveInfo, 0, primitives.size(), + &totalNodes, orderedPrims, &orderedPrimsOffset); + CHECK_EQ(orderedPrimsOffset.load(), orderedPrims.size()); + } + + primitives.swap(orderedPrims); + primitiveInfo.resize(0); + LOG_VERBOSE("BVH created with %d nodes for %d primitives (%.2f MB)", + totalNodes.load(), (int)primitives.size(), + float(totalNodes.load() * sizeof(LinearBVHNode)) / (1024.f * 1024.f)); + + // Compute representation of depth-first traversal of BVH tree + treeBytes += totalNodes * sizeof(LinearBVHNode) + sizeof(*this) + + primitives.size() * sizeof(primitives[0]); + nodes = new LinearBVHNode[totalNodes]; + int offset = 0; + flattenBVHTree(root, &offset); + CHECK_EQ(totalNodes.load(), offset); +} + +Bounds3f BVHAccel::Bounds() const { + CHECK(nodes != nullptr); + return nodes[0].bounds; +} + +BVHBuildNode *BVHAccel::recursiveBuild(std::vector &threadAllocators, + std::vector &primitiveInfo, + int start, int end, std::atomic *totalNodes, + std::vector &orderedPrims, + std::atomic *orderedPrimsOffset) { + DCHECK_NE(start, end); + Allocator alloc = threadAllocators[ThreadIndex]; + BVHBuildNode *node = alloc.new_object(); + (*totalNodes)++; + // Compute bounds of all primitives in BVH node + Bounds3f bounds; + for (int i = start; i < end; ++i) + bounds = Union(bounds, primitiveInfo[i].bounds); + + int nPrimitives = end - start; + if (bounds.SurfaceArea() == 0 || nPrimitives == 1) { + // Create leaf _BVHBuildNode_ + int firstPrimOffset = orderedPrimsOffset->fetch_add(nPrimitives); + for (int i = start; i < end; ++i) { + int primNum = primitiveInfo[i].primitiveNumber; + orderedPrims[firstPrimOffset + i - start] = primitives[primNum]; + } + node->InitLeaf(firstPrimOffset, nPrimitives, bounds); + return node; + + } else { + // Compute bound of primitive centroids, choose split dimension _dim_ + Bounds3f centroidBounds; + for (int i = start; i < end; ++i) + centroidBounds = Union(centroidBounds, primitiveInfo[i].centroid); + int dim = centroidBounds.MaxDimension(); + + // Partition primitives into two sets and build children + int mid = (start + end) / 2; + if (centroidBounds.pMax[dim] == centroidBounds.pMin[dim]) { + // Create leaf _BVHBuildNode_ + int firstPrimOffset = orderedPrimsOffset->fetch_add(nPrimitives); + for (int i = start; i < end; ++i) { + int primNum = primitiveInfo[i].primitiveNumber; + orderedPrims[firstPrimOffset + i - start] = primitives[primNum]; + } + node->InitLeaf(firstPrimOffset, nPrimitives, bounds); + return node; + + } else { + // Partition primitives based on _splitMethod_ + switch (splitMethod) { + case SplitMethod::Middle: { + // Partition primitives through node's midpoint + Float pmid = (centroidBounds.pMin[dim] + centroidBounds.pMax[dim]) / 2; + BVHPrimitiveInfo *midPtr = + std::partition(&primitiveInfo[start], &primitiveInfo[end - 1] + 1, + [dim, pmid](const BVHPrimitiveInfo &pi) { + return pi.centroid[dim] < pmid; + }); + mid = midPtr - &primitiveInfo[0]; + // For lots of prims with large overlapping bounding boxes, this + // may fail to partition; in that case don't break and fall through + // to EqualCounts. + if (mid != start && mid != end) + break; + } + case SplitMethod::EqualCounts: { + // Partition primitives into equally sized subsets + mid = (start + end) / 2; + std::nth_element( + &primitiveInfo[start], &primitiveInfo[mid], + &primitiveInfo[end - 1] + 1, + [dim](const BVHPrimitiveInfo &a, const BVHPrimitiveInfo &b) { + return a.centroid[dim] < b.centroid[dim]; + }); + + break; + } + case SplitMethod::SAH: + default: { + // Partition primitives using approximate SAH + if (nPrimitives <= 2) { + // Partition primitives into equally sized subsets + mid = (start + end) / 2; + std::nth_element( + &primitiveInfo[start], &primitiveInfo[mid], + &primitiveInfo[end - 1] + 1, + [dim](const BVHPrimitiveInfo &a, const BVHPrimitiveInfo &b) { + return a.centroid[dim] < b.centroid[dim]; + }); + + } else { + // Allocate _BucketInfo_ for SAH partition buckets + constexpr int nBuckets = 12; + BucketInfo buckets[nBuckets]; + + // Initialize _BucketInfo_ for SAH partition buckets + for (int i = start; i < end; ++i) { + int b = nBuckets * + centroidBounds.Offset(primitiveInfo[i].centroid)[dim]; + if (b == nBuckets) + b = nBuckets - 1; + DCHECK_GE(b, 0); + DCHECK_LT(b, nBuckets); + buckets[b].count++; + buckets[b].bounds = + Union(buckets[b].bounds, primitiveInfo[i].bounds); + } + + // Compute costs for splitting after each bucket + int minCostSplitBucket = -1; + Float minCost = Infinity; + constexpr int nSplits = nBuckets - 1; + int countBelow[nSplits], countAbove[nSplits]; + Bounds3f boundsBelow[nSplits], boundsAbove[nSplits]; + + countBelow[0] = buckets[0].count; + boundsBelow[0] = buckets[0].bounds; + for (int i = 1; i < nSplits; ++i) { + countBelow[i] = countBelow[i - 1] + buckets[i].count; + boundsBelow[i] = Union(boundsBelow[i - 1], buckets[i].bounds); + } + + countAbove[nSplits - 1] = buckets[nBuckets - 1].count; + boundsAbove[nSplits - 1] = buckets[nBuckets - 1].bounds; + for (int i = nSplits - 2; i >= 0; --i) { + countAbove[i] = countAbove[i + 1] + buckets[i + 1].count; + boundsAbove[i] = Union(boundsAbove[i + 1], buckets[i + 1].bounds); + } + + // Find bucket to split at that minimizes SAH metric + for (int i = 0; i < nSplits; ++i) { + if (countBelow[i] == 0 || countAbove[i] == 0) + continue; + + Float cost = (countBelow[i] * boundsBelow[i].SurfaceArea() + + countAbove[i] * boundsAbove[i].SurfaceArea()); + if (cost < minCost) { + minCost = cost; + minCostSplitBucket = i; + } + } + minCost = 1 + minCost / bounds.SurfaceArea(); + + // Either create leaf or split primitives at selected SAH bucket + Float leafCost = nPrimitives; + if (nPrimitives > maxPrimsInNode || minCost < leafCost) { + BVHPrimitiveInfo *pmid = std::partition( + &primitiveInfo[start], &primitiveInfo[end - 1] + 1, + [=](const BVHPrimitiveInfo &pi) { + int b = + nBuckets * centroidBounds.Offset(pi.centroid)[dim]; + if (b == nBuckets) + b = nBuckets - 1; + return b <= minCostSplitBucket; + }); + mid = pmid - &primitiveInfo[0]; + } else { + // Create leaf _BVHBuildNode_ + int firstPrimOffset = orderedPrimsOffset->fetch_add(nPrimitives); + for (int i = start; i < end; ++i) { + int primNum = primitiveInfo[i].primitiveNumber; + orderedPrims[firstPrimOffset + i - start] = + primitives[primNum]; + } + node->InitLeaf(firstPrimOffset, nPrimitives, bounds); + return node; + } + } + + break; + } + } + + BVHBuildNode *children[2]; + if (end - start > 1024 * 1024) { + ParallelFor(0, 2, [&](int i) { + if (i == 0) + children[0] = + recursiveBuild(threadAllocators, primitiveInfo, start, mid, + totalNodes, orderedPrims, orderedPrimsOffset); + else + children[1] = + recursiveBuild(threadAllocators, primitiveInfo, mid, end, + totalNodes, orderedPrims, orderedPrimsOffset); + }); + } else { + children[0] = + recursiveBuild(threadAllocators, primitiveInfo, start, mid, + totalNodes, orderedPrims, orderedPrimsOffset); + children[1] = + recursiveBuild(threadAllocators, primitiveInfo, mid, end, totalNodes, + orderedPrims, orderedPrimsOffset); + } + node->InitInterior(dim, children[0], children[1]); + } + } + return node; +} + +BVHBuildNode *BVHAccel::HLBVHBuild(Allocator alloc, + const std::vector &primitiveInfo, + std::atomic *totalNodes, + std::vector &orderedPrims) { + // Compute bounding box of all primitive centroids + Bounds3f bounds; + for (const BVHPrimitiveInfo &pi : primitiveInfo) + bounds = Union(bounds, pi.centroid); + + // Compute Morton indices of primitives + std::vector mortonPrims(primitiveInfo.size()); + ParallelFor(0, primitiveInfo.size(), [&](int64_t start, int64_t end) { + for (int64_t i = start; i < end; ++i) { + // Initialize _mortonPrims[i]_ for _i_th primitive + constexpr int mortonBits = 10; + constexpr int mortonScale = 1 << mortonBits; + mortonPrims[i].primitiveIndex = primitiveInfo[i].primitiveNumber; + Vector3f centroidOffset = bounds.Offset(primitiveInfo[i].centroid); + Vector3f offset = centroidOffset * mortonScale; + mortonPrims[i].mortonCode = EncodeMorton3(offset.x, offset.y, offset.z); + } + }); + + // Radix sort primitive Morton indices + RadixSort(&mortonPrims); + + // Create LBVH treelets at bottom of BVH + // Find intervals of primitives for each treelet + std::vector treeletsToBuild; + for (int start = 0, end = 1; end <= (int)mortonPrims.size(); ++end) { + uint32_t mask = 0b00111111111111000000000000000000; + if (end == (int)mortonPrims.size() || ((mortonPrims[start].mortonCode & mask) != + (mortonPrims[end].mortonCode & mask))) { + // Add entry to _treeletsToBuild_ for this treelet + int nPrimitives = end - start; + int maxBVHNodes = 2 * nPrimitives - 1; + BVHBuildNode *nodes = alloc.allocate_object(maxBVHNodes); + treeletsToBuild.push_back({start, nPrimitives, nodes}); + + start = end; + } + } + + // Create LBVHs for treelets in parallel + std::atomic orderedPrimsOffset(0); + ParallelFor(0, treeletsToBuild.size(), [&](int i) { + // Generate _i_th LBVH treelet + int nodesCreated = 0; + const int firstBitIndex = 29 - 12; + LBVHTreelet &tr = treeletsToBuild[i]; + tr.buildNodes = emitLBVH( + tr.buildNodes, primitiveInfo, &mortonPrims[tr.startIndex], tr.nPrimitives, + &nodesCreated, orderedPrims, &orderedPrimsOffset, firstBitIndex); + *totalNodes += nodesCreated; + }); + + // Create and return SAH BVH from LBVH treelets + std::vector finishedTreelets; + finishedTreelets.reserve(treeletsToBuild.size()); + for (LBVHTreelet &treelet : treeletsToBuild) + finishedTreelets.push_back(treelet.buildNodes); + return buildUpperSAH(alloc, finishedTreelets, 0, finishedTreelets.size(), totalNodes); +} + +BVHBuildNode *BVHAccel::emitLBVH(BVHBuildNode *&buildNodes, + const std::vector &primitiveInfo, + MortonPrimitive *mortonPrims, int nPrimitives, + int *totalNodes, + std::vector &orderedPrims, + std::atomic *orderedPrimsOffset, int bitIndex) { + CHECK_GT(nPrimitives, 0); + if (bitIndex == -1 || nPrimitives < maxPrimsInNode) { + // Create and return leaf node of LBVH treelet + (*totalNodes)++; + BVHBuildNode *node = buildNodes++; + Bounds3f bounds; + int firstPrimOffset = orderedPrimsOffset->fetch_add(nPrimitives); + for (int i = 0; i < nPrimitives; ++i) { + int primitiveIndex = mortonPrims[i].primitiveIndex; + orderedPrims[firstPrimOffset + i] = primitives[primitiveIndex]; + bounds = Union(bounds, primitiveInfo[primitiveIndex].bounds); + } + node->InitLeaf(firstPrimOffset, nPrimitives, bounds); + return node; + + } else { + int mask = 1 << bitIndex; + // Advance to next subtree level if there's no LBVH split for this bit + if ((mortonPrims[0].mortonCode & mask) == + (mortonPrims[nPrimitives - 1].mortonCode & mask)) + return emitLBVH(buildNodes, primitiveInfo, mortonPrims, nPrimitives, + totalNodes, orderedPrims, orderedPrimsOffset, bitIndex - 1); + + // Find LBVH split point for this dimension + int splitOffset = FindInterval(nPrimitives, [&](int index) { + return ((mortonPrims[0].mortonCode & mask) == + (mortonPrims[index].mortonCode & mask)); + }); + ++splitOffset; + CHECK_LE(splitOffset, nPrimitives - 1); + CHECK_NE(mortonPrims[splitOffset - 1].mortonCode & mask, + mortonPrims[splitOffset].mortonCode & mask); + + // Create and return interior LBVH node + (*totalNodes)++; + BVHBuildNode *node = buildNodes++; + BVHBuildNode *lbvh[2] = { + emitLBVH(buildNodes, primitiveInfo, mortonPrims, splitOffset, totalNodes, + orderedPrims, orderedPrimsOffset, bitIndex - 1), + emitLBVH(buildNodes, primitiveInfo, &mortonPrims[splitOffset], + nPrimitives - splitOffset, totalNodes, orderedPrims, + orderedPrimsOffset, bitIndex - 1)}; + int axis = bitIndex % 3; + node->InitInterior(axis, lbvh[0], lbvh[1]); + return node; + } +} + +int BVHAccel::flattenBVHTree(BVHBuildNode *node, int *offset) { + LinearBVHNode *linearNode = &nodes[*offset]; + linearNode->bounds = node->bounds; + int myOffset = (*offset)++; + if (node->nPrimitives > 0) { + CHECK(!node->children[0] && !node->children[1]); + CHECK_LT(node->nPrimitives, 65536); + linearNode->primitivesOffset = node->firstPrimOffset; + linearNode->nPrimitives = node->nPrimitives; + } else { + // Create interior flattened BVH node + linearNode->axis = node->splitAxis; + linearNode->nPrimitives = 0; + flattenBVHTree(node->children[0], offset); + linearNode->secondChildOffset = flattenBVHTree(node->children[1], offset); + } + return myOffset; +} + +pstd::optional BVHAccel::Intersect(const Ray &ray, Float tMax) const { + if (nodes == nullptr) + return {}; + pstd::optional si; + Vector3f invDir(1 / ray.d.x, 1 / ray.d.y, 1 / ray.d.z); + int dirIsNeg[3] = {static_cast(invDir.x < 0), static_cast(invDir.y < 0), + static_cast(invDir.z < 0)}; + // Follow ray through BVH nodes to find primitive intersections + int toVisitOffset = 0, currentNodeIndex = 0; + int nodesToVisit[64]; + int nodesVisited = 0; + while (true) { + ++nodesVisited; + const LinearBVHNode *node = &nodes[currentNodeIndex]; + // Check ray against BVH node + if (node->bounds.IntersectP(ray.o, ray.d, tMax, invDir, dirIsNeg)) { + if (node->nPrimitives > 0) { + // Intersect ray with primitives in leaf BVH node + for (int i = 0; i < node->nPrimitives; ++i) { + pstd::optional primSi = + primitives[node->primitivesOffset + i].Intersect(ray, tMax); + if (primSi) { + si = primSi; + tMax = si->tHit; + } + } + if (toVisitOffset == 0) + break; + currentNodeIndex = nodesToVisit[--toVisitOffset]; + + } else { + // Put far BVH node on _nodesToVisit_ stack, advance to near node + if (dirIsNeg[node->axis]) { + nodesToVisit[toVisitOffset++] = currentNodeIndex + 1; + currentNodeIndex = node->secondChildOffset; + } else { + nodesToVisit[toVisitOffset++] = node->secondChildOffset; + currentNodeIndex = currentNodeIndex + 1; + } + } + } else { + if (toVisitOffset == 0) + break; + currentNodeIndex = nodesToVisit[--toVisitOffset]; + } + } + + bvhNodesVisited += nodesVisited; + return si; +} + +bool BVHAccel::IntersectP(const Ray &ray, Float tMax) const { + if (nodes == nullptr) + return false; + Vector3f invDir(1.f / ray.d.x, 1.f / ray.d.y, 1.f / ray.d.z); + int dirIsNeg[3] = {static_cast(invDir.x < 0), static_cast(invDir.y < 0), + static_cast(invDir.z < 0)}; + int nodesToVisit[64]; + int toVisitOffset = 0, currentNodeIndex = 0; + int nodesVisited = 0; + + while (true) { + ++nodesVisited; + const LinearBVHNode *node = &nodes[currentNodeIndex]; + if (node->bounds.IntersectP(ray.o, ray.d, tMax, invDir, dirIsNeg)) { + // Process BVH node _node_ for traversal + if (node->nPrimitives > 0) { + for (int i = 0; i < node->nPrimitives; ++i) { + if (primitives[node->primitivesOffset + i].IntersectP(ray, tMax)) { + bvhNodesVisited += nodesVisited; + return true; + } + } + if (toVisitOffset == 0) + break; + currentNodeIndex = nodesToVisit[--toVisitOffset]; + } else { + if (dirIsNeg[node->axis] != 0) { + /// second child first + nodesToVisit[toVisitOffset++] = currentNodeIndex + 1; + currentNodeIndex = node->secondChildOffset; + } else { + nodesToVisit[toVisitOffset++] = node->secondChildOffset; + currentNodeIndex = currentNodeIndex + 1; + } + } + } else { + if (toVisitOffset == 0) + break; + currentNodeIndex = nodesToVisit[--toVisitOffset]; + } + } + bvhNodesVisited += nodesVisited; + return false; +} + +BVHBuildNode *BVHAccel::buildUpperSAH(Allocator alloc, + std::vector &treeletRoots, + int start, int end, + std::atomic *totalNodes) const { + CHECK_LT(start, end); + int nNodes = end - start; + if (nNodes == 1) + return treeletRoots[start]; + (*totalNodes)++; + BVHBuildNode *node = alloc.new_object(); + + // Compute bounds of all nodes under this HLBVH node + Bounds3f bounds; + for (int i = start; i < end; ++i) + bounds = Union(bounds, treeletRoots[i]->bounds); + + // Compute bound of HLBVH node centroids, choose split dimension _dim_ + Bounds3f centroidBounds; + for (int i = start; i < end; ++i) { + Point3f centroid = + (treeletRoots[i]->bounds.pMin + treeletRoots[i]->bounds.pMax) * 0.5f; + centroidBounds = Union(centroidBounds, centroid); + } + int dim = centroidBounds.MaxDimension(); + // FIXME: if this hits, what do we need to do? + // Make sure the SAH split below does something... ? + CHECK_NE(centroidBounds.pMax[dim], centroidBounds.pMin[dim]); + + // Allocate _BucketInfo_ for SAH partition buckets + constexpr int nBuckets = 12; + struct BucketInfo { + int count = 0; + Bounds3f bounds; + }; + BucketInfo buckets[nBuckets]; + + // Initialize _BucketInfo_ for HLBVH SAH partition buckets + for (int i = start; i < end; ++i) { + Float centroid = + (treeletRoots[i]->bounds.pMin[dim] + treeletRoots[i]->bounds.pMax[dim]) * + 0.5f; + int b = nBuckets * ((centroid - centroidBounds.pMin[dim]) / + (centroidBounds.pMax[dim] - centroidBounds.pMin[dim])); + if (b == nBuckets) + b = nBuckets - 1; + CHECK_GE(b, 0); + CHECK_LT(b, nBuckets); + buckets[b].count++; + buckets[b].bounds = Union(buckets[b].bounds, treeletRoots[i]->bounds); + } + + // Compute costs for splitting after each bucket + Float cost[nBuckets - 1]; + for (int i = 0; i < nBuckets - 1; ++i) { + Bounds3f b0, b1; + int count0 = 0, count1 = 0; + for (int j = 0; j <= i; ++j) { + b0 = Union(b0, buckets[j].bounds); + count0 += buckets[j].count; + } + for (int j = i + 1; j < nBuckets; ++j) { + b1 = Union(b1, buckets[j].bounds); + count1 += buckets[j].count; + } + cost[i] = .125f + (count0 * b0.SurfaceArea() + count1 * b1.SurfaceArea()) / + bounds.SurfaceArea(); + } + + // Find bucket to split at that minimizes SAH metric + Float minCost = cost[0]; + int minCostSplitBucket = 0; + for (int i = 1; i < nBuckets - 1; ++i) { + if (cost[i] < minCost) { + minCost = cost[i]; + minCostSplitBucket = i; + } + } + + // Split nodes and create interior HLBVH SAH node + BVHBuildNode **pmid = std::partition( + &treeletRoots[start], &treeletRoots[end - 1] + 1, [=](const BVHBuildNode *node) { + Float centroid = (node->bounds.pMin[dim] + node->bounds.pMax[dim]) * 0.5f; + int b = nBuckets * ((centroid - centroidBounds.pMin[dim]) / + (centroidBounds.pMax[dim] - centroidBounds.pMin[dim])); + if (b == nBuckets) + b = nBuckets - 1; + CHECK_GE(b, 0); + CHECK_LT(b, nBuckets); + return b <= minCostSplitBucket; + }); + int mid = pmid - &treeletRoots[0]; + CHECK_GT(mid, start); + CHECK_LT(mid, end); + node->InitInterior(dim, + this->buildUpperSAH(alloc, treeletRoots, start, mid, totalNodes), + this->buildUpperSAH(alloc, treeletRoots, mid, end, totalNodes)); + return node; +} + +BVHAccel *BVHAccel::Create(std::vector prims, + const ParameterDictionary ¶meters) { + std::string splitMethodName = parameters.GetOneString("splitmethod", "sah"); + BVHAccel::SplitMethod splitMethod; + if (splitMethodName == "sah") + splitMethod = BVHAccel::SplitMethod::SAH; + else if (splitMethodName == "hlbvh") + splitMethod = BVHAccel::SplitMethod::HLBVH; + else if (splitMethodName == "middle") + splitMethod = BVHAccel::SplitMethod::Middle; + else if (splitMethodName == "equal") + splitMethod = BVHAccel::SplitMethod::EqualCounts; + else { + Warning(R"(BVH split method "%s" unknown. Using "sah".)", splitMethodName); + splitMethod = BVHAccel::SplitMethod::SAH; + } + + int maxPrimsInNode = parameters.GetOneInt("maxnodeprims", 4); + return new BVHAccel(std::move(prims), maxPrimsInNode, splitMethod); +} + +// KdToDo Definition +struct KdToDo { + const KdAccelNode *node; + Float tMin, tMax; +}; + +// KdAccelNode Definition +struct alignas(8) KdAccelNode { + // KdAccelNode Methods + void InitLeaf(int *primNums, int np, std::vector *primitiveIndices); + + void InitInterior(int axis, int ac, Float s) { + split = s; + flags = axis; + aboveChild |= (ac << 2); + } + + Float SplitPos() const { return split; } + int nPrimitives() const { return nPrims >> 2; } + int SplitAxis() const { return flags & 3; } + bool IsLeaf() const { return (flags & 3) == 3; } + int AboveChild() const { return aboveChild >> 2; } + + union { + Float split; // Interior + int onePrimitive; // Leaf + int primitiveIndicesOffset; // Leaf + }; + + private: + union { + int flags; // Both + int nPrims; // Leaf + int aboveChild; // Interior + }; +}; + +// EdgeType Definition +enum class EdgeType { Start, End }; + +// BoundEdge Definition +struct BoundEdge { + // BoundEdge Public Methods + BoundEdge() {} + + BoundEdge(Float t, int primNum, bool starting) : t(t), primNum(primNum) { + type = starting ? EdgeType::Start : EdgeType::End; + } + + Float t; + int primNum; + EdgeType type; +}; + +STAT_PIXEL_COUNTER("Kd-Tree/Nodes visited", kdNodesVisited); + +// KdTreeAccel Method Definitions +KdTreeAccel::KdTreeAccel(std::vector p, int isectCost, int traversalCost, + Float emptyBonus, int maxPrims, int maxDepth) + : isectCost(isectCost), + traversalCost(traversalCost), + maxPrims(maxPrims), + emptyBonus(emptyBonus), + primitives(std::move(p)) { + // Build kd-tree for accelerator + nextFreeNode = nAllocedNodes = 0; + if (maxDepth <= 0) + maxDepth = std::round(8 + 1.3f * Log2Int(int64_t(primitives.size()))); + // Compute bounds for kd-tree construction + std::vector primBounds; + primBounds.reserve(primitives.size()); + for (PrimitiveHandle &prim : primitives) { + Bounds3f b = prim.Bounds(); + bounds = Union(bounds, b); + primBounds.push_back(b); + } + + // Allocate working memory for kd-tree construction + std::unique_ptr edges[3]; + for (int i = 0; i < 3; ++i) + edges[i] = std::make_unique(2 * primitives.size()); + + std::unique_ptr prims0 = std::make_unique(primitives.size()); + std::unique_ptr prims1 = + std::make_unique((maxDepth + 1) * primitives.size()); + + // Initialize _primNums_ for kd-tree construction + std::unique_ptr primNums = std::make_unique(primitives.size()); + for (size_t i = 0; i < primitives.size(); ++i) + primNums[i] = i; + + // Start recursive construction of kd-tree + buildTree(0, bounds, primBounds, primNums.get(), primitives.size(), maxDepth, edges, + prims0.get(), prims1.get()); +} + +void KdAccelNode::InitLeaf(int *primNums, int np, std::vector *primitiveIndices) { + flags = 3; + nPrims |= (np << 2); + // Store primitive ids for leaf node + if (np == 0) + onePrimitive = 0; + else if (np == 1) + onePrimitive = primNums[0]; + else { + primitiveIndicesOffset = primitiveIndices->size(); + for (int i = 0; i < np; ++i) + primitiveIndices->push_back(primNums[i]); + } +} + +void KdTreeAccel::buildTree(int nodeNum, const Bounds3f &nodeBounds, + const std::vector &allPrimBounds, int *primNums, + int nPrimitives, int depth, + const std::unique_ptr edges[3], int *prims0, + int *prims1, int badRefines) { + CHECK_EQ(nodeNum, nextFreeNode); + // Get next free node from _nodes_ array + if (nextFreeNode == nAllocedNodes) { + int nNewAllocNodes = std::max(2 * nAllocedNodes, 512); + KdAccelNode *n = new KdAccelNode[nNewAllocNodes]; + if (nAllocedNodes > 0) { + memcpy(n, nodes, nAllocedNodes * sizeof(KdAccelNode)); + delete[] nodes; + } + nodes = n; + nAllocedNodes = nNewAllocNodes; + } + ++nextFreeNode; + + // Initialize leaf node if termination criteria met + if (nPrimitives <= maxPrims || depth == 0) { + nodes[nodeNum].InitLeaf(primNums, nPrimitives, &primitiveIndices); + return; + } + + // Initialize interior node and continue recursion + // Choose split axis position for interior node + int bestAxis = -1, bestOffset = -1; + Float bestCost = Infinity; + Float oldCost = isectCost * Float(nPrimitives); + Float totalSA = nodeBounds.SurfaceArea(); + Float invTotalSA = 1 / totalSA; + Vector3f d = nodeBounds.pMax - nodeBounds.pMin; + // Choose which axis to split along + int axis = nodeBounds.MaxDimension(); + + int retries = 0; +retrySplit: + // Initialize edges for _axis_ + for (int i = 0; i < nPrimitives; ++i) { + int pn = primNums[i]; + const Bounds3f &bounds = allPrimBounds[pn]; + edges[axis][2 * i] = BoundEdge(bounds.pMin[axis], pn, true); + edges[axis][2 * i + 1] = BoundEdge(bounds.pMax[axis], pn, false); + } + // Sort _edges_ for _axis_ + std::sort(&edges[axis][0], &edges[axis][2 * nPrimitives], + [](const BoundEdge &e0, const BoundEdge &e1) -> bool { + if (e0.t == e1.t) + return (int)e0.type < (int)e1.type; + else + return e0.t < e1.t; + }); + + // Compute cost of all splits for _axis_ to find best + int nBelow = 0, nAbove = nPrimitives; + for (int i = 0; i < 2 * nPrimitives; ++i) { + if (edges[axis][i].type == EdgeType::End) + --nAbove; + Float edgeT = edges[axis][i].t; + if (edgeT > nodeBounds.pMin[axis] && edgeT < nodeBounds.pMax[axis]) { + // Compute cost for split at _i_th edge + // Compute child surface areas for split at _edgeT_ + int otherAxis0 = (axis + 1) % 3, otherAxis1 = (axis + 2) % 3; + Float belowSA = + 2 * (d[otherAxis0] * d[otherAxis1] + + (edgeT - nodeBounds.pMin[axis]) * (d[otherAxis0] + d[otherAxis1])); + Float aboveSA = + 2 * (d[otherAxis0] * d[otherAxis1] + + (nodeBounds.pMax[axis] - edgeT) * (d[otherAxis0] + d[otherAxis1])); + + Float pBelow = belowSA * invTotalSA; + Float pAbove = aboveSA * invTotalSA; + Float eb = (nAbove == 0 || nBelow == 0) ? emptyBonus : 0; + Float cost = traversalCost + + isectCost * (1 - eb) * (pBelow * nBelow + pAbove * nAbove); + // Update best split if this is lowest cost so far + if (cost < bestCost) { + bestCost = cost; + bestAxis = axis; + bestOffset = i; + } + } + if (edges[axis][i].type == EdgeType::Start) + ++nBelow; + } + CHECK(nBelow == nPrimitives && nAbove == 0); + + // Create leaf if no good splits were found + if (bestAxis == -1 && retries < 2) { + ++retries; + axis = (axis + 1) % 3; + goto retrySplit; + } + if (bestCost > oldCost) + ++badRefines; + if ((bestCost > 4 * oldCost && nPrimitives < 16) || bestAxis == -1 || + badRefines == 3) { + nodes[nodeNum].InitLeaf(primNums, nPrimitives, &primitiveIndices); + return; + } + + // Classify primitives with respect to split + int n0 = 0, n1 = 0; + for (int i = 0; i < bestOffset; ++i) + if (edges[bestAxis][i].type == EdgeType::Start) + prims0[n0++] = edges[bestAxis][i].primNum; + for (int i = bestOffset + 1; i < 2 * nPrimitives; ++i) + if (edges[bestAxis][i].type == EdgeType::End) + prims1[n1++] = edges[bestAxis][i].primNum; + + // Recursively initialize children nodes + Float tSplit = edges[bestAxis][bestOffset].t; + Bounds3f bounds0 = nodeBounds, bounds1 = nodeBounds; + bounds0.pMax[bestAxis] = bounds1.pMin[bestAxis] = tSplit; + buildTree(nodeNum + 1, bounds0, allPrimBounds, prims0, n0, depth - 1, edges, prims0, + prims1 + nPrimitives, badRefines); + int aboveChild = nextFreeNode; + nodes[nodeNum].InitInterior(bestAxis, aboveChild, tSplit); + buildTree(aboveChild, bounds1, allPrimBounds, prims1, n1, depth - 1, edges, prims0, + prims1 + nPrimitives, badRefines); +} + +pstd::optional KdTreeAccel::Intersect(const Ray &ray, + Float raytMax) const { + // Compute initial parametric range of ray inside kd-tree extent + Float tMin, tMax; + if (!bounds.IntersectP(ray.o, ray.d, raytMax, &tMin, &tMax)) + return {}; + + // Prepare to traverse kd-tree for ray + Vector3f invDir(1 / ray.d.x, 1 / ray.d.y, 1 / ray.d.z); + constexpr int maxTodo = 64; + KdToDo todo[maxTodo]; + int todoPos = 0; + int nodesVisited = 0; + + // Traverse kd-tree nodes in order for ray + pstd::optional si; + const KdAccelNode *node = &nodes[0]; + while (node != nullptr) { + // Bail out if we found a hit closer than the current node + if (raytMax < tMin) + break; + + ++nodesVisited; + if (!node->IsLeaf()) { + // Process kd-tree interior node + // Compute parametric distance along ray to split plane + int axis = node->SplitAxis(); + Float tSplit = (node->SplitPos() - ray.o[axis]) * invDir[axis]; + + // Get node children pointers for ray + const KdAccelNode *firstChild, *secondChild; + int belowFirst = (ray.o[axis] < node->SplitPos()) || + (ray.o[axis] == node->SplitPos() && ray.d[axis] <= 0); + if (belowFirst) { + firstChild = node + 1; + secondChild = &nodes[node->AboveChild()]; + } else { + firstChild = &nodes[node->AboveChild()]; + secondChild = node + 1; + } + + // Advance to next child node, possibly enqueue other child + if (tSplit > tMax || tSplit <= 0) + node = firstChild; + else if (tSplit < tMin) + node = secondChild; + else { + // Enqueue _secondChild_ in todo list + todo[todoPos].node = secondChild; + todo[todoPos].tMin = tSplit; + todo[todoPos].tMax = tMax; + ++todoPos; + + node = firstChild; + tMax = tSplit; + } + + } else { + // Check for intersections inside leaf node + int nPrimitives = node->nPrimitives(); + if (nPrimitives == 1) { + const PrimitiveHandle &p = primitives[node->onePrimitive]; + // Check one primitive inside leaf node + pstd::optional primSi = p.Intersect(ray, raytMax); + if (primSi) { + si = primSi; + raytMax = si->tHit; + } + + } else { + for (int i = 0; i < nPrimitives; ++i) { + int index = primitiveIndices[node->primitiveIndicesOffset + i]; + const PrimitiveHandle &p = primitives[index]; + // Check one primitive inside leaf node + pstd::optional primSi = p.Intersect(ray, raytMax); + if (primSi) { + si = primSi; + raytMax = si->tHit; + } + } + } + + // Grab next node to process from todo list + if (todoPos > 0) { + --todoPos; + node = todo[todoPos].node; + tMin = todo[todoPos].tMin; + tMax = todo[todoPos].tMax; + } else + break; + } + } + kdNodesVisited += nodesVisited; + return si; +} + +bool KdTreeAccel::IntersectP(const Ray &ray, Float raytMax) const { + // Compute initial parametric range of ray inside kd-tree extent + Float tMin, tMax; + if (!bounds.IntersectP(ray.o, ray.d, raytMax, &tMin, &tMax)) + return false; + + // Prepare to traverse kd-tree for ray + Vector3f invDir(1 / ray.d.x, 1 / ray.d.y, 1 / ray.d.z); + constexpr int maxTodo = 64; + KdToDo todo[maxTodo]; + int todoPos = 0; + int nodesVisited = 0; + const KdAccelNode *node = &nodes[0]; + while (node != nullptr) { + ++nodesVisited; + if (node->IsLeaf()) { + // Check for shadow ray intersections inside leaf node + int nPrimitives = node->nPrimitives(); + if (nPrimitives == 1) { + const PrimitiveHandle &p = primitives[node->onePrimitive]; + if (p.IntersectP(ray, raytMax)) { + kdNodesVisited += nodesVisited; + return true; + } + } else { + for (int i = 0; i < nPrimitives; ++i) { + int primitiveIndex = + primitiveIndices[node->primitiveIndicesOffset + i]; + const PrimitiveHandle &prim = primitives[primitiveIndex]; + if (prim.IntersectP(ray, raytMax)) { + kdNodesVisited += nodesVisited; + return true; + } + } + } + + // Grab next node to process from todo list + if (todoPos > 0) { + --todoPos; + node = todo[todoPos].node; + tMin = todo[todoPos].tMin; + tMax = todo[todoPos].tMax; + } else + break; + } else { + // Process kd-tree interior node + + // Compute parametric distance along ray to split plane + int axis = node->SplitAxis(); + Float tSplit = (node->SplitPos() - ray.o[axis]) * invDir[axis]; + + // Get node children pointers for ray + const KdAccelNode *firstChild, *secondChild; + int belowFirst = + static_cast((ray.o[axis] < node->SplitPos()) || + (ray.o[axis] == node->SplitPos() && ray.d[axis] <= 0)); + if (belowFirst != 0) { + firstChild = node + 1; + secondChild = &nodes[node->AboveChild()]; + } else { + firstChild = &nodes[node->AboveChild()]; + secondChild = node + 1; + } + + // Advance to next child node, possibly enqueue other child + if (tSplit > tMax || tSplit <= 0) + node = firstChild; + else if (tSplit < tMin) + node = secondChild; + else { + // Enqueue _secondChild_ in todo list + todo[todoPos].node = secondChild; + todo[todoPos].tMin = tSplit; + todo[todoPos].tMax = tMax; + ++todoPos; + node = firstChild; + tMax = tSplit; + } + } + } + kdNodesVisited += nodesVisited; + return false; +} + +KdTreeAccel *KdTreeAccel::Create(std::vector prims, + const ParameterDictionary ¶meters) { + int isectCost = parameters.GetOneInt("intersectcost", 80); + int travCost = parameters.GetOneInt("traversalcost", 1); + Float emptyBonus = parameters.GetOneFloat("emptybonus", 0.5f); + int maxPrims = parameters.GetOneInt("maxprims", 1); + int maxDepth = parameters.GetOneInt("maxdepth", -1); + return new KdTreeAccel(std::move(prims), isectCost, travCost, emptyBonus, maxPrims, + maxDepth); +} + +PrimitiveHandle CreateAccelerator(const std::string &name, + std::vector prims, + const ParameterDictionary ¶meters) { + PrimitiveHandle accel = nullptr; + if (name == "bvh") + accel = BVHAccel::Create(std::move(prims), parameters); + else if (name == "kdtree") + accel = KdTreeAccel::Create(std::move(prims), parameters); + else + ErrorExit("%s: accelerator type unknown.", name); + + if (!accel) + ErrorExit("%s: unable to create accelerator.", name); + + parameters.ReportUnused(); + return accel; +} + +} // namespace pbrt diff --git a/src/pbrt/cpu/accelerators.h b/src/pbrt/cpu/accelerators.h new file mode 100644 index 00000000..3298ff44 --- /dev/null +++ b/src/pbrt/cpu/accelerators.h @@ -0,0 +1,108 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_CPU_ACCELERATORS_H +#define PBRT_CPU_ACCELERATORS_H + +#include + +#include + +#include +#include +#include + +namespace pbrt { + +PrimitiveHandle CreateAccelerator(const std::string &name, + std::vector prims, + const ParameterDictionary ¶meters); + +struct BVHBuildNode; +struct BVHPrimitiveInfo; +struct LinearBVHNode; +struct MortonPrimitive; + +// BVHAccel Definition +class BVHAccel { + public: + // BVHAccel Public Types + enum class SplitMethod { SAH, HLBVH, Middle, EqualCounts }; + + // BVHAccel Public Methods + BVHAccel(std::vector p, int maxPrimsInNode = 1, + SplitMethod splitMethod = SplitMethod::SAH); + + static BVHAccel *Create(std::vector prims, + const ParameterDictionary ¶meters); + + Bounds3f Bounds() const; + pstd::optional Intersect(const Ray &ray, Float tMax) const; + bool IntersectP(const Ray &ray, Float tMax) const; + + private: + // BVHAccel Private Methods + BVHBuildNode *recursiveBuild(std::vector &threadAllocators, + std::vector &primitiveInfo, int start, + int end, std::atomic *totalNodes, + std::vector &orderedPrims, + std::atomic *orderedPrimsOffset); + BVHBuildNode *HLBVHBuild(Allocator alloc, + const std::vector &primitiveInfo, + std::atomic *totalNodes, + std::vector &orderedPrims); + BVHBuildNode *emitLBVH(BVHBuildNode *&buildNodes, + const std::vector &primitiveInfo, + MortonPrimitive *mortonPrims, int nPrimitives, int *totalNodes, + std::vector &orderedPrims, + std::atomic *orderedPrimsOffset, int bitIndex); + BVHBuildNode *buildUpperSAH(Allocator alloc, + std::vector &treeletRoots, int start, + int end, std::atomic *totalNodes) const; + int flattenBVHTree(BVHBuildNode *node, int *offset); + + // BVHAccel Private Members + int maxPrimsInNode; + SplitMethod splitMethod; + std::vector primitives; + LinearBVHNode *nodes = nullptr; +}; + +struct KdAccelNode; +struct BoundEdge; + +// KdTreeAccel Definition +class KdTreeAccel { + public: + // KdTreeAccel Public Methods + KdTreeAccel(std::vector p, int isectCost = 80, int traversalCost = 1, + Float emptyBonus = 0.5, int maxPrims = 1, int maxDepth = -1); + static KdTreeAccel *Create(std::vector prims, + const ParameterDictionary ¶meters); + pstd::optional Intersect(const Ray &ray, Float tMax) const; + + Bounds3f Bounds() const { return bounds; } + + bool IntersectP(const Ray &ray, Float tMax) const; + + private: + // KdTreeAccel Private Methods + void buildTree(int nodeNum, const Bounds3f &bounds, + const std::vector &primBounds, int *primNums, int nprims, + int depth, const std::unique_ptr edges[3], int *prims0, + int *prims1, int badRefines = 0); + + // KdTreeAccel Private Members + int isectCost, traversalCost, maxPrims; + Float emptyBonus; + std::vector primitives; + std::vector primitiveIndices; + KdAccelNode *nodes; + int nAllocedNodes, nextFreeNode; + Bounds3f bounds; +}; + +} // namespace pbrt + +#endif // PBRT_CPU_ACCELERATORS_H diff --git a/src/pbrt/cpu/integrators.cpp b/src/pbrt/cpu/integrators.cpp new file mode 100644 index 00000000..fbbaa879 --- /dev/null +++ b/src/pbrt/cpu/integrators.cpp @@ -0,0 +1,3281 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pbrt { + +STAT_COUNTER("Integrator/Camera rays traced", nCameraRays); + +// RandomWalkIntegrator Method Definitions +std::unique_ptr RandomWalkIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + return std::make_unique(maxDepth, camera, sampler, aggregate, + lights); +} + +std::string RandomWalkIntegrator::ToString() const { + return StringPrintf("[ RandomWalkIntegrator maxDepth: %d ]", maxDepth); +} + +SampledSpectrum RandomWalkIntegrator::Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const { + return RandomWalk(ray, lambda, sampler, scratchBuffer, 0); +} + +SampledSpectrum RandomWalkIntegrator::RandomWalk(RayDifferential ray, + SampledWavelengths &lambda, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer, + int depth) const { + SampledSpectrum L(0.f); + // Intersect ray with scene and return if no intersection + pstd::optional si = Intersect(ray); + if (!si) { + // Return emitted light from infinite light sources + for (LightHandle light : infiniteLights) + L += light.Le(ray, lambda); + return L; + } + SurfaceInteraction &isect = si->intr; + + // Get emitted radiance at surface intersection + L = isect.Le(-ray.d, lambda); + + // Terminate random walk if maximum depth has been reached + if (depth == maxDepth) + return L; + + // Compute BSDF at random walk intersection point + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) + return L; + + // Randomly sample direction leaving surface for random walk + Point2f u = sampler.Get2D(); + Vector3f wi = SampleUniformSphere(u); + + // Evaluate BSDF at surface for sampled direction + Vector3f wo = -ray.d; + SampledSpectrum beta = bsdf.f(wo, wi) * AbsDot(wi, isect.shading.n) / (1 / (4 * Pi)); + if (!beta) + return L; + + // Recursively trace ray to estimate incident radiance at surface + ray = isect.SpawnRay(wi); + return L + beta * RandomWalk(ray, lambda, sampler, scratchBuffer, depth + 1); +} + +// Integrator Method Definitions +Integrator::~Integrator() {} + +// ImageTileIntegrator Method Definitions +void ImageTileIntegrator::Render() { + // Handle debugStart, if set + if (!Options->debugStart.empty()) { + pstd::optional> c = SplitStringToInts(Options->debugStart, ','); + if (!c) + ErrorExit("Didn't find integer values after --debugstart: %s", + Options->debugStart); + if (c->size() != 3) + ErrorExit("Didn't find three integer values after --debugstart: %s", + Options->debugStart); + + Point2i pPixel((*c)[0], (*c)[1]); + int sampleIndex = (*c)[2]; + + ScratchBuffer scratchBuffer(65536); + SamplerHandle tileSampler = samplerPrototype.Clone(1, Allocator())[0]; + tileSampler.StartPixelSample(pPixel, sampleIndex); + + EvaluatePixelSample(pPixel, sampleIndex, tileSampler, scratchBuffer); + + return; + } + + thread_local Point2i threadPixel; + thread_local int threadSampleIndex; + CheckCallbackScope _([&]() { + return StringPrintf("Rendering failed at pixel (%d, %d) sample %d. Debug with " + "\"--debugstart %d,%d,%d\"\n", + threadPixel.x, threadPixel.y, threadSampleIndex, + threadPixel.x, threadPixel.y, threadSampleIndex); + }); + + // Declare common variables for rendering image in tiles + Bounds2i pixelBounds = camera.GetFilm().PixelBounds(); + int spp = samplerPrototype.SamplesPerPixel(); + int startWave = 0, endWave = 1, waveDelta = 1; + + std::vector scratchBuffers; + for (int i = 0; i < MaxThreadIndex(); ++i) + scratchBuffers.push_back(ScratchBuffer(65536)); + + std::vector samplers = + samplerPrototype.Clone(MaxThreadIndex(), Allocator()); + + ProgressReporter progress(int64_t(spp) * pixelBounds.Area(), "Rendering", + Options->quiet); + + if (Options->recordPixelStatistics) + StatsEnablePixelStats(pixelBounds, + RemoveExtension(camera.GetFilm().GetFilename())); + // Handle MSE referene image, if provided + pstd::optional referenceImage; + FILE *mseOutFile = nullptr; + if (!Options->mseReferenceImage.empty()) { + auto mse = Image::Read(Options->mseReferenceImage); + referenceImage = mse.image; + + Bounds2i msePixelBounds = + mse.metadata.pixelBounds + ? *mse.metadata.pixelBounds + : Bounds2i(Point2i(0, 0), referenceImage->Resolution()); + if (!Inside(pixelBounds, msePixelBounds)) + ErrorExit("Output image pixel bounds %s aren't inside the MSE " + "image's pixel bounds %s.", + pixelBounds, msePixelBounds); + + // Transform the pixelBounds of the image we're rendering to the + // coordinate system with msePixelBounds.pMin at the origin, which + // in turn gives us the section of the MSE image to crop. (This is + // complicated by the fact that Image doesn't support pixel + // bounds...) + Bounds2i cropBounds(Point2i(pixelBounds.pMin - msePixelBounds.pMin), + Point2i(pixelBounds.pMax - msePixelBounds.pMin)); + *referenceImage = referenceImage->Crop(cropBounds); + CHECK_EQ(referenceImage->Resolution(), Point2i(pixelBounds.Diagonal())); + + mseOutFile = fopen(Options->mseReferenceOutput.c_str(), "w"); + if (!mseOutFile) + ErrorExit("%s: %s", Options->mseReferenceOutput, ErrorString()); + } + + // Connect to display server if needed + if (!Options->displayServer.empty()) { + FilmHandle film = camera.GetFilm(); + DisplayDynamic(film.GetFilename(), Point2i(pixelBounds.Diagonal()), + {"R", "G", "B"}, + [=](Bounds2i b, pstd::span> displayValue) { + int index = 0; + for (Point2i p : b) { + RGB rgb = film.GetPixelRGB(pixelBounds.pMin + p); + for (int c = 0; c < 3; ++c) + displayValue[c][index] = rgb[c]; + ++index; + } + }); + } + + while (startWave < spp) { + // Render image tiles in parallel + ParallelFor2D(pixelBounds, [&](Bounds2i tileBounds) { + // Render image tile given by _tileBounds_ + ScratchBuffer &scratchBuffer = scratchBuffers[ThreadIndex]; + SamplerHandle &sampler = samplers[ThreadIndex]; + VLOG(1, "Starting image tile %s startWave %d, endWave %d", tileBounds, + startWave, endWave); + for (Point2i pPixel : tileBounds) { + StatsReportPixelStart(pPixel); + threadPixel = pPixel; + // Render samples in pixel _pPixel_ + for (int sampleIndex = startWave; sampleIndex < endWave; ++sampleIndex) { + threadSampleIndex = sampleIndex; + sampler.StartPixelSample(pPixel, sampleIndex); + EvaluatePixelSample(pPixel, sampleIndex, sampler, scratchBuffer); + scratchBuffer.Reset(); + } + + StatsReportPixelEnd(pPixel); + } + VLOG(1, "Finished image tile %s", tileBounds); + progress.Update((endWave - startWave) * tileBounds.Area()); + }); + + // Update start and end wave + startWave = endWave; + endWave = std::min(spp, endWave + waveDelta); + if (!referenceImage) + waveDelta = std::min(2 * waveDelta, 64); + + // Write current image to disk + LOG_VERBOSE("Writing image with spp = %d", startWave); + ImageMetadata metadata; + metadata.renderTimeSeconds = progress.ElapsedSeconds(); + metadata.samplesPerPixel = startWave; + if (referenceImage) { + ImageMetadata filmMetadata; + Image filmImage = camera.GetFilm().GetImage(&filmMetadata, 1.f / startWave); + ImageChannelValues mse = + filmImage.MSE(filmImage.AllChannelsDesc(), *referenceImage); + fprintf(mseOutFile, "%d, %.9g\n", startWave, mse.Average()); + metadata.MSE = mse.Average(); + fflush(mseOutFile); + } + camera.InitMetadata(&metadata); + camera.GetFilm().WriteImage(metadata, 1.0f / startWave); + } + if (mseOutFile) + fclose(mseOutFile); + progress.Done(); + LOG_VERBOSE("Rendering finished"); +} + +// RayIntegrator Method Definitions +void RayIntegrator::EvaluatePixelSample(const Point2i &pPixel, int sampleIndex, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer) { + // Initialize _CameraSample_ for current sample + FilterHandle filter = camera.GetFilm().GetFilter(); + CameraSample cameraSample = GetCameraSample(sampler, pPixel, filter); + + // Sample wavelengths for the ray + Float lu = RadicalInverse(1, sampleIndex) + BlueNoise(47, pPixel.x, pPixel.y); + if (lu >= 1) + lu -= 1; + if (Options->disableWavelengthJitter) + lu = 0.5; + SampledWavelengths lambda = camera.GetFilm().SampleWavelengths(lu); + + // Generate camera ray for current sample + pstd::optional cameraRay = + camera.GenerateRayDifferential(cameraSample, lambda); + + SampledSpectrum L(0.); + VisibleSurface visibleSurface; + bool initializeVisibleSurface = camera.GetFilm().UsesVisibleSurface(); + // Trace _cameraRay_ if valid + if (cameraRay) { + // Double check that the ray's direction is normalized. + DCHECK_GT(Length(cameraRay->ray.d), .999f); + DCHECK_LT(Length(cameraRay->ray.d), 1.001f); + // Scale camera ray differentials based on sampling rate + Float rayDiffScale = + std::max(.125, 1 / std::sqrt((Float)sampler.SamplesPerPixel())); + if (!Options->disablePixelJitter) + cameraRay->ray.ScaleDifferentials(rayDiffScale); + + ++nCameraRays; + // Evaluate radiance along camera ray + L = cameraRay->weight * Li(cameraRay->ray, lambda, sampler, scratchBuffer, + initializeVisibleSurface ? &visibleSurface : nullptr); + + // Issue warning if unexpected radiance value is returned + if (L.HasNaNs()) { + LOG_ERROR("Not-a-number radiance value returned for pixel (%d, " + "%d), sample %d. " + "Setting to black.", + pPixel.x, pPixel.y, sampleIndex); + L = SampledSpectrum(0.f); + } else if (std::isinf(L.y(lambda))) { + LOG_ERROR("Infinite radiance value returned for pixel (%d, %d), " + "sample %d. " + "Setting to black.", + pPixel.x, pPixel.y, sampleIndex); + L = SampledSpectrum(0.f); + } + + if (cameraRay) + VLOG(2, "Camera sample: %s -> ray %s -> L = %s, visibleSurface %s", + cameraSample, cameraRay->ray, L, + (visibleSurface ? visibleSurface.ToString() : "(none)")); + else + VLOG(2, "Camera sample: %s -> no ray generated", cameraSample); + } + + // Add camera ray's contribution to image + camera.GetFilm().AddSample(pPixel, L, lambda, &visibleSurface, cameraSample.weight); +} + +// Integrator Utility Functions +STAT_COUNTER("Intersections/Regular ray intersection tests", nIntersectionTests); +STAT_COUNTER("Intersections/Shadow ray intersection tests", nShadowTests); + +// Integrator Method Definitions +pstd::optional Integrator::Intersect(const Ray &ray, + Float tMax) const { + ++nIntersectionTests; + DCHECK_NE(ray.d, Vector3f(0, 0, 0)); + if (aggregate) + return aggregate.Intersect(ray, tMax); + else + return {}; +} + +bool Integrator::IntersectP(const Ray &ray, Float tMax) const { + ++nShadowTests; + DCHECK_NE(ray.d, Vector3f(0, 0, 0)); + if (aggregate) + return aggregate.IntersectP(ray, tMax); + else + return false; +} + +std::string Integrator::ToString() const { + std::string s = StringPrintf("[ Scene aggregate: %s sceneBounds: %s lights[%d]: [ ", + aggregate, sceneBounds, lights.size()); + for (const auto &l : lights) + s += StringPrintf("%s, ", l.ToString()); + s += StringPrintf("] infiniteLights[%d]: [ ", infiniteLights.size()); + for (const auto &l : infiniteLights) + s += StringPrintf("%s, ", l.ToString()); + return s + " ]"; +} + +SampledSpectrum Integrator::Tr(const Interaction &p0, const Interaction &p1, + const SampledWavelengths &lambda, RNG &rng) const { + auto rescale = [](SampledSpectrum &Tr, SampledSpectrum &pdf) { + if (Tr.MaxComponentValue() > 0x1p24f || pdf.MaxComponentValue() > 0x1p24f) { + Tr /= 0x1p24f; + pdf /= 0x1p24f; + } + }; + + // :-( + Ray ray = + p0.IsSurfaceInteraction() ? p0.AsSurface().SpawnRayTo(p1) : p0.SpawnRayTo(p1); + SampledSpectrum Tr(1.f), pdf(1.f); + if (LengthSquared(ray.d) == 0) + return Tr; + + while (true) { + pstd::optional si = Intersect(ray, 1 - ShadowEpsilon); + // Handle opaque surface along ray's path + if (si && si->intr.material) + return SampledSpectrum(0.0f); + + // Update transmittance for current ray segment + if (ray.medium != nullptr) { + Point3f pExit = ray(si ? si->tHit : (1 - ShadowEpsilon)); + ray.d = pExit - ray.o; + + ray.medium.SampleTmaj(ray, 1.f, rng, lambda, + [&](const MediumSample &ms) -> bool { + const SampledSpectrum &Tmaj = ms.Tmaj; + + if (!ms.intr) { + Tr *= Tmaj; + return false; + } + + const MediumInteraction &intr = *ms.intr; + SampledSpectrum sigma_n = intr.sigma_n(); + + // ratio-tracking: only evaluate null scattering + Tr *= Tmaj * sigma_n; + pdf *= Tmaj * intr.sigma_maj; + + if (!Tr) + return false; + + rescale(Tr, pdf); + return true; + }); + } + + // Generate next ray segment or return final transmittance + if (!si) + break; + ray = si->intr.SpawnRayTo(p1); + } + VLOG(2, "Tr from %s to %s = %s", p0.pi, p1.pi, Tr); + return Tr / pdf.Average(); +} + +// SimplePathIntegrator Method Definitions +SimplePathIntegrator::SimplePathIntegrator(int maxDepth, bool sampleLights, + bool sampleBSDF, CameraHandle camera, + SamplerHandle sampler, + PrimitiveHandle aggregate, + std::vector lights) + : RayIntegrator(camera, sampler, aggregate, lights), + maxDepth(maxDepth), + sampleLights(sampleLights), + sampleBSDF(sampleBSDF), + lightSampler(lights, Allocator()) {} + +SampledSpectrum SimplePathIntegrator::Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const { + SampledSpectrum L(0.f), beta(1.f); + bool specularBounce = true; + int depth = 0; + + while (beta) { + // Find next _SimplePathIntegrator_ path vertex and accumulate contribution + // Intersect _ray_ with scene + pstd::optional si = Intersect(ray); + + // Account for infinite lights if ray has no intersection + if (!si) { + if (!sampleLights || specularBounce) + for (const auto &light : infiniteLights) + L += beta * light.Le(ray, lambda); + break; + } + + // Account for emsisive surface if light wasn't sampled + SurfaceInteraction &isect = si->intr; + if (!sampleLights || specularBounce) + L += beta * isect.Le(-ray.d, lambda); + + // End path if maximum depth reached + if (depth++ == maxDepth) + break; + + // Compute scattering functions and skip over medium boundaries + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + continue; + } + + // Sample direct illumination if _sampleLights_ is true + Vector3f wo = -ray.d; + if (sampleLights) { + pstd::optional sampledLight = + lightSampler.Sample(sampler.Get1D()); + if (sampledLight) { + // Sample point on _sampledLight_ to estimate direct illumination + Point2f uLight = sampler.Get2D(); + LightLiSample ls = sampledLight->light.SampleLi(isect, uLight, lambda); + if (ls && ls.L) { + // Evaluate BSDF for light and possibly add scattered radiance + Vector3f wi = ls.wi; + SampledSpectrum f = bsdf.f(wo, wi) * AbsDot(wi, isect.shading.n); + if (f && Unoccluded(isect, ls.pLight)) + L += beta * f * ls.L / (sampledLight->pdf * ls.pdf); + } + } + } + + // Sample outoing direction at intersection to continue path + if (sampleBSDF) { + // Sample BSDF for new path direction + Float u = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(wo, u, sampler.Get2D()); + if (!bs) + break; + beta *= bs.f * AbsDot(bs.wi, isect.shading.n) / bs.pdf; + specularBounce = bs.IsSpecular(); + ray = isect.SpawnRay(bs.wi); + + } else { + // Uniformly sample sphere or hemisphere to get new path direction + Float pdf; + Vector3f wi; + if (bsdf.HasReflection() && bsdf.HasTransmission()) { + wi = SampleUniformSphere(sampler.Get2D()); + pdf = UniformSpherePDF(); + } else { + wi = SampleUniformHemisphere(sampler.Get2D()); + pdf = UniformHemispherePDF(); + if (bsdf.HasReflection() && Dot(wo, isect.n) * Dot(wi, isect.n) < 0) + wi = -wi; + else if (bsdf.HasTransmission() && + Dot(wo, isect.n) * Dot(wi, isect.n) > 0) + wi = -wi; + } + beta *= bsdf.f(wo, wi) * AbsDot(wi, isect.shading.n) / pdf; + specularBounce = false; + ray = isect.SpawnRay(wi); + } + + CHECK_GE(beta.y(lambda), 0.f); + DCHECK(!std::isinf(beta.y(lambda))); + } + return L; +} + +std::string SimplePathIntegrator::ToString() const { + return StringPrintf("[ SimplePathIntegrator maxDepth: %d sampleLights: %s " + "sampleBSDF: %s ]", + maxDepth, sampleLights, sampleBSDF); +} + +std::unique_ptr SimplePathIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + bool sampleLights = parameters.GetOneBool("samplelights", true); + bool sampleBSDF = parameters.GetOneBool("samplebsdf", true); + return std::make_unique(maxDepth, sampleLights, sampleBSDF, + camera, sampler, aggregate, lights); +} + +// LightPathIntegrator Method Definitions +LightPathIntegrator::LightPathIntegrator(int maxDepth, CameraHandle camera, + SamplerHandle sampler, PrimitiveHandle aggregate, + std::vector lights) + : ImageTileIntegrator(camera, sampler, aggregate, lights), maxDepth(maxDepth) { + lightSampler = std::make_unique(lights, Allocator()); +} + +void LightPathIntegrator::EvaluatePixelSample(const Point2i &pPixel, int sampleIndex, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer) { + // Eat the first two samples since they're "special"... + (void)sampler.Get2D(); + + // Sample wavelengths for the ray + Float lu = RadicalInverse(1, sampleIndex) + BlueNoise(47, pPixel.x, pPixel.y); + if (lu >= 1) + lu -= 1; + if (Options->disableWavelengthJitter) + lu = 0.5; + SampledWavelengths lambda = camera.GetFilm().SampleWavelengths(lu); + + // Sample a light + pstd::optional sampledLight = lightSampler->Sample(sampler.Get1D()); + if (!sampledLight) + return; + + LightHandle light = sampledLight->light; + Float lightPDF = sampledLight->pdf; + + Float time = camera.SampleTime(sampler.Get1D()); + LightLeSample les = light.SampleLe(sampler.Get2D(), sampler.Get2D(), lambda, time); + if (!les || les.pdfPos == 0 || les.pdfDir == 0 || !les.L) + return; + RayDifferential ray(les.ray); + SampledSpectrum beta = + les.L * les.AbsCosTheta(ray.d) / (lightPDF * les.pdfPos * les.pdfDir); + + // Is the light sample directly visible? + if (les.intr) { + pstd::optional cs = + camera.SampleWi(*les.intr, sampler.Get2D(), lambda); + if (cs && cs->pdf != 0) { + Float pdf = light.PDF_Li(cs->pLens, cs->wi); + if (pdf > 0) { + SampledSpectrum Le = + light.L(les.intr->p(), les.intr->n, les.intr->uv, cs->wi, lambda); + if (Le && Unoccluded(cs->pRef, cs->pLens)) { + SampledSpectrum L = Le * les.AbsCosTheta(cs->wi) * cs->Wi / + (lightPDF * pdf * cs->pdf); + camera.GetFilm().AddSplat(cs->pRaster, L, lambda); + } + } + } + } + + for (int depth = 0; depth < maxDepth && beta; ++depth) { + pstd::optional si = Intersect(ray); + if (!si) + break; + + // Compute scattering functions for _mode_ and skip over medium + // boundaries + SurfaceInteraction &isect = si->intr; + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + --depth; + continue; + } + Vector3f wo = isect.wo; + + // Try to splat into the film + pstd::optional cs = + camera.SampleWi(isect, sampler.Get2D(), lambda); + if (cs && cs->pdf != 0) { + SampledSpectrum L = beta * bsdf.f(wo, cs->wi, TransportMode::Importance) * + AbsDot(cs->wi, isect.shading.n) * cs->Wi / cs->pdf; + if (L && Unoccluded(cs->pRef, cs->pLens)) + camera.GetFilm().AddSplat(cs->pRaster, L, lambda); + } + + // Sample the BSDF... + Float u = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(wo, u, sampler.Get2D(), TransportMode::Importance); + if (!bs) + break; + + beta *= bs.f * AbsDot(bs.wi, isect.shading.n) / bs.pdf; + ray = isect.SpawnRay(ray, bsdf, bs.wi, bs.flags); + } +} + +std::string LightPathIntegrator::ToString() const { + return StringPrintf("[ LightPathIntegrator maxDepth: %d lightSampler: %s ]", maxDepth, + lightSampler); +} + +std::unique_ptr LightPathIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + return std::make_unique(maxDepth, camera, sampler, aggregate, + lights); +} + +STAT_PERCENT("Integrator/Zero-radiance paths", zeroRadiancePaths, totalPaths); +STAT_PERCENT("Integrator/Regularized BSDFs", regularizedBSDFs, totalBSDFs); +STAT_INT_DISTRIBUTION("Integrator/Path length", pathLength); + +// PathIntegrator Method Definitions +PathIntegrator::PathIntegrator(int maxDepth, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, + Float rrThreshold, const std::string &lightSampleStrategy, + bool regularize) + : RayIntegrator(camera, sampler, aggregate, lights), + maxDepth(maxDepth), + rrThreshold(rrThreshold), + lightSampler(LightSamplerHandle::Create(lightSampleStrategy, lights, Allocator())), + regularize(regularize) {} + +SampledSpectrum PathIntegrator::Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const { + SampledSpectrum L(0.f), beta(1.f); + bool specularBounce = false, anyNonSpecularBounces = false; + int depth = 0; + Float etaScale = 1, bsdfPDF; + SurfaceInteraction prevIntr; + + while (true) { + // Find next path vertex and accumulate contribution + pstd::optional si = Intersect(ray); + // Add emitted light at path vertex or from the environment + if (!si) { + // Incorporate emission from infinite lights for escaped ray + for (const auto &light : infiniteLights) { + SampledSpectrum Le = light.Le(ray, lambda); + if (depth == 0 || specularBounce) + L += beta * Le; + else { + // Compute MIS weight for infinite light + Float lightPDF = + lightSampler.PDF(prevIntr, light) * + light.PDF_Li(prevIntr, ray.d, LightSamplingMode::WithMIS); + Float weight = PowerHeuristic(1, bsdfPDF, 1, lightPDF); + + L += beta * weight * Le; + } + } + + break; + } + // Incorporate emission from emissive surface hit by ray + SampledSpectrum Le = si->intr.Le(-ray.d, lambda); + if (Le) { + if (depth == 0 || specularBounce) + L += beta * Le; + else { + // Compute MIS weight for area light + LightHandle areaLight(si->intr.areaLight); + Float lightPDF = + lightSampler.PDF(prevIntr, areaLight) * + areaLight.PDF_Li(prevIntr, ray.d, LightSamplingMode::WithMIS); + Float weight = PowerHeuristic(1, bsdfPDF, 1, lightPDF); + + L += beta * weight * Le; + } + } + + SurfaceInteraction &isect = si->intr; + + // Compute scattering functions and skip over medium boundaries + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + continue; + } + + // Initialize _visibleSurface_ at first intersection + if (depth == 0 && visibleSurface != nullptr) { + // Estimate BSDF's albedo + constexpr int nRhoSamples = 16; + SampledSpectrum rho(0.f); + for (int i = 0; i < nRhoSamples; ++i) { + // Generate sample for hemispherical-directional reflectance + Float uc = RadicalInverse(0, i + 1); + Point2f u(RadicalInverse(1, i + 1), RadicalInverse(2, i + 1)); + + // Estimate one term of $\rho_\roman{hd}$ + auto bs = bsdf.Sample_f(si->intr.wo, uc, u); + if (bs && bs.pdf > 0) + rho += bs.f * AbsDot(bs.wi, si->intr.shading.n) / bs.pdf; + } + SampledSpectrum albedo = rho / nRhoSamples; + + *visibleSurface = + VisibleSurface(si->intr, camera.GetCameraTransform(), albedo, lambda); + } + + // End path if maximum depth reached + if (depth++ == maxDepth) + break; + + // Possibly regularize the BSDF + if (regularize && anyNonSpecularBounces) { + ++regularizedBSDFs; + bsdf.Regularize(); + } + + ++totalBSDFs; + // Sample direct illumination from the light sources + if (bsdf.IsNonSpecular()) { + ++totalPaths; + SampledSpectrum Ld = SampleLd(isect, bsdf, lambda, sampler); + if (!Ld) + ++zeroRadiancePaths; + L += beta * Ld; + } + + // Sample BSDF to get new path direction + Vector3f wo = -ray.d; + Float u = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(wo, u, sampler.Get2D()); + if (!bs) + break; + // Update path state variables for after surface scattering + beta *= bs.f * AbsDot(bs.wi, isect.shading.n) / bs.pdf; + bsdfPDF = bsdf.SampledPDFIsProportional() ? bsdf.PDF(wo, bs.wi) : bs.pdf; + DCHECK(!std::isinf(beta.y(lambda))); + specularBounce = bs.IsSpecular(); + anyNonSpecularBounces |= !bs.IsSpecular(); + if (bs.IsTransmission()) + etaScale *= Sqr(bsdf.eta); + prevIntr = si->intr; + + ray = isect.SpawnRay(ray, bsdf, bs.wi, bs.flags); + + // Possibly terminate the path with Russian roulette + SampledSpectrum rrBeta = beta * etaScale; + if (rrBeta.MaxComponentValue() < rrThreshold && depth > 1) { + Float q = std::max(0, 1 - rrBeta.MaxComponentValue()); + if (sampler.Get1D() < q) + break; + beta /= 1 - q; + DCHECK(!std::isinf(beta.y(lambda))); + } + } + ReportValue(pathLength, depth); + return L; +} + +SampledSpectrum PathIntegrator::SampleLd(const SurfaceInteraction &intr, const BSDF &bsdf, + SampledWavelengths &lambda, + SamplerHandle sampler) const { + // Choose a light source for the direct lighting calculation + pstd::optional sampledLight = + lightSampler.Sample(intr, sampler.Get1D()); + Point2f uLight = sampler.Get2D(); + if (!sampledLight) + return {}; + LightHandle light = sampledLight->light; + DCHECK(light != nullptr && sampledLight->pdf > 0); + + // Sample a point on the light source for direct lighting + LightLiSample ls = light.SampleLi(intr, uLight, lambda, LightSamplingMode::WithMIS); + if (!ls || !ls.L) + return {}; + + // Evaluate BSDF for light sample and check light visibility + Vector3f wo = intr.wo, wi = ls.wi; + SampledSpectrum f = bsdf.f(wo, wi) * AbsDot(wi, intr.shading.n); + if (!f || !Unoccluded(intr, ls.pLight)) + return {}; + + // Return light's contribution to reflected radiance + Float lightPDF = sampledLight->pdf * ls.pdf; + if (IsDeltaLight(light.Type())) + return f * ls.L / lightPDF; + else { + Float bsdfPDF = bsdf.PDF(wo, wi); + CHECK_RARE(1e-6, bsdf.SampledPDFIsProportional() == false && bsdfPDF == 0); + Float weight = PowerHeuristic(1, lightPDF, 1, bsdfPDF); + return f * ls.L * weight / lightPDF; + } +} + +std::string PathIntegrator::ToString() const { + return StringPrintf("[ PathIntegrator maxDepth: %d rrThreshold: %f " + "lightSampler: %s regularize: %s ]", + maxDepth, rrThreshold, lightSampler, regularize); +} + +std::unique_ptr PathIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + Float rrThreshold = parameters.GetOneFloat("rrthreshold", 1.); + std::string lightStrategy = parameters.GetOneString("lightsampler", "bvh"); + bool regularize = parameters.GetOneBool("regularize", false); + return std::make_unique(maxDepth, camera, sampler, aggregate, lights, + rrThreshold, lightStrategy, regularize); +} + +// SimpleVolPathIntegrator Method Definitions +SimpleVolPathIntegrator::SimpleVolPathIntegrator(int maxDepth, CameraHandle camera, + SamplerHandle sampler, + PrimitiveHandle aggregate, + std::vector lights) + : RayIntegrator(camera, sampler, aggregate, lights), maxDepth(maxDepth) { + for (LightHandle light : lights) { + if (IsDeltaLight(light.Type())) + ErrorExit("SimpleVolPathIntegrator only supports area and infinite light " + "sources"); + } +} + +SampledSpectrum SimpleVolPathIntegrator::Li(RayDifferential ray, + SampledWavelengths &lambda, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer, + VisibleSurface *) const { + SampledSpectrum L(0.f), beta(1.f); + int numScatters = 0; + lambda.TerminateSecondary(); + while (true) { + // Estimate radiance for ray path using delta tracking + pstd::optional si = Intersect(ray); + bool scattered = false, terminated = false; + if (ray.medium) { + // Sample medium scattering for _SimpleVolPathIntegrator_ + Float tMax = si ? si->tHit : Infinity; + RNG rng(Hash(sampler.Get1D()), Hash(sampler.Get1D())); + ray.medium.SampleTmaj(ray, tMax, rng, lambda, [&](const MediumSample &ms) { + // Update delta-tracking estimator for path sample + if (!ms.intr) + return false; + const MediumInteraction &intr = *ms.intr; + const SampledSpectrum &sigma_a = intr.sigma_a, &sigma_s = intr.sigma_s; + // Compute medium event probabilities for interaction + Float pAbsorb = sigma_a[0] / intr.sigma_maj[0]; + Float pScatter = sigma_s[0] / intr.sigma_maj[0]; + Float pNull = std::max(0, 1 - pAbsorb - pScatter); + + // Randomly sample medium scattering event for delta-tracking + Float u = sampler.Get1D(); + int mode = SampleDiscrete({pAbsorb, pScatter, pNull}, u); + if (mode == 0) { + // Handle absorption event for delta-tracking + // absorbed; done + L += intr.Le; + terminated = true; + return false; + + } else if (mode == 1) { + // Handle scattering event for delta-tracking + if (numScatters++ >= maxDepth) { + terminated = true; + return false; + } + Vector3f wi = SampleUniformSphere(sampler.Get2D()); + beta *= intr.phase.p(-ray.d, wi) / UniformSpherePDF(); + ray = intr.SpawnRay(wi); + scattered = true; + return false; + + } else { + // Handle null scattering event for delta-tracking + // null -- keep going... + return true; + } + }); + } + if (terminated) + break; + if (!scattered) { + // Add emission to un-scattered ray + if (!si) { + for (const auto &light : infiniteLights) + L += beta * light.Le(ray, lambda); + return L; + } + SurfaceInteraction &isect = si->intr; + L += beta * isect.Le(-ray.d, lambda); + + // Handle surface intersection for _SimpleVolPathIntegrator_ + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) + isect.SkipIntersection(&ray, si->tHit); + else if (bsdf.Sample_f(-ray.d, sampler.Get1D(), sampler.Get2D())) + ErrorExit( + "SimpleVolPathIntegrator doesn't support scattering from surfaces"); + else + break; + } + } + return L; +} + +std::string SimpleVolPathIntegrator::ToString() const { + return StringPrintf("[ SimpleVolPathIntegrator maxDepth: %d ] ", maxDepth); +} + +std::unique_ptr SimpleVolPathIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + return std::make_unique(maxDepth, camera, sampler, aggregate, + lights); +} + +STAT_COUNTER("Integrator/Volume interactions", volumeInteractions); +STAT_COUNTER("Integrator/Surface interactions", surfaceInteractions); + +// VolPathIntegrator Method Definitions +SampledSpectrum VolPathIntegrator::Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const { + // Declare state variables for volumetric path + // NOTE: beta means something different here... + SampledSpectrum L(0.f), beta(1.f), pdfUni(1.f), pdfNEE(1.f); + bool specularBounce = false, anyNonSpecularBounces = false; + Float etaScale = 1; + pstd::optional prevSurfaceIntr; + pstd::optional prevMediumIntr; + int depth = 0; + + while (true) { + // Sample segment of volumetric scattering path + VLOG(2, "Path tracer depth %d, current L = %s, beta = %s", depth, L, beta); + pstd::optional si = Intersect(ray); + bool scattered = false, terminated = false; + if (ray.medium) { + // Sample the participating medium + Float tMax = si ? si->tHit : Infinity; + RNG rng(Hash(sampler.Get1D()), Hash(sampler.Get1D())); + ray.medium.SampleTmaj( + ray, tMax, rng, lambda, [&](const MediumSample &mediumSample) { + // Handle medium scattering event for ray + if (!mediumSample.intr) { + // Update _beta_ and _pdfUni_ for ray that escaped the medium + // FIXME: review this, esp the pdf... + beta *= mediumSample.Tmaj; + pdfUni *= mediumSample.Tmaj; + return false; + } + ++volumeInteractions; + const MediumInteraction &intr = *mediumSample.intr; + const SampledSpectrum &sigma_a = intr.sigma_a, + &sigma_s = intr.sigma_s; + const SampledSpectrum &Tmaj = mediumSample.Tmaj; + // Add emission from medium scattering event + if (depth < maxDepth) + L += beta * intr.Le * sigma_a / + (intr.sigma_maj[0] * pdfUni.Average()); + + // Compute medium event probabilities for interaction + Float pAbsorb = sigma_a[0] / intr.sigma_maj[0]; + Float pScatter = sigma_s[0] / intr.sigma_maj[0]; + Float pNull = std::max(0, 1 - pAbsorb - pScatter); + + CHECK_GE(1 - pAbsorb - pScatter, -1e-6); + // Sample medium scattering event type and update path + Float um = rng.Uniform(); + int mode = SampleDiscrete({pAbsorb, pScatter, pNull}, um); + if (mode == 0) { + // Handle absorption along ray path + // beta *= Tmaj * sigma_a; + // pdfUni *= Tmaj * sigma_a; + terminated = true; + return false; + + } else if (mode == 1) { + // Handle scattering along ray path + if (depth++ >= maxDepth) { + terminated = true; + return false; + } + beta *= Tmaj * sigma_s; + pdfUni *= Tmaj * sigma_s; + // Sample direct lighting at volume scattering event + L += SampleLd(intr, nullptr, lambda, sampler, beta, pdfUni); + + // Sample indirect lighting at volume scattering event + PhaseFunctionSample ps = + intr.phase.Sample_p(-ray.d, sampler.Get2D()); + if (!ps) { + terminated = true; + return false; + } + // Update ray path state for indirect volume scattering + beta *= ps.p; + pdfNEE = pdfUni; + pdfUni *= ps.pdf; + prevMediumIntr = intr; + prevSurfaceIntr.reset(); + scattered = true; + ray = intr.SpawnRay(ps.wi); + specularBounce = false; + anyNonSpecularBounces = true; + + return false; + + } else { + // Handle null scattering along ray path + SampledSpectrum sigma_n = intr.sigma_n(); + beta *= Tmaj * sigma_n; + pdfUni *= Tmaj * sigma_n; + pdfNEE *= Tmaj * intr.sigma_maj; + rescale(beta, pdfUni, pdfNEE); + return true; + } + }); + } + if (terminated) + return L; + if (scattered) + continue; + // Handle scattering at point on surface for volumetric path tracer + ++surfaceInteractions; + if (depth > 0) + CHECK(prevSurfaceIntr.has_value() ^ prevMediumIntr.has_value()); + // Add emitted light at volume path vertex or from the environment + if (!si) { + // Accumulate contributions from infinite light sources + for (const auto &light : infiniteLights) { + SampledSpectrum Le = light.Le(ray, lambda); + if (Le) { + if (depth == 0 || specularBounce) + L += beta * Le / pdfUni.Average(); + else { + // Add infinite light contribution using both PDFs with MIS + LightSampleContext prevIntrContext; + if (prevSurfaceIntr) + prevIntrContext = LightSampleContext(*prevSurfaceIntr); + else + prevIntrContext = LightSampleContext(*prevMediumIntr); + Float lightPDF = lightSampler.PDF(prevIntrContext, light) * + light.PDF_Li(prevIntrContext, ray.d, + LightSamplingMode::WithMIS); + pdfNEE *= lightPDF; + L += beta * Le / (pdfUni + pdfNEE).Average(); + } + } + } + + break; + } + SurfaceInteraction &isect = si->intr; + SampledSpectrum Le = isect.Le(-ray.d, lambda); + if (Le) { + // Add contribution of emission from intersected surface + if (depth == 0 || specularBounce) + L += beta * Le / pdfUni.Average(); + else { + // Add surface light contribution using both PDFs with MIS + LightHandle areaLight(isect.areaLight); + LightSampleContext prevIntrContext; + if (prevSurfaceIntr) + prevIntrContext = LightSampleContext(*prevSurfaceIntr); + else + prevIntrContext = LightSampleContext(*prevMediumIntr); + Float lightPDF = + lightSampler.PDF(prevIntrContext, areaLight) * + areaLight.PDF_Li(prevIntrContext, ray.d, LightSamplingMode::WithMIS); + pdfNEE *= lightPDF; + L += beta * Le / (pdfUni + pdfNEE).Average(); + } + } + + // Compute scattering functions and skip over medium boundaries + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + continue; + } + + prevSurfaceIntr = isect; + prevMediumIntr.reset(); + // Terminate path if maximum depth reached + if (depth++ >= maxDepth) + return L; + + // Possibly regularize BSDF + if (regularize && anyNonSpecularBounces) { + ++regularizedBSDFs; + bsdf.Regularize(); + } + ++totalBSDFs; + + // Sample illumination from lights to find attenuated path contribution + if (bsdf.IsNonSpecular()) { + L += SampleLd(isect, &bsdf, lambda, sampler, beta, pdfUni); + DCHECK(std::isinf(L.y(lambda)) == false); + } + + // Sample BSDF to get new volumetric path direction + Vector3f wo = -ray.d; + Float u = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(wo, u, sampler.Get2D()); + if (!bs) + break; + // Update _beta_ and PDFs for BSDF scattering + beta *= bs.f * AbsDot(bs.wi, isect.shading.n); + pdfNEE = pdfUni; + if (bsdf.SampledPDFIsProportional()) { + Float pdf = bsdf.PDF(wo, bs.wi); + beta *= pdf / bs.pdf; + pdfUni *= pdf; + } else + pdfUni *= bs.pdf; + rescale(beta, pdfUni, pdfNEE); + + VLOG(2, "Sampled BSDF, f = %s, pdf = %f -> beta = %s", bs.f, bs.pdf, beta); + DCHECK(std::isinf(beta.y(lambda)) == false); + specularBounce = bs.IsSpecular(); + anyNonSpecularBounces |= !bs.IsSpecular(); + if (bs.IsTransmission()) + etaScale *= Sqr(bsdf.eta); + ray = isect.SpawnRay(ray, bsdf, bs.wi, bs.flags); + + // Account for attenuated subsurface scattering, if applicable + BSSRDFHandle bssrdf = isect.GetBSSRDF(ray, lambda, camera, scratchBuffer); + if (bssrdf && bs.IsTransmission()) { + // Sample BSSRDF probe segment to find exit point + BSSRDFProbeSegment probeSeg = bssrdf.Sample(sampler.Get1D(), sampler.Get2D()); + if (!probeSeg) + break; + + // Sample random intersection along BSSRDF probe segment + uint64_t seed = MixBits(FloatToBits(sampler.Get1D())); + WeightedReservoirSampler interactionSampler(seed); + // Intersect BSSRDF sampling ray against the scene geometry + Interaction base(probeSeg.p0, probeSeg.time, (MediumHandle) nullptr); + while (true) { + Ray r = base.SpawnRayTo(probeSeg.p1); + if (r.d == Vector3f(0, 0, 0)) + break; + pstd::optional si = Intersect(r, 1); + if (!si) + break; + base = si->intr; + if (si->intr.material == isect.material) + interactionSampler.Add(SubsurfaceInteraction(si->intr), 1.f); + } + + if (!interactionSampler.HasSample()) + break; + + // Convert probe intersection to _BSSRDFSample_ and update _beta_ + SubsurfaceInteraction ssi = interactionSampler.GetSample(); + BSSRDFSample bssrdfSample = + bssrdf.ProbeIntersectionToSample(ssi, scratchBuffer); + if (!bssrdfSample.S || bssrdfSample.pdf == 0) + break; + // Can ignore path pdf here as well since bssrdfSample.pdf + // is non-spectral. + beta *= bssrdfSample.S * interactionSampler.WeightSum() / bssrdfSample.pdf; + SurfaceInteraction pi = ssi; + BSDF &bsdf = bssrdfSample.bsdf; + pi.wo = bssrdfSample.wo; + + // Possibly regularize subsurface BSDF and update _prevSurfaceIntr_ + anyNonSpecularBounces = true; + if (regularize) { + ++regularizedBSDFs; + bsdf.Regularize(); + } else + ++totalBSDFs; + prevSurfaceIntr = pi; + CHECK(!prevMediumIntr.has_value()); + + // Account for attenuated direct subsurface scattering + L += SampleLd(pi, &bsdf, lambda, sampler, beta, pdfUni); + + // Sample ray for indirect subsurface scattering + Float u = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(pi.wo, u, sampler.Get2D()); + if (!bs) + break; + beta *= bs.f * AbsDot(bs.wi, pi.shading.n); + pdfNEE = pdfUni; + pdfUni *= bs.pdf; + // don't increment depth this time... + DCHECK(!std::isinf(beta.y(lambda))); + specularBounce = bs.IsSpecular(); + ray = RayDifferential(pi.SpawnRay(bs.wi)); + } + + // Possibly terminate volumetric path with Russian roulette + if (!beta) + break; + SampledSpectrum rrBeta = beta * etaScale / pdfUni.Average(); + VLOG(2, "etaScale %f -> rrBeta %s", etaScale, rrBeta); + if (rrBeta.MaxComponentValue() < rrThreshold && depth > 1) { + Float q = std::max(0, 1 - rrBeta.MaxComponentValue()); + if (sampler.Get1D() < q) + break; + pdfUni *= 1 - q; + pdfNEE *= 1 - q; + } + } + return L; +} + +SampledSpectrum VolPathIntegrator::SampleLd(const Interaction &intr, const BSDF *bsdf, + SampledWavelengths &lambda, + SamplerHandle sampler, + const SampledSpectrum &beta, + const SampledSpectrum &pathPDF) const { + // Sample a light source using _lightSampler_ + Float u = sampler.Get1D(); + pstd::optional sampledLight = + bsdf ? lightSampler.Sample(intr.AsSurface(), u) : lightSampler.Sample(intr, u); + Point2f uLight = sampler.Get2D(); + if (!sampledLight) + return SampledSpectrum(0.f); + LightHandle light = sampledLight->light; + CHECK(light != nullptr && sampledLight->pdf != 0); + + // Sample a point on the light source + LightSampleContext ctx; + if (bsdf) + ctx = LightSampleContext(intr.AsSurface()); + else + ctx = LightSampleContext(intr); + LightLiSample ls = light.SampleLi(ctx, uLight, lambda, LightSamplingMode::WithMIS); + if (!ls || !ls.L) + return SampledSpectrum(0.f); + Float lightPDF = sampledLight->pdf * ls.pdf; + + // Evaluate BSDF or phase function for light sample direction + Float scatterPDF; + SampledSpectrum betaLight = beta; + Vector3f wo = intr.wo, wi = ls.wi; + if (bsdf) { + // Update _bsdfLight_ and _scatterPDF_ accounting for the BSDF + betaLight *= bsdf->f(wo, wi) * AbsDot(wi, intr.AsSurface().shading.n); + scatterPDF = bsdf->PDF(wo, wi); + + } else { + // Update _bsdfLight_ and _scatterPDF_ accounting for the phase function + CHECK(intr.IsMediumInteraction()); + PhaseFunctionHandle phase = intr.AsMedium().phase; + betaLight *= phase.p(wo, wi); + scatterPDF = phase.PDF(wo, wi); + } + if (!betaLight) + return SampledSpectrum(0.f); + + // Declare path state variables for ray to light source + Ray lightRay = intr.SpawnRayTo(ls.pLight); + SampledSpectrum pdfLight = pathPDF * lightPDF; // p_nee in paper + SampledSpectrum pdfUni = pathPDF * scatterPDF; // p_uni + RNG rng(Hash(lightRay.o), Hash(lightRay.d)); + + while (true) { + // Trace ray through media to estimate transmittance + pstd::optional si = Intersect(lightRay, 1 - ShadowEpsilon); + // Handle opaque surface along ray's path + if (si && si->intr.material) + return SampledSpectrum(0.f); + + // Update transmittance for current ray segment + if (lightRay.medium != nullptr) { + Float tMax = si ? si->tHit : (1 - ShadowEpsilon); + lightRay.medium.SampleTmaj( + lightRay, tMax, rng, lambda, [&](const MediumSample &mediumSample) { + // Account for medium scattering event along shadow ray + const SampledSpectrum &Tmaj = mediumSample.Tmaj; + if (!mediumSample.intr) { + // CO betaLight *= Tmaj; + return false; + } + const MediumInteraction &intr = *mediumSample.intr; + // Update _betaLight_ and PDFs using ratio-tracking estimator + SampledSpectrum sigma_n = intr.sigma_n(); + // ratio-tracking: only evaluate null scattering + betaLight *= Tmaj * sigma_n; + pdfLight *= Tmaj * intr.sigma_maj; + pdfUni *= Tmaj * sigma_n; + + if (!betaLight) + return false; + rescale(betaLight, pdfLight, pdfUni); + return true; + }); + } + + // Generate next ray segment or return final transmittance + if (!si) + break; + lightRay = si->intr.SpawnRayTo(ls.pLight); + } + // Return weighted light contribution to direct lighting + if (IsDeltaLight(light.Type())) + // pdfUni unused... + return betaLight * ls.L / pdfLight.Average(); + else + return betaLight * ls.L / (pdfLight + pdfUni).Average(); +} + +std::string VolPathIntegrator::ToString() const { + return StringPrintf("[ VolPathIntegrator maxDepth: %d rrThreshold: %f " + "lightSampler: %s regularize: %s ]", + maxDepth, rrThreshold, lightSampler, regularize); +} + +std::unique_ptr VolPathIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + Float rrThreshold = parameters.GetOneFloat("rrthreshold", 1.); + std::string lightStrategy = parameters.GetOneString("lightsampler", "bvh"); + bool regularize = parameters.GetOneBool("regularize", false); + return std::make_unique(maxDepth, camera, sampler, aggregate, + lights, rrThreshold, lightStrategy, + regularize); +} + +// AOIntegrator Method Definitions +AOIntegrator::AOIntegrator(bool cosSample, Float maxDist, CameraHandle camera, + SamplerHandle sampler, PrimitiveHandle aggregate, + std::vector lights, SpectrumHandle illuminant) + : RayIntegrator(camera, sampler, aggregate, lights), + cosSample(cosSample), + maxDist(maxDist), + illuminant(illuminant) {} + +SampledSpectrum AOIntegrator::Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const { + SampledSpectrum L(0.f); + + // Intersect _ray_ with scene and store intersection in _isect_ + pstd::optional si; +retry: + si = Intersect(ray); + if (si) { + SurfaceInteraction &isect = si->intr; + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + goto retry; + } + + // Compute coordinate frame based on true geometry, not shading + // geometry. + Normal3f n = FaceForward(isect.n, -ray.d); + Vector3f s = Normalize(isect.dpdu); + Vector3f t = Cross(isect.n, s); + + Vector3f wi; + Float pdf; + Point2f u = sampler.Get2D(); + if (cosSample) { + wi = SampleCosineHemisphere(u); + pdf = CosineHemispherePDF(std::abs(wi.z)); + } else { + wi = SampleUniformHemisphere(u); + pdf = UniformHemispherePDF(); + } + if (pdf == 0) + return SampledSpectrum(0.); + + Frame f = Frame::FromZ(n); + wi = f.FromLocal(wi); + + // Divide by pi so that fully visible is one. + Ray r = isect.SpawnRay(wi); + if (!IntersectP(r, maxDist)) + return illuminant.Sample(lambda) * SampledSpectrum(Dot(wi, n) / (Pi * pdf)); + } + return SampledSpectrum(0.); +} + +std::string AOIntegrator::ToString() const { + return StringPrintf("[ AOIntegrator cosSample: %s maxDist: %f illuminant: %s ]", + cosSample, maxDist, illuminant); +} + +std::unique_ptr AOIntegrator::Create( + const ParameterDictionary ¶meters, SpectrumHandle illuminant, CameraHandle camera, + SamplerHandle sampler, PrimitiveHandle aggregate, std::vector lights, + const FileLoc *loc) { + bool cosSample = parameters.GetOneBool("cossample", true); + Float maxDist = parameters.GetOneFloat("maxdistance", Infinity); + return std::make_unique(cosSample, maxDist, camera, sampler, aggregate, + lights, illuminant); +} + +// BDPT Utility Function Declarations +int RandomWalk(const Integrator &integrator, SampledWavelengths &lambda, + RayDifferential ray, SamplerHandle sampler, CameraHandle camera, + ScratchBuffer &scratchBuffer, SampledSpectrum beta, Float pdf, + int maxDepth, TransportMode mode, Vertex *path, bool regularize); + +SampledSpectrum ConnectBDPT(const Integrator &integrator, SampledWavelengths &lambda, + Vertex *lightVertices, Vertex *cameraVertices, int s, int t, + LightSamplerHandle lightSampler, CameraHandle camera, + SamplerHandle sampler, pstd::optional *pRaster, + Float *misWeightPtr = nullptr); + +Float InfiniteLightDensity(const std::vector &infiniteLights, + LightSamplerHandle lightSampler, const Vector3f &w); + +// VertexType Definition +enum class VertexType { Camera, Light, Surface, Medium }; + +// ScopedAssignment Definition +template +class ScopedAssignment { + public: + // ScopedAssignment Public Methods + ScopedAssignment(Type *target = nullptr, Type value = Type()) : target(target) { + if (target) { + backup = *target; + *target = value; + } + } + ~ScopedAssignment() { + if (target) + *target = backup; + } + ScopedAssignment(const ScopedAssignment &) = delete; + ScopedAssignment &operator=(const ScopedAssignment &) = delete; + + ScopedAssignment &operator=(ScopedAssignment &&other) { + target = other.target; + backup = other.backup; + other.target = nullptr; + return *this; + } + + private: + Type *target, backup; +}; + +// EndpointInteraction Definition +struct EndpointInteraction : Interaction { + union { + CameraHandle camera; + LightHandle light; + }; + // EndpointInteraction Public Methods + EndpointInteraction() : Interaction(), light(nullptr) {} + EndpointInteraction(const Interaction &it, CameraHandle camera) + : Interaction(it), camera(camera) {} + EndpointInteraction(CameraHandle camera, const Ray &ray) + : Interaction(ray.o, ray.time, ray.medium), camera(camera) {} + EndpointInteraction(const EndpointInteraction &ei) + : Interaction(ei), camera(ei.camera) { + static_assert(sizeof(LightHandle) == sizeof(CameraHandle), + "Expect both union members have same size"); + } + + EndpointInteraction(LightHandle light, const Ray &r, const Interaction &intr) + : Interaction(intr), light(light) {} + EndpointInteraction(LightHandle light, const Ray &r) + : Interaction(r.o, r.time, r.medium), light(light) {} + + EndpointInteraction(const Interaction &it, LightHandle light) + : Interaction(it), light(light) {} + EndpointInteraction(const Ray &ray) + : Interaction(ray(1), Normal3f(-ray.d), ray.time, ray.medium), light(nullptr) {} +}; + +// BDPT Vertex Definition +struct Vertex { + // Vertex Public Members + VertexType type; + SampledSpectrum beta; + union { + EndpointInteraction ei; + MediumInteraction mi; + SurfaceInteraction si; + }; + BSDF bsdf; + bool delta = false; + Float pdfFwd = 0, pdfRev = 0; + + // Vertex Public Methods + // Need to define these two to make compilers happy with the non-POD + // objects in the anonymous union above. + Vertex(const Vertex &v) { memcpy(this, &v, sizeof(Vertex)); } + Vertex &operator=(const Vertex &v) { + memcpy(this, &v, sizeof(Vertex)); + return *this; + } + + Vertex() : ei() {} + + Vertex(VertexType type, const EndpointInteraction &ei, const SampledSpectrum &beta) + : type(type), beta(beta), ei(ei) {} + + Vertex(const SurfaceInteraction &si, const BSDF &bsdf, const SampledSpectrum &beta) + : type(VertexType::Surface), beta(beta), si(si), bsdf(bsdf) {} + + static inline Vertex CreateCamera(CameraHandle camera, const Ray &ray, + const SampledSpectrum &beta); + static inline Vertex CreateCamera(CameraHandle camera, const Interaction &it, + const SampledSpectrum &beta); + static inline Vertex CreateLight(LightHandle light, const Ray &ray, + const SampledSpectrum &Le, Float pdf); + static inline Vertex CreateLight(LightHandle light, const Ray &ray, + const Interaction &intr, const SampledSpectrum &Le, + Float pdf); + static inline Vertex CreateLight(const EndpointInteraction &ei, + const SampledSpectrum &beta, Float pdf); + static inline Vertex CreateMedium(const MediumInteraction &mi, + const SampledSpectrum &beta, Float pdf, + const Vertex &prev); + static inline Vertex CreateSurface(const SurfaceInteraction &si, const BSDF &bsdf, + const SampledSpectrum &beta, Float pdf, + const Vertex &prev); + + Vertex(const MediumInteraction &mi, const SampledSpectrum &beta) + : type(VertexType::Medium), beta(beta), mi(mi) {} + + const Interaction &GetInteraction() const { + switch (type) { + case VertexType::Medium: + return mi; + case VertexType::Surface: + return si; + default: + return ei; + } + } + + Point3f p() const { return GetInteraction().p(); } + + Float time() const { return GetInteraction().time; } + const Normal3f &ng() const { return GetInteraction().n; } + const Normal3f &ns() const { + if (type == VertexType::Surface) + return si.shading.n; + else + return GetInteraction().n; + } + + bool IsOnSurface() const { return ng() != Normal3f(); } + + SampledSpectrum f(const Vertex &next, TransportMode mode) const { + Vector3f wi = next.p() - p(); + if (LengthSquared(wi) == 0) + return {}; + wi = Normalize(wi); + switch (type) { + case VertexType::Surface: + return bsdf.f(si.wo, wi, mode); + case VertexType::Medium: + return SampledSpectrum(mi.phase.p(mi.wo, wi)); + default: + LOG_FATAL("Vertex::f(): Unimplemented"); + return SampledSpectrum(0.f); + } + } + + bool IsConnectible() const { + switch (type) { + case VertexType::Medium: + return true; + case VertexType::Light: + return ei.light.Type() != LightType::DeltaDirection; + case VertexType::Camera: + return true; + case VertexType::Surface: + return bsdf.IsNonSpecular(); + } + LOG_FATAL("Unhandled vertex type in IsConnectable()"); + } + + bool IsLight() const { + return type == VertexType::Light || (type == VertexType::Surface && si.areaLight); + } + + bool IsDeltaLight() const { + return type == VertexType::Light && ei.light && + pbrt::IsDeltaLight(ei.light.Type()); + } + + bool IsInfiniteLight() const { + return type == VertexType::Light && + (!ei.light || ei.light.Type() == LightType::Infinite || + ei.light.Type() == LightType::DeltaDirection); + } + + SampledSpectrum Le(const std::vector &infiniteLights, const Vertex &v, + const SampledWavelengths &lambda) const { + if (!IsLight()) + return SampledSpectrum(0.f); + Vector3f w = v.p() - p(); + if (LengthSquared(w) == 0) + return SampledSpectrum(0.); + w = Normalize(w); + if (IsInfiniteLight()) { + // Return emitted radiance for infinite light sources + SampledSpectrum Le(0.f); + for (const auto &light : infiniteLights) + Le += light.Le(Ray(p(), -w), lambda); + return Le; + + } else { + return si.areaLight ? si.areaLight.L(si.p(), si.n, si.uv, w, lambda) + : SampledSpectrum(0.); + } + } + + std::string ToString() const { + std::string s = std::string("[ Vertex type: "); + switch (type) { + case VertexType::Camera: + s += "camera"; + break; + case VertexType::Light: + s += "light"; + break; + case VertexType::Surface: + s += "surface"; + break; + case VertexType::Medium: + s += "medium"; + break; + } + s += StringPrintf(" connectible: %s p: %s ng: %s pdfFwd: %f pdfRev: %f beta: %s", + IsConnectible(), p(), ng(), pdfFwd, pdfRev, beta); + switch (type) { + case VertexType::Camera: + // TODO + break; + case VertexType::Light: + // TODO + break; + case VertexType::Surface: + s += std::string("\n bsdf: ") + bsdf.ToString(); + break; + case VertexType::Medium: + s += std::string("\n phase: ") + mi.phase.ToString(); + break; + } + s += std::string(" ]"); + return s; + } + + Float ConvertDensity(Float pdf, const Vertex &next) const { + // Return solid angle density if _next_ is an infinite area light + if (next.IsInfiniteLight()) + return pdf; + + Vector3f w = next.p() - p(); + if (LengthSquared(w) == 0) + return 0; + Float invDist2 = 1 / LengthSquared(w); + if (next.IsOnSurface()) + pdf *= AbsDot(next.ng(), w * std::sqrt(invDist2)); + return pdf * invDist2; + } + + Float PDF(const Integrator &integrator, const Vertex *prev, + const Vertex &next) const { + if (type == VertexType::Light) + return PdfLight(integrator, next); + // Compute directions to preceding and next vertex + Vector3f wn = next.p() - p(); + if (LengthSquared(wn) == 0) + return 0; + wn = Normalize(wn); + Vector3f wp; + if (prev) { + wp = prev->p() - p(); + if (LengthSquared(wp) == 0) + return 0; + wp = Normalize(wp); + } else + CHECK(type == VertexType::Camera); + + // Compute directional density depending on the vertex type + Float pdf = 0, unused; + if (type == VertexType::Camera) + ei.camera.PDF_We(ei.SpawnRay(wn), &unused, &pdf); + else if (type == VertexType::Surface) + pdf = bsdf.PDF(wp, wn); + else if (type == VertexType::Medium) + pdf = mi.phase.p(wp, wn); + else + LOG_FATAL("Vertex::PDF(): Unimplemented"); + + // Return probability per unit area at vertex _next_ + return ConvertDensity(pdf, next); + } + + Float PdfLight(const Integrator &integrator, const Vertex &v) const { + Vector3f w = v.p() - p(); + Float invDist2 = 1 / LengthSquared(w); + w *= std::sqrt(invDist2); + Float pdf; + if (IsInfiniteLight()) { + // Compute planar sampling density for infinite light sources + Point3f worldCenter; + Float worldRadius; + integrator.SceneBounds().BoundingSphere(&worldCenter, &worldRadius); + pdf = 1 / (Pi * worldRadius * worldRadius); + + } else if (IsOnSurface()) { + // Compute sampling density at emissive surface + if (type == VertexType::Light) + CHECK(ei.light.Is()); // since that's all we've + // got currently... + LightHandle light = (type == VertexType::Light) ? ei.light : si.areaLight; + Float pdfPos, pdfDir; + light.PDF_Le(ei, w, &pdfPos, &pdfDir); + pdf = pdfDir * invDist2; + + } else { + // Get pointer _light_ to the light source at the vertex + CHECK(type == VertexType::Light); + CHECK(ei.light != nullptr); + LightHandle light = ei.light; + + // Compute sampling density for non-infinite light sources + Float pdfPos, pdfDir; + light.PDF_Le(Ray(p(), w, time()), &pdfPos, &pdfDir); + pdf = pdfDir * invDist2; + } + if (v.IsOnSurface()) + pdf *= AbsDot(v.ng(), w); + return pdf; + } + + Float PdfLightOrigin(const std::vector &infiniteLights, const Vertex &v, + LightSamplerHandle lightSampler) { + Vector3f w = v.p() - p(); + if (LengthSquared(w) == 0) + return 0.; + w = Normalize(w); + if (IsInfiniteLight()) { + // Return solid angle density for infinite light sources + return InfiniteLightDensity(infiniteLights, lightSampler, w); + + } else if (IsOnSurface()) { + // Return probability for emissive surface + if (type == VertexType::Light) + CHECK(ei.light.Is()); // since that's all we've + // got currently... + LightHandle light = (type == VertexType::Light) ? ei.light : si.areaLight; + Float pdfChoice = lightSampler.PDF(light); + Float pdfPos, pdfDir; + light.PDF_Le(ei, w, &pdfPos, &pdfDir); + return pdfPos * pdfChoice; + + } else { + // Return solid angle density for non-infinite light sources + Float pdfPos, pdfDir; + CHECK(IsLight()); + LightHandle light = type == VertexType::Light ? ei.light : si.areaLight; + CHECK(light != nullptr); + Float pdfChoice = lightSampler.PDF(light); + light.PDF_Le(Ray(p(), w, time()), &pdfPos, &pdfDir); + return pdfPos * pdfChoice; + } + } +}; + +// BDPT Vertex Inline Method Definitions +inline Vertex Vertex::CreateCamera(CameraHandle camera, const Ray &ray, + const SampledSpectrum &beta) { + return Vertex(VertexType::Camera, EndpointInteraction(camera, ray), beta); +} + +inline Vertex Vertex::CreateCamera(CameraHandle camera, const Interaction &it, + const SampledSpectrum &beta) { + return Vertex(VertexType::Camera, EndpointInteraction(it, camera), beta); +} + +inline Vertex Vertex::CreateLight(LightHandle light, const Ray &ray, + const SampledSpectrum &Le, Float pdf) { + Vertex v(VertexType::Light, EndpointInteraction(light, ray), Le); + v.pdfFwd = pdf; + return v; +} + +inline Vertex Vertex::CreateLight(LightHandle light, const Ray &ray, + const Interaction &intr, const SampledSpectrum &Le, + Float pdf) { + Vertex v(VertexType::Light, EndpointInteraction(light, ray, intr), Le); + v.pdfFwd = pdf; + return v; +} + +inline Vertex Vertex::CreateSurface(const SurfaceInteraction &si, const BSDF &bsdf, + const SampledSpectrum &beta, Float pdf, + const Vertex &prev) { + Vertex v(si, bsdf, beta); + v.pdfFwd = prev.ConvertDensity(pdf, v); + return v; +} + +inline Vertex Vertex::CreateMedium(const MediumInteraction &mi, + const SampledSpectrum &beta, Float pdf, + const Vertex &prev) { + Vertex v(mi, beta); + v.pdfFwd = prev.ConvertDensity(pdf, v); + return v; +} + +inline Vertex Vertex::CreateLight(const EndpointInteraction &ei, + const SampledSpectrum &beta, Float pdf) { + Vertex v(VertexType::Light, ei, beta); + v.pdfFwd = pdf; + return v; +} + +// BDPT Utility Functions +inline int BufferIndex(int s, int t) { + int above = s + t - 2; + return s + above * (5 + above) / 2; +} + +int GenerateCameraSubpath(const Integrator &integrator, const RayDifferential &ray, + SampledWavelengths &lambda, SamplerHandle sampler, + ScratchBuffer &scratchBuffer, int maxDepth, CameraHandle camera, + Vertex *path, bool regularize) { + if (maxDepth == 0) + return 0; + SampledSpectrum beta(1.f); + // Generate first vertex on camera subpath and start random walk + Float pdfPos, pdfDir; + path[0] = Vertex::CreateCamera(camera, ray, beta); + camera.PDF_We(ray, &pdfPos, &pdfDir); + return RandomWalk(integrator, lambda, ray, sampler, camera, scratchBuffer, beta, + pdfDir, maxDepth - 1, TransportMode::Radiance, path + 1, + regularize) + + 1; +} + +int GenerateLightSubpath(const Integrator &integrator, SampledWavelengths &lambda, + SamplerHandle sampler, CameraHandle camera, + ScratchBuffer &scratchBuffer, int maxDepth, Float time, + LightSamplerHandle lightSampler, Vertex *path, bool regularize) { + if (maxDepth == 0) + return 0; + // Sample initial ray for light subpath + pstd::optional sampledLight = lightSampler.Sample(sampler.Get1D()); + if (!sampledLight) + return 0; + LightHandle light = sampledLight->light; + Float lightPDF = sampledLight->pdf; + LightLeSample les = light.SampleLe(sampler.Get2D(), sampler.Get2D(), lambda, time); + if (!les || les.pdfPos == 0 || les.pdfDir == 0 || !les.L) + return 0; + RayDifferential ray(les.ray); + + // Generate first vertex on light subpath and start random walk + path[0] = les.intr ? Vertex::CreateLight(light, ray, *les.intr, les.L, + les.pdfPos * lightPDF) + : Vertex::CreateLight(light, ray, les.L, les.pdfPos * lightPDF); + SampledSpectrum beta = + les.L * les.AbsCosTheta(ray.d) / (lightPDF * les.pdfPos * les.pdfDir); + VLOG(2, "Starting light subpath. Ray: %s, Le %s, beta %s, pdfPos %f, pdfDir %f", ray, + les.L, beta, les.pdfPos, les.pdfDir); + int nVertices = RandomWalk(integrator, lambda, ray, sampler, camera, scratchBuffer, + beta, les.pdfDir, maxDepth - 1, TransportMode::Importance, + path + 1, regularize); + // Correct subpath sampling densities for infinite area lights + if (path[0].IsInfiniteLight()) { + // Set spatial density of _path[1]_ for infinite area light + if (nVertices > 0) { + path[1].pdfFwd = les.pdfPos; + if (path[1].IsOnSurface()) + path[1].pdfFwd *= AbsDot(ray.d, path[1].ng()); + } + + // Set spatial density of _path[0]_ for infinite area light + path[0].pdfFwd = + InfiniteLightDensity(integrator.infiniteLights, lightSampler, ray.d); + } + + return nVertices + 1; +} + +int RandomWalk(const Integrator &integrator, SampledWavelengths &lambda, + RayDifferential ray, SamplerHandle sampler, CameraHandle camera, + ScratchBuffer &scratchBuffer, SampledSpectrum beta, Float pdf, + int maxDepth, TransportMode mode, Vertex *path, bool regularize) { + if (maxDepth == 0) + return 0; + int bounces = 0; + bool anyNonSpecularBounces = false; + // Declare variables for forward and reverse probability densities + Float pdfFwd = pdf, pdfRev = 0; + + while (true) { + // Attempt to create the next subpath vertex in _path_ + VLOG(2, "Random walk. Bounces %d, beta %s, pdfFwd %f, pdfRef %f", bounces, beta, + pdfFwd, pdfRev); + if (!beta) + break; + // Trace a ray and sample the medium, if any + Vertex &vertex = path[bounces], &prev = path[bounces - 1]; + pstd::optional si = integrator.Intersect(ray); + bool scattered = false, terminated = false; + if (ray.medium) { + Float tMax = si ? si->tHit : Infinity; + RNG rng(Hash(ray.d.x), Hash(ray.d.y)); + ray.medium.SampleTmaj( + ray, tMax, rng, lambda, [&](const MediumSample &mediumSample) { + const SampledSpectrum &Tmaj = mediumSample.Tmaj; + if (!mediumSample.intr) { + beta *= Tmaj / Tmaj.Average(); + return false; // onward to the surface path... + } + + const MediumInteraction &intr = *mediumSample.intr; + const SampledSpectrum &sigma_a = intr.sigma_a; + const SampledSpectrum &sigma_s = intr.sigma_s; + + Float pAbsorb = sigma_a[0] / intr.sigma_maj[0]; + Float pScatter = sigma_s[0] / intr.sigma_maj[0]; + Float pNull = std::max(0, 1 - pAbsorb - pScatter); + DCHECK_GE(1 - pAbsorb - pScatter, -1e-6); + + Float um = sampler.Get1D(); + int mode = SampleDiscrete({pAbsorb, pScatter, pNull}, um); + + if (mode == 0) { + // absorption; done + terminated = true; + return false; + } else if (mode == 1) { + // scatter + beta *= Tmaj * sigma_s / (Tmaj * sigma_s).Average(); + + // Record medium interaction in _path_ and compute forward density + vertex = Vertex::CreateMedium(intr, beta, pdfFwd, prev); + if (++bounces >= maxDepth) { + terminated = true; + return false; + } + + // Sample direction and compute reverse density at preceding + // vertex + PhaseFunctionSample ps = + intr.phase.Sample_p(-ray.d, sampler.Get2D()); + if (!ps) { + terminated = true; + return false; + } + pdfFwd = pdfRev = ps.pdf; + beta *= ps.p / pdfFwd; + ray = intr.SpawnRay(ps.wi); + anyNonSpecularBounces = true; + + // Compute reverse area density at preceding vertex + prev.pdfRev = vertex.ConvertDensity(pdfRev, prev); + + scattered = true; + return false; + } else { + // null scatter + SampledSpectrum sigma_n = intr.sigma_n(); + + beta *= Tmaj * sigma_n / (Tmaj * sigma_n).Average(); + return true; + } + }); + } + + if (terminated) + return bounces; + if (scattered) + continue; + // Handle surface interaction for path generation + if (!si) { + // Capture escaped rays when tracing from the camera + if (mode == TransportMode::Radiance) { + vertex = Vertex::CreateLight(EndpointInteraction(ray), beta, pdfFwd); + ++bounces; + } + + break; + } + SurfaceInteraction &isect = si->intr; + // Compute scattering functions and skip over medium boundaries + BSDF bsdf = isect.GetBSDF(ray, lambda, camera, scratchBuffer, sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + continue; + } + + // Possibly regularize the BSDF + if (regularize && anyNonSpecularBounces) { + ++regularizedBSDFs; + bsdf.Regularize(); + } + + ++totalBSDFs; + // Initialize _vertex_ with surface intersection information + vertex = Vertex::CreateSurface(isect, bsdf, beta, pdfFwd, prev); + + if (++bounces >= maxDepth) + break; + // Sample BSDF at current vertex and compute reverse probability + Vector3f wo = isect.wo; + Float u = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(wo, u, sampler.Get2D(), mode); + if (!bs) + break; + pdfFwd = bs.pdf; + anyNonSpecularBounces |= !bs.IsSpecular(); + beta *= bs.f * AbsDot(bs.wi, isect.shading.n) / bs.pdf; + // TODO: confirm. I believe that ~mode is right. Interestingly, + // it makes no difference in the test suite either way. + pdfRev = bsdf.PDF(bs.wi, wo, ~mode); + if (bs.IsSpecular()) { + vertex.delta = true; + pdfRev = pdfFwd = 0; + } + VLOG(2, "Random walk beta after shading normal correction %s", beta); + ray = isect.SpawnRay(ray, bsdf, bs.wi, bs.flags); + + // Compute reverse area density at preceding vertex + prev.pdfRev = vertex.ConvertDensity(pdfRev, prev); + } + return bounces; +} + +SampledSpectrum G(const Integrator &integrator, SamplerHandle sampler, const Vertex &v0, + const Vertex &v1, const SampledWavelengths &lambda) { + Vector3f d = v0.p() - v1.p(); + Float g = 1 / LengthSquared(d); + d *= std::sqrt(g); + if (v0.IsOnSurface()) + g *= AbsDot(v0.ns(), d); + if (v1.IsOnSurface()) + g *= AbsDot(v1.ns(), d); + RNG rng(Hash(v0.p()), Hash(v1.p())); + return g * integrator.Tr(v0.GetInteraction(), v1.GetInteraction(), lambda, rng); +} + +Float MISWeight(const Integrator &integrator, Vertex *lightVertices, + Vertex *cameraVertices, Vertex &sampled, int s, int t, + LightSamplerHandle lightSampler) { + if (s + t == 2) + return 1; + Float sumRi = 0; + // Define helper function _remap0_ that deals with Dirac delta functions + auto remap0 = [](float f) -> Float { return f != 0 ? f : 1; }; + + // Temporarily update vertex properties for current strategy + // Look up connection vertices and their predecessors + Vertex *qs = s > 0 ? &lightVertices[s - 1] : nullptr, + *pt = t > 0 ? &cameraVertices[t - 1] : nullptr, + *qsMinus = s > 1 ? &lightVertices[s - 2] : nullptr, + *ptMinus = t > 1 ? &cameraVertices[t - 2] : nullptr; + + // Update sampled vertex for $s=1$ or $t=1$ strategy + ScopedAssignment a1; + if (s == 1) + a1 = {qs, sampled}; + else if (t == 1) + a1 = {pt, sampled}; + + // Mark connection vertices as non-degenerate + ScopedAssignment a2, a3; + if (pt) + a2 = {&pt->delta, false}; + if (qs) + a3 = {&qs->delta, false}; + + // Update reverse density of vertex $\pt{}_{t-1}$ + ScopedAssignment a4; + if (pt) + a4 = {&pt->pdfRev, s > 0 ? qs->PDF(integrator, qsMinus, *pt) + : pt->PdfLightOrigin(integrator.infiniteLights, *ptMinus, + lightSampler)}; + + // Update reverse density of vertex $\pt{}_{t-2}$ + ScopedAssignment a5; + if (ptMinus) + a5 = {&ptMinus->pdfRev, s > 0 ? pt->PDF(integrator, qs, *ptMinus) + : pt->PdfLight(integrator, *ptMinus)}; + + // Update reverse density of vertices $\pq{}_{s-1}$ and $\pq{}_{s-2}$ + ScopedAssignment a6; + if (qs) + a6 = {&qs->pdfRev, pt->PDF(integrator, ptMinus, *qs)}; + ScopedAssignment a7; + if (qsMinus) + a7 = {&qsMinus->pdfRev, qs->PDF(integrator, pt, *qsMinus)}; + + // Consider hypothetical connection strategies along the camera subpath + Float ri = 1; + for (int i = t - 1; i > 0; --i) { + ri *= remap0(cameraVertices[i].pdfRev) / remap0(cameraVertices[i].pdfFwd); + if (!cameraVertices[i].delta && !cameraVertices[i - 1].delta) + sumRi += ri; + } + + // Consider hypothetical connection strategies along the light subpath + ri = 1; + for (int i = s - 1; i >= 0; --i) { + ri *= remap0(lightVertices[i].pdfRev) / remap0(lightVertices[i].pdfFwd); + bool deltaLightvertex = + i > 0 ? lightVertices[i - 1].delta : lightVertices[0].IsDeltaLight(); + if (!lightVertices[i].delta && !deltaLightvertex) + sumRi += ri; + } + + return 1 / (1 + sumRi); +} + +Float InfiniteLightDensity(const std::vector &infiniteLights, + LightSamplerHandle lightSampler, const Vector3f &w) { + Float pdf = 0; + for (const auto &light : infiniteLights) + pdf += light.PDF_Li(Interaction(), -w) * lightSampler.PDF(light); + return pdf; +} + +// BDPT Method Definitions +void BDPTIntegrator::Render() { + // Allocate buffers for debug visualization + if (visualizeStrategies || visualizeWeights) { + const int bufferCount = (1 + maxDepth) * (6 + maxDepth) / 2; + weightFilms.resize(bufferCount); + for (int depth = 0; depth <= maxDepth; ++depth) { + for (int s = 0; s <= depth + 2; ++s) { + int t = depth + 2 - s; + if (t == 0 || (s == 1 && t == 1)) + continue; + + std::string filename = + StringPrintf("bdpt_d%02i_s%02i_t%02i.exr", depth, s, t); + + // FIXME: leaks + weightFilms[BufferIndex(s, t)] = new RGBFilm( + camera.GetFilm().FullResolution(), + Bounds2i(Point2i(0, 0), camera.GetFilm().FullResolution()), + new BoxFilter, // FIXME: leaks + camera.GetFilm().Diagonal() * 1000, filename, 1.f, + RGBColorSpace::sRGB); + } + } + } + + RayIntegrator::Render(); + + // Write buffers for debug visualization + if (visualizeStrategies || visualizeWeights) { + const Float invSampleCount = 1.0f / samplerPrototype.SamplesPerPixel(); + for (size_t i = 0; i < weightFilms.size(); ++i) { + ImageMetadata metadata; + if (weightFilms[i]) + weightFilms[i].WriteImage(metadata, invSampleCount); + } + weightFilms.clear(); + } +} + +SampledSpectrum BDPTIntegrator::Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const { + // Trace the camera and light subpaths + Vertex *cameraVertices = scratchBuffer.Alloc(maxDepth + 2); + int nCamera = GenerateCameraSubpath(*this, ray, lambda, sampler, scratchBuffer, + maxDepth + 2, camera, cameraVertices, regularize); + Vertex *lightVertices = scratchBuffer.Alloc(maxDepth + 1); + int nLight = GenerateLightSubpath(*this, lambda, sampler, camera, scratchBuffer, + maxDepth + 1, cameraVertices[0].time(), + lightSampler, lightVertices, regularize); + + SampledSpectrum L(0.f); + // Execute all BDPT connection strategies + for (int t = 1; t <= nCamera; ++t) { + for (int s = 0; s <= nLight; ++s) { + int depth = t + s - 2; + if ((s == 1 && t == 1) || depth < 0 || depth > maxDepth) + continue; + // Execute the $(s, t)$ connection strategy and update _L_ + pstd::optional pFilmNew; + Float misWeight = 0.f; + SampledSpectrum Lpath = + ConnectBDPT(*this, lambda, lightVertices, cameraVertices, s, t, + lightSampler, camera, sampler, &pFilmNew, &misWeight); + VLOG(2, "Connect bdpt s: %d, t: %d, Lpath: %s, misWeight: %f", s, t, Lpath, + misWeight); + if (visualizeStrategies || visualizeWeights) { + SampledSpectrum value; + if (visualizeStrategies) + value = misWeight == 0 ? SampledSpectrum(0.) : Lpath / misWeight; + if (visualizeWeights) + value = Lpath; + CHECK(pFilmNew.has_value()); + weightFilms[BufferIndex(s, t)].AddSplat(*pFilmNew, value, lambda); + } + if (t != 1) + L += Lpath; + else if (Lpath) { + CHECK(pFilmNew.has_value()); + camera.GetFilm().AddSplat(*pFilmNew, Lpath, lambda); + } + } + } + + return L; +} + +SampledSpectrum ConnectBDPT(const Integrator &integrator, SampledWavelengths &lambda, + Vertex *lightVertices, Vertex *cameraVertices, int s, int t, + LightSamplerHandle lightSampler, CameraHandle camera, + SamplerHandle sampler, pstd::optional *pRaster, + Float *misWeightPtr) { + SampledSpectrum L(0.f); + // Ignore invalid connections related to infinite area lights + if (t > 1 && s != 0 && cameraVertices[t - 1].type == VertexType::Light) + return SampledSpectrum(0.f); + + // Perform connection and write contribution to _L_ + Vertex sampled; + if (s == 0) { + // Interpret the camera subpath as a complete path + const Vertex &pt = cameraVertices[t - 1]; + if (pt.IsLight()) + L = pt.Le(integrator.infiniteLights, cameraVertices[t - 2], lambda) * pt.beta; + DCHECK(!L.HasNaNs()); + + } else if (t == 1) { + // Sample a point on the camera and connect it to the light subpath + const Vertex &qs = lightVertices[s - 1]; + if (qs.IsConnectible()) { + pstd::optional cs = + camera.SampleWi(qs.GetInteraction(), sampler.Get2D(), lambda); + if (cs) { + *pRaster = cs->pRaster; + // Initialize dynamically sampled vertex and _L_ for $t=1$ case + sampled = Vertex::CreateCamera(camera, cs->pLens, cs->Wi / cs->pdf); + L = qs.beta * qs.f(sampled, TransportMode::Importance) * sampled.beta; + if (qs.IsOnSurface()) + L *= AbsDot(cs->wi, qs.ns()); + DCHECK(!L.HasNaNs()); + // Only check visibility after we know that the path would + // make a non-zero contribution. + if (L) { + RNG rng(Hash(cs->pRaster), Hash(cs->pLens)); + L *= integrator.Tr(cs->pRef, cs->pLens, lambda, rng); + } + } + } + + } else if (s == 1) { + // Sample a point on a light and connect it to the camera subpath + const Vertex &pt = cameraVertices[t - 1]; + if (pt.IsConnectible()) { + pstd::optional sampledLight = + lightSampler.Sample(sampler.Get1D()); + + if (sampledLight) { + LightHandle light = sampledLight->light; + Float lightPDF = sampledLight->pdf; + + LightSampleContext ctx; + if (pt.IsOnSurface()) + ctx = LightSampleContext(pt.GetInteraction().AsSurface()); + else + ctx = LightSampleContext(pt.GetInteraction()); + LightLiSample lightWeight = light.SampleLi(ctx, sampler.Get2D(), lambda); + if (lightWeight) { + EndpointInteraction ei(lightWeight.pLight, light); + sampled = Vertex::CreateLight( + ei, lightWeight.L / (lightWeight.pdf * lightPDF), 0); + sampled.pdfFwd = sampled.PdfLightOrigin(integrator.infiniteLights, pt, + lightSampler); + L = pt.beta * pt.f(sampled, TransportMode::Radiance) * sampled.beta; + if (pt.IsOnSurface()) + L *= AbsDot(lightWeight.wi, pt.ns()); + // Only check visibility if the path would carry radiance. + if (L) { + RNG rng(Hash(ctx.p()), Hash(ctx.n)); + L *= integrator.Tr(pt.GetInteraction(), lightWeight.pLight, + lambda, rng); + } + } + } + } + + } else { + // Handle all other bidirectional connection cases + const Vertex &qs = lightVertices[s - 1], &pt = cameraVertices[t - 1]; + if (qs.IsConnectible() && pt.IsConnectible()) { + L = qs.beta * qs.f(pt, TransportMode::Importance) * + pt.f(qs, TransportMode::Radiance) * pt.beta; + VLOG(2, + "General connect s: %d, t: %d, qs: %s, pt: %s, qs.f(pt): %s, " + "pt.f(qs): %s, G: %s, dist^2: %f", + s, t, qs, pt, qs.f(pt, TransportMode::Importance), + pt.f(qs, TransportMode::Radiance), + G(integrator, sampler, qs, pt, lambda), DistanceSquared(qs.p(), pt.p())); + if (L) + L *= G(integrator, sampler, qs, pt, lambda); + } + } + + ++totalPaths; + if (!L) + ++zeroRadiancePaths; + ReportValue(pathLength, s + t - 2); + // Compute MIS weight for connection strategy + Float misWeight = L ? MISWeight(integrator, lightVertices, cameraVertices, sampled, s, + t, lightSampler) + : 0.f; + VLOG(2, "MIS weight for (s,t) = (%d, %d) connection: %f", s, t, misWeight); + DCHECK(!std::isnan(misWeight)); + L *= misWeight; + if (misWeightPtr != nullptr) + *misWeightPtr = misWeight; + + return L; +} + +std::string BDPTIntegrator::ToString() const { + return StringPrintf("[ BDPTIntegrator maxDepth: %d visualizeStrategies: %s " + "visualizeWeights: %s lightSampleStrategy: %s regularize: %s " + "lightSampler: %s ]", + maxDepth, visualizeStrategies, visualizeWeights, + lightSampleStrategy, regularize, lightSampler); +} + +std::unique_ptr BDPTIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + bool visualizeStrategies = parameters.GetOneBool("visualizestrategies", false); + bool visualizeWeights = parameters.GetOneBool("visualizeweights", false); + + if ((visualizeStrategies || visualizeWeights) && maxDepth > 5) { + Warning(loc, "visualizestrategies/visualizeweights was enabled, limiting " + "maxdepth to 5"); + maxDepth = 5; + } + + std::string lightStrategy = parameters.GetOneString("lightsampler", "power"); + bool regularize = parameters.GetOneBool("regularize", false); + return std::make_unique(camera, sampler, aggregate, lights, maxDepth, + visualizeStrategies, visualizeWeights, + lightStrategy, regularize); +} + +STAT_PERCENT("Integrator/Acceptance rate", acceptedMutations, totalMutations); + +// MLTIntegrator Method Definitions +SampledSpectrum MLTIntegrator::L(ScratchBuffer &scratchBuffer, MLTSampler &sampler, + int depth, Point2f *pRaster, + SampledWavelengths *lambda) { + sampler.StartStream(cameraStreamIndex); + // Determine the number of available strategies and pick a specific one + int s, t, nStrategies; + if (depth == 0) { + nStrategies = 1; + s = 0; + t = 2; + } else { + nStrategies = depth + 2; + s = std::min(sampler.Get1D() * nStrategies, nStrategies - 1); + t = nStrategies - s; + } + + // Sample wavelengths for MLT path + if (Options->disableWavelengthJitter) + *lambda = camera.GetFilm().SampleWavelengths(0.5); + else + *lambda = camera.GetFilm().SampleWavelengths(sampler.Get1D()); + + // Generate a camera subpath with exactly _t_ vertices + Vertex *cameraVertices = scratchBuffer.Alloc(t); + Bounds2f sampleBounds = camera.GetFilm().SampleBounds(); + *pRaster = sampleBounds.Lerp(sampler.Get2D()); + CameraSample cameraSample; + cameraSample.pFilm = *pRaster; + cameraSample.time = sampler.Get1D(); + cameraSample.pLens = sampler.Get2D(); + pstd::optional crd = + camera.GenerateRayDifferential(cameraSample, *lambda); + if (!crd || !crd->weight) + return SampledSpectrum(0.f); + Float rayDiffScale = + std::max(.125, 1 / std::sqrt((Float)sampler.SamplesPerPixel())); + crd->ray.ScaleDifferentials(rayDiffScale); + + if (GenerateCameraSubpath(*this, crd->ray, *lambda, &sampler, scratchBuffer, t, + camera, cameraVertices, regularize) != t) + return SampledSpectrum(0.f); + + // Generate a light subpath with exactly _s_ vertices + sampler.StartStream(lightStreamIndex); + Vertex *lightVertices = scratchBuffer.Alloc(s); + if (GenerateLightSubpath(*this, *lambda, &sampler, camera, scratchBuffer, s, + cameraVertices[0].time(), lightSampler, lightVertices, + regularize) != s) + return SampledSpectrum(0.f); + + // Execute connection strategy and return the radiance estimate + sampler.StartStream(connectionStreamIndex); + pstd::optional pRasterNew; + SampledSpectrum L = ConnectBDPT(*this, *lambda, lightVertices, cameraVertices, s, t, + lightSampler, camera, &sampler, &pRasterNew) * + nStrategies; + if (pRasterNew.has_value()) + *pRaster = *pRasterNew; + return L; +} + +void MLTIntegrator::Render() { + // Handle statistics and debugstart for MLTIntegrator + if (Options->recordPixelStatistics) + StatsEnablePixelStats(camera.GetFilm().PixelBounds(), + RemoveExtension(camera.GetFilm().GetFilename())); + + if (!Options->debugStart.empty()) { + std::vector c = SplitString(Options->debugStart, ','); + if (c.empty()) + ErrorExit("Didn't find comma-separated values after --debugstart: %s", + Options->debugStart); + + int depth; + if (!Atoi(c[0], &depth)) + ErrorExit("Unable to decode first --debugstart value: %s", c[0]); + + pstd::span span = pstd::MakeSpan(c); + span.remove_prefix(1); + DebugMLTSampler sampler = DebugMLTSampler::Create(span, nSampleStreams); + + Point2f pRaster; + SampledWavelengths lambda; + ScratchBuffer scratchBuffer(65536); + (void)L(scratchBuffer, sampler, depth, &pRaster, &lambda); + return; + } + + thread_local MLTSampler *threadSampler = nullptr; + thread_local int threadDepth; + CheckCallbackScope _([&]() -> std::string { + return StringPrintf("Rendering failed. Debug with --debugstart %d,%s\"\n", + threadDepth, threadSampler->DumpState()); + }); + + // Generate bootstrap samples and compute normalization constant $b$ + Timer timer; + int nBootstrapSamples = nBootstrap * (maxDepth + 1); + std::vector bootstrapWeights(nBootstrapSamples, 0); + if (!lights.empty()) { + // Allocate scratch buffers for bootstrap samples + std::vector bootstrapScratchBuffers; + for (int i = 0; i < MaxThreadIndex(); ++i) + bootstrapScratchBuffers.push_back(ScratchBuffer(65536)); + + ProgressReporter progress(nBootstrap, "Generating bootstrap paths", + Options->quiet); + ParallelFor(0, nBootstrap, [&](int64_t start, int64_t end) { + ScratchBuffer &scratchBuffer = bootstrapScratchBuffers[ThreadIndex]; + for (int64_t i = start; i < end; ++i) { + // Generate _i_th bootstrap sample + for (int depth = 0; depth <= maxDepth; ++depth) { + int rngIndex = i * (maxDepth + 1) + depth; + MLTSampler sampler(mutationsPerPixel, rngIndex, sigma, + largeStepProbability, nSampleStreams); + threadSampler = &sampler; + threadDepth = depth; + + Point2f pRaster; + SampledWavelengths lambda; + bootstrapWeights[rngIndex] = + L(scratchBuffer, sampler, depth, &pRaster, &lambda).Average(); + + scratchBuffer.Reset(); + } + } + progress.Update(end - start); + }); + progress.Done(); + } + AliasTable bootstrapTable(bootstrapWeights); + Float b = std::accumulate(bootstrapWeights.begin(), bootstrapWeights.end(), 0.) / + bootstrapWeights.size() * (maxDepth + 1); + + // Set up connection to display server, if enabled + if (!Options->displayServer.empty()) { + FilmHandle film = camera.GetFilm(); + Bounds2i pixelBounds = film.PixelBounds(); + DisplayDynamic(film.GetFilename(), Point2i(pixelBounds.Diagonal()), + {"R", "G", "B"}, + [=](Bounds2i b, pstd::span> displayValue) { + int index = 0; + for (Point2i p : b) { + RGB rgb = film.GetPixelRGB(pixelBounds.pMin + p); + for (int c = 0; c < 3; ++c) + displayValue[c][index] = rgb[c]; + ++index; + } + }); + } + + // Run _nChains_ Markov chains in parallel + FilmHandle film = camera.GetFilm(); + int64_t nTotalMutations = + (int64_t)mutationsPerPixel * (int64_t)film.SampleBounds().Area(); + if (!lights.empty()) { + // Allocate scratch buffers for MLT Markov chains + std::vector threadScratchBuffers; + for (int i = 0; i < MaxThreadIndex(); ++i) + threadScratchBuffers.push_back(ScratchBuffer(65536)); + + ProgressReporter progress(nChains, "Rendering", Options->quiet); + ParallelFor(0, nChains, [&](int i) { + int64_t nChainMutations = + std::min((i + 1) * nTotalMutations / nChains, nTotalMutations) - + i * nTotalMutations / nChains; + // Follow {i}th Markov chain for _nChainMutations_ + ScratchBuffer &scratchBuffer = threadScratchBuffers[ThreadIndex]; + // Select initial state from the set of bootstrap samples + RNG rng(i); + int bootstrapIndex = bootstrapTable.Sample(rng.Uniform()); + int depth = bootstrapIndex % (maxDepth + 1); + threadDepth = depth; + + // Initialize local variables for selected state + MLTSampler sampler(mutationsPerPixel, bootstrapIndex, sigma, + largeStepProbability, nSampleStreams); + threadSampler = &sampler; + Point2f pCurrent; + SampledWavelengths lambdaCurrent; + SampledSpectrum LCurrent = + L(scratchBuffer, sampler, depth, &pCurrent, &lambdaCurrent); + + // Run the Markov chain for _nChainMutations_ steps + for (int64_t j = 0; j < nChainMutations; ++j) { + StatsReportPixelStart(Point2i(pCurrent)); + sampler.StartIteration(); + Point2f pProposed; + SampledWavelengths lambdaProposed; + SampledSpectrum LProposed = + L(scratchBuffer, sampler, depth, &pProposed, &lambdaProposed); + // Compute acceptance probability for proposed sample + Float accept = + std::min(1, LProposed.Average() / LCurrent.Average()); + + // Splat both current and proposed samples to _film_ + if (accept > 0) + film.AddSplat(pProposed, LProposed * accept / LProposed.Average(), + lambdaProposed); + film.AddSplat(pCurrent, LCurrent * (1 - accept) / LCurrent.Average(), + lambdaCurrent); + + // Accept or reject the proposal + if (rng.Uniform() < accept) { + StatsReportPixelEnd(Point2i(pCurrent)); + StatsReportPixelStart(Point2i(pProposed)); + pCurrent = pProposed; + LCurrent = LProposed; + lambdaCurrent = lambdaProposed; + sampler.Accept(); + ++acceptedMutations; + } else + sampler.Reject(); + + ++totalMutations; + scratchBuffer.Reset(); + StatsReportPixelEnd(Point2i(pCurrent)); + } + + progress.Update(1); + }); + progress.Done(); + } + + // Store final image computed with MLT + ImageMetadata metadata; + metadata.renderTimeSeconds = timer.ElapsedSeconds(); + camera.InitMetadata(&metadata); + camera.GetFilm().WriteImage(metadata, b / mutationsPerPixel); +} + +std::string MLTIntegrator::ToString() const { + return StringPrintf("[ MLTIntegrator camera: %s maxDepth: %d nBootstrap: %d " + "nChains: %d mutationsPerPixel: %d sigma: %f " + "largeStepProbability: %f lightSampler: %s regularize: %s ]", + camera, maxDepth, nBootstrap, nChains, mutationsPerPixel, sigma, + largeStepProbability, lightSampler, regularize); +} + +std::unique_ptr MLTIntegrator::Create( + const ParameterDictionary ¶meters, CameraHandle camera, PrimitiveHandle aggregate, + std::vector lights, const FileLoc *loc) { + int maxDepth = parameters.GetOneInt("maxdepth", 5); + int nBootstrap = parameters.GetOneInt("bootstrapsamples", 100000); + int64_t nChains = parameters.GetOneInt("chains", 1000); + int mutationsPerPixel = parameters.GetOneInt("mutationsperpixel", 100); + Float largeStepProbability = parameters.GetOneFloat("largestepprobability", 0.3f); + Float sigma = parameters.GetOneFloat("sigma", .01f); + if (Options->quickRender) { + mutationsPerPixel = std::max(1, mutationsPerPixel / 16); + nBootstrap = std::max(1, nBootstrap / 16); + } + bool regularize = parameters.GetOneBool("regularize", false); + return std::make_unique(camera, aggregate, lights, maxDepth, + nBootstrap, nChains, mutationsPerPixel, sigma, + largeStepProbability, regularize); +} + +STAT_RATIO("Stochastic Progressive Photon Mapping/Visible points checked per photon " + "intersection", + visiblePointsChecked, totalPhotonSurfaceInteractions); +STAT_COUNTER("Stochastic Progressive Photon Mapping/Photon paths followed", photonPaths); +STAT_INT_DISTRIBUTION( + "Stochastic Progressive Photon Mapping/Grid cells per visible point", + gridCellsPerVisiblePoint); +STAT_MEMORY_COUNTER("Memory/SPPM Pixels", pixelMemoryBytes); +STAT_MEMORY_COUNTER("Memory/SPPM BSDF and Grid Memory", sppmMemoryArenaBytes); + +// SPPMPixel Definition +struct SPPMPixel { + // SPPMPixel Public Members + Float radius = 0; + RGB Ld; + struct VisiblePoint { + // VisiblePoint Public Methods + VisiblePoint() = default; + VisiblePoint(const Point3f &p, const Vector3f &wo, const BSDF &bsdf, + const SampledSpectrum &beta) + : p(p), wo(wo), bsdf(bsdf), beta(beta) {} + Point3f p; + Vector3f wo; + BSDF bsdf; + SampledSpectrum beta; + } vp; + AtomicFloat Phi[NSpectrumSamples]; + std::atomic M{0}; + Float N = 0; + RGB tau; +}; + +// SPPMPixelListNode Definition +struct SPPMPixelListNode { + SPPMPixel *pixel; + SPPMPixelListNode *next; +}; + +// SPPM Utility Functions +static bool ToGrid(const Point3f &p, const Bounds3f &bounds, const int gridRes[3], + Point3i *pi) { + bool inBounds = true; + Vector3f pg = bounds.Offset(p); + for (int i = 0; i < 3; ++i) { + (*pi)[i] = (int)(gridRes[i] * pg[i]); + inBounds &= ((*pi)[i] >= 0 && (*pi)[i] < gridRes[i]); + (*pi)[i] = Clamp((*pi)[i], 0, gridRes[i] - 1); + } + return inBounds; +} + +inline unsigned int hash(const Point3i &p, int hashSize) { + return Hash(p.x, p.y, p.z) % hashSize; +} + +// SPPM Method Definitions +void SPPMIntegrator::Render() { + // Initialize local variables for _SPPMIntegrator::Render()_ + if (Options->recordPixelStatistics) + StatsEnablePixelStats(camera.GetFilm().PixelBounds(), + RemoveExtension(camera.GetFilm().GetFilename())); + // Allocate samplers for SPPM rendering + std::unique_ptr> digitPermutations( + ComputeRadicalInversePermutations(digitPermutationsSeed)); + HaltonSampler sampler(nIterations, camera.GetFilm().FullResolution()); + std::vector tileSamplers = + sampler.Clone(MaxThreadIndex(), Allocator()); + + // Initialize _pixelBounds_ and _pixels_ array for SPPM + Bounds2i pixelBounds = camera.GetFilm().PixelBounds(); + CHECK(!pixelBounds.IsEmpty()); + int nPixels = pixelBounds.Area(); + Array2D pixels(pixelBounds); + for (SPPMPixel &p : pixels) + p.radius = initialSearchRadius; + + const Float invSqrtSPP = 1.f / std::sqrt(nIterations); + pixelMemoryBytes += pixels.size() * sizeof(SPPMPixel); + // Create light samplers for SPPM rendering + BVHLightSampler directLightSampler(lights, Allocator()); + PowerLightSampler shootLightSampler(lights, Allocator()); + + ProgressReporter progress(2 * nIterations, "Rendering", Options->quiet); + std::vector perThreadScratchBuffers; + for (int i = 0; i < MaxThreadIndex(); ++i) + // TODO: size this + perThreadScratchBuffers.push_back(ScratchBuffer(nPixels * 1024)); + + for (int iter = 0; iter < nIterations; ++iter) { + // Generate SPPM visible points + // Sample wavelengths for SPPM pass + SampledWavelengths lambda = + Options->disableWavelengthJitter + ? camera.GetFilm().SampleWavelengths(0.5) + : camera.GetFilm().SampleWavelengths(RadicalInverse(1, iter)); + + { + ParallelFor2D(pixelBounds, [&](Bounds2i tileBounds) { + ScratchBuffer &scratchBuffer = perThreadScratchBuffers[ThreadIndex]; + SamplerHandle &tileSampler = tileSamplers[ThreadIndex]; + // Follow camera paths for _tile_ in image for SPPM + for (Point2i pPixel : tileBounds) { + // Prepare _tileSampler_ for _pPixel_ + tileSampler.StartPixelSample(pPixel, iter); + + // Generate camera ray for pixel for SPPM + FilterHandle filter = camera.GetFilm().GetFilter(); + CameraSample cameraSample = + GetCameraSample(tileSampler, pPixel, filter); + pstd::optional crd = + camera.GenerateRayDifferential(cameraSample, lambda); + if (!crd || !crd->weight) + continue; + SampledSpectrum beta = crd->weight; + RayDifferential &ray = crd->ray; + if (!Options->disablePixelJitter) + ray.ScaleDifferentials(invSqrtSPP); + + // Follow camera ray path until a visible point is created + SPPMPixel &pixel = pixels[pPixel]; + Float etaScale = 1; + bool specularBounce = false, anyNonSpecularBounces = false; + for (int depth = 0; depth < maxDepth; ++depth) { + ++totalPhotonSurfaceInteractions; + pstd::optional si = Intersect(ray); + if (!si) { + // Accumulate light contributions for ray with no intersection + if (depth == 0) { + for (const auto &light : infiniteLights) { + SampledSpectrum L = beta * light.Le(ray, lambda); + pixel.Ld += L.ToRGB(lambda, *colorSpace); + } + } + + break; + } + // Process SPPM camera ray intersection + // Compute BSDF at SPPM camera ray intersection + SurfaceInteraction &isect = si->intr; + BSDF bsdf = + isect.GetBSDF(ray, lambda, camera, scratchBuffer, &sampler); + if (!bsdf) { + isect.SkipIntersection(&ray, si->tHit); + --depth; + continue; + } + + // Possibly regularize the BSDF + if (regularize && anyNonSpecularBounces) { + ++regularizedBSDFs; + bsdf.Regularize(); + } + + ++totalBSDFs; + // Accumulate direct illumination at SPPM camera ray intersection + Vector3f wo = -ray.d; + if (depth == 0 || specularBounce) { + SampledSpectrum L = beta * isect.Le(wo, lambda); + pixel.Ld += L.ToRGB(lambda, *colorSpace); + } + SampledSpectrum Ld = SampleLd(isect, bsdf, lambda, tileSampler, + &directLightSampler); + pixel.Ld += (beta * Ld).ToRGB(lambda, *colorSpace); + + // Possibly create visible point and end camera path + if (bsdf.IsDiffuse() || + (bsdf.IsGlossy() && depth == maxDepth - 1)) { + pixel.vp = {isect.p(), wo, bsdf, beta}; + break; + } + + // Spawn ray from SPPM camera path vertex + if (depth < maxDepth - 1) { + Float u = tileSampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(wo, u, tileSampler.Get2D()); + if (!bs) + break; + specularBounce = bs.IsSpecular(); + anyNonSpecularBounces |= !bs.IsSpecular(); + if (bs.IsTransmission()) + etaScale *= Sqr(bsdf.eta); + + beta *= bs.f * AbsDot(bs.wi, isect.shading.n) / bs.pdf; + SampledSpectrum rrBeta = beta * etaScale; + if (rrBeta.MaxComponentValue() < 1) { + Float q = + std::max(.05f, 1 - rrBeta.MaxComponentValue()); + if (tileSampler.Get1D() < q) + break; + beta /= 1 - q; + } + ray = isect.SpawnRay(ray, bsdf, bs.wi, bs.flags); + } + } + } + }); + } + progress.Update(); + // Create grid of all SPPM visible points + // Allocate grid for SPPM visible points + const int hashSize = NextPrime(nPixels); + std::vector> grid(hashSize); + + // Compute grid bounds for SPPM visible points + Bounds3f gridBounds; + Float maxRadius = 0.; + for (const SPPMPixel &pixel : pixels) { + if (!pixel.vp.beta) + continue; + Bounds3f vpBound = Expand(Bounds3f(pixel.vp.p), pixel.radius); + gridBounds = Union(gridBounds, vpBound); + maxRadius = std::max(maxRadius, pixel.radius); + } + + // Compute resolution of SPPM grid in each dimension + int gridRes[3]; + Vector3f diag = gridBounds.Diagonal(); + Float maxDiag = MaxComponentValue(diag); + int baseGridRes = (int)(maxDiag / maxRadius); + for (int i = 0; i < 3; ++i) + gridRes[i] = std::max(baseGridRes * diag[i] / maxDiag, 1); + + // Add visible points to SPPM grid + ParallelFor2D(pixelBounds, [&](Bounds2i tileBounds) { + ScratchBuffer &scratchBuffer = perThreadScratchBuffers[ThreadIndex]; + for (Point2i pPixel : tileBounds) { + SPPMPixel &pixel = pixels[pPixel]; + if (pixel.vp.beta) { + // Add pixel's visible point to applicable grid cells + Float radius = pixel.radius; + Point3i pMin, pMax; + ToGrid(pixel.vp.p - Vector3f(radius, radius, radius), gridBounds, + gridRes, &pMin); + ToGrid(pixel.vp.p + Vector3f(radius, radius, radius), gridBounds, + gridRes, &pMax); + for (int z = pMin.z; z <= pMax.z; ++z) + for (int y = pMin.y; y <= pMax.y; ++y) + for (int x = pMin.x; x <= pMax.x; ++x) { + // Add visible point to grid cell $(x, y, z)$ + int h = hash(Point3i(x, y, z), hashSize); + SPPMPixelListNode *node = + scratchBuffer.Alloc(); + node->pixel = &pixel; + + // Atomically add _node_ to the start of _grid[h]_'s + // linked list + node->next = grid[h]; + while (!grid[h].compare_exchange_weak(node->next, node)) + ; + } + ReportValue(gridCellsPerVisiblePoint, (1 + pMax.x - pMin.x) * + (1 + pMax.y - pMin.y) * + (1 + pMax.z - pMin.z)); + } + } + }); + + // Trace photons and accumulate contributions + // Create per-thread scratch buffers for photon shooting + std::vector photonShootScratchBuffers; + for (int i = 0; i < MaxThreadIndex(); ++i) + photonShootScratchBuffers.push_back(ScratchBuffer(65536)); + + ParallelFor(0, photonsPerIteration, [&](int64_t start, int64_t end) { + ScratchBuffer &scratchBuffer = photonShootScratchBuffers[ThreadIndex]; + for (int64_t photonIndex = start; photonIndex < end; ++photonIndex) { + // Follow photon path for _photonIndex_ + // Define sampling lambda functions for photon shooting + uint64_t haltonIndex = + (uint64_t)iter * (uint64_t)photonsPerIteration + photonIndex; + int haltonDim = 0; + auto Sample1D = [&]() { + Float u = ScrambledRadicalInverse(haltonDim, haltonIndex, + (*digitPermutations)[haltonDim]); + ++haltonDim; + return u; + }; + auto Sample2D = [&]() { + Point2f u( + ScrambledRadicalInverse(haltonDim, haltonIndex, + (*digitPermutations)[haltonDim]), + ScrambledRadicalInverse(haltonDim + 1, haltonIndex, + (*digitPermutations)[haltonDim + 1])); + haltonDim += 2; + return u; + }; + + // Choose light to shoot photon from + pstd::optional sampledLight = + shootLightSampler.Sample(Sample1D()); + if (!sampledLight) + continue; + LightHandle light = sampledLight->light; + Float lightPDF = sampledLight->pdf; + + // Compute sample values for photon ray leaving light source + Point2f uLight0 = Sample2D(); + Point2f uLight1 = Sample2D(); + Float uLightTime = camera.SampleTime(Sample1D()); + + // Generate _photonRay_ from light source and initialize _beta_ + LightLeSample les = light.SampleLe(uLight0, uLight1, lambda, uLightTime); + if (!les || les.pdfPos == 0 || les.pdfDir == 0 || !les.L) + continue; + RayDifferential photonRay = RayDifferential(les.ray); + SampledSpectrum beta = (les.AbsCosTheta(photonRay.d) * les.L) / + (lightPDF * les.pdfPos * les.pdfDir); + if (!beta) + continue; + + // Follow photon path through scene and record intersections + SurfaceInteraction isect; + for (int depth = 0; depth < maxDepth; ++depth) { + pstd::optional si = Intersect(photonRay); + if (!si) + break; + SurfaceInteraction &isect = si->intr; + ++totalPhotonSurfaceInteractions; + if (depth > 0) { + // Add photon contribution to nearby visible points + Point3i photonGridIndex; + if (ToGrid(isect.p(), gridBounds, gridRes, &photonGridIndex)) { + int h = hash(photonGridIndex, hashSize); + // Add photon contribution to visible points in _grid[h]_ + for (SPPMPixelListNode *node = + grid[h].load(std::memory_order_relaxed); + node != nullptr; node = node->next) { + ++visiblePointsChecked; + SPPMPixel &pixel = *node->pixel; + Float radius = pixel.radius; + if (DistanceSquared(pixel.vp.p, isect.p()) > + radius * radius) + continue; + // Update _pixel_ $\Phi$ and $M$ for nearby photon + Vector3f wi = -photonRay.d; + SampledSpectrum Phi = + beta * pixel.vp.bsdf.f(pixel.vp.wo, wi); + for (int i = 0; i < NSpectrumSamples; ++i) + pixel.Phi[i].Add(Phi[i]); + ++pixel.M; + } + } + } + // Sample new photon ray direction + // Compute BSDF at photon intersection point + BSDF photonBSDF = + isect.GetBSDF(photonRay, lambda, camera, scratchBuffer, &sampler); + if (!photonBSDF) { + isect.SkipIntersection(&photonRay, si->tHit); + --depth; + continue; + } + + // Sample BSDF _fr_ and direction _wi_ for reflected photon + Vector3f wo = -photonRay.d; + Float bsdfSample = Sample1D(); + Point2f bsdfSample2 = Sample2D(); + BSDFSample bs = photonBSDF.Sample_f(wo, bsdfSample, bsdfSample2, + TransportMode::Importance); + if (!bs) + break; + SampledSpectrum bnew = + beta * bs.f * AbsDot(bs.wi, isect.shading.n) / bs.pdf; + + // Possibly terminate photon path with Russian roulette + Float q = std::max( + 0, 1 - (bnew.MaxComponentValue() / beta.MaxComponentValue())); + if (Sample1D() < q) + break; + beta = bnew / (1 - q); + + photonRay = RayDifferential(isect.SpawnRay(bs.wi)); + } + + scratchBuffer.Reset(); + } + }); + // CAN CUT THIS?? + for (ScratchBuffer &scratchBuffer : perThreadScratchBuffers) + scratchBuffer.Reset(); + + progress.Update(); + photonPaths += photonsPerIteration; + + // Update pixel values from this pass's photons + ParallelFor2D(pixelBounds, [&](Point2i pPixel) { + SPPMPixel &p = pixels[pPixel]; + int M = p.M.load(); + if (M > 0) { + // Update pixel photon count, search radius, and $\tau$ from photons + Float gamma = (Float)2 / (Float)3; + Float Nnew = p.N + gamma * M; + Float Rnew = p.radius * std::sqrt(Nnew / (p.N + M)); + SampledSpectrum Phi; + for (int j = 0; j < NSpectrumSamples; ++j) + Phi[j] = p.Phi[j]; + RGB rgb = (p.vp.beta * Phi).ToRGB(lambda, *colorSpace); + p.tau = (p.tau + rgb) * (Rnew * Rnew) / (p.radius * p.radius); + p.N = Nnew; + p.radius = Rnew; + + p.M = 0; + for (int j = 0; j < NSpectrumSamples; ++j) + p.Phi[j] = (Float)0; + } + // Reset _VisiblePoint_ in pixel + p.vp.beta = SampledSpectrum(0.); + p.vp.bsdf = BSDF(); + }); + + // Periodically store SPPM image in film and write image + if (iter + 1 == nIterations || (iter + 1 <= 64 && IsPowerOf2(iter + 1)) || + ((iter + 1) % 64 == 0)) { + uint64_t Np = (uint64_t)(iter + 1) * (uint64_t)photonsPerIteration; + Image rgbImage(PixelFormat::Float, Point2i(pixelBounds.Diagonal()), + {"R", "G", "B"}); + + ParallelFor2D(pixelBounds, [&](Point2i pPixel) { + // Compute radiance _L_ for SPPM pixel _pixel_ + const SPPMPixel &pixel = pixels[pPixel]; + RGB L = pixel.Ld / (iter + 1); + L += pixel.tau / (Np * Pi * pixel.radius * pixel.radius); + Point2i pImage = Point2i(pPixel - pixelBounds.pMin); + rgbImage.SetChannels(pImage, {L.r, L.g, L.b}); + }); + + ImageMetadata metadata; + metadata.renderTimeSeconds = progress.ElapsedSeconds(); + metadata.samplesPerPixel = iter + 1; + metadata.pixelBounds = pixelBounds; + metadata.fullResolution = camera.GetFilm().FullResolution(); + metadata.colorSpace = colorSpace; + camera.InitMetadata(&metadata); + rgbImage.Write(camera.GetFilm().GetFilename(), metadata); + + // Write SPPM radius image, if requested + if (getenv("SPPM_RADIUS") != nullptr) { + Image rimg(PixelFormat::Float, Point2i(pixelBounds.Diagonal()), + {"Radius"}); + Float minrad = 1e30f, maxrad = 0; + for (const SPPMPixel &p : pixels) { + minrad = std::min(minrad, p.radius); + maxrad = std::max(maxrad, p.radius); + } + fprintf(stderr, "iterations: %d (%.2f s) radius range: %f - %f\n", + iter + 1, progress.ElapsedSeconds(), minrad, maxrad); + int offset = 0; + for (Point2i pPixel : pixelBounds) { + const SPPMPixel &p = pixels[pPixel]; + Float v = 1.f - (p.radius - minrad) / (maxrad - minrad); + Point2i pImage = Point2i(pPixel - pixelBounds.pMin); + rimg.SetChannel(pImage, 0, v); + } + ImageMetadata metadata; + metadata.pixelBounds = pixelBounds; + metadata.fullResolution = camera.GetFilm().FullResolution(); + rimg.Write("sppm_radius.png", metadata); + } + } + } +#if 0 + // FIXME + sppmMemoryArenaBytes += std::accumulate(perThreadArenas.begin(), perThreadArenas.end(), + size_t(0), [&](size_t v, const MemoryArena &arena) { + return v + arena.BytesAllocated(); + }); +#endif + progress.Done(); +} + +SampledSpectrum SPPMIntegrator::SampleLd(const SurfaceInteraction &intr, const BSDF &bsdf, + SampledWavelengths &lambda, + SamplerHandle sampler, + LightSamplerHandle lightSampler) const { + // NOTE: share fragments from PathIntegrator::SampleLd here... + pstd::optional sampledLight = + lightSampler.Sample(intr, sampler.Get1D()); + + Point2f uLight = sampler.Get2D(); + + SampledSpectrum Ld(0.f); + + if (sampledLight) { + LightHandle light = sampledLight->light; + DCHECK(light != nullptr && sampledLight->pdf > 0); + + // Sample light source with multiple importance sampling + LightLiSample ls = + light.SampleLi(intr, uLight, lambda, LightSamplingMode::WithMIS); + if (ls && ls.L) { + // Evaluate BSDF for light sampling strategy + Vector3f wo = intr.wo, wi = ls.wi; + SampledSpectrum f = bsdf.f(wo, wi) * AbsDot(wi, intr.shading.n); + if (f) { + SampledSpectrum Li = ls.L; + if (Unoccluded(intr, ls.pLight)) { + // Add light's contribution to reflected radiance + Float lightPDF = sampledLight->pdf * ls.pdf; + if (IsDeltaLight(light.Type())) + Ld = f * Li / lightPDF; + else { + Float bsdfPDF = bsdf.PDF(wo, wi); + CHECK_RARE(1e-6, bsdf.SampledPDFIsProportional() == false && + bsdfPDF == 0); + Float weight = PowerHeuristic(1, lightPDF, 1, bsdfPDF); + Ld = f * Li * weight / lightPDF; + } + } + } + } + } + + Float uScattering = sampler.Get1D(); + BSDFSample bs = bsdf.Sample_f(intr.wo, uScattering, sampler.Get2D()); + if (!bs || !bs.f) + return Ld; + + Vector3f wi = bs.wi; + SampledSpectrum f = bs.f * AbsDot(wi, intr.shading.n); + + Ray ray = intr.SpawnRay(wi); + pstd::optional si = Intersect(ray); + if (si) { + SampledSpectrum Le = si->intr.Le(-ray.d, lambda); + if (Le) { + if (bs.IsSpecular()) + Ld += f * Le / bs.pdf; + else { + // Compute MIS pdf... + LightHandle areaLight(si->intr.areaLight); + Float lightPDF = lightSampler.PDF(intr, areaLight) * + areaLight.PDF_Li(intr, wi, LightSamplingMode::WithMIS); + Float bsdfPDF = + bsdf.SampledPDFIsProportional() ? bsdf.PDF(intr.wo, wi) : bs.pdf; + Float weight = PowerHeuristic(1, bsdfPDF, 1, lightPDF); + Ld += f * Le * weight / bs.pdf; + } + } + } else { + for (const auto &light : infiniteLights) { + SampledSpectrum Le = light.Le(ray, lambda); + if (bs.IsSpecular()) + Ld += f * Le / bs.pdf; + else { + // Compute MIS pdf... + Float lightPDF = lightSampler.PDF(intr, light) * + light.PDF_Li(intr, wi, LightSamplingMode::WithMIS); + Float bsdfPDF = + bsdf.SampledPDFIsProportional() ? bsdf.PDF(intr.wo, wi) : bs.pdf; + Float weight = PowerHeuristic(1, bsdfPDF, 1, lightPDF); + Ld += f * Le * weight / bs.pdf; + } + } + } + return Ld; +} + +std::string SPPMIntegrator::ToString() const { + return StringPrintf("[ SPPMIntegrator camera: %s initialSearchRadius: %f " + "nIterations: %d maxDepth: %d photonsPerIteration: %d " + "regularize: %s colorSpace: %s digitPermutations:(elided) ]", + camera, initialSearchRadius, nIterations, maxDepth, + photonsPerIteration, regularize, *colorSpace); +} + +std::unique_ptr SPPMIntegrator::Create( + const ParameterDictionary ¶meters, const RGBColorSpace *colorSpace, + CameraHandle camera, PrimitiveHandle aggregate, std::vector lights, + const FileLoc *loc) { + int nIterations = parameters.GetOneInt("iterations", 64); + int maxDepth = parameters.GetOneInt("maxdepth", 5); + int photonsPerIter = parameters.GetOneInt("photonsperiteration", -1); + Float radius = parameters.GetOneFloat("radius", 1.f); + if (Options->quickRender) + nIterations = std::max(1, nIterations / 16); + bool regularize = parameters.GetOneBool("regularize", false); + int seed = parameters.GetOneInt("seed", 0); + return std::make_unique(camera, aggregate, lights, nIterations, + photonsPerIter, maxDepth, radius, regularize, + seed, colorSpace); +} + +std::unique_ptr Integrator::Create( + const std::string &name, const ParameterDictionary ¶meters, CameraHandle camera, + SamplerHandle sampler, PrimitiveHandle aggregate, std::vector lights, + const RGBColorSpace *colorSpace, const FileLoc *loc) { + std::unique_ptr integrator; + if (name == "path") + integrator = + PathIntegrator::Create(parameters, camera, sampler, aggregate, lights, loc); + else if (name == "simplepath") + integrator = SimplePathIntegrator::Create(parameters, camera, sampler, aggregate, + lights, loc); + else if (name == "lightpath") + integrator = LightPathIntegrator::Create(parameters, camera, sampler, aggregate, + lights, loc); + else if (name == "simplevolpath") + integrator = SimpleVolPathIntegrator::Create(parameters, camera, sampler, + aggregate, lights, loc); + else if (name == "volpath") + integrator = VolPathIntegrator::Create(parameters, camera, sampler, aggregate, + lights, loc); + else if (name == "bdpt") + integrator = + BDPTIntegrator::Create(parameters, camera, sampler, aggregate, lights, loc); + else if (name == "mlt") + integrator = MLTIntegrator::Create(parameters, camera, aggregate, lights, loc); + else if (name == "ambientocclusion") + integrator = AOIntegrator::Create(parameters, &colorSpace->illuminant, camera, + sampler, aggregate, lights, loc); + else if (name == "randomwalk") + integrator = RandomWalkIntegrator::Create(parameters, camera, sampler, aggregate, + lights, loc); + else if (name == "sppm") + integrator = SPPMIntegrator::Create(parameters, colorSpace, camera, aggregate, + lights, loc); + else + ErrorExit(loc, "%s: integrator type unknown.", name); + + if (!integrator) + ErrorExit(loc, "%s: unable to create integrator.", name); + + parameters.ReportUnused(); + return integrator; +} + +} // namespace pbrt diff --git a/src/pbrt/cpu/integrators.h b/src/pbrt/cpu/integrators.h new file mode 100644 index 00000000..bb6975d8 --- /dev/null +++ b/src/pbrt/cpu/integrators.h @@ -0,0 +1,470 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_CPU_INTEGRATORS_H +#define PBRT_CPU_INTEGRATORS_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace pbrt { + +// Integrator Definition +class Integrator { + public: + // Integrator Public Methods + virtual ~Integrator(); + + static std::unique_ptr Create(const std::string &name, + const ParameterDictionary ¶meters, + CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, + std::vector lights, + const RGBColorSpace *colorSpace, + const FileLoc *loc); + + virtual std::string ToString() const = 0; + + const Bounds3f &SceneBounds() const { return sceneBounds; } + + pstd::optional Intersect(const Ray &ray, + Float tMax = Infinity) const; + bool IntersectP(const Ray &ray, Float tMax = Infinity) const; + + virtual void Render() = 0; + + bool Unoccluded(const Interaction &p0, const Interaction &p1) const { + return !IntersectP(p0.SpawnRayTo(p1), 1 - ShadowEpsilon); + } + + SampledSpectrum Tr(const Interaction &p0, const Interaction &p1, + const SampledWavelengths &lambda, RNG &rng) const; + + // Integrator Public Members + std::vector lights; + std::vector infiniteLights; + + protected: + // Integrator Private Methods + Integrator(PrimitiveHandle aggregate, std::vector l) + : lights(std::move(l)), aggregate(aggregate) { + // Integrator Constructor Implementation + if (aggregate) + sceneBounds = aggregate.Bounds(); + + for (auto &light : lights) { + light.Preprocess(sceneBounds); + if (light.Type() == LightType::Infinite) + infiniteLights.push_back(light); + } + } + + // Integrator Private Members + PrimitiveHandle aggregate; + Bounds3f sceneBounds; +}; + +// ImageTileIntegrator Definition +class ImageTileIntegrator : public Integrator { + public: + // ImageTileIntegrator Public Methods + ImageTileIntegrator(CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights) + : Integrator(aggregate, lights), camera(camera), samplerPrototype(sampler) {} + + void Render(); + + virtual void EvaluatePixelSample(const Point2i &pPixel, int sampleIndex, + SamplerHandle sampler, + ScratchBuffer &scratchBuffer) = 0; + + protected: + // ImageTileIntegrator Protected Members + CameraHandle camera; + SamplerHandle samplerPrototype; +}; + +// RayIntegrator Definition +class RayIntegrator : public ImageTileIntegrator { + public: + // RayIntegrator Public Methods + RayIntegrator(CameraHandle camera, SamplerHandle sampler, PrimitiveHandle aggregate, + std::vector lights) + : ImageTileIntegrator(camera, sampler, aggregate, lights) {} + + void EvaluatePixelSample(const Point2i &pPixel, int sampleIndex, + SamplerHandle sampler, ScratchBuffer &scratchBuffer) final; + + virtual SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface = nullptr) const = 0; +}; + +// RandomWalkIntegrator Definition +class RandomWalkIntegrator : public RayIntegrator { + public: + // RandomWalkIntegrator Public Methods + RandomWalkIntegrator(int maxDepth, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights) + : RayIntegrator(camera, sampler, aggregate, lights), maxDepth(maxDepth) {} + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface = nullptr) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + // RandomWalkIntegrator Private Methods + SampledSpectrum RandomWalk(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + int depth) const; + + // RandomWalkIntegrator Private Members + int maxDepth; +}; + +// SimplePathIntegrator Definition +class SimplePathIntegrator : public RayIntegrator { + public: + // SimplePathIntegrator Public Methods + SimplePathIntegrator(int maxDepth, bool sampleLights, bool sampleBSDF, + CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights); + + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + // SimplePathIntegrator Private Members + int maxDepth; + bool sampleLights, sampleBSDF; + UniformLightSampler lightSampler; +}; + +// PathIntegrator Definition +class PathIntegrator : public RayIntegrator { + public: + // PathIntegrator Public Methods + PathIntegrator(int maxDepth, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, + Float rrThreshold = 1, const std::string &lightSampleStrategy = "bvh", + bool regularize = false); + + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + // PathIntegrator Private Methods + SampledSpectrum SampleLd(const SurfaceInteraction &intr, const BSDF &bsdf, + SampledWavelengths &lambda, SamplerHandle sampler) const; + + // PathIntegrator Private Members + int maxDepth; + Float rrThreshold; + LightSamplerHandle lightSampler; + bool regularize; +}; + +// SimpleVolPathIntegrator Definition +class SimpleVolPathIntegrator : public RayIntegrator { + public: + // SimpleVolPathIntegrator Public Methods + SimpleVolPathIntegrator(int maxDepth, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights); + + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + int maxDepth; + bool sampleLights, samplePhase; +}; + +// VolPathIntegrator Definition +class VolPathIntegrator : public RayIntegrator { + public: + // VolPathIntegrator Public Methods + VolPathIntegrator(int maxDepth, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, + Float rrThreshold = 1, + const std::string &lightSampleStrategy = "bvh", + bool regularize = false) + : RayIntegrator(camera, sampler, aggregate, lights), + maxDepth(maxDepth), + rrThreshold(rrThreshold), + lightSampler( + LightSamplerHandle::Create(lightSampleStrategy, lights, Allocator())), + regularize(regularize) {} + + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + // VolPathIntegrator Private Methods + SampledSpectrum SampleLd(const Interaction &intr, const BSDF *bsdf, + SampledWavelengths &lambda, SamplerHandle sampler, + const SampledSpectrum &beta, + const SampledSpectrum &pathPDF) const; + + static void rescale(SampledSpectrum &beta, SampledSpectrum &pdfLight, + SampledSpectrum &pdfUni) { + if (beta.MaxComponentValue() > 0x1p24f || + pdfLight.MaxComponentValue() > 0x1p24f || + pdfUni.MaxComponentValue() > 0x1p24f) { + beta /= 0x1p24f; + pdfLight /= 0x1p24f; + pdfUni /= 0x1p24f; + } + } + + // VolPathIntegrator Private Members + const int maxDepth; + const Float rrThreshold; + LightSamplerHandle lightSampler; + bool regularize; +}; + +// AOIntegrator Definition +class AOIntegrator : public RayIntegrator { + public: + // AOIntegrator Public Methods + AOIntegrator(bool cosSample, Float maxDist, CameraHandle camera, + SamplerHandle sampler, PrimitiveHandle aggregate, + std::vector lights, SpectrumHandle illuminant); + + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, SpectrumHandle illuminant, + CameraHandle camera, SamplerHandle sampler, PrimitiveHandle aggregate, + std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + bool cosSample; + Float maxDist; + SpectrumHandle illuminant; +}; + +// LightPathIntegrator Definition +class LightPathIntegrator : public ImageTileIntegrator { + public: + // LightPathIntegrator Public Methods + LightPathIntegrator(int maxDepth, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights); + + void EvaluatePixelSample(const Point2i &pPixel, int sampleIndex, + SamplerHandle sampler, ScratchBuffer &scratchBuffer); + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + private: + // LightPathIntegrator Private Data + int maxDepth; + std::unique_ptr lightSampler; +}; + +// BDPTIntegrator Definition +struct Vertex; +class BDPTIntegrator : public RayIntegrator { + public: + // BDPTIntegrator Public Methods + BDPTIntegrator(CameraHandle camera, SamplerHandle sampler, PrimitiveHandle aggregate, + std::vector lights, int maxDepth, + bool visualizeStrategies, bool visualizeWeights, + const std::string &lightSampleStrategy = "power", + bool regularize = false) + : RayIntegrator(camera, sampler, aggregate, lights), + maxDepth(maxDepth), + visualizeStrategies(visualizeStrategies), + visualizeWeights(visualizeWeights), + lightSampleStrategy(lightSampleStrategy), + lightSampler(new PowerLightSampler(lights, Allocator())), + regularize(regularize) {} + + SampledSpectrum Li(RayDifferential ray, SampledWavelengths &lambda, + SamplerHandle sampler, ScratchBuffer &scratchBuffer, + VisibleSurface *visibleSurface) const; + + static std::unique_ptr Create( + const ParameterDictionary ¶meters, CameraHandle camera, SamplerHandle sampler, + PrimitiveHandle aggregate, std::vector lights, const FileLoc *loc); + + std::string ToString() const; + + void Render(); + + private: + // BDPTIntegrator Private Members + int maxDepth; + bool visualizeStrategies; + bool visualizeWeights; + std::string lightSampleStrategy; + bool regularize; + LightSamplerHandle lightSampler; + mutable std::vector weightFilms; +}; + +// MLTIntegrator Definition +class MLTSampler; + +class MLTIntegrator : public Integrator { + public: + // MLTIntegrator Public Methods + MLTIntegrator(CameraHandle camera, PrimitiveHandle aggregate, + std::vector lights, int maxDepth, int nBootstrap, + int nChains, int mutationsPerPixel, Float sigma, + Float largeStepProbability, bool regularize) + : Integrator(aggregate, lights), + lightSampler(new PowerLightSampler(lights, Allocator())), + camera(camera), + maxDepth(maxDepth), + nBootstrap(nBootstrap), + nChains(nChains), + mutationsPerPixel(mutationsPerPixel), + sigma(sigma), + largeStepProbability(largeStepProbability), + regularize(regularize) {} + + void Render(); + + static std::unique_ptr Create(const ParameterDictionary ¶meters, + CameraHandle camera, + PrimitiveHandle aggregate, + std::vector lights, + const FileLoc *loc); + + std::string ToString() const; + + private: + // MLTIntegrator Constants + static constexpr int cameraStreamIndex = 0; + static constexpr int lightStreamIndex = 1; + static constexpr int connectionStreamIndex = 2; + static constexpr int nSampleStreams = 3; + + // MLTIntegrator Private Methods + SampledSpectrum L(ScratchBuffer &scratchBuffer, MLTSampler &sampler, int k, + Point2f *pRaster, SampledWavelengths *lambda); + + // MLTIntegrator Private Members + LightSamplerHandle lightSampler; + bool regularize; + CameraHandle camera; + int maxDepth; + int nBootstrap; + int mutationsPerPixel; + Float sigma, largeStepProbability; + int nChains; +}; + +// SPPMIntegrator Definition +class SPPMIntegrator : public Integrator { + public: + // SPPMIntegrator Public Methods + SPPMIntegrator(CameraHandle camera, PrimitiveHandle aggregate, + std::vector lights, int nIterations, + int photonsPerIteration, int maxDepth, Float initialSearchRadius, + bool regularize, int seed, const RGBColorSpace *colorSpace) + : Integrator(aggregate, lights), + camera(camera), + initialSearchRadius(initialSearchRadius), + nIterations(nIterations), + maxDepth(maxDepth), + photonsPerIteration(photonsPerIteration > 0 + ? photonsPerIteration + : camera.GetFilm().PixelBounds().Area()), + regularize(regularize), + colorSpace(colorSpace), + digitPermutationsSeed(seed) {} + + static std::unique_ptr Create(const ParameterDictionary ¶meters, + const RGBColorSpace *colorSpace, + CameraHandle camera, + PrimitiveHandle aggregate, + std::vector lights, + const FileLoc *loc); + + std::string ToString() const; + + void Render(); + + private: + // SPPMIntegrator Private Methods + SampledSpectrum SampleLd(const SurfaceInteraction &intr, const BSDF &bsdf, + SampledWavelengths &lambda, SamplerHandle sampler, + LightSamplerHandle lightSampler) const; + + // SPPMIntegrator Private Members + CameraHandle camera; + Float initialSearchRadius; + int digitPermutationsSeed; + int nIterations; + bool regularize; + int maxDepth; + int photonsPerIteration; + const RGBColorSpace *colorSpace; +}; + +} // namespace pbrt + +#endif // PBRT_CPU_INTEGRATORS_H diff --git a/src/pbrt/cpu/integrators_test.cpp b/src/pbrt/cpu/integrators_test.cpp new file mode 100644 index 00000000..196627ca --- /dev/null +++ b/src/pbrt/cpu/integrators_test.cpp @@ -0,0 +1,421 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace pbrt; + +static std::string inTestDir(const std::string &path) { + return path; +} + +struct TestScene { + PrimitiveHandle aggregate; + std::vector lights; + std::string description; + float expected; +}; + +struct TestIntegrator { + Integrator *integrator; + const FilmHandle film; + std::string description; + TestScene scene; +}; + +void PrintTo(const TestIntegrator &tr, ::std::ostream *os) { + *os << tr.description; +} + +void CheckSceneAverage(const std::string &filename, float expected) { + pstd::optional im = Image::Read(filename); + ASSERT_TRUE((bool)im); + ASSERT_EQ(im->image.NChannels(), 3); + + float delta = .025; + float sum = 0; + + Image &image = im->image; + for (int t = 0; t < image.Resolution()[1]; ++t) + for (int s = 0; s < image.Resolution()[0]; ++s) + for (int c = 0; c < 3; ++c) + sum += image.GetChannel(Point2i(s, t), c); + int nPixels = image.Resolution().x * image.Resolution().y * 3; + EXPECT_NEAR(expected, sum / nPixels, delta); +} + +std::vector GetScenes() { + std::vector scenes; + + Allocator alloc; + static Transform identity; + { + // Unit sphere, Kd = 0.5, point light I = 3.1415 at center + // -> With GI, should have radiance of 1. + ShapeHandle sphere = new Sphere(&identity, &identity, + true /* reverse orientation */, 1, -1, 1, 360); + + static ConstantSpectrum cs(0.5); + SpectrumTextureHandle Kd = alloc.new_object(&cs); + FloatTextureHandle sigma = alloc.new_object(0.); + // FIXME: here and below, Materials leak... + MaterialHandle material = new DiffuseMaterial(Kd, sigma, nullptr); + + MediumInterface mediumInterface; + std::vector prims; + prims.push_back(PrimitiveHandle( + new GeometricPrimitive(sphere, material, nullptr, mediumInterface))); + PrimitiveHandle bvh(new BVHAccel(std::move(prims))); + + static ConstantSpectrum I(Pi); + std::vector lights; + lights.push_back(new PointLight(identity, MediumInterface(), &I, Allocator())); + + scenes.push_back({bvh, lights, "Sphere, 1 light, Kd = 0.5", 1.0}); + } + + { + // Unit sphere, Kd = 0.5, 4 point lights I = 3.1415/4 at center + // -> With GI, should have radiance of 1. + ShapeHandle sphere = new Sphere(&identity, &identity, + true /* reverse orientation */, 1, -1, 1, 360); + + static ConstantSpectrum cs(0.5); + SpectrumTextureHandle Kd = alloc.new_object(&cs); + FloatTextureHandle sigma = alloc.new_object(0.); + const MaterialHandle material = new DiffuseMaterial(Kd, sigma, nullptr); + + MediumInterface mediumInterface; + std::vector prims; + prims.push_back(PrimitiveHandle( + new GeometricPrimitive(sphere, material, nullptr, mediumInterface))); + PrimitiveHandle bvh(new BVHAccel(std::move(prims))); + + static ConstantSpectrum I(Pi / 4); + std::vector lights; + lights.push_back(new PointLight(identity, MediumInterface(), &I, Allocator())); + lights.push_back(new PointLight(identity, MediumInterface(), &I, Allocator())); + lights.push_back(new PointLight(identity, MediumInterface(), &I, Allocator())); + lights.push_back(new PointLight(identity, MediumInterface(), &I, Allocator())); + + scenes.push_back({bvh, lights, "Sphere, 1 light, Kd = 0.5", 1.0}); + } + + { + // Unit sphere, Kd = 0.5, Le = 0.5 + // -> With GI, should have radiance of 1. + ShapeHandle sphere = new Sphere(&identity, &identity, + true /* reverse orientation */, 1, -1, 1, 360); + + static ConstantSpectrum cs(0.5); + SpectrumTextureHandle Kd = alloc.new_object(&cs); + FloatTextureHandle sigma = alloc.new_object(0.); + const MaterialHandle material = new DiffuseMaterial(Kd, sigma, nullptr); + + static ConstantSpectrum Le(0.5); + LightHandle areaLight = + new DiffuseAreaLight(identity, MediumInterface(), &Le, 1.f, sphere, Image(), + nullptr, false, Allocator()); + + std::vector lights; + lights.push_back(areaLight); + + MediumInterface mediumInterface; + std::vector prims; + prims.push_back(PrimitiveHandle( + new GeometricPrimitive(sphere, material, lights.back(), mediumInterface))); + PrimitiveHandle bvh(new BVHAccel(std::move(prims))); + + scenes.push_back({bvh, lights, "Sphere, Kd = 0.5, Le = 0.5", 1.0}); + } + +#if 0 + { + // Unit sphere, Kd = 0.25, Kr = .5, point light I = 7.4 at center + // -> With GI, should have radiance of ~1. + ShapeHandle sphere = new Sphere( + &identity, &identity, true /* reverse orientation */, 1, -1, 1, 360); + + static ConstantSpectrum cs5(0.5), cs25(0.25); + SpectrumTextureHandle Kd = + alloc.new_object(&cs25); + SpectrumTextureHandle Kr = + alloc.new_object(&cs5); + SpectrumTextureHandle black = + alloc.new_object(Spectra::Zero()); + SpectrumTextureHandle white = + alloc.new_object(Spectra::One()); + FloatTextureHandle zero = + alloc.new_object(0.); + FloatTextureHandle one = + alloc.new_object(1.); + const MaterialHandle material = new UberMaterial( + Kd, black, Kr, black, zero, zero, one, nullptr, false, nullptr); + + MediumInterface mediumInterface; + std::vector prims; + prims.push_back(PrimitiveHandle(new GeometricPrimitive( + sphere, material, nullptr, mediumInterface))); + PrimitiveHandle bvh(new BVHAccel(std::move(prims))); + + static ConstantSpectrum I(3. * Pi); + std::vector lights; + lights.push_back(std::make_unique(identity, + nullptr, &I, Allocator())); + + scenes.push_back({bvh, lights, "Sphere, 1 light, Kd = 0.25 Kr = 0.5", 1.0}); + } +#endif + +#if 0 + { + // Unit sphere, Kd = 0.25, Kr = .5, Le .587 + // -> With GI, should have radiance of ~1. + ShapeHandle sphere = new Sphere( + &identity, &identity, true /* reverse orientation */, 1, -1, 1, 360); + + static ConstantSpectrum cs5(0.5), cs25(0.25); + SpectrumTextureHandle Kd = + alloc.new_object(&cs25); + SpectrumTextureHandle Kr = + alloc.new_object(&cs5); + SpectrumTextureHandle black = + alloc.new_object(Spectra::Zero()); + SpectrumTextureHandle white = + alloc.new_object(Spectra::One()); + FloatTextureHandle zero = + alloc.new_object(0.); + FloatTextureHandle one = + alloc.new_object(1.); + std::shared_ptr material = std::make_shared( + Kd, black, Kr, black, zero, zero, zero, white, one, nullptr, false, nullptr); + + static ConstantSpectrum Le(0.587); + std::shared_ptr areaLight = std::make_shared( + identity, nullptr, &Le, 8, sphere, true, false, + std::make_shared(std::initializer_list{}, nullptr)); + + MediumInterface mediumInterface; + std::vector> prims; + prims.push_back(PrimitiveHandle(new GeometricPrimitive( + sphere, material, areaLight, mediumInterface))); + PrimitiveHandle bvh(new BVHAccel(std::move(prims))); + + std::vector> lights; + lights.push_back(std::move(areaLight)); + + scenes.push_back({bvh, lights, "Sphere, Kd = 0.25 Kr = 0.5, Le = 0.587", 1.0}); + } +#endif + + return scenes; +} + +std::vector> GetSamplers( + const Point2i &resolution) { + std::vector> samplers; + + samplers.push_back(std::make_pair(new HaltonSampler(256, resolution), "Halton 256")); + samplers.push_back(std::make_pair(new PaddedSobolSampler(256, RandomizeStrategy::Xor), + "Padded Sobol 256")); + samplers.push_back( + std::make_pair(new SobolSampler(256, resolution, RandomizeStrategy::None), + "Sobol 256 Not Randomized")); + samplers.push_back(std::make_pair( + new SobolSampler(256, resolution, RandomizeStrategy::CranleyPatterson), + "Sobol 256 Cranley Patterson Randomization")); + samplers.push_back( + std::make_pair(new SobolSampler(256, resolution, RandomizeStrategy::Xor), + "Sobol 256 XOR Scramble")); + samplers.push_back( + std::make_pair(new SobolSampler(256, resolution, RandomizeStrategy::Owen), + "Sobol 256 Owen Scramble")); + samplers.push_back(std::make_pair(new RandomSampler(256), "Random 256")); + samplers.push_back( + std::make_pair(new StratifiedSampler(16, 16, true), "Stratified 16x16")); + samplers.push_back(std::make_pair(new PMJ02BNSampler(256), "PMJ02bn 256")); + + return samplers; +} + +std::vector GetIntegrators() { + std::vector integrators; + + Point2i resolution(10, 10); + static Transform id; + AnimatedTransform identity(id, 0, id, 1); + for (const auto &scene : GetScenes()) { + // Path tracing integrators + for (auto &sampler : GetSamplers(resolution)) { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + PerspectiveCamera *camera = new PerspectiveCamera( + CameraTransform(identity), Bounds2f(Point2f(-1, -1), Point2f(1, 1)), 0., + 1., 0., 10., 45, film, nullptr); + + const FilmHandle filmp = camera->GetFilm(); + Integrator *integrator = new PathIntegrator(8, camera, sampler.first, + scene.aggregate, scene.lights); + integrators.push_back({integrator, filmp, + "Path, depth 8, Perspective, " + sampler.second + + ", " + scene.description, + scene}); + } + + for (auto &sampler : GetSamplers(resolution)) { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + OrthographicCamera *camera = new OrthographicCamera( + CameraTransform(identity), Bounds2f(Point2f(-.1, -.1), Point2f(.1, .1)), + 0., 1., 0., 10., film, nullptr); + const FilmHandle filmp = camera->GetFilm(); + + Integrator *integrator = new PathIntegrator(8, camera, sampler.first, + scene.aggregate, scene.lights); + integrators.push_back( + {integrator, filmp, + "Path, depth 8, Ortho, " + sampler.second + ", " + scene.description, + scene}); + } + + // Volume path tracing integrators + for (auto &sampler : GetSamplers(resolution)) { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + PerspectiveCamera *camera = new PerspectiveCamera( + CameraTransform(identity), Bounds2f(Point2f(-1, -1), Point2f(1, 1)), 0., + 1., 0., 10., 45, film, nullptr); + const FilmHandle filmp = camera->GetFilm(); + + Integrator *integrator = new VolPathIntegrator(8, camera, sampler.first, + scene.aggregate, scene.lights); + integrators.push_back({integrator, filmp, + "VolPath, depth 8, Perspective, " + sampler.second + + ", " + scene.description, + scene}); + } + for (auto &sampler : GetSamplers(resolution)) { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + OrthographicCamera *camera = new OrthographicCamera( + CameraTransform(identity), Bounds2f(Point2f(-.1, -.1), Point2f(.1, .1)), + 0., 1., 0., 10., film, nullptr); + const FilmHandle filmp = camera->GetFilm(); + + Integrator *integrator = new VolPathIntegrator(8, camera, sampler.first, + scene.aggregate, scene.lights); + integrators.push_back( + {integrator, filmp, + "VolPath, depth 8, Ortho, " + sampler.second + ", " + scene.description, + scene}); + } + + // Simple path (perspective only, still sample light and BSDFs). Yolo + for (auto &sampler : GetSamplers(resolution)) { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + PerspectiveCamera *camera = new PerspectiveCamera( + CameraTransform(identity), Bounds2f(Point2f(-1, -1), Point2f(1, 1)), 0., + 1., 0., 10., 45, film, nullptr); + + const FilmHandle filmp = camera->GetFilm(); + Integrator *integrator = new SimplePathIntegrator( + 8, true, true, camera, sampler.first, scene.aggregate, scene.lights); + integrators.push_back({integrator, filmp, + "SimplePath, depth 8, Perspective, " + sampler.second + + ", " + scene.description, + scene}); + } + + // BDPT + for (auto &sampler : GetSamplers(resolution)) { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + PerspectiveCamera *camera = new PerspectiveCamera( + CameraTransform(identity), Bounds2f(Point2f(-1, -1), Point2f(1, 1)), 0., + 1., 0., 10., 45, film, nullptr); + const FilmHandle filmp = camera->GetFilm(); + + Integrator *integrator = + new BDPTIntegrator(camera, sampler.first, scene.aggregate, scene.lights, + 6, false, false, "power", false); + integrators.push_back({integrator, filmp, + "BDPT, depth 8, Perspective, " + sampler.second + + ", " + scene.description, + scene}); + } + + // MLT + { + FilterHandle filter = new BoxFilter(Vector2f(0.5, 0.5)); + RGBFilm *film = new RGBFilm(resolution, + Bounds2i(Point2i(0, 0), resolution), filter, 1., + inTestDir("test.exr"), 1., RGBColorSpace::sRGB); + PerspectiveCamera *camera = new PerspectiveCamera( + CameraTransform(identity), Bounds2f(Point2f(-1, -1), Point2f(1, 1)), 0., + 1., 0., 10., 45, film, nullptr); + const FilmHandle filmp = camera->GetFilm(); + + Integrator *integrator = + new MLTIntegrator(camera, scene.aggregate, scene.lights, 8 /* depth */, + 100000 /* n bootstrap */, 1000 /* nchains */, + 1024 /* mutations per pixel */, 0.01 /* sigma */, + 0.3 /* large step prob */, false /* regularize */); + integrators.push_back({integrator, filmp, + "MLT, depth 8, Perspective, " + scene.description, + scene}); + } + } + + return integrators; +} + +struct RenderTest : public testing::TestWithParam {}; + +TEST_P(RenderTest, RadianceMatches) { + const TestIntegrator &tr = GetParam(); + tr.integrator->Render(); + CheckSceneAverage(inTestDir("test.exr"), tr.scene.expected); + // The SpatialLightSampler class keeps a per-thread cache that + // must be cleared out between test runs. In turn, this means that we + // must delete the Integrator here in order to make sure that its + // destructor runs. (This is ugly and should be fixed in a better way.) + delete tr.integrator; + + EXPECT_EQ(0, remove(inTestDir("test.exr").c_str())); +} + +INSTANTIATE_TEST_CASE_P(AnalyticTestScenes, RenderTest, + testing::ValuesIn(GetIntegrators())); diff --git a/src/pbrt/cpu/primitive.cpp b/src/pbrt/cpu/primitive.cpp new file mode 100644 index 00000000..014e8589 --- /dev/null +++ b/src/pbrt/cpu/primitive.cpp @@ -0,0 +1,172 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pbrt { + +Bounds3f PrimitiveHandle::Bounds() const { + auto bounds = [&](auto ptr) { return ptr->Bounds(); }; + return DispatchCPU(bounds); +} + +pstd::optional PrimitiveHandle::Intersect(const Ray &r, + Float tMax) const { + auto isect = [&](auto ptr) { return ptr->Intersect(r, tMax); }; + return DispatchCPU(isect); +} + +bool PrimitiveHandle::IntersectP(const Ray &r, Float tMax) const { + auto isectp = [&](auto ptr) { return ptr->IntersectP(r, tMax); }; + return DispatchCPU(isectp); +} + +// GeometricPrimitive Method Definitions +GeometricPrimitive::GeometricPrimitive(ShapeHandle shape, MaterialHandle material, + LightHandle areaLight, + const MediumInterface &mediumInterface, + FloatTextureHandle alpha) + : shape(shape), + material(material), + areaLight(areaLight), + mediumInterface(mediumInterface), + alpha(alpha) { + primitiveMemory += sizeof(*this); +} + +pstd::optional GeometricPrimitive::Intersect(const Ray &r, + Float tMax) const { + pstd::optional si = shape.Intersect(r, tMax); + if (!si) + return {}; + CHECK_LT(si->tHit, 1.001 * tMax); + // Test intersection against alpha texture, if present + if (alpha && alpha.Evaluate(si->intr) == 0) { + // Ignore this hit and trace a new ray. + Ray rNext = si->intr.SpawnRay(r.d); + pstd::optional siNext = Intersect(rNext, tMax - si->tHit); + if (siNext) + // The returned t value has to account for both ray segments. + siNext->tHit += si->tHit; + return siNext; + } + + // Initialize _SurfaceInteraction_ after _Shape_ intersection + si->intr.areaLight = areaLight; + si->intr.material = material; + CHECK_GE(Dot(si->intr.n, si->intr.shading.n), 0.); + if (mediumInterface.IsMediumTransition()) + si->intr.mediumInterface = &mediumInterface; + else + si->intr.medium = r.medium; + + return si; +} + +bool GeometricPrimitive::IntersectP(const Ray &r, Float tMax) const { + // Skip shadow intersection test for transparent materials + if (material && material.IsTransparent()) + return false; + + if (alpha) + return Intersect(r, tMax).has_value(); + else + return shape.IntersectP(r, tMax); +} + +Bounds3f GeometricPrimitive::Bounds() const { + return shape.Bounds(); +} + +// SimplePrimitive Method Definitions +SimplePrimitive::SimplePrimitive(ShapeHandle shape, MaterialHandle material) + : shape(shape), material(material) { + primitiveMemory += sizeof(*this); +} + +Bounds3f SimplePrimitive::Bounds() const { + return shape.Bounds(); +} + +bool SimplePrimitive::IntersectP(const Ray &r, Float tMax) const { + if (material && material.IsTransparent()) + return false; + return shape.IntersectP(r, tMax); +} + +pstd::optional SimplePrimitive::Intersect(const Ray &r, + Float tMax) const { + pstd::optional si = shape.Intersect(r, tMax); + if (!si) + return {}; + + CHECK_LT(si->tHit, 1.001 * tMax); + si->intr.areaLight = nullptr; + si->intr.material = material; + + CHECK_GE(Dot(si->intr.n, si->intr.shading.n), 0.); + si->intr.medium = r.medium; + return si; +} + +// TransformedPrimitive Method Definitions +pstd::optional TransformedPrimitive::Intersect(const Ray &r, + Float tMax) const { + // Transform ray to primitive-space and intersect with primitive + Ray ray = renderFromPrimitive->ApplyInverse(r, &tMax); + pstd::optional si = primitive.Intersect(ray, tMax); + if (!si) + return {}; + CHECK_LT(si->tHit, 1.001 * tMax); + + // Return transformed instance's intersection information + si->intr = (*renderFromPrimitive)(si->intr); + CHECK_GE(Dot(si->intr.n, si->intr.shading.n), 0); + return si; +} + +bool TransformedPrimitive::IntersectP(const Ray &r, Float tMax) const { + Ray ray = renderFromPrimitive->ApplyInverse(r, &tMax); + return primitive.IntersectP(ray, tMax); +} + +// AnimatedPrimitive Method Definitions +AnimatedPrimitive::AnimatedPrimitive(PrimitiveHandle p, + const AnimatedTransform &renderFromPrimitive) + : primitive(p), renderFromPrimitive(renderFromPrimitive) { + primitiveMemory += sizeof(*this); + CHECK(renderFromPrimitive.IsAnimated()); +} + +pstd::optional AnimatedPrimitive::Intersect(const Ray &r, + Float tMax) const { + // Compute _ray_ after transformation by _renderFromPrimitive_ + Transform interpRenderFromPrimitive = renderFromPrimitive.Interpolate(r.time); + Ray ray = interpRenderFromPrimitive.ApplyInverse(r, &tMax); + pstd::optional si = primitive.Intersect(ray, tMax); + if (!si) + return {}; + + // Transform instance's intersection data to render space + si->intr = interpRenderFromPrimitive(si->intr); + CHECK_GE(Dot(si->intr.n, si->intr.shading.n), 0); + return si; +} + +bool AnimatedPrimitive::IntersectP(const Ray &r, Float tMax) const { + Ray ray = renderFromPrimitive.ApplyInverse(r, &tMax); + return primitive.IntersectP(ray, tMax); +} + +} // namespace pbrt diff --git a/src/pbrt/cpu/primitive.h b/src/pbrt/cpu/primitive.h new file mode 100644 index 00000000..8f8f6a00 --- /dev/null +++ b/src/pbrt/cpu/primitive.h @@ -0,0 +1,122 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_CPU_PRIMITIVE_H +#define PBRT_CPU_PRIMITIVE_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +STAT_MEMORY_COUNTER("Memory/Primitives", primitiveMemory); + +class SimplePrimitive; +class GeometricPrimitive; +class TransformedPrimitive; +class AnimatedPrimitive; +class BVHAccel; +class KdTreeAccel; + +// PrimitiveHandle Definition +class PrimitiveHandle + : public TaggedPointer { + public: + // Primitive Interface + using TaggedPointer::TaggedPointer; + + Bounds3f Bounds() const; + + pstd::optional Intersect(const Ray &r, + Float tMax = Infinity) const; + bool IntersectP(const Ray &r, Float tMax = Infinity) const; +}; + +// GeometricPrimitive Definition +class GeometricPrimitive { + public: + // GeometricPrimitive Public Methods + GeometricPrimitive(ShapeHandle shape, MaterialHandle material, LightHandle areaLight, + const MediumInterface &mediumInterface, + FloatTextureHandle alpha = nullptr); + Bounds3f Bounds() const; + pstd::optional Intersect(const Ray &r, Float tMax) const; + bool IntersectP(const Ray &r, Float tMax) const; + + private: + // GeometricPrimitive Private Members + ShapeHandle shape; + MaterialHandle material; + LightHandle areaLight; + MediumInterface mediumInterface; + FloatTextureHandle alpha; +}; + +// SimplePrimitive Definition +class SimplePrimitive { + public: + // SimplePrimitive Public Methods + Bounds3f Bounds() const; + pstd::optional Intersect(const Ray &r, Float tMax) const; + bool IntersectP(const Ray &r, Float tMax) const; + SimplePrimitive(ShapeHandle shape, MaterialHandle material); + + private: + ShapeHandle shape; + MaterialHandle material; +}; + +// TransformedPrimitive Definition +class TransformedPrimitive { + public: + // TransformedPrimitive Public Methods + TransformedPrimitive(PrimitiveHandle primitive, const Transform *renderFromPrimitive) + : primitive(primitive), renderFromPrimitive(renderFromPrimitive) { + primitiveMemory += sizeof(*this); + } + + pstd::optional Intersect(const Ray &r, Float tMax) const; + bool IntersectP(const Ray &r, Float tMax) const; + + Bounds3f Bounds() const { return (*renderFromPrimitive)(primitive.Bounds()); } + + private: + // TransformedPrimitive Private Members + PrimitiveHandle primitive; + const Transform *renderFromPrimitive; +}; + +// AnimatedPrimitive Definition +class AnimatedPrimitive { + public: + // AnimatedPrimitive Public Methods + AnimatedPrimitive(PrimitiveHandle primitive, + const AnimatedTransform &renderFromPrimitive); + pstd::optional Intersect(const Ray &r, Float tMax) const; + bool IntersectP(const Ray &r, Float tMax) const; + + Bounds3f Bounds() const { + return renderFromPrimitive.MotionBounds(primitive.Bounds()); + } + + private: + // AnimatedPrimitive Private Members + PrimitiveHandle primitive; + AnimatedTransform renderFromPrimitive; +}; + +} // namespace pbrt + +#endif // PBRT_CPU_PRIMITIVE_H diff --git a/src/pbrt/cpu/render.cpp b/src/pbrt/cpu/render.cpp new file mode 100644 index 00000000..1df81d4e --- /dev/null +++ b/src/pbrt/cpu/render.cpp @@ -0,0 +1,340 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pbrt { + +void CPURender(ParsedScene &parsedScene) { + Allocator alloc; + + // Create media first (so have them for the camera...) + std::map media = parsedScene.CreateMedia(alloc); + + bool haveScatteringMedia = false; + auto findMedium = [&media, &haveScatteringMedia](const std::string &s, + const FileLoc *loc) -> MediumHandle { + if (s.empty()) + return nullptr; + + auto iter = media.find(s); + if (iter == media.end()) + ErrorExit(loc, "%s: medium not defined", s); + haveScatteringMedia = true; + return iter->second; + }; + + // Filter + FilterHandle filter = + FilterHandle::Create(parsedScene.filter.name, parsedScene.filter.parameters, + &parsedScene.filter.loc, alloc); + + // Film + FilmHandle film = + FilmHandle::Create(parsedScene.film.name, parsedScene.film.parameters, + &parsedScene.film.loc, filter, alloc); + + // Camera + MediumHandle cameraMedium = + findMedium(parsedScene.camera.medium, &parsedScene.camera.loc); + CameraHandle camera = CameraHandle::Create( + parsedScene.camera.name, parsedScene.camera.parameters, cameraMedium, + parsedScene.camera.cameraTransform, film, &parsedScene.camera.loc, alloc); + + // Create _Sampler_ for rendering + SamplerHandle sampler = SamplerHandle::Create( + parsedScene.sampler.name, parsedScene.sampler.parameters, + camera.GetFilm().FullResolution(), &parsedScene.sampler.loc, alloc); + + // Textures + std::map floatTextures; + std::map spectrumTextures; + parsedScene.CreateTextures(&floatTextures, &spectrumTextures, alloc, false); + + // Materials + std::map namedMaterials; + std::vector materials; + parsedScene.CreateMaterials(floatTextures, spectrumTextures, alloc, &namedMaterials, + &materials); + bool haveSubsurface = false; + for (const auto &mtl : parsedScene.materials) + if (mtl.name == "subsurface") + haveSubsurface = true; + for (const auto &namedMtl : parsedScene.namedMaterials) + if (namedMtl.second.name == "subsurface") + haveSubsurface = true; + + // Lights (area lights will be done later, with shapes...) + std::vector lights; + lights.reserve(parsedScene.lights.size() + parsedScene.areaLights.size()); + for (const auto &light : parsedScene.lights) { + MediumHandle outsideMedium = findMedium(light.medium, &light.loc); + if (light.renderFromObject.IsAnimated()) + Warning(&light.loc, + "Animated lights aren't supported. Using the start transform."); + LightHandle l = LightHandle::Create( + light.name, light.parameters, light.renderFromObject.startTransform, + parsedScene.camera.cameraTransform, outsideMedium, &light.loc, alloc); + lights.push_back(l); + } + + // Primitives + auto getAlphaTexture = [&](const ParameterDictionary ¶meters, + const FileLoc *loc) -> FloatTextureHandle { + std::string alphaTexName = parameters.GetTexture("alpha"); + if (!alphaTexName.empty()) { + if (floatTextures.find(alphaTexName) != floatTextures.end()) + return floatTextures[alphaTexName]; + else + ErrorExit(loc, "%s: couldn't find float texture for \"alpha\" parameter.", + alphaTexName); + } else if (parameters.GetOneFloat("alpha", 1.f) == 0.f) + return alloc.new_object(0.f); + else + return nullptr; + }; + + // Non-animated shapes + auto CreatePrimitivesForShapes = + [&](const std::vector &shapes) -> std::vector { + std::vector primitives; + for (const auto &sh : shapes) { + pstd::vector shapes = + ShapeHandle::Create(sh.name, sh.renderFromObject, sh.objectFromRender, + sh.reverseOrientation, sh.parameters, &sh.loc, alloc); + if (shapes.empty()) + continue; + + FloatTextureHandle alphaTex = getAlphaTexture(sh.parameters, &sh.loc); + sh.parameters.ReportUnused(); // do now so can grab alpha... + + MaterialHandle mtl = nullptr; + if (!sh.materialName.empty()) { + auto iter = namedMaterials.find(sh.materialName); + if (iter == namedMaterials.end()) + ErrorExit(&sh.loc, "%s: no named material defined.", sh.materialName); + mtl = iter->second; + } else { + CHECK_LT(sh.materialIndex, materials.size()); + mtl = materials[sh.materialIndex]; + } + + MediumInterface mi(findMedium(sh.insideMedium, &sh.loc), + findMedium(sh.outsideMedium, &sh.loc)); + + for (auto &s : shapes) { + // Possibly create area light for shape + LightHandle areaHandle = nullptr; + if (sh.lightIndex != -1) { + CHECK_LT(sh.lightIndex, parsedScene.areaLights.size()); + const auto &areaLightEntity = parsedScene.areaLights[sh.lightIndex]; + + LightHandle area = LightHandle::CreateArea( + areaLightEntity.name, areaLightEntity.parameters, + *sh.renderFromObject, mi, s, &areaLightEntity.loc, Allocator{}); + areaHandle = area; + if (area) + lights.push_back(area); + } + if (areaHandle == nullptr && !mi.IsMediumTransition() && !alphaTex) + primitives.push_back(new SimplePrimitive(s, mtl)); + else + primitives.push_back( + new GeometricPrimitive(s, mtl, areaHandle, mi, alphaTex)); + } + } + return primitives; + }; + + std::vector primitives = + CreatePrimitivesForShapes(parsedScene.shapes); + + // Animated shapes + auto CreatePrimitivesForAnimatedShapes = + [&](const std::vector &shapes) + -> std::vector { + std::vector primitives; + primitives.reserve(shapes.size()); + + for (const auto &sh : shapes) { + pstd::vector shapes = + ShapeHandle::Create(sh.name, sh.identity, sh.identity, + sh.reverseOrientation, sh.parameters, &sh.loc, alloc); + if (shapes.empty()) + continue; + + FloatTextureHandle alphaTex = getAlphaTexture(sh.parameters, &sh.loc); + sh.parameters.ReportUnused(); // do now so can grab alpha... + + // Create initial shape or shapes for animated shape + + MaterialHandle mtl = nullptr; + if (!sh.materialName.empty()) { + auto iter = namedMaterials.find(sh.materialName); + if (iter == namedMaterials.end()) + ErrorExit(&sh.loc, "%s: no named material defined.", sh.materialName); + mtl = iter->second; + } else { + CHECK_LT(sh.materialIndex, materials.size()); + mtl = materials[sh.materialIndex]; + } + + MediumInterface mi(findMedium(sh.insideMedium, &sh.loc), + findMedium(sh.outsideMedium, &sh.loc)); + + std::vector prims; + for (auto &s : shapes) { + // Possibly create area light for shape + LightHandle areaHandle = nullptr; + if (sh.lightIndex != -1) { + CHECK_LT(sh.lightIndex, parsedScene.areaLights.size()); + const auto &areaLightEntity = parsedScene.areaLights[sh.lightIndex]; + + if (sh.renderFromObject.IsAnimated()) + Warning(&sh.loc, "Animated area lights aren't supported. Using " + "the start transform."); + + LightHandle area = LightHandle::CreateArea( + areaLightEntity.name, areaLightEntity.parameters, + sh.renderFromObject.startTransform, mi, s, &sh.loc, Allocator{}); + areaHandle = area; + if (area) + lights.push_back(area); + } + if (areaHandle == nullptr && !mi.IsMediumTransition() && !alphaTex) + prims.push_back(new SimplePrimitive(s, mtl)); + else + prims.push_back( + new GeometricPrimitive(s, mtl, areaHandle, mi, alphaTex)); + } + + // TODO: could try to be greedy or even segment them according + // to same sh.renderFromObject... + + // Create single _Primitive_ for _prims_ + if (prims.size() > 1) { + PrimitiveHandle bvh = new BVHAccel(std::move(prims)); + prims.clear(); + prims.push_back(bvh); + } + primitives.push_back(new AnimatedPrimitive(prims[0], sh.renderFromObject)); + } + return primitives; + }; + std::vector animatedPrimitives = + CreatePrimitivesForAnimatedShapes(parsedScene.animatedShapes); + primitives.insert(primitives.end(), animatedPrimitives.begin(), + animatedPrimitives.end()); + + // Instance definitions + std::map instanceDefinitions; + for (const auto &inst : parsedScene.instanceDefinitions) { + if (instanceDefinitions.find(inst.first) != instanceDefinitions.end()) + ErrorExit("%s: object instance redefined", inst.first); + + std::vector instancePrimitives = + CreatePrimitivesForShapes(inst.second.shapes); + std::vector movingInstancePrimitives = + CreatePrimitivesForAnimatedShapes(inst.second.animatedShapes); + instancePrimitives.insert(instancePrimitives.end(), + movingInstancePrimitives.begin(), + movingInstancePrimitives.end()); + if (instancePrimitives.empty()) { + instanceDefinitions[inst.first] = nullptr; + } else { + if (instancePrimitives.size() > 1) { + PrimitiveHandle bvh = new BVHAccel(std::move(instancePrimitives)); + instancePrimitives.clear(); + instancePrimitives.push_back(bvh); + } + instanceDefinitions[inst.first] = instancePrimitives[0]; + } + } + + // Instances + for (const auto &inst : parsedScene.instances) { + auto iter = instanceDefinitions.find(inst.name); + if (iter == instanceDefinitions.end()) + ErrorExit(&inst.loc, "%s: object instance not defined", inst.name); + + if (iter->second == nullptr) + // empty instance + continue; + + if (inst.renderFromInstance) + primitives.push_back( + new TransformedPrimitive(iter->second, inst.renderFromInstance)); + else + primitives.push_back( + new AnimatedPrimitive(iter->second, inst.renderFromInstanceAnim)); + } + + // Accelerator + PrimitiveHandle accel = nullptr; + if (!primitives.empty()) + accel = CreateAccelerator(parsedScene.accelerator.name, std::move(primitives), + parsedScene.accelerator.parameters); + + // Integrator + const RGBColorSpace *integratorColorSpace = parsedScene.film.parameters.ColorSpace(); + std::unique_ptr integrator(Integrator::Create( + parsedScene.integrator.name, parsedScene.integrator.parameters, camera, sampler, + accel, lights, integratorColorSpace, &parsedScene.integrator.loc)); + + // Helpful warnings + if (haveScatteringMedia && parsedScene.integrator.name != "volpath" && + parsedScene.integrator.name != "simplevolpath" && + parsedScene.integrator.name != "bdpt" && parsedScene.integrator.name != "mlt") + Warning("Scene has scattering media but \"%s\" integrator doesn't support " + "volume scattering. Consider using \"volpath\", \"simplevolpath\", " + "\"bdpt\", or \"mlt\".", + parsedScene.integrator.name); + + bool haveLights = !lights.empty(); + for (const auto &m : media) + haveLights |= m.second.IsEmissive(); + + if (!haveLights && parsedScene.integrator.name != "ambientocclusion" && + parsedScene.integrator.name != "aov") + Warning("No light sources defined in scene; rendering a black image."); + + if (parsedScene.film.name == "gbuffer" && parsedScene.integrator.name != "path") + Warning(&parsedScene.film.loc, + "GBufferFilm is not supported by %s. The channels " + "other than R, G, B will be zero.", + parsedScene.integrator.name); + + if (haveSubsurface && parsedScene.integrator.name != "volpath") + Warning("Some objects in the scene have subsurface scattering, which is " + "not supported by the %s integrator. Use the \"volpath\" integrator " + "to render them correctly.", + parsedScene.integrator.name); + + LOG_VERBOSE("Memory used after scene creation: %d", GetCurrentRSS()); + + // Render! + integrator->Render(); + + LOG_VERBOSE("Memory used after rendering: %s", GetCurrentRSS()); + + PtexTextureBase::ReportStats(); + ImageTextureBase::ClearCache(); + FreeBufferCaches(); +} + +} // namespace pbrt diff --git a/src/pbrt/cpu/render.h b/src/pbrt/cpu/render.h new file mode 100644 index 00000000..fe38256b --- /dev/null +++ b/src/pbrt/cpu/render.h @@ -0,0 +1,18 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_CPU_RENDER_H +#define PBRT_CPU_RENDER_H + +#include + +namespace pbrt { + +class ParsedScene; + +void CPURender(ParsedScene &scene); + +} // namespace pbrt + +#endif // PBRT_CPU_RENDER_H diff --git a/src/pbrt/film.cpp b/src/pbrt/film.cpp new file mode 100644 index 00000000..6147dd8f --- /dev/null +++ b/src/pbrt/film.cpp @@ -0,0 +1,586 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pbrt { + +void FilmHandle::AddSplat(const Point2f &p, SampledSpectrum v, + const SampledWavelengths &lambda) { + auto splat = [&](auto ptr) { return ptr->AddSplat(p, v, lambda); }; + return Dispatch(splat); +} + +void FilmHandle::WriteImage(ImageMetadata metadata, Float splatScale) { + auto write = [&](auto ptr) { return ptr->WriteImage(metadata, splatScale); }; + return DispatchCPU(write); +} + +Image FilmHandle::GetImage(ImageMetadata *metadata, Float splatScale) { + auto get = [&](auto ptr) { return ptr->GetImage(metadata, splatScale); }; + return DispatchCPU(get); +} + +std::string FilmHandle::ToString() const { + if (ptr() == nullptr) + return "(nullptr)"; + + auto ts = [&](auto ptr) { return ptr->ToString(); }; + return DispatchCPU(ts); +} + +std::string FilmHandle::GetFilename() const { + auto get = [&](auto ptr) { return ptr->GetFilename(); }; + return DispatchCPU(get); +} + +// FilmBase Method Definitions +std::string FilmBase::BaseToString() const { + return StringPrintf("fullResolution: %s diagonal: %f filter: %s filename: %s " + "pixelBounds: %s", + fullResolution, diagonal, filter, filename, pixelBounds); +} + +Bounds2f FilmBase::SampleBounds() const { + return Bounds2f(Point2f(pixelBounds.pMin) - filter.Radius() + Vector2f(0.5f, 0.5f), + Point2f(pixelBounds.pMax) + filter.Radius() - Vector2f(0.5f, 0.5f)); +} + +// VisibleSurface Method Definitions +VisibleSurface::VisibleSurface(const SurfaceInteraction &si, + const CameraTransform &cameraTransform, + const SampledSpectrum &albedo, + const SampledWavelengths &lambda) + : albedo(albedo) { + set = true; + // Initialize geometric _VisibleSurface_ members + Transform cameraFromRender = cameraTransform.CameraFromRender(si.time); + p = cameraFromRender(si.p()); + Vector3f wo = cameraFromRender(si.wo); + n = FaceForward(cameraFromRender(si.n), wo); + ns = FaceForward(cameraFromRender(si.shading.n), wo); + time = si.time; + dzdx = cameraFromRender(si.dpdx).z; + dzdy = cameraFromRender(si.dpdy).z; +} + +std::string VisibleSurface::ToString() const { + return StringPrintf("[ VisibleSurface set: %s p: %s n: %s ns: %s dzdx: %f dzdy: %f " + "time: %f albedo: %s ]", + set, p, n, ns, dzdx, dzdy, time, albedo); +} + +STAT_MEMORY_COUNTER("Memory/Film pixels", filmPixelMemory); + +// RGBFilm Method Definitions +RGBFilm::RGBFilm(const Point2i &resolution, const Bounds2i &pixelBounds, + FilterHandle filter, Float diagonal, const std::string &filename, + Float scale, const RGBColorSpace *colorSpace, Float maxComponentValue, + bool writeFP16, Allocator allocator) + : FilmBase(resolution, pixelBounds, filter, diagonal, filename), + pixels(pixelBounds, allocator), + scale(scale), + colorSpace(colorSpace), + maxComponentValue(maxComponentValue), + writeFP16(writeFP16) { + filterIntegral = filter.Integral(); + CHECK(!pixelBounds.IsEmpty()); + CHECK(colorSpace != nullptr); + filmPixelMemory += pixelBounds.Area() * sizeof(Pixel); +} + +SampledWavelengths RGBFilm::SampleWavelengths(Float u) const { + return SampledWavelengths::SampleXYZ(u); +} + +void RGBFilm::AddSplat(const Point2f &p, SampledSpectrum v, + const SampledWavelengths &lambda) { + CHECK(!v.HasNaNs()); + RGB rgb = v.ToRGB(lambda, *colorSpace); + // Optionally clamp splat sensor RGB value + Float m = std::max({rgb.r, rgb.g, rgb.b}); + if (m > maxComponentValue) + rgb *= maxComponentValue / m; + + // Compute bounds of affected pixels for splat, _splatBounds_ + Point2f pDiscrete = p + Vector2f(0.5, 0.5); + Bounds2i splatBounds(Point2i(Floor(pDiscrete - filter.Radius())), + Point2i(Floor(pDiscrete + filter.Radius())) + Vector2i(1, 1)); + splatBounds = Intersect(splatBounds, pixelBounds); + + for (Point2i pi : splatBounds) { + // Evaluate filter at _pi_ and add splat contribution + Float wt = filter.Evaluate(Point2f(p - pi - Vector2f(0.5, 0.5))); + if (wt != 0) { + Pixel &pixel = pixels[pi]; + for (int i = 0; i < 3; ++i) + pixel.splatRGB[i].Add(wt * rgb[i]); + } + } +} + +void RGBFilm::WriteImage(ImageMetadata metadata, Float splatScale) { + Image image = GetImage(&metadata, splatScale); + LOG_VERBOSE("Writing image %s with bounds %s", filename, pixelBounds); + image.Write(filename, metadata); +} + +Image RGBFilm::GetImage(ImageMetadata *metadata, Float splatScale) { + // Convert image to RGB and compute final pixel values + LOG_VERBOSE("Converting image to RGB and computing final weighted pixel values"); + PixelFormat format = writeFP16 ? PixelFormat::Half : PixelFormat::Float; + Image image(format, Point2i(pixelBounds.Diagonal()), {"R", "G", "B"}); + + ParallelFor2D(pixelBounds, [&](Point2i p) { + RGB rgb = GetPixelRGB(p, splatScale); + + Point2i pOffset(p.x - pixelBounds.pMin.x, p.y - pixelBounds.pMin.y); + image.SetChannels(pOffset, {rgb[0], rgb[1], rgb[2]}); + }); + + metadata->pixelBounds = pixelBounds; + metadata->fullResolution = fullResolution; + metadata->colorSpace = colorSpace; + + Float varianceSum = 0; + for (Point2i p : pixelBounds) { + const Pixel &pixel = pixels[p]; + varianceSum += Float(pixel.varianceEstimator.Variance()); + } + metadata->estimatedVariance = varianceSum / pixelBounds.Area(); + + return image; +} + +std::string RGBFilm::ToString() const { + return StringPrintf("[ RGBFilm %s scale: %f colorSpace: %s maxComponentValue: %f " + "writeFP16: %s ]", + BaseToString(), scale, *colorSpace, maxComponentValue, writeFP16); +} + +RGBFilm *RGBFilm::Create(const ParameterDictionary ¶meters, FilterHandle filter, + const RGBColorSpace *colorSpace, const FileLoc *loc, + Allocator alloc) { + std::string filename = parameters.GetOneString("filename", ""); + if (!Options->imageFile.empty()) { + if (!filename.empty()) + Warning(loc, + "Output filename supplied on command line, \"%s\" will " + "override " + "filename provided in scene description file, \"%s\".", + Options->imageFile, filename); + filename = Options->imageFile; + } else if (filename.empty()) + filename = "pbrt.exr"; + + Point2i fullResolution(parameters.GetOneInt("xresolution", 1280), + parameters.GetOneInt("yresolution", 720)); + if (Options->quickRender) { + fullResolution.x = std::max(1, fullResolution.x / 4); + fullResolution.y = std::max(1, fullResolution.y / 4); + } + + Bounds2i pixelBounds(Point2i(0, 0), fullResolution); + std::vector pb = parameters.GetIntArray("pixelbounds"); + if (Options->pixelBounds) { + Bounds2i newBounds = *Options->pixelBounds; + if (Intersect(newBounds, pixelBounds) != newBounds) + Warning(loc, "Supplied pixel bounds extend beyond image " + "resolution. Clamping."); + pixelBounds = Intersect(newBounds, pixelBounds); + + if (!pb.empty()) + Warning(loc, "Both pixel bounds and crop window were specified. Using the " + "crop window."); + } else if (!pb.empty()) { + if (pb.size() != 4) + Error(loc, "%d values supplied for \"pixelbounds\". Expected 4.", + int(pb.size())); + else { + Bounds2i newBounds = Bounds2i({pb[0], pb[2]}, {pb[1], pb[3]}); + if (Intersect(newBounds, pixelBounds) != newBounds) + Warning(loc, "Supplied pixel bounds extend beyond image " + "resolution. Clamping."); + pixelBounds = Intersect(newBounds, pixelBounds); + } + } + + std::vector cr = parameters.GetFloatArray("cropwindow"); + if (Options->cropWindow) { + Bounds2f crop = *Options->cropWindow; + // Compute film image bounds + pixelBounds = Bounds2i(Point2i(std::ceil(fullResolution.x * crop.pMin.x), + std::ceil(fullResolution.y * crop.pMin.y)), + Point2i(std::ceil(fullResolution.x * crop.pMax.x), + std::ceil(fullResolution.y * crop.pMax.y))); + + if (!cr.empty()) + Warning(loc, "Crop window supplied on command line will override " + "crop window specified with Film."); + if (Options->pixelBounds || !pb.empty()) + Warning(loc, "Both pixel bounds and crop window were specified. Using the " + "crop window."); + } else if (!cr.empty()) { + if (Options->pixelBounds) + Warning(loc, "Ignoring \"cropwindow\" since pixel bounds were specified " + "on the command line."); + else if (cr.size() == 4) { + if (!pb.empty()) + Warning(loc, "Both pixel bounds and crop window were " + "specified. Using the " + "crop window."); + + Bounds2f crop; + crop.pMin.x = Clamp(std::min(cr[0], cr[1]), 0.f, 1.f); + crop.pMax.x = Clamp(std::max(cr[0], cr[1]), 0.f, 1.f); + crop.pMin.y = Clamp(std::min(cr[2], cr[3]), 0.f, 1.f); + crop.pMax.y = Clamp(std::max(cr[2], cr[3]), 0.f, 1.f); + + // Compute film image bounds + pixelBounds = Bounds2i(Point2i(std::ceil(fullResolution.x * crop.pMin.x), + std::ceil(fullResolution.y * crop.pMin.y)), + Point2i(std::ceil(fullResolution.x * crop.pMax.x), + std::ceil(fullResolution.y * crop.pMax.y))); + } else + Error(loc, "%d values supplied for \"cropwindow\". Expected 4.", + (int)cr.size()); + } + + if (pixelBounds.IsEmpty()) + ErrorExit(loc, "Degenerate pixel bounds provided to film: %s.", pixelBounds); + + Float scale = parameters.GetOneFloat("scale", 1.); + Float diagonal = parameters.GetOneFloat("diagonal", 35.); + Float maxComponentValue = parameters.GetOneFloat("maxcomponentvalue", Infinity); + bool writeFP16 = parameters.GetOneBool("savefp16", true); + + return alloc.new_object(fullResolution, pixelBounds, filter, diagonal, + filename, scale, colorSpace, maxComponentValue, + writeFP16, alloc); +} + +// GBufferFilm Method Definitions +void GBufferFilm::AddSample(const Point2i &pFilm, SampledSpectrum L, + const SampledWavelengths &lambda, + const VisibleSurface *visibleSurface, Float weight) { + RGB rgb = L.ToRGB(lambda, *colorSpace); + Float m = std::max({rgb.r, rgb.g, rgb.b}); + if (m > maxComponentValue) { + L *= maxComponentValue / m; + rgb *= maxComponentValue / m; + } + + Pixel &p = pixels[pFilm]; + if (visibleSurface && *visibleSurface) { + // Update variance estimates. + // TODO: store channels independently? + p.rgbVarianceEstimator.Add(L.y(lambda)); + + p.pSum += weight * visibleSurface->p; + + p.nSum += weight * visibleSurface->n; + p.nsSum += weight * visibleSurface->ns; + + p.dzdxSum += weight * visibleSurface->dzdx; + p.dzdySum += weight * visibleSurface->dzdy; + + SampledSpectrum albedo = + visibleSurface->albedo * colorSpace->illuminant.Sample(lambda); + RGB albedoRGB = albedo.ToRGB(lambda, *colorSpace); + for (int c = 0; c < 3; ++c) + p.albedoSum[c] += weight * albedoRGB[c]; + } + + for (int c = 0; c < 3; ++c) + p.rgbSum[c] += rgb[c] * weight; + p.weightSum += weight; +} + +GBufferFilm::GBufferFilm(const Point2i &resolution, const Bounds2i &pixelBounds, + FilterHandle filter, Float diagonal, const std::string &filename, + Float scale, const RGBColorSpace *colorSpace, + Float maxComponentValue, bool writeFP16, Allocator alloc) + : FilmBase(resolution, pixelBounds, filter, diagonal, filename), + pixels(pixelBounds, alloc), + scale(scale), + colorSpace(colorSpace), + maxComponentValue(maxComponentValue), + writeFP16(writeFP16), + filterIntegral(filter.Integral()) { + CHECK(!pixelBounds.IsEmpty()); + filmPixelMemory += pixelBounds.Area() * sizeof(Pixel); +} + +SampledWavelengths GBufferFilm::SampleWavelengths(Float u) const { + return SampledWavelengths::SampleXYZ(u); +} + +void GBufferFilm::AddSplat(const Point2f &p, SampledSpectrum v, + const SampledWavelengths &lambda) { + // NOTE: same code as RGBFilm::AddSplat()... + CHECK(!v.HasNaNs()); + RGB rgb = v.ToRGB(lambda, *colorSpace); + Float m = std::max({rgb.r, rgb.g, rgb.b}); + if (m > maxComponentValue) + rgb *= maxComponentValue / m; + + Point2f pDiscrete = p + Vector2f(0.5, 0.5); + Bounds2i splatBounds(Point2i(Floor(pDiscrete - filter.Radius())), + Point2i(Floor(pDiscrete + filter.Radius())) + Vector2i(1, 1)); + splatBounds = Intersect(splatBounds, pixelBounds); + for (Point2i pi : splatBounds) { + Float wt = filter.Evaluate(Point2f(p - pi - Vector2f(0.5, 0.5))); + if (wt != 0) { + Pixel &pixel = pixels[pi]; + for (int i = 0; i < 3; ++i) + pixel.splatRGB[i].Add(wt * rgb[i]); + } + } +} + +void GBufferFilm::WriteImage(ImageMetadata metadata, Float splatScale) { + Image image = GetImage(&metadata, splatScale); + LOG_VERBOSE("Writing image %s with bounds %s", filename, pixelBounds); + image.Write(filename, metadata); +} + +Image GBufferFilm::GetImage(ImageMetadata *metadata, Float splatScale) { + // Convert image to RGB and compute final pixel values + LOG_VERBOSE("Converting image to RGB and computing final weighted pixel values"); + PixelFormat format = writeFP16 ? PixelFormat::Half : PixelFormat::Float; + Image image(format, Point2i(pixelBounds.Diagonal()), + {"R", + "G", + "B", + "Albedo.R", + "Albedo.G", + "Albedo.B", + "Px", + "Py", + "Pz", + "dzdx", + "dzdy", + "Nx", + "Ny", + "Nz", + "Nsx", + "Nsy", + "Nsz", + "materialId.R", + "materialId.G", + "materialId.B", + "rgbVariance", + "rgbRelativeVariance"}); + + ImageChannelDesc rgbDesc = image.GetChannelDesc({"R", "G", "B"}); + ImageChannelDesc pDesc = image.GetChannelDesc({"Px", "Py", "Pz"}); + ImageChannelDesc dzDesc = image.GetChannelDesc({"dzdx", "dzdy"}); + ImageChannelDesc nDesc = image.GetChannelDesc({"Nx", "Ny", "Nz"}); + ImageChannelDesc nsDesc = image.GetChannelDesc({"Nsx", "Nsy", "Nsz"}); + ImageChannelDesc albedoRgbDesc = + image.GetChannelDesc({"Albedo.R", "Albedo.G", "Albedo.B"}); + ImageChannelDesc varianceDesc = + image.GetChannelDesc({"rgbVariance", "rgbRelativeVariance"}); + + ParallelFor2D(pixelBounds, [&](Point2i p) { + Pixel &pixel = pixels[p]; + RGB rgb(pixel.rgbSum[0], pixel.rgbSum[1], pixel.rgbSum[2]); + RGB albedoRgb(pixel.albedoSum[0], pixel.albedoSum[1], pixel.albedoSum[2]); + + // Normalize pixel with weight sum + Float weightSum = pixel.weightSum; + Point3f pt = pixel.pSum; + Float dzdx = pixel.dzdxSum, dzdy = pixel.dzdySum; + if (weightSum != 0) { + rgb /= weightSum; + albedoRgb /= weightSum; + pt /= weightSum; + dzdx /= weightSum; + dzdy /= weightSum; + } + + // Add splat value at pixel + for (int c = 0; c < 3; ++c) + rgb[c] += splatScale * pixel.splatRGB[c] / filterIntegral; + + rgb *= scale; + + Point2i pOffset(p.x - pixelBounds.pMin.x, p.y - pixelBounds.pMin.y); + image.SetChannels(pOffset, rgbDesc, {rgb[0], rgb[1], rgb[2]}); + image.SetChannels(pOffset, albedoRgbDesc, + {albedoRgb[0], albedoRgb[1], albedoRgb[2]}); + + Normal3f n = + LengthSquared(pixel.nSum) > 0 ? Normalize(pixel.nSum) : Normal3f(0, 0, 0); + Normal3f ns = + LengthSquared(pixel.nsSum) > 0 ? Normalize(pixel.nsSum) : Normal3f(0, 0, 0); + image.SetChannels(pOffset, pDesc, {pt.x, pt.y, pt.z}); + image.SetChannels(pOffset, dzDesc, {std::abs(dzdx), std::abs(dzdy)}); + image.SetChannels(pOffset, nDesc, {n.x, n.y, n.z}); + image.SetChannels(pOffset, nsDesc, {ns.x, ns.y, ns.z}); + image.SetChannels(pOffset, varianceDesc, + {pixel.rgbVarianceEstimator.Variance(), + pixel.rgbVarianceEstimator.RelativeVariance()}); + }); + + metadata->pixelBounds = pixelBounds; + metadata->fullResolution = fullResolution; + metadata->colorSpace = colorSpace; + + Float varianceSum = 0; + for (Point2i p : pixelBounds) { + const Pixel &pixel = pixels[p]; + varianceSum += pixel.rgbVarianceEstimator.Variance(); + } + metadata->estimatedVariance = varianceSum / pixelBounds.Area(); + + return image; +} + +std::string GBufferFilm::ToString() const { + return StringPrintf("[ GBufferFilm %s colorSpace: %s maxComponentValue: %f " + "writeFP16: %s ]", + BaseToString(), *colorSpace, maxComponentValue, writeFP16); +} + +GBufferFilm *GBufferFilm::Create(const ParameterDictionary ¶meters, + FilterHandle filter, const RGBColorSpace *colorSpace, + const FileLoc *loc, Allocator alloc) { + std::string filename = parameters.GetOneString("filename", ""); + if (!Options->imageFile.empty()) { + if (!filename.empty()) + Warning(loc, + "Output filename supplied on command line, \"%s\" will " + "override " + "filename provided in scene description file, \"%s\".", + Options->imageFile, filename); + filename = Options->imageFile; + } else if (filename.empty()) + filename = "pbrt.exr"; + + Point2i fullResolution(parameters.GetOneInt("xresolution", 1280), + parameters.GetOneInt("yresolution", 720)); + if (Options->quickRender) { + fullResolution.x = std::max(1, fullResolution.x / 4); + fullResolution.y = std::max(1, fullResolution.y / 4); + } + + Bounds2i pixelBounds(Point2i(0, 0), fullResolution); + std::vector pb = parameters.GetIntArray("pixelbounds"); + if (Options->pixelBounds) { + Bounds2i newBounds = *Options->pixelBounds; + if (Intersect(newBounds, pixelBounds) != newBounds) + Warning(loc, "Supplied pixel bounds extend beyond image " + "resolution. Clamping."); + pixelBounds = Intersect(newBounds, pixelBounds); + + if (!pb.empty()) + Warning(loc, "Both pixel bounds and crop window were specified. Using the " + "crop window."); + } else if (!pb.empty()) { + if (pb.size() != 4) + Error(loc, "%d values supplied for \"pixelbounds\". Expected 4.", + int(pb.size())); + else { + Bounds2i newBounds = Bounds2i({pb[0], pb[2]}, {pb[1], pb[3]}); + if (Intersect(newBounds, pixelBounds) != newBounds) + Warning(loc, "Supplied pixel bounds extend beyond image " + "resolution. Clamping."); + pixelBounds = Intersect(newBounds, pixelBounds); + } + } + + std::vector cr = parameters.GetFloatArray("cropwindow"); + if (Options->cropWindow) { + Bounds2f crop = *Options->cropWindow; + // Compute film image bounds + pixelBounds = Bounds2i(Point2i(std::ceil(fullResolution.x * crop.pMin.x), + std::ceil(fullResolution.y * crop.pMin.y)), + Point2i(std::ceil(fullResolution.x * crop.pMax.x), + std::ceil(fullResolution.y * crop.pMax.y))); + + if (!cr.empty()) + Warning(loc, "Crop window supplied on command line will override " + "crop window specified with Film."); + if (Options->pixelBounds || !pb.empty()) + Warning(loc, "Both pixel bounds and crop window were specified. Using the " + "crop window."); + } else if (!cr.empty()) { + if (Options->pixelBounds) + Warning(loc, "Ignoring \"cropwindow\" since pixel bounds were specified " + "on the command line."); + else if (cr.size() == 4) { + if (!pb.empty()) + Warning(loc, "Both pixel bounds and crop window were " + "specified. Using the " + "crop window."); + + Bounds2f crop; + crop.pMin.x = Clamp(std::min(cr[0], cr[1]), 0.f, 1.f); + crop.pMax.x = Clamp(std::max(cr[0], cr[1]), 0.f, 1.f); + crop.pMin.y = Clamp(std::min(cr[2], cr[3]), 0.f, 1.f); + crop.pMax.y = Clamp(std::max(cr[2], cr[3]), 0.f, 1.f); + + // Compute film image bounds + pixelBounds = Bounds2i(Point2i(std::ceil(fullResolution.x * crop.pMin.x), + std::ceil(fullResolution.y * crop.pMin.y)), + Point2i(std::ceil(fullResolution.x * crop.pMax.x), + std::ceil(fullResolution.y * crop.pMax.y))); + } else + Error(loc, "%d values supplied for \"cropwindow\". Expected 4.", + (int)cr.size()); + } + + if (pixelBounds.IsEmpty()) + ErrorExit(loc, "Degenerate pixel bounds provided to film: %s.", pixelBounds); + + Float diagonal = parameters.GetOneFloat("diagonal", 35.); + Float maxComponentValue = parameters.GetOneFloat("maxcomponentvalue", Infinity); + Float scale = parameters.GetOneFloat("scale", 1.); + bool writeFP16 = parameters.GetOneBool("savefp16", true); + + return alloc.new_object(fullResolution, pixelBounds, filter, diagonal, + filename, scale, colorSpace, maxComponentValue, + writeFP16, alloc); +} + +FilmHandle FilmHandle::Create(const std::string &name, + const ParameterDictionary ¶meters, const FileLoc *loc, + FilterHandle filter, Allocator alloc) { + FilmHandle film; + if (name == "rgb") + film = RGBFilm::Create(parameters, filter, parameters.ColorSpace(), loc, alloc); + else if (name == "gbuffer") + film = + GBufferFilm::Create(parameters, filter, parameters.ColorSpace(), loc, alloc); + else + ErrorExit(loc, "%s: film type unknown.", name); + + if (!film) + ErrorExit(loc, "%s: unable to create film.", name); + + parameters.ReportUnused(); + return film; +} + +} // namespace pbrt diff --git a/src/pbrt/film.h b/src/pbrt/film.h new file mode 100644 index 00000000..88527668 --- /dev/null +++ b/src/pbrt/film.h @@ -0,0 +1,323 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_FILM_H +#define PBRT_FILM_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace pbrt { + +// VisibleSurface Definition +class VisibleSurface { + public: + // VisibleSurface Public Methods + VisibleSurface() = default; + PBRT_CPU_GPU + VisibleSurface(const SurfaceInteraction &si, const CameraTransform &cameraTransform, + const SampledSpectrum &albedo, const SampledWavelengths &lambda); + + std::string ToString() const; + + PBRT_CPU_GPU + operator bool() const { return set; } + + // VisibleSurface Public Members + bool set = false; + Point3f p; + Normal3f n, ns; + Float time = 0; + Float dzdx = 0, dzdy = 0; // x/y: raster space, z: camera space + SampledSpectrum albedo; +}; + +// FilmBase Definition +class FilmBase { + public: + // FilmBase Public Methods + FilmBase(const Point2i &resolution, const Bounds2i &pixelBounds, FilterHandle filter, + Float diagonal, const std::string &filename) + : fullResolution(resolution), + diagonal(diagonal * .001), + filter(filter), + filename(filename), + pixelBounds(pixelBounds) { + CHECK(!pixelBounds.IsEmpty()); + CHECK_GE(pixelBounds.pMin.x, 0); + CHECK_LE(pixelBounds.pMax.x, resolution.x); + CHECK_GE(pixelBounds.pMin.y, 0); + CHECK_LE(pixelBounds.pMax.y, resolution.y); + LOG_VERBOSE("Created film with full resolution %s, pixelBounds %s", resolution, + pixelBounds); + } + + PBRT_CPU_GPU + FilterHandle GetFilter() const { return filter; } + PBRT_CPU_GPU + Point2i FullResolution() const { return fullResolution; } + PBRT_CPU_GPU + Float Diagonal() const { return diagonal; } + PBRT_CPU_GPU + Bounds2i PixelBounds() const { return pixelBounds; } + std::string GetFilename() const { return filename; } + + std::string BaseToString() const; + + PBRT_CPU_GPU + Bounds2f SampleBounds() const; + + protected: + // FilmBase Protected Members + Point2i fullResolution; + Float diagonal; + FilterHandle filter; + std::string filename; + Bounds2i pixelBounds; +}; + +// RGBFilm Definition +class RGBFilm : public FilmBase { + public: + // RGBFilm Public Methods + PBRT_CPU_GPU + void AddSample(const Point2i &pFilm, SampledSpectrum L, + const SampledWavelengths &lambda, const VisibleSurface *visibleSurface, + Float weight) { + RGB rgb = L.ToRGB(lambda, *colorSpace); + // Optionally clamp sensor RGB value + Float m = std::max({rgb.r, rgb.g, rgb.b}); + if (m > maxComponentValue) { + L *= maxComponentValue / m; + rgb *= maxComponentValue / m; + } + + DCHECK(InsideExclusive(pFilm, pixelBounds)); + // Update pixel variance estimate + pixels[pFilm].varianceEstimator.Add(L.Average()); + + // Update pixel values with filtered sample contribution + Pixel &pixel = pixels[pFilm]; + for (int c = 0; c < 3; ++c) + pixel.rgbSum[c] += weight * rgb[c]; + pixel.weightSum += weight; + } + + PBRT_CPU_GPU + bool UsesVisibleSurface() const { return false; } + + PBRT_CPU_GPU + RGB GetPixelRGB(const Point2i &p, Float splatScale = 1) const { + const Pixel &pixel = pixels[p]; + RGB rgb(pixel.rgbSum[0], pixel.rgbSum[1], pixel.rgbSum[2]); + // Normalize _rgb_ with weight sum + Float weightSum = pixel.weightSum; + if (weightSum != 0) + rgb /= weightSum; + + // Add splat value at pixel + for (int c = 0; c < 3; ++c) + rgb[c] += splatScale * pixel.splatRGB[c] / filterIntegral; + + // Scale pixel value by _scale_ + rgb *= scale; + + return rgb; + } + + RGBFilm() = default; + RGBFilm(const Point2i &resolution, const Bounds2i &pixelBounds, FilterHandle filter, + Float diagonal, const std::string &filename, Float scale, + const RGBColorSpace *colorSpace, Float maxComponentValue = Infinity, + bool writeFP16 = true, Allocator allocator = {}); + + static RGBFilm *Create(const ParameterDictionary ¶meters, FilterHandle filter, + const RGBColorSpace *colorSpace, const FileLoc *loc, + Allocator alloc); + + PBRT_CPU_GPU + SampledWavelengths SampleWavelengths(Float u) const; + + PBRT_CPU_GPU + void AddSplat(const Point2f &p, SampledSpectrum v, const SampledWavelengths &lambda); + + void WriteImage(ImageMetadata metadata, Float splatScale = 1); + Image GetImage(ImageMetadata *metadata, Float splatScale = 1); + + std::string ToString() const; + + private: + // RGBFilm::Pixel Definition + struct Pixel { + Pixel() = default; + double rgbSum[3] = {0., 0., 0.}; + double weightSum = 0.; + AtomicDouble splatRGB[3]; + VarianceEstimator varianceEstimator; + }; + + // RGBFilm Private Members + Array2D pixels; + Float scale; + const RGBColorSpace *colorSpace; + Float maxComponentValue; + bool writeFP16; + Float filterIntegral; +}; + +// GBufferFilm Definition +class GBufferFilm : public FilmBase { + public: + // GBufferFilm Public Methods + GBufferFilm(const Point2i &resolution, const Bounds2i &pixelBounds, + FilterHandle filter, Float diagonal, const std::string &filename, + Float scale, const RGBColorSpace *colorSpace, + Float maxComponentValue = Infinity, bool writeFP16 = true, + Allocator alloc = {}); + + static GBufferFilm *Create(const ParameterDictionary ¶meters, FilterHandle filter, + const RGBColorSpace *colorSpace, const FileLoc *loc, + Allocator alloc); + + PBRT_CPU_GPU + SampledWavelengths SampleWavelengths(Float u) const; + + PBRT_CPU_GPU + void AddSample(const Point2i &pFilm, SampledSpectrum L, + const SampledWavelengths &lambda, const VisibleSurface *visibleSurface, + Float weight); + + PBRT_CPU_GPU + void AddSplat(const Point2f &p, SampledSpectrum v, const SampledWavelengths &lambda); + + PBRT_CPU_GPU + bool UsesVisibleSurface() const { return true; } + + PBRT_CPU_GPU + RGB GetPixelRGB(const Point2i &p, Float splatScale = 1) const { + const Pixel &pixel = pixels[p]; + RGB rgb(pixel.rgbSum[0], pixel.rgbSum[1], pixel.rgbSum[2]); + + // Normalize pixel with weight sum + Float weightSum = pixel.weightSum; + if (weightSum != 0) + rgb /= weightSum; + + // Add splat value at pixel + for (int c = 0; c < 3; ++c) + rgb[c] += splatScale * pixel.splatRGB[c] / filterIntegral; + + // Scale pixel value by _scale_ + rgb *= scale; + + return rgb; + } + + void WriteImage(ImageMetadata metadata, Float splatScale = 1); + Image GetImage(ImageMetadata *metadata, Float splatScale = 1); + + std::string ToString() const; + + private: + // GBufferFilm::Pixel Definition + struct Pixel { + Pixel() = default; + double rgbSum[3] = {0., 0., 0.}; + double weightSum = 0.; + AtomicDouble splatRGB[3]; + Point3f pSum; + Float dzdxSum = 0, dzdySum = 0; + Normal3f nSum, nsSum; + double albedoSum[3] = {0., 0., 0.}; + VarianceEstimator rgbVarianceEstimator; + }; + + // GBufferFilm Private Members + Array2D pixels; + Float scale; + const RGBColorSpace *colorSpace; + Float maxComponentValue; + bool writeFP16; + Float filterIntegral; +}; + +PBRT_CPU_GPU +inline SampledWavelengths FilmHandle::SampleWavelengths(Float u) const { + auto sample = [&](auto ptr) { return ptr->SampleWavelengths(u); }; + return Dispatch(sample); +} + +PBRT_CPU_GPU +inline Bounds2f FilmHandle::SampleBounds() const { + auto sb = [&](auto ptr) { return ptr->SampleBounds(); }; + return Dispatch(sb); +} + +PBRT_CPU_GPU +inline Bounds2i FilmHandle::PixelBounds() const { + auto pb = [&](auto ptr) { return ptr->PixelBounds(); }; + return Dispatch(pb); +} + +PBRT_CPU_GPU +inline Point2i FilmHandle::FullResolution() const { + auto fr = [&](auto ptr) { return ptr->FullResolution(); }; + return Dispatch(fr); +} + +PBRT_CPU_GPU +inline Float FilmHandle::Diagonal() const { + auto diag = [&](auto ptr) { return ptr->Diagonal(); }; + return Dispatch(diag); +} + +PBRT_CPU_GPU +inline FilterHandle FilmHandle::GetFilter() const { + auto filter = [&](auto ptr) { return ptr->GetFilter(); }; + return Dispatch(filter); +} + +PBRT_CPU_GPU +inline bool FilmHandle::UsesVisibleSurface() const { + auto uses = [&](auto ptr) { return ptr->UsesVisibleSurface(); }; + return Dispatch(uses); +} + +PBRT_CPU_GPU +inline RGB FilmHandle::GetPixelRGB(const Point2i &p, Float splatScale) const { + auto get = [&](auto ptr) { return ptr->GetPixelRGB(p, splatScale); }; + return Dispatch(get); +} + +PBRT_CPU_GPU +inline void FilmHandle::AddSample(const Point2i &pFilm, SampledSpectrum L, + const SampledWavelengths &lambda, + const VisibleSurface *visibleSurface, Float weight) { + auto add = [&](auto ptr) { + return ptr->AddSample(pFilm, L, lambda, visibleSurface, weight); + }; + return Dispatch(add); +} + +} // namespace pbrt + +#endif // PBRT_FILM_H diff --git a/src/pbrt/filters.cpp b/src/pbrt/filters.cpp new file mode 100644 index 00000000..6ed8bf6c --- /dev/null +++ b/src/pbrt/filters.cpp @@ -0,0 +1,163 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include + +namespace pbrt { + +std::string FilterHandle::ToString() const { + if (ptr() == nullptr) + return "(nullptr)"; + + auto ts = [&](auto ptr) { return ptr->ToString(); }; + return DispatchCPU(ts); +} + +// Box Filter Method Definitions +std::string BoxFilter::ToString() const { + return StringPrintf("[ BoxFilter radius: %s ]", radius); +} + +BoxFilter *BoxFilter::Create(const ParameterDictionary ¶meters, const FileLoc *loc, + Allocator alloc) { + Float xw = parameters.GetOneFloat("xradius", 0.5f); + Float yw = parameters.GetOneFloat("yradius", 0.5f); + return alloc.new_object(Vector2f(xw, yw)); +} + +// Gaussian Filter Method Definitions +std::string GaussianFilter::ToString() const { + return StringPrintf( + "[ GaussianFilter radius: %s sigma: %f expX: %f expY: %f sampler: %s ]", radius, + sigma, expX, expY, sampler); +} + +GaussianFilter *GaussianFilter::Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc) { + // Find common filter parameters + Float xw = parameters.GetOneFloat("xradius", 1.5f); + Float yw = parameters.GetOneFloat("yradius", 1.5f); + Float sigma = parameters.GetOneFloat("sigma", 0.5f); // equivalent to old alpha = 2 + return alloc.new_object(Vector2f(xw, yw), sigma, alloc); +} + +// Mitchell Filter Method Definitions +std::string MitchellFilter::ToString() const { + return StringPrintf("[ MitchellFilter radius: %s B: %f C: %f sampler: %s ]", radius, + B, C, sampler); +} + +MitchellFilter *MitchellFilter::Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc) { + // Find common filter parameters + Float xw = parameters.GetOneFloat("xradius", 2.f); + Float yw = parameters.GetOneFloat("yradius", 2.f); + Float B = parameters.GetOneFloat("B", 1.f / 3.f); + Float C = parameters.GetOneFloat("C", 1.f / 3.f); + return alloc.new_object(Vector2f(xw, yw), B, C, alloc); +} + +// Sinc Filter Method Definitions +Float LanczosSincFilter::Integral() const { + Float sum = 0; + int sqrtSamples = 64; + int nSamples = sqrtSamples * sqrtSamples; + Float area = 2 * radius.x * 2 * radius.y; + RNG rng; + for (int y = 0; y < sqrtSamples; ++y) { + for (int x = 0; x < sqrtSamples; ++x) { + Point2f u((x + rng.Uniform()) / sqrtSamples, + (y + rng.Uniform()) / sqrtSamples); + Point2f p(Lerp(u.x, -radius.x, radius.x), Lerp(u.y, -radius.y, radius.y)); + sum += Evaluate(p); + } + } + return sum / nSamples * area; +} + +std::string LanczosSincFilter::ToString() const { + return StringPrintf("[ LanczosSincFilter radius: %s tau: %f sampler: %s ]", radius, + tau, sampler); +} + +LanczosSincFilter *LanczosSincFilter::Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc) { + Float xw = parameters.GetOneFloat("xradius", 4.); + Float yw = parameters.GetOneFloat("yradius", 4.); + Float tau = parameters.GetOneFloat("tau", 3.f); + return alloc.new_object(Vector2f(xw, yw), tau, alloc); +} + +// Triangle Filter Method Definitions +std::string TriangleFilter::ToString() const { + return StringPrintf("[ TriangleFilter radius: %s ]", radius); +} + +TriangleFilter *TriangleFilter::Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc) { + // Find common filter parameters + Float xw = parameters.GetOneFloat("xradius", 2.f); + Float yw = parameters.GetOneFloat("yradius", 2.f); + return alloc.new_object(Vector2f(xw, yw)); +} + +FilterHandle FilterHandle::Create(const std::string &name, + const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc) { + FilterHandle filter = nullptr; + if (name == "box") + filter = BoxFilter::Create(parameters, loc, alloc); + else if (name == "gaussian") + filter = GaussianFilter::Create(parameters, loc, alloc); + else if (name == "mitchell") + filter = MitchellFilter::Create(parameters, loc, alloc); + else if (name == "sinc") + filter = LanczosSincFilter::Create(parameters, loc, alloc); + else if (name == "triangle") + filter = TriangleFilter::Create(parameters, loc, alloc); + else + ErrorExit(loc, "%s: filter type unknown.", name); + + if (!filter) + ErrorExit(loc, "%s: unable to create filter.", name); + + parameters.ReportUnused(); + return filter; +} + +// FilterSampler Method Definitions +FilterSampler::FilterSampler(FilterHandle filter, int freq, Allocator alloc) + : domain(Point2f(-filter.Radius()), Point2f(filter.Radius())), + values(int(16 * 2 * filter.Radius().x), int(16 * 2 * filter.Radius().y), alloc), + distrib(alloc) { + for (int y = 0; y < values.ySize(); ++y) { + for (int x = 0; x < values.xSize(); ++x) { + Point2f p = domain.Lerp( + Point2f((x + 0.5f) / values.xSize(), (y + 0.5f) / values.ySize())); + values(x, y) = std::abs(filter.Evaluate(p)); + } + } + + distrib = std::move(PiecewiseConstant2D(values, domain, alloc)); + + // And again without the abs() for use in Sample... + for (int y = 0; y < values.ySize(); ++y) { + for (int x = 0; x < values.xSize(); ++x) { + Point2f p = domain.Lerp( + Point2f((x + 0.5f) / values.xSize(), (y + 0.5f) / values.ySize())); + values(x, y) = filter.Evaluate(p); + } + } +} + +std::string FilterSampler::ToString() const { + return StringPrintf("[ FilterSampler domain: %s values: %s distrib: %s ]", domain, + values, distrib); +} + +} // namespace pbrt diff --git a/src/pbrt/filters.h b/src/pbrt/filters.h new file mode 100644 index 00000000..4bdfff48 --- /dev/null +++ b/src/pbrt/filters.h @@ -0,0 +1,258 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_FILTERS_H +#define PBRT_FILTERS_H + +#include + +#include +#include +#include + +#include +#include +#include + +namespace pbrt { + +// FilterSample Definition +struct FilterSample { + Point2f p; + Float weight; +}; + +class FilterSampler { + public: + // FilterSampler Public Methods + FilterSampler(FilterHandle filter, int freq = 64, Allocator alloc = {}); + std::string ToString() const; + + PBRT_CPU_GPU + FilterSample Sample(const Point2f &u) const { + Point2f p = distrib.Sample(u); + Point2f p01 = Point2f(domain.Offset(p)); + Point2i pi(Clamp(p01.x * values.xSize() + 0.5f, 0, values.xSize() - 1), + Clamp(p01.y * values.ySize() + 0.5f, 0, values.ySize() - 1)); + return {p, values[pi] < 0 ? -1.f : 1.f}; + } + + private: + // FilterSampler Private Members + Bounds2f domain; + Array2D values; + PiecewiseConstant2D distrib; +}; + +// BoxFilter Definition +class BoxFilter { + public: + // BoxFilter Public Methods + BoxFilter(const Vector2f &radius = Vector2f(0.5, 0.5)) : radius(radius) {} + + static BoxFilter *Create(const ParameterDictionary ¶meters, const FileLoc *loc, + Allocator alloc); + + PBRT_CPU_GPU + Vector2f Radius() const { return radius; } + + std::string ToString() const; + + PBRT_CPU_GPU + Float Evaluate(const Point2f &p) const { + return (std::abs(p.x) <= radius.x && std::abs(p.y) <= radius.y) ? 1 : 0; + } + + PBRT_CPU_GPU + FilterSample Sample(const Point2f &u) const { + Point2f p(Lerp(u[0], -radius.x, radius.x), Lerp(u[1], -radius.y, radius.y)); + return {p, 1.f}; + } + + PBRT_CPU_GPU + Float Integral() const { return 2 * radius.x * 2 * radius.y; } + + private: + Vector2f radius; +}; + +// GaussianFilter Definition +class GaussianFilter { + public: + // GaussianFilter Public Methods + GaussianFilter(const Vector2f &radius, Float sigma = 0.5f, Allocator alloc = {}) + : radius(radius), + sigma(sigma), + expX(Gaussian(radius.x, 0, sigma)), + expY(Gaussian(radius.y, 0, sigma)), + sampler(this, 64, alloc) {} + + static GaussianFilter *Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc); + + PBRT_CPU_GPU + Vector2f Radius() const { return radius; } + + std::string ToString() const; + + PBRT_CPU_GPU + Float Evaluate(const Point2f &p) const { + return (std::max(0, Gaussian(p.x, 0, sigma) - expX) * + std::max(0, Gaussian(p.y, 0, sigma) - expY)); + } + + PBRT_CPU_GPU + FilterSample Sample(const Point2f &u) const { return sampler.Sample(u); } + + PBRT_CPU_GPU + Float Integral() const { + return ((GaussianIntegral(-radius.x, radius.x, 0, sigma) - 2 * radius.x * expX) * + (GaussianIntegral(-radius.y, radius.y, 0, sigma) - 2 * radius.y * expY)); + } + + private: + // GaussianFilter Private Members + Vector2f radius; + Float sigma; + Float expX, expY; + FilterSampler sampler; +}; + +// MitchellFilter Definition +class MitchellFilter { + public: + // MitchellFilter Public Methods + MitchellFilter(const Vector2f &radius, Float B = 1.f / 3.f, Float C = 1.f / 3.f, + Allocator alloc = {}) + : radius(radius), B(B), C(C), sampler(this, 64, alloc) {} + + static MitchellFilter *Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc); + + PBRT_CPU_GPU + Vector2f Radius() const { return radius; } + + std::string ToString() const; + + PBRT_CPU_GPU + Float Evaluate(const Point2f &p) const { + return Mitchell1D(p.x / radius.x) * Mitchell1D(p.y / radius.y); + } + + PBRT_CPU_GPU + FilterSample Sample(const Point2f &u) const { return sampler.Sample(u); } + + PBRT_CPU_GPU + Float Integral() const { return radius.x * radius.y / 4; } + + private: + // MitchellFilter Private Methods + PBRT_CPU_GPU + Float Mitchell1D(Float x) const { + x = std::abs(2 * x); + if (x <= 1) + return ((12 - 9 * B - 6 * C) * x * x * x + (-18 + 12 * B + 6 * C) * x * x + + (6 - 2 * B)) * + (1.f / 6.f); + else if (x <= 2) + return ((-B - 6 * C) * x * x * x + (6 * B + 30 * C) * x * x + + (-12 * B - 48 * C) * x + (8 * B + 24 * C)) * + (1.f / 6.f); + else + return 0; + } + + // MitchellFilter Private Members + Vector2f radius; + Float B, C; + FilterSampler sampler; +}; + +// LanczosSincFilter Definition +class LanczosSincFilter { + public: + // LanczosSincFilter Public Methods + LanczosSincFilter(const Vector2f &radius, Float tau = 3.f, Allocator alloc = {}) + : radius(radius), tau(tau), sampler(this, 64, alloc) {} + + static LanczosSincFilter *Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc); + + PBRT_CPU_GPU + Vector2f Radius() const { return radius; } + + std::string ToString() const; + + PBRT_CPU_GPU + Float Evaluate(const Point2f &p) const { + return WindowedSinc(p.x, radius.x, tau) * WindowedSinc(p.y, radius.y, tau); + } + + PBRT_CPU_GPU + FilterSample Sample(const Point2f &u) const { return sampler.Sample(u); } + + PBRT_CPU_GPU + Float Integral() const; + + private: + Vector2f radius; + Float tau; + FilterSampler sampler; +}; + +// TriangleFilter Definition +class TriangleFilter { + public: + // TriangleFilter Public Methods + TriangleFilter(const Vector2f &radius) : radius(radius) {} + + static TriangleFilter *Create(const ParameterDictionary ¶meters, + const FileLoc *loc, Allocator alloc); + + PBRT_CPU_GPU + Vector2f Radius() const { return radius; } + + std::string ToString() const; + + PBRT_CPU_GPU + Float Evaluate(const Point2f &p) const { + return std::max(0, radius.x - std::abs(p.x)) * + std::max(0, radius.y - std::abs(p.y)); + } + + PBRT_CPU_GPU + FilterSample Sample(const Point2f &u) const { + return {Point2f(SampleTent(u[0], radius.x), SampleTent(u[1], radius.y)), 1.f}; + } + + PBRT_CPU_GPU + Float Integral() const { return radius.x * radius.x * radius.y * radius.y; } + + private: + Vector2f radius; +}; + +inline Float FilterHandle::Evaluate(const Point2f &p) const { + auto eval = [&](auto ptr) { return ptr->Evaluate(p); }; + return Dispatch(eval); +} + +inline FilterSample FilterHandle::Sample(const Point2f &u) const { + auto sample = [&](auto ptr) { return ptr->Sample(u); }; + return Dispatch(sample); +} + +inline Vector2f FilterHandle::Radius() const { + auto radius = [&](auto ptr) { return ptr->Radius(); }; + return Dispatch(radius); +} + +inline Float FilterHandle::Integral() const { + auto integral = [&](auto ptr) { return ptr->Integral(); }; + return Dispatch(integral); +} + +} // namespace pbrt + +#endif // PBRT_FILTERS_H diff --git a/src/pbrt/filters_test.cpp b/src/pbrt/filters_test.cpp new file mode 100644 index 00000000..1146e021 --- /dev/null +++ b/src/pbrt/filters_test.cpp @@ -0,0 +1,100 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include + +#include +#include + +using namespace pbrt; + +TEST(Sinc, ZeroHandling) { + Float x = 0; + Float prev = 1; + for (int i = 0; i < 10000; ++i) { + Float cur = Sinc(x); + EXPECT_LE(cur, prev); + x = NextFloatUp(x); + prev = cur; + } + + x = -0; + prev = 1; + for (int i = 0; i < 10000; ++i) { + Float cur = Sinc(x); + EXPECT_LE(cur, prev); + x = NextFloatDown(x); + prev = cur; + } +} + +TEST(Filter, ZeroPastRadius) { + auto makeFilters = [](const Vector2f &radius) -> std::vector { + return {new BoxFilter(radius), new GaussianFilter(radius), + new MitchellFilter(radius), new LanczosSincFilter(radius), + new TriangleFilter(radius)}; + }; + + for (Vector2f r : {Vector2f(1, 1), Vector2f(1.5, .25), Vector2f(.33, 5.2), + Vector2f(.1, .1), Vector2f(3, 3)}) { + for (FilterHandle f : makeFilters(r)) { + EXPECT_EQ(0, f.Evaluate(Point2f(0, r.y + 1e-3))); + EXPECT_EQ(0, f.Evaluate(Point2f(r.x, r.y + 1e-3))); + EXPECT_EQ(0, f.Evaluate(Point2f(-r.x, r.y + 1e-3))); + EXPECT_EQ(0, f.Evaluate(Point2f(0, -r.y - 1e-3))); + EXPECT_EQ(0, f.Evaluate(Point2f(r.x, -r.y - 1e-3))); + EXPECT_EQ(0, f.Evaluate(Point2f(-r.x, -r.y - 1e-3))); + EXPECT_EQ(0, f.Evaluate(Point2f(r.x + 1e-3, 0))); + EXPECT_EQ(0, f.Evaluate(Point2f(r.x + 1e-3, r.y))); + EXPECT_EQ(0, f.Evaluate(Point2f(r.x + 1e-3, -r.y))); + EXPECT_EQ(0, f.Evaluate(Point2f(-r.x - 1e-3, 0))); + EXPECT_EQ(0, f.Evaluate(Point2f(-r.x - 1e-3, r.y))); + EXPECT_EQ(0, f.Evaluate(Point2f(-r.x - 1e-3, -r.y))); + } + } +} + +static Float integrateFilter(FilterHandle f) { + Float sum = 0; + int sqrtSamples = 256; + int nSamples = sqrtSamples * sqrtSamples; + Float area = 2 * f.Radius().x * 2 * f.Radius().y; + for (Point2f u : Stratified2D(sqrtSamples, sqrtSamples)) { + Point2f p(Lerp(u.x, -f.Radius().x, f.Radius().x), + Lerp(u.y, -f.Radius().y, f.Radius().y)); + sum += f.Evaluate(p); + } + return sum / nSamples * area; +} + +TEST(Filter, Integral) { + auto approxEqual = [](Float a, Float b) { + if (std::max(std::abs(a), std::abs(b)) < 1e-3) + return std::abs(a - b) < 1e-5; + else + return 2 * std::abs(a - b) / std::abs(a + b) < 1e-2; + }; + auto makeFilters = [](const Vector2f &radius) -> std::vector { + return {new BoxFilter(radius), new GaussianFilter(radius), + new MitchellFilter(radius), new LanczosSincFilter(radius), + new TriangleFilter(radius)}; + }; + + for (FilterHandle f : makeFilters(Vector2f(1, 1))) + EXPECT_TRUE(approxEqual(f.Integral(), integrateFilter(f))) << f; + + for (FilterHandle f : makeFilters(Vector2f(2.5, 1))) + EXPECT_TRUE(approxEqual(f.Integral(), integrateFilter(f))) << f; + + for (FilterHandle f : makeFilters(Vector2f(1, 2.5))) + EXPECT_TRUE(approxEqual(f.Integral(), integrateFilter(f))) << f; + + for (FilterHandle f : makeFilters(Vector2f(3.4, 2.5))) + EXPECT_TRUE(approxEqual(f.Integral(), integrateFilter(f))) << f; +} diff --git a/src/pbrt/gpu/accel.cpp b/src/pbrt/gpu/accel.cpp new file mode 100644 index 00000000..1441c7a4 --- /dev/null +++ b/src/pbrt/gpu/accel.cpp @@ -0,0 +1,1207 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#ifdef NVTX +#include +#endif + +#define OPTIX_CHECK(EXPR) \ + do { \ + OptixResult res = EXPR; \ + if (res != OPTIX_SUCCESS) \ + LOG_FATAL("OptiX call " #EXPR " failed with code %d: \"%s\"", int(res), \ + optixGetErrorString(res)); \ + } while (false) /* eat semicolon */ + +namespace pbrt { + +struct __align__(OPTIX_SBT_RECORD_ALIGNMENT) RaygenRecord { + __align__(OPTIX_SBT_RECORD_ALIGNMENT) char header[OPTIX_SBT_RECORD_HEADER_SIZE]; +}; + +struct __align__(OPTIX_SBT_RECORD_ALIGNMENT) MissRecord { + __align__(OPTIX_SBT_RECORD_ALIGNMENT) char header[OPTIX_SBT_RECORD_HEADER_SIZE]; +}; + +struct __align__(OPTIX_SBT_RECORD_ALIGNMENT) GPUAccel::HitgroupRecord { + HitgroupRecord() {} + HitgroupRecord(const HitgroupRecord &r) { memcpy(this, &r, sizeof(HitgroupRecord)); } + + __align__(OPTIX_SBT_RECORD_ALIGNMENT) char header[OPTIX_SBT_RECORD_HEADER_SIZE]; + union { + TriangleMeshRecord triRec; + BilinearMeshRecord bilinearRec; + QuadricRecord quadricRec; + }; +}; + +extern "C" { +extern const unsigned char PBRT_EMBEDDED_PTX[]; +} + +STAT_MEMORY_COUNTER("Memory/Acceleration structures", gpuBVHBytes); + +OptixTraversableHandle GPUAccel::buildBVH( + const std::vector &buildInputs) { + // Figure out memory requirements. + OptixAccelBuildOptions accelOptions = {}; + accelOptions.buildFlags = + (OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_PREFER_FAST_TRACE); + accelOptions.motionOptions.numKeys = 1; + accelOptions.operation = OPTIX_BUILD_OPERATION_BUILD; + + OptixAccelBufferSizes blasBufferSizes; + OPTIX_CHECK(optixAccelComputeMemoryUsage(optixContext, &accelOptions, + buildInputs.data(), buildInputs.size(), + &blasBufferSizes)); + + uint64_t *compactedSizeBufferPtr = alloc.new_object(); + OptixAccelEmitDesc emitDesc; + emitDesc.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; + emitDesc.result = (CUdeviceptr)compactedSizeBufferPtr; + + // Allocate buffers. + void *tempBuffer; + CUDA_CHECK(cudaMalloc(&tempBuffer, blasBufferSizes.tempSizeInBytes)); + void *outputBuffer; + CUDA_CHECK(cudaMalloc(&outputBuffer, blasBufferSizes.outputSizeInBytes)); + + // Build. + OptixTraversableHandle traversableHandle{0}; + OPTIX_CHECK(optixAccelBuild( + optixContext, cudaStream, &accelOptions, buildInputs.data(), buildInputs.size(), + CUdeviceptr(tempBuffer), blasBufferSizes.tempSizeInBytes, + CUdeviceptr(outputBuffer), blasBufferSizes.outputSizeInBytes, &traversableHandle, + &emitDesc, 1)); + + CUDA_CHECK(cudaDeviceSynchronize()); + + gpuBVHBytes += *compactedSizeBufferPtr; + + // Compact + void *asBuffer; + CUDA_CHECK(cudaMalloc(&asBuffer, *compactedSizeBufferPtr)); + + OPTIX_CHECK(optixAccelCompact(optixContext, cudaStream, traversableHandle, + CUdeviceptr(asBuffer), *compactedSizeBufferPtr, + &traversableHandle)); + CUDA_CHECK(cudaDeviceSynchronize()); + + CUDA_CHECK(cudaFree(tempBuffer)); + CUDA_CHECK(cudaFree(outputBuffer)); + alloc.delete_object(compactedSizeBufferPtr); + + return traversableHandle; +} + +static MaterialHandle getMaterial( + const ShapeSceneEntity &shape, + const std::map &namedMaterials, + const std::vector &materials) { + if (!shape.materialName.empty()) { + auto iter = namedMaterials.find(shape.materialName); + if (iter == namedMaterials.end()) + ErrorExit(&shape.loc, "%s: material not defined", shape.materialName); + return iter->second; + } else { + CHECK_NE(shape.materialIndex, -1); + return materials[shape.materialIndex]; + } +} + +static FloatTextureHandle getAlphaTexture( + const ShapeSceneEntity &shape, + const std::map &floatTextures) { + std::string alphaTexName = shape.parameters.GetTexture("alpha"); + if (alphaTexName.empty()) + return nullptr; + + auto iter = floatTextures.find(alphaTexName); + if (iter == floatTextures.end()) + ErrorExit(&shape.loc, "%s: alpha texture not defined.", alphaTexName); + + FloatTextureHandle alphaTextureHandle = iter->second; + + if (!BasicTextureEvaluator().CanEvaluate({alphaTextureHandle}, {})) { + // It would be nice to just use the UniversalTextureEvaluator (maybe + // always), but optix complains "Error: Found call graph recursion"... + Warning(&shape.loc, + "%s: alpha texture too complex for BasicTextureEvaluator " + "(need fallback path). Ignoring for now.", + alphaTexName); + alphaTextureHandle = nullptr; + } + + return alphaTextureHandle; +} + +static int getOptixGeometryFlags(bool isTriangle, FloatTextureHandle alphaTextureHandle, + MaterialHandle materialHandle) { + if (materialHandle && materialHandle.HasSubsurfaceScattering()) + return OPTIX_GEOMETRY_FLAG_REQUIRE_SINGLE_ANYHIT_CALL; + else if ((alphaTextureHandle && isTriangle) || + (materialHandle && materialHandle.IsTransparent())) + // Need anyhit + return OPTIX_GEOMETRY_FLAG_NONE; + else + return OPTIX_GEOMETRY_FLAG_DISABLE_ANYHIT; +} + +static MediumInterface *getMediumInterface( + const ShapeSceneEntity &shape, const std::map &media, + Allocator alloc) { + if (shape.insideMedium.empty() && shape.outsideMedium.empty()) + return nullptr; + + auto getMedium = [&](const std::string &name) -> MediumHandle { + if (name.empty()) + return nullptr; + + auto iter = media.find(name); + if (iter == media.end()) + ErrorExit(&shape.loc, "%s: medium not defined", name); + return iter->second; + }; + + return alloc.new_object(getMedium(shape.insideMedium), + getMedium(shape.outsideMedium)); +} + +OptixTraversableHandle GPUAccel::createGASForTriangles( + const std::vector &shapes, const OptixProgramGroup &intersectPG, + const OptixProgramGroup &shadowPG, const OptixProgramGroup &randomHitPG, + const std::map &floatTextures, + const std::map &namedMaterials, + const std::vector &materials, + const std::map &media, + const std::map *> &shapeIndexToAreaLights, + Bounds3f *gasBounds) { + std::vector buildInputs; + std::vector pDeviceDevicePtrs; + std::vector triangleInputFlags; + + // Allocate space for potentially all shapes being triangle meshes so + // that we can write them in order (just potentially sparsely...) + std::vector meshes(shapes.size(), nullptr); + std::vector meshBounds(shapes.size()); + std::atomic meshesCreated{0}; + + ParallelFor(0, shapes.size(), [&](int64_t shapeIndex) { + const auto &shape = shapes[shapeIndex]; + if (shape.name == "trianglemesh" || shape.name == "plymesh" || + shape.name == "loopsubdiv") { + TriangleMesh *mesh = nullptr; + if (shape.name == "trianglemesh") { + mesh = + Triangle::CreateMesh(shape.renderFromObject, shape.reverseOrientation, + shape.parameters, &shape.loc, alloc); + CHECK(mesh != nullptr); + } else if (shape.name == "loopsubdiv") { + // Copied from pbrt/shapes.cpp... :-p + int nLevels = shape.parameters.GetOneInt("levels", 3); + std::vector vertexIndices = shape.parameters.GetIntArray("indices"); + if (vertexIndices.empty()) + ErrorExit(&shape.loc, "Vertex indices \"indices\" not " + "provided for LoopSubdiv shape."); + + std::vector P = shape.parameters.GetPoint3fArray("P"); + if (P.empty()) + ErrorExit(&shape.loc, "Vertex positions \"P\" not provided " + "for LoopSubdiv shape."); + + // don't actually use this for now... + std::string scheme = shape.parameters.GetOneString("scheme", "loop"); + + mesh = LoopSubdivide(shape.renderFromObject, shape.reverseOrientation, + nLevels, vertexIndices, P, alloc); + CHECK(mesh != nullptr); + } else { + CHECK_EQ(shape.name, "plymesh"); + std::string filename = + ResolveFilename(shape.parameters.GetOneString("filename", "")); + if (filename.empty()) + ErrorExit(&shape.loc, "plymesh: \"filename\" must be provided."); + TriQuadMesh plyMesh = TriQuadMesh::ReadPLY(filename); // todo: alloc + if (plyMesh.triIndices.empty() && plyMesh.quadIndices.empty()) + return; + + plyMesh.ConvertToOnlyTriangles(); + + mesh = alloc.new_object( + *shape.renderFromObject, shape.reverseOrientation, plyMesh.triIndices, + plyMesh.p, std::vector(), plyMesh.n, plyMesh.uv, + plyMesh.faceIndices); + } + + Bounds3f bounds; + for (size_t i = 0; i < mesh->nVertices; ++i) + bounds = Union(bounds, mesh->p[i]); + + meshes[shapeIndex] = mesh; + meshBounds[shapeIndex] = bounds; + ++meshesCreated; + } + }); + + buildInputs.resize(meshesCreated.load()); + // Important so that these aren't reallocated so we can take pointers to + // elements... + pDeviceDevicePtrs.resize(meshesCreated.load()); + triangleInputFlags.resize(meshesCreated.load()); + + int buildIndex = 0; + for (int shapeIndex = 0; shapeIndex < meshes.size(); ++shapeIndex) { + TriangleMesh *mesh = meshes[shapeIndex]; + if (!mesh) + continue; + + const auto &shape = shapes[shapeIndex]; + + FloatTextureHandle alphaTextureHandle = getAlphaTexture(shape, floatTextures); + MaterialHandle materialHandle = getMaterial(shape, namedMaterials, materials); + + OptixBuildInput input = {}; + + input.type = OPTIX_BUILD_INPUT_TYPE_TRIANGLES; + + input.triangleArray.vertexFormat = OPTIX_VERTEX_FORMAT_FLOAT3; + input.triangleArray.vertexStrideInBytes = sizeof(Point3f); + input.triangleArray.numVertices = mesh->nVertices; + pDeviceDevicePtrs[buildIndex] = CUdeviceptr(mesh->p); + input.triangleArray.vertexBuffers = &pDeviceDevicePtrs[buildIndex]; + + input.triangleArray.indexFormat = OPTIX_INDICES_FORMAT_UNSIGNED_INT3; + input.triangleArray.indexStrideInBytes = 3 * sizeof(int); + input.triangleArray.numIndexTriplets = mesh->nTriangles; + input.triangleArray.indexBuffer = CUdeviceptr(mesh->vertexIndices); + + triangleInputFlags[buildIndex] = + getOptixGeometryFlags(true, alphaTextureHandle, materialHandle); + input.triangleArray.flags = &triangleInputFlags[buildIndex]; + + input.triangleArray.numSbtRecords = 1; + input.triangleArray.sbtIndexOffsetBuffer = CUdeviceptr(nullptr); + input.triangleArray.sbtIndexOffsetSizeInBytes = 0; + input.triangleArray.sbtIndexOffsetStrideInBytes = 0; + + buildInputs[buildIndex] = input; + + HitgroupRecord hgRecord; + OPTIX_CHECK(optixSbtRecordPackHeader(intersectPG, &hgRecord)); + hgRecord.triRec.mesh = mesh; + hgRecord.triRec.material = materialHandle; + hgRecord.triRec.alphaTexture = alphaTextureHandle; + hgRecord.triRec.areaLights = {}; + if (shape.lightIndex != -1) { + // Note: this will hit if we try to have an instance as an area + // light. + auto iter = shapeIndexToAreaLights.find(shapeIndex); + CHECK(iter != shapeIndexToAreaLights.end()); + CHECK_EQ(iter->second->size(), mesh->nTriangles); + hgRecord.triRec.areaLights = pstd::MakeSpan(*iter->second); + } + hgRecord.triRec.mediumInterface = getMediumInterface(shape, media, alloc); + + *gasBounds = Union(*gasBounds, meshBounds[shapeIndex]); + + intersectHGRecords.push_back(hgRecord); + + OPTIX_CHECK(optixSbtRecordPackHeader(randomHitPG, &hgRecord)); + randomHitHGRecords.push_back(hgRecord); + + OPTIX_CHECK(optixSbtRecordPackHeader(shadowPG, &hgRecord)); + shadowHGRecords.push_back(hgRecord); + + ++buildIndex; + } + + if (buildInputs.empty()) + return {}; + + return buildBVH(buildInputs); +} + +OptixTraversableHandle GPUAccel::createGASForBLPs( + const std::vector &shapes, const OptixProgramGroup &intersectPG, + const OptixProgramGroup &shadowPG, const OptixProgramGroup &randomHitPG, + const std::map &floatTextures, + const std::map &namedMaterials, + const std::vector &materials, + const std::map &media, + const std::map *> &shapeIndexToAreaLights, + Bounds3f *gasBounds) { + std::vector buildInputs; + pstd::vector shapeAABBs(alloc); + std::vector aabbPtrs; + std::vector flags; + + for (size_t shapeIndex = 0; shapeIndex < shapes.size(); ++shapeIndex) { + const auto &shape = shapes[shapeIndex]; + if (shape.name != "bilinearmesh") + continue; + + BilinearPatchMesh *mesh = + BilinearPatch::CreateMesh(shape.renderFromObject, shape.reverseOrientation, + shape.parameters, &shape.loc, alloc); + CHECK(mesh != nullptr); + + OptixBuildInput buildInput = {}; + buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; + buildInput.customPrimitiveArray.numSbtRecords = 1; + buildInput.customPrimitiveArray.numPrimitives = mesh->nVertices; + // aabbBuffers and flags pointers are set when we're done + buildInputs.push_back(buildInput); + + Bounds3f shapeBounds; + for (size_t i = 0; i < mesh->nVertices; ++i) + shapeBounds = Union(shapeBounds, mesh->p[i]); + + OptixAabb aabb = {shapeBounds.pMin.x, shapeBounds.pMin.y, shapeBounds.pMin.z, + shapeBounds.pMax.x, shapeBounds.pMax.y, shapeBounds.pMax.z}; + shapeAABBs.push_back(aabb); + + *gasBounds = Union(*gasBounds, shapeBounds); + + MaterialHandle materialHandle = getMaterial(shape, namedMaterials, materials); + FloatTextureHandle alphaTextureHandle = getAlphaTexture(shape, floatTextures); + + flags.push_back(getOptixGeometryFlags(false, alphaTextureHandle, materialHandle)); + + HitgroupRecord hgRecord; + OPTIX_CHECK(optixSbtRecordPackHeader(intersectPG, &hgRecord)); + hgRecord.bilinearRec.mesh = mesh; + hgRecord.bilinearRec.material = materialHandle; + hgRecord.bilinearRec.alphaTexture = alphaTextureHandle; + hgRecord.bilinearRec.areaLights = {}; + if (shape.lightIndex != -1) { + auto iter = shapeIndexToAreaLights.find(shapeIndex); + // Note: this will hit if we try to have an instance as an area + // light. + CHECK(iter != shapeIndexToAreaLights.end()); + CHECK_EQ(iter->second->size(), mesh->nPatches); + hgRecord.bilinearRec.areaLights = pstd::MakeSpan(*iter->second); + } + hgRecord.bilinearRec.mediumInterface = getMediumInterface(shape, media, alloc); + + intersectHGRecords.push_back(hgRecord); + + OPTIX_CHECK(optixSbtRecordPackHeader(randomHitPG, &hgRecord)); + randomHitHGRecords.push_back(hgRecord); + + OPTIX_CHECK(optixSbtRecordPackHeader(shadowPG, &hgRecord)); + shadowHGRecords.push_back(hgRecord); + } + + if (buildInputs.empty()) + return {}; + + for (size_t i = 0; i < shapeAABBs.size(); ++i) + aabbPtrs.push_back(CUdeviceptr(&shapeAABBs[i])); + + CHECK_EQ(buildInputs.size(), flags.size()); + for (size_t i = 0; i < buildInputs.size(); ++i) { + buildInputs[i].customPrimitiveArray.aabbBuffers = &aabbPtrs[i]; + buildInputs[i].customPrimitiveArray.flags = &flags[i]; + } + + return buildBVH(buildInputs); +} + +OptixTraversableHandle GPUAccel::createGASForQuadrics( + const std::vector &shapes, const OptixProgramGroup &intersectPG, + const OptixProgramGroup &shadowPG, const OptixProgramGroup &randomHitPG, + const std::map &floatTextures, + const std::map &namedMaterials, + const std::vector &materials, + const std::map &media, + const std::map *> &shapeIndexToAreaLights, + Bounds3f *gasBounds) { + std::vector buildInputs; + pstd::vector shapeAABBs(alloc); + std::vector aabbPtrs; + std::vector flags; + + for (size_t shapeIndex = 0; shapeIndex < shapes.size(); ++shapeIndex) { + const auto &shape = shapes[shapeIndex]; + if (shape.name != "sphere" && shape.name != "cylinder" && shape.name != "disk") + continue; + + pstd::vector shapeHandles = ShapeHandle::Create( + shape.name, shape.renderFromObject, shape.objectFromRender, + shape.reverseOrientation, shape.parameters, &shape.loc, alloc); + if (shapeHandles.empty()) + continue; + CHECK_EQ(1, shapeHandles.size()); + ShapeHandle shapeHandle = shapeHandles[0]; + + OptixBuildInput buildInput = {}; + memset(&buildInput, 0, sizeof(buildInput)); + + buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; + buildInput.customPrimitiveArray.numSbtRecords = 1; + buildInput.customPrimitiveArray.numPrimitives = 1; + // aabbBuffers and flags pointers are set when we're done + + buildInputs.push_back(buildInput); + + Bounds3f shapeBounds = shapeHandle.Bounds(); + OptixAabb aabb = {shapeBounds.pMin.x, shapeBounds.pMin.y, shapeBounds.pMin.z, + shapeBounds.pMax.x, shapeBounds.pMax.y, shapeBounds.pMax.z}; + shapeAABBs.push_back(aabb); + + *gasBounds = Union(*gasBounds, shapeBounds); + + // Find alpha texture, if present. + MaterialHandle materialHandle = getMaterial(shape, namedMaterials, materials); + FloatTextureHandle alphaTextureHandle = getAlphaTexture(shape, floatTextures); + flags.push_back(getOptixGeometryFlags(false, alphaTextureHandle, materialHandle)); + + HitgroupRecord hgRecord; + OPTIX_CHECK(optixSbtRecordPackHeader(intersectPG, &hgRecord)); + hgRecord.quadricRec.shape = shapeHandle; + hgRecord.quadricRec.material = materialHandle; + hgRecord.quadricRec.alphaTexture = alphaTextureHandle; + hgRecord.quadricRec.areaLight = nullptr; + if (shape.lightIndex != -1) { + auto iter = shapeIndexToAreaLights.find(shapeIndex); + // Note: this will hit if we try to have an instance as an area + // light. + CHECK(iter != shapeIndexToAreaLights.end()); + CHECK_EQ(iter->second->size(), 1); + hgRecord.quadricRec.areaLight = (*iter->second)[0]; + } + hgRecord.quadricRec.mediumInterface = getMediumInterface(shape, media, alloc); + + intersectHGRecords.push_back(hgRecord); + + OPTIX_CHECK(optixSbtRecordPackHeader(randomHitPG, &hgRecord)); + randomHitHGRecords.push_back(hgRecord); + + OPTIX_CHECK(optixSbtRecordPackHeader(shadowPG, &hgRecord)); + shadowHGRecords.push_back(hgRecord); + } + + if (buildInputs.empty()) + return {}; + + for (size_t i = 0; i < shapeAABBs.size(); ++i) + aabbPtrs.push_back(CUdeviceptr(&shapeAABBs[i])); + + CHECK_EQ(buildInputs.size(), flags.size()); + for (size_t i = 0; i < buildInputs.size(); ++i) { + buildInputs[i].customPrimitiveArray.aabbBuffers = &aabbPtrs[i]; + buildInputs[i].customPrimitiveArray.flags = &flags[i]; + } + + return buildBVH(buildInputs); +} + +GPUAccel::GPUAccel( + const ParsedScene &scene, Allocator alloc, CUstream cudaStream, + const std::map *> &shapeIndexToAreaLights, + const std::map &media, + pstd::array *haveBasicEvalMaterial, + pstd::array *haveUniversalEvalMaterial, + bool *haveSubsurface) + : alloc(alloc), + cudaStream(cudaStream), + intersectHGRecords(alloc), + shadowHGRecords(alloc), + randomHitHGRecords(alloc) { + CUcontext cudaContext; + CU_CHECK(cuCtxGetCurrent(&cudaContext)); + CHECK(cudaContext != nullptr); + + paramsPool.resize(256); // should be plenty + for (ParamBufferState &ps : paramsPool) { + void *ptr; + CUDA_CHECK(cudaMalloc(&ptr, sizeof(RayIntersectParameters))); + ps.ptr = (CUdeviceptr)ptr; + CUDA_CHECK(cudaEventCreate(&ps.finishedEvent)); + CUDA_CHECK(cudaMallocHost(&ps.hostPtr, sizeof(RayIntersectParameters))); + } + + // Create OptiX context + OPTIX_CHECK(optixInit()); + OPTIX_CHECK(optixDeviceContextCreate(cudaContext, 0, &optixContext)); + + LOG_VERBOSE("Optix successfully initialized"); + + // OptiX module + OptixModuleCompileOptions moduleCompileOptions = {}; + // TODO: REVIEW THIS + moduleCompileOptions.maxRegisterCount = OPTIX_COMPILE_DEFAULT_MAX_REGISTER_COUNT; +#ifndef NDEBUG + moduleCompileOptions.optLevel = OPTIX_COMPILE_OPTIMIZATION_LEVEL_0; + moduleCompileOptions.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL; +#else + moduleCompileOptions.optLevel = OPTIX_COMPILE_OPTIMIZATION_DEFAULT; + moduleCompileOptions.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE; +#endif + + OptixPipelineCompileOptions pipelineCompileOptions = {}; + pipelineCompileOptions.traversableGraphFlags = OPTIX_TRAVERSABLE_GRAPH_FLAG_ALLOW_ANY; + pipelineCompileOptions.usesMotionBlur = false; + pipelineCompileOptions.numPayloadValues = 3; + pipelineCompileOptions.numAttributeValues = 4; + // OPTIX_EXCEPTION_FLAG_NONE; + pipelineCompileOptions.exceptionFlags = + (OPTIX_EXCEPTION_FLAG_STACK_OVERFLOW | OPTIX_EXCEPTION_FLAG_TRACE_DEPTH | + OPTIX_EXCEPTION_FLAG_DEBUG); + pipelineCompileOptions.pipelineLaunchParamsVariableName = "params"; + + OptixPipelineLinkOptions pipelineLinkOptions = {}; + pipelineLinkOptions.maxTraceDepth = 2; + pipelineLinkOptions.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL; + + const std::string ptxCode((const char *)PBRT_EMBEDDED_PTX); + + char log[4096]; + size_t logSize = sizeof(log); + OPTIX_CHECK(optixModuleCreateFromPTX(optixContext, &moduleCompileOptions, + &pipelineCompileOptions, ptxCode.c_str(), + ptxCode.size(), log, &logSize, &optixModule)); + LOG_VERBOSE("%s", log); + + // Optix program groups... + OptixProgramGroupOptions pgOptions = {}; + OptixProgramGroup raygenPGClosest; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN; + desc.raygen.module = optixModule; + desc.raygen.entryFunctionName = "__raygen__findClosest"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &raygenPGClosest)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup missPGNoOp; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS; + desc.miss.module = optixModule; + desc.miss.entryFunctionName = "__miss__noop"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &missPGNoOp)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup hitPGTriangle; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleCH = optixModule; + desc.hitgroup.entryFunctionNameCH = "__closesthit__triangle"; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__triangle"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &hitPGTriangle)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup hitPGBilinearPatch; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleCH = optixModule; + desc.hitgroup.entryFunctionNameCH = "__closesthit__bilinearPatch"; + desc.hitgroup.moduleIS = optixModule; + desc.hitgroup.entryFunctionNameIS = "__intersection__bilinearPatch"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &hitPGBilinearPatch)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup hitPGQuadric; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleCH = optixModule; + desc.hitgroup.entryFunctionNameCH = "__closesthit__quadric"; + desc.hitgroup.moduleIS = optixModule; + desc.hitgroup.entryFunctionNameIS = "__intersection__quadric"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &hitPGQuadric)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup raygenPGShadow; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN; + desc.raygen.module = optixModule; + desc.raygen.entryFunctionName = "__raygen__shadow"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &raygenPGShadow)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup missPGShadow; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS; + desc.miss.module = optixModule; + desc.miss.entryFunctionName = "__miss__shadow"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &missPGShadow)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup anyhitPGShadowTriangle; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__shadowTriangle"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &anyhitPGShadowTriangle)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup raygenPGShadowTr; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN; + desc.raygen.module = optixModule; + desc.raygen.entryFunctionName = "__raygen__shadow_Tr"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &raygenPGShadowTr)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup missPGShadowTr; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS; + desc.miss.module = optixModule; + desc.miss.entryFunctionName = "__miss__shadow_Tr"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &missPGShadowTr)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup anyhitPGShadowBilinearPatch; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleIS = optixModule; + desc.hitgroup.entryFunctionNameIS = "__intersection__bilinearPatch"; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__shadowBilinearPatch"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &anyhitPGShadowBilinearPatch)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup anyhitPGShadowQuadric; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleIS = optixModule; + desc.hitgroup.entryFunctionNameIS = "__intersection__quadric"; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__shadowQuadric"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &anyhitPGShadowQuadric)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup raygenPGRandomHit; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN; + desc.raygen.module = optixModule; + desc.raygen.entryFunctionName = "__raygen__randomHit"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &raygenPGRandomHit)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup hitPGRandomHitTriangle; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__randomHitTriangle"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &hitPGRandomHitTriangle)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup hitPGRandomHitBilinearPatch; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleIS = optixModule; + desc.hitgroup.entryFunctionNameIS = "__intersection__bilinearPatch"; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__randomHitBilinearPatch"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &hitPGRandomHitBilinearPatch)); + LOG_VERBOSE("%s", log); + } + + OptixProgramGroup hitPGRandomHitQuadric; + { + OptixProgramGroupDesc desc = {}; + desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP; + desc.hitgroup.moduleIS = optixModule; + desc.hitgroup.entryFunctionNameIS = "__intersection__quadric"; + desc.hitgroup.moduleAH = optixModule; + desc.hitgroup.entryFunctionNameAH = "__anyhit__randomHitQuadric"; + OPTIX_CHECK(optixProgramGroupCreate(optixContext, &desc, 1, &pgOptions, log, + &logSize, &hitPGRandomHitQuadric)); + LOG_VERBOSE("%s", log); + } + + // Optix pipeline... + OptixProgramGroup allPGs[] = {raygenPGClosest, + missPGNoOp, + hitPGTriangle, + hitPGBilinearPatch, + hitPGQuadric, + raygenPGShadow, + missPGShadow, + anyhitPGShadowTriangle, + anyhitPGShadowBilinearPatch, + anyhitPGShadowQuadric, + raygenPGShadowTr, + missPGShadowTr, + raygenPGRandomHit, + hitPGRandomHitTriangle, + hitPGRandomHitBilinearPatch, + hitPGRandomHitQuadric}; + OPTIX_CHECK(optixPipelineCreate( + optixContext, &pipelineCompileOptions, &pipelineLinkOptions, allPGs, + sizeof(allPGs) / sizeof(allPGs[0]), log, &logSize, &optixPipeline)); + LOG_VERBOSE("%s", log); + +#if 0 + OPTIX_CHECK(optixPipelineSetStackSize( + optixPipeline, + 0, /* direct callables from intersect or any-hit */ + 0, /* direct callables from raygen, miss, or closest hit */ + 4 * 1024, /* continuation stack */ + 2 /* max graph depth. NOTE: this is 3 when we have motion xforms... */)); +#endif + + // Shader binding tables... + // Hitgroups are done as meshes are processed + + // Closest intersection + RaygenRecord *raygenClosestRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(raygenPGClosest, raygenClosestRecord)); + intersectSBT.raygenRecord = (CUdeviceptr)raygenClosestRecord; + + MissRecord *missNoOpRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(missPGNoOp, missNoOpRecord)); + intersectSBT.missRecordBase = (CUdeviceptr)missNoOpRecord; + intersectSBT.missRecordStrideInBytes = sizeof(MissRecord); + intersectSBT.missRecordCount = 1; + + // Shadow + RaygenRecord *raygenShadowRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(raygenPGShadow, raygenShadowRecord)); + shadowSBT.raygenRecord = (CUdeviceptr)raygenShadowRecord; + + MissRecord *missShadowRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(missPGShadow, missShadowRecord)); + shadowSBT.missRecordBase = (CUdeviceptr)missShadowRecord; + shadowSBT.missRecordStrideInBytes = sizeof(MissRecord); + shadowSBT.missRecordCount = 1; + + // Shadow + Tr + RaygenRecord *raygenShadowTrRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(raygenPGShadowTr, raygenShadowTrRecord)); + shadowTrSBT.raygenRecord = (CUdeviceptr)raygenShadowTrRecord; + + MissRecord *missShadowTrRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(missPGShadowTr, missShadowTrRecord)); + shadowTrSBT.missRecordBase = (CUdeviceptr)missShadowTrRecord; + shadowTrSBT.missRecordStrideInBytes = sizeof(MissRecord); + shadowTrSBT.missRecordCount = 1; + + // Random hit + RaygenRecord *raygenRandomHitRecord = alloc.new_object(); + OPTIX_CHECK(optixSbtRecordPackHeader(raygenPGRandomHit, raygenRandomHitRecord)); + randomHitSBT.raygenRecord = (CUdeviceptr)raygenRandomHitRecord; + randomHitSBT.missRecordBase = (CUdeviceptr)missNoOpRecord; + randomHitSBT.missRecordStrideInBytes = sizeof(MissRecord); + randomHitSBT.missRecordCount = 1; + + // Textures + std::map floatTextures; + std::map spectrumTextures; + scene.CreateTextures(&floatTextures, &spectrumTextures, alloc, true); + + // Materials + std::map namedMaterials; + std::vector materials; + scene.CreateMaterials(floatTextures, spectrumTextures, alloc, &namedMaterials, + &materials); + + // Report which Materials are actually present... + auto updateMaterialNeeds = [&](MaterialHandle m) { + if (!m) + return; + + *haveSubsurface |= m.HasSubsurfaceScattering(); + + FloatTextureHandle displace = m.GetDisplacement(); + if (m.CanEvaluateTextures(BasicTextureEvaluator()) && + (!displace && BasicTextureEvaluator().CanEvaluate({displace}, {}))) + (*haveBasicEvalMaterial)[m.Tag()] = true; + else + (*haveUniversalEvalMaterial)[m.Tag()] = true; + }; + for (MaterialHandle m : materials) + updateMaterialNeeds(m); + for (const auto &m : namedMaterials) + updateMaterialNeeds(m.second); + + for (const auto &shape : scene.shapes) + if (shape.name != "sphere" && shape.name != "cylinder" && shape.name != "disk" && + shape.name != "trianglemesh" && shape.name != "plymesh" && + shape.name != "loopsubdiv" && shape.name != "bilinearmesh") + ErrorExit(&shape.loc, "%s: unknown shape", shape.name); + + OptixTraversableHandle triangleGASTraversable = createGASForTriangles( + scene.shapes, hitPGTriangle, anyhitPGShadowTriangle, hitPGRandomHitTriangle, + floatTextures, namedMaterials, materials, media, shapeIndexToAreaLights, &bounds); + int bilinearSBTOffset = intersectHGRecords.size(); + OptixTraversableHandle bilinearPatchGASTraversable = + createGASForBLPs(scene.shapes, hitPGBilinearPatch, anyhitPGShadowBilinearPatch, + hitPGRandomHitBilinearPatch, floatTextures, namedMaterials, + materials, media, shapeIndexToAreaLights, &bounds); + int quadricSBTOffset = intersectHGRecords.size(); + OptixTraversableHandle quadricGASTraversable = createGASForQuadrics( + scene.shapes, hitPGQuadric, anyhitPGShadowQuadric, hitPGRandomHitQuadric, + floatTextures, namedMaterials, materials, media, shapeIndexToAreaLights, &bounds); + + pstd::vector iasInstances(alloc); + + OptixInstance gasInstance = {}; + float identity[12] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}; + memcpy(gasInstance.transform, identity, 12 * sizeof(float)); + gasInstance.visibilityMask = 255; + gasInstance.flags = + OPTIX_INSTANCE_FLAG_NONE; // TODO: OPTIX_INSTANCE_FLAG_DISABLE_ANYHIT + if (triangleGASTraversable) { + gasInstance.traversableHandle = triangleGASTraversable; + gasInstance.sbtOffset = 0; + iasInstances.push_back(gasInstance); + } + if (bilinearPatchGASTraversable) { + gasInstance.traversableHandle = bilinearPatchGASTraversable; + gasInstance.sbtOffset = bilinearSBTOffset; + iasInstances.push_back(gasInstance); + } + if (quadricGASTraversable) { + gasInstance.traversableHandle = quadricGASTraversable; + gasInstance.sbtOffset = quadricSBTOffset; + iasInstances.push_back(gasInstance); + } + + // Create GASs for instance definitions + // TODO: better name here... + struct Instance { + OptixTraversableHandle handle; + Bounds3f bounds; + int sbtOffset; + }; + std::map instanceMap; + for (const auto &def : scene.instanceDefinitions) { + if (!def.second.animatedShapes.empty()) + Warning("Ignoring %d animated shapes in instance \"%s\".", + def.second.animatedShapes.size(), def.first); + + Instance inst; + inst.sbtOffset = intersectHGRecords.size(); + inst.handle = createGASForTriangles( + def.second.shapes, hitPGTriangle, anyhitPGShadowTriangle, + hitPGRandomHitTriangle, floatTextures, namedMaterials, materials, media, {}, + &inst.bounds); + instanceMap[def.first] = inst; + } + + // Create OptixInstances for instances + for (const auto &inst : scene.instances) { + if (instanceMap.find(inst.name) == instanceMap.end()) + ErrorExit(&inst.loc, "%s: object instance not defined.", inst.name); + + if (inst.renderFromInstance == nullptr) { + Warning(&inst.loc, "%s: object instance has animated transformation. TODO", + inst.name); + continue; + } + + const Instance &in = instanceMap[inst.name]; + if (!in.handle) { + // Warning(&inst.loc, "Skipping instance of empty instance + // definition"); + continue; + } + + bounds = Union(bounds, (*inst.renderFromInstance)(instanceMap[inst.name].bounds)); + + OptixInstance optixInstance = {}; + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 4; ++j) + optixInstance.transform[4 * i + j] = + inst.renderFromInstance->GetMatrix()[i][j]; + optixInstance.visibilityMask = 255; + optixInstance.sbtOffset = instanceMap[inst.name].sbtOffset; + optixInstance.flags = + OPTIX_INSTANCE_FLAG_NONE; // TODO: + // OPTIX_INSTANCE_FLAG_DISABLE_ANYHIT + optixInstance.traversableHandle = instanceMap[inst.name].handle; + iasInstances.push_back(optixInstance); + } + + // Build the top-level IAS + OptixBuildInput buildInput = {}; + buildInput.type = OPTIX_BUILD_INPUT_TYPE_INSTANCES; + buildInput.instanceArray.instances = CUdeviceptr(iasInstances.data()); + buildInput.instanceArray.numInstances = iasInstances.size(); + std::vector buildInputs = {buildInput}; + + rootTraversable = buildBVH({buildInput}); + + if (!scene.animatedShapes.empty()) + Warning("Ignoring %d animated shapes", scene.animatedShapes.size()); + + intersectSBT.hitgroupRecordBase = (CUdeviceptr)intersectHGRecords.data(); + intersectSBT.hitgroupRecordStrideInBytes = sizeof(HitgroupRecord); + intersectSBT.hitgroupRecordCount = intersectHGRecords.size(); + + shadowSBT.hitgroupRecordBase = (CUdeviceptr)shadowHGRecords.data(); + shadowSBT.hitgroupRecordStrideInBytes = sizeof(HitgroupRecord); + shadowSBT.hitgroupRecordCount = shadowHGRecords.size(); + + // Still want to run the closest hit shaders... + shadowTrSBT.hitgroupRecordBase = (CUdeviceptr)intersectHGRecords.data(); + shadowTrSBT.hitgroupRecordStrideInBytes = sizeof(HitgroupRecord); + shadowTrSBT.hitgroupRecordCount = intersectHGRecords.size(); + + randomHitSBT.hitgroupRecordBase = (CUdeviceptr)randomHitHGRecords.data(); + randomHitSBT.hitgroupRecordStrideInBytes = sizeof(HitgroupRecord); + randomHitSBT.hitgroupRecordCount = randomHitHGRecords.size(); +} + +GPUAccel::ParamBufferState &GPUAccel::getParamBuffer( + const RayIntersectParameters ¶ms) const { + CHECK(nextParamOffset < paramsPool.size()); + + ParamBufferState &pbs = paramsPool[nextParamOffset]; + if (++nextParamOffset == paramsPool.size()) + nextParamOffset = 0; + if (!pbs.used) + pbs.used = true; + else + CUDA_CHECK(cudaEventSynchronize(pbs.finishedEvent)); + + // Copy to host-side pinned memory + memcpy(pbs.hostPtr, ¶ms, sizeof(params)); + CUDA_CHECK(cudaMemcpyAsync((void *)pbs.ptr, pbs.hostPtr, sizeof(params), + cudaMemcpyHostToDevice)); + + return pbs; +} + +std::pair GPUAccel::IntersectClosest( + int maxRays, EscapedRayQueue *escapedRayQueue, HitAreaLightQueue *hitAreaLightQueue, + MaterialEvalQueue *basicEvalMaterialQueue, + MaterialEvalQueue *universalEvalMaterialQueue, + MediumTransitionQueue *mediumTransitionQueue, MediumSampleQueue *mediumSampleQueue, + RayQueue *rayQueue) const { + cudaEvent_t start, stop; + cudaEventCreate(&start); + cudaEventCreate(&stop); + + cudaEventRecord(start); + + if (rootTraversable) { + RayIntersectParameters params; + params.traversable = rootTraversable; + params.rayQueue = rayQueue; + params.escapedRayQueue = escapedRayQueue; + params.hitAreaLightQueue = hitAreaLightQueue; + params.basicEvalMaterialQueue = basicEvalMaterialQueue; + params.universalEvalMaterialQueue = universalEvalMaterialQueue; + params.mediumTransitionQueue = mediumTransitionQueue; + params.mediumSampleQueue = mediumSampleQueue; + + ParamBufferState &pbs = getParamBuffer(params); + +#ifndef NDEBUG + LOG_VERBOSE("Launching intersect closest"); +#endif +#ifdef NVTX + nvtxRangePush("GPUAccel::IntersectClosest"); +#endif + + OPTIX_CHECK(optixLaunch(optixPipeline, cudaStream, pbs.ptr, + sizeof(RayIntersectParameters), &intersectSBT, maxRays, 1, + 1)); + CUDA_CHECK(cudaEventRecord(pbs.finishedEvent)); + +#ifdef NVTX + nvtxRangePop(); +#endif +#ifndef NDEBUG + CUDA_CHECK(cudaDeviceSynchronize()); + LOG_VERBOSE("Post-sync triangle intersect closest"); +#endif + } + + cudaEventRecord(stop); + + return std::make_pair(start, stop); +}; + +std::pair GPUAccel::IntersectShadow( + int maxRays, ShadowRayQueue *shadowRayQueue) const { + cudaEvent_t start, stop; + cudaEventCreate(&start); + cudaEventCreate(&stop); + + cudaEventRecord(start); + + if (rootTraversable) { + RayIntersectParameters params; + params.traversable = rootTraversable; + params.shadowRayQueue = shadowRayQueue; + + ParamBufferState &pbs = getParamBuffer(params); + +#ifndef NDEBUG + LOG_VERBOSE("Launching intersect shadow"); +#endif +#ifdef NVTX + nvtxRangePush("GPUAccel::IntersectShadow"); +#endif + + OPTIX_CHECK(optixLaunch(optixPipeline, cudaStream, pbs.ptr, + sizeof(RayIntersectParameters), &shadowSBT, maxRays, 1, + 1)); + CUDA_CHECK(cudaEventRecord(pbs.finishedEvent)); + +#ifdef NVTX + nvtxRangePop(); +#endif +#ifndef NDEBUG + CUDA_CHECK(cudaDeviceSynchronize()); + LOG_VERBOSE("Post-sync intersect shadow"); +#endif + } + + cudaEventRecord(stop); + return std::make_pair(start, stop); +} + +std::pair GPUAccel::IntersectShadowTr( + int maxRays, ShadowRayQueue *shadowRayQueue) const { + cudaEvent_t start, stop; + cudaEventCreate(&start); + cudaEventCreate(&stop); + + cudaEventRecord(start); + + if (rootTraversable) { + RayIntersectParameters params; + params.traversable = rootTraversable; + params.shadowRayQueue = shadowRayQueue; + + ParamBufferState &pbs = getParamBuffer(params); + +#ifndef NDEBUG + LOG_VERBOSE("Launching intersect shadow Tr"); +#endif +#ifdef NVTX + nvtxRangePush("GPUAccel::IntersectShadowTr"); +#endif + + OPTIX_CHECK(optixLaunch(optixPipeline, cudaStream, pbs.ptr, + sizeof(RayIntersectParameters), &shadowTrSBT, maxRays, 1, + 1)); + CUDA_CHECK(cudaEventRecord(pbs.finishedEvent)); + +#ifdef NVTX + nvtxRangePop(); +#endif +#ifndef NDEBUG + CUDA_CHECK(cudaDeviceSynchronize()); + LOG_VERBOSE("Post-sync intersect shadow Tr"); +#endif + } + + cudaEventRecord(stop); + return std::make_pair(start, stop); +} + +std::pair GPUAccel::IntersectOneRandom( + int maxRays, SubsurfaceScatterQueue *subsurfaceScatterQueue) const { + cudaEvent_t start, stop; + cudaEventCreate(&start); + cudaEventCreate(&stop); + + cudaEventRecord(start); + + if (rootTraversable) { + RayIntersectParameters params; + params.traversable = rootTraversable; + params.subsurfaceScatterQueue = subsurfaceScatterQueue; + + ParamBufferState &pbs = getParamBuffer(params); + +#ifndef NDEBUG + LOG_VERBOSE("Launching intersect random"); +#endif +#ifdef NVTX + nvtxRangePush("GPUAccel::IntersectOneRandom"); +#endif + + OPTIX_CHECK(optixLaunch(optixPipeline, cudaStream, pbs.ptr, + sizeof(RayIntersectParameters), &randomHitSBT, maxRays, 1, + 1)); + CUDA_CHECK(cudaEventRecord(pbs.finishedEvent)); + +#ifdef NVTX + nvtxRangePop(); +#endif +#ifndef NDEBUG + CUDA_CHECK(cudaDeviceSynchronize()); + LOG_VERBOSE("Post-sync triangle intersect random"); +#endif + } + + cudaEventRecord(stop); + + return std::make_pair(start, stop); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/accel.h b/src/pbrt/gpu/accel.h new file mode 100644 index 00000000..69bcd092 --- /dev/null +++ b/src/pbrt/gpu/accel.h @@ -0,0 +1,120 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_ACCEL_H +#define PBRT_GPU_ACCEL_H + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace pbrt { + +class GPUAccel { + public: + GPUAccel(const ParsedScene &scene, Allocator alloc, CUstream cudaStream, + const std::map *> &shapeIndexToAreaLights, + const std::map &media, + pstd::array *haveBasicEvalMaterial, + pstd::array *haveUniversalEvalMaterial, + bool *haveSubsurface); + + Bounds3f Bounds() const { return bounds; } + + std::pair IntersectClosest( + int maxRays, EscapedRayQueue *escapedRayQueue, + HitAreaLightQueue *hitAreaLightQueue, MaterialEvalQueue *basicEvalMaterialQueue, + MaterialEvalQueue *universalEvalMaterialQueue, + MediumTransitionQueue *mediumTransitionQueue, + MediumSampleQueue *mediumSampleQueue, RayQueue *rayQueue) const; + + std::pair IntersectShadow( + int maxRays, ShadowRayQueue *shadowRayQueue) const; + + std::pair IntersectShadowTr(int maxRays, + ShadowRayQueue *shadowRayQueue) const; + + std::pair IntersectOneRandom( + int maxRays, SubsurfaceScatterQueue *subsurfaceScatterQueue) const; + + private: + struct HitgroupRecord; + + OptixTraversableHandle createGASForTriangles( + const std::vector &shapes, const OptixProgramGroup &intersectPG, + const OptixProgramGroup &shadowPG, const OptixProgramGroup &randomHitPG, + const std::map &floatTextures, + const std::map &namedMaterials, + const std::vector &materials, + const std::map &media, + const std::map *> &shapeIndexToAreaLights, + Bounds3f *gasBounds); + + OptixTraversableHandle createGASForBLPs( + const std::vector &shapes, const OptixProgramGroup &intersectPG, + const OptixProgramGroup &shadowPG, const OptixProgramGroup &randomHitPG, + const std::map &floatTextures, + const std::map &namedMaterials, + const std::vector &materials, + const std::map &media, + const std::map *> &shapeIndexToAreaLights, + Bounds3f *gasBounds); + + OptixTraversableHandle createGASForQuadrics( + const std::vector &shapes, const OptixProgramGroup &intersectPG, + const OptixProgramGroup &shadowPG, const OptixProgramGroup &randomHitPG, + const std::map &floatTextures, + const std::map &namedMaterials, + const std::vector &materials, + const std::map &media, + const std::map *> &shapeIndexToAreaLights, + Bounds3f *gasBounds); + + OptixTraversableHandle buildBVH(const std::vector &buildInputs); + + Allocator alloc; + Bounds3f bounds; + CUstream cudaStream; + OptixDeviceContext optixContext; + OptixModule optixModule; + OptixPipeline optixPipeline; + + struct ParamBufferState { + bool used = false; + cudaEvent_t finishedEvent; + CUdeviceptr ptr = 0; + void *hostPtr = nullptr; + }; + mutable std::vector paramsPool; + mutable size_t nextParamOffset = 0; + + ParamBufferState &getParamBuffer(const RayIntersectParameters &) const; + + pstd::vector intersectHGRecords; + pstd::vector shadowHGRecords; + pstd::vector randomHitHGRecords; + OptixShaderBindingTable intersectSBT = {}, shadowSBT = {}, shadowTrSBT = {}; + OptixShaderBindingTable randomHitSBT = {}; + OptixTraversableHandle rootTraversable = {}; +}; + +} // namespace pbrt + +#endif // PBRT_GPU_ACCEL_H diff --git a/src/pbrt/gpu/camera.cpp b/src/pbrt/gpu/camera.cpp new file mode 100644 index 00000000..453f21a3 --- /dev/null +++ b/src/pbrt/gpu/camera.cpp @@ -0,0 +1,96 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif // PBRT_GPU_DBG + +namespace pbrt { + +template +void GPUPathIntegrator::GenerateCameraRays(int y0, int sampleIndex) { + Vector2i resolution = film.PixelBounds().Diagonal(); + Bounds2i pixelBounds = film.PixelBounds(); + + GPUParallelFor("Generate Camera rays", maxQueueSize, [=] PBRT_GPU(int pixelIndex) { + Point2i pPixel(pixelBounds.pMin.x + int(pixelIndex) % resolution.x, + pixelBounds.pMin.y + y0 + int(pixelIndex) / resolution.x); + pixelSampleState.pPixel[pixelIndex] = pPixel; + + // If we've split the image into multiple spans of scanlines, + // then in the final pass, we may have a few more threads + // launched than there are remaining pixels. Bail out without + // enqueuing a ray if so. + if (!InsideExclusive(pPixel, pixelBounds)) + return; + + // Initialize the Sampler for the current pixel and sample. + Sampler sampler = *this->sampler.Cast(); + sampler.StartPixelSample(pPixel, sampleIndex, 0); + + // Sample wavelengths for the ray path for the pixel sample. + // Use a blue noise pattern rather than the Sampler. + Float lu = RadicalInverse(1, sampleIndex) + BlueNoise(47, pPixel.x, pPixel.y); + if (lu >= 1) + lu -= 1; + if (GetOptions().disableWavelengthJitter) + lu = 0.5f; + SampledWavelengths lambda = film.SampleWavelengths(lu); + + // Generate samples for the camera ray and the ray itself. + CameraSample cameraSample = GetCameraSample(sampler, pPixel, filter); + CameraRay cameraRay = camera.GenerateRay(cameraSample, lambda); + + // Initialize the rest of the pixel sample's state. + pixelSampleState.L[pixelIndex] = SampledSpectrum(0.f); + pixelSampleState.lambda[pixelIndex] = lambda; + pixelSampleState.cameraRayWeight[pixelIndex] = cameraRay.weight; + pixelSampleState.filterWeight[pixelIndex] = cameraSample.weight; + if (initializeVisibleSurface) + pixelSampleState.visibleSurface[pixelIndex] = VisibleSurface(); + + if (cameraRay.weight) + // Enqueue the camera ray if the camera gave us one with + // non-zero weight. (RealisticCamera doesn't always return + // a ray, e.g. in the case of vignetting...) + rayQueues[0]->PushCameraRay(cameraRay.ray, lambda, pixelIndex); + }); +} + +void GPUPathIntegrator::GenerateCameraRays(int y0, int sampleIndex) { + auto generateRays = [=](auto sampler) { + using Sampler = std::remove_reference_t; + if constexpr (!std::is_same_v && + !std::is_same_v) + GenerateCameraRays(y0, sampleIndex); + }; + // Somewhat surprisingly, GenerateCameraRays() is specialized on the + // type of the Sampler being used and not on, say, the Camera. By + // specializing on the sampler type, the particular Sampler used can be + // stack allocated (rather than living in global memory), which in turn + // allows its state to be stored in registers in the + // GenerateCameraRays() kernel. There's little benefit from + // specializing on the Camera since its state is read-only and shared + // among all of the threads, so caches well in practice. + sampler.DispatchCPU(generateRays); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/film.cpp b/src/pbrt/gpu/film.cpp new file mode 100644 index 00000000..d13aaadc --- /dev/null +++ b/src/pbrt/gpu/film.cpp @@ -0,0 +1,44 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif + +namespace pbrt { + +void GPUPathIntegrator::UpdateFilm() { + GPUParallelFor("Update Film", maxQueueSize, [=] PBRT_GPU(int pixelIndex) { + Point2i pPixel = pixelSampleState.pPixel[pixelIndex]; + if (!InsideExclusive(pPixel, film.PixelBounds())) + return; + + // Compute final weighted radiance value + SampledSpectrum Lw = SampledSpectrum(pixelSampleState.L[pixelIndex]) * + pixelSampleState.cameraRayWeight[pixelIndex]; + + SampledWavelengths lambda = pixelSampleState.lambda[pixelIndex]; + Float filterWeight = pixelSampleState.filterWeight[pixelIndex]; + + if (initializeVisibleSurface) { + VisibleSurface visibleSurface = pixelSampleState.visibleSurface[pixelIndex]; + film.AddSample(pPixel, Lw, lambda, &visibleSurface, filterWeight); + } else + film.AddSample(pPixel, Lw, lambda, nullptr, filterWeight); + }); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/init.cpp b/src/pbrt/gpu/init.cpp new file mode 100644 index 00000000..0d98c958 --- /dev/null +++ b/src/pbrt/gpu/init.cpp @@ -0,0 +1,72 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include + +#include + +#ifdef NVTX +#include +#endif + +namespace pbrt { + +void GPUInit() { + cudaFree(nullptr); + + int driverVersion; + CUDA_CHECK(cudaDriverGetVersion(&driverVersion)); + int runtimeVersion; + CUDA_CHECK(cudaRuntimeGetVersion(&runtimeVersion)); + auto versionToString = [](int version) { + int major = version / 1000; + int minor = (version - major * 1000) / 10; + return StringPrintf("%d.%d", major, minor); + }; + LOG_VERBOSE("GPU CUDA driver %s, CUDA runtime %s", versionToString(driverVersion), + versionToString(runtimeVersion)); + + int nDevices; + CUDA_CHECK(cudaGetDeviceCount(&nDevices)); + for (int i = 0; i < nDevices; ++i) { + cudaDeviceProp deviceProperties; + CUDA_CHECK(cudaGetDeviceProperties(&deviceProperties, i)); + CHECK(deviceProperties.canMapHostMemory); + + size_t stackSize; + CUDA_CHECK(cudaDeviceGetLimit(&stackSize, cudaLimitStackSize)); + size_t printfFIFOSize; + CUDA_CHECK(cudaDeviceGetLimit(&printfFIFOSize, cudaLimitPrintfFifoSize)); + + LOG_VERBOSE( + "CUDA device %d (%s) with %f MiB, %d SMs running at %f MHz " + "with shader model %d.%d, max stack %d printf FIFO %d", + i, deviceProperties.name, deviceProperties.totalGlobalMem / (1024. * 1024.), + deviceProperties.multiProcessorCount, deviceProperties.clockRate / 1000., + deviceProperties.major, deviceProperties.minor, stackSize, printfFIFOSize); + } + + int device = Options->gpuDevice ? *Options->gpuDevice : 0; + LOG_VERBOSE("Selecting GPU device %d", device); +#ifdef NVTX + nvtxNameCuDevice(device, "PBRT_GPU"); +#endif + CUDA_CHECK(cudaSetDevice(device)); + + CUDA_CHECK(cudaDeviceSetLimit(cudaLimitStackSize, 8192)); + size_t stackSize; + CUDA_CHECK(cudaDeviceGetLimit(&stackSize, cudaLimitStackSize)); + LOG_VERBOSE("Reset stack size to %d", stackSize); + + CUDA_CHECK(cudaDeviceSetLimit(cudaLimitPrintfFifoSize, 32 * 1024 * 1024)); + + CUDA_CHECK(cudaDeviceSetCacheConfig(cudaFuncCachePreferL1)); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/init.h b/src/pbrt/gpu/init.h new file mode 100644 index 00000000..812ebf8d --- /dev/null +++ b/src/pbrt/gpu/init.h @@ -0,0 +1,14 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_INIT_H +#define PBRT_GPU_INIT_H + +namespace pbrt { + +void GPUInit(); + +} // namespace pbrt + +#endif // PBRT_GPU_INIT_H diff --git a/src/pbrt/gpu/launch.cpp b/src/pbrt/gpu/launch.cpp new file mode 100644 index 00000000..57eea357 --- /dev/null +++ b/src/pbrt/gpu/launch.cpp @@ -0,0 +1,77 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include + +#include +#include + +namespace pbrt { + +static std::vector gpuKernelLaunchOrder; +static std::map gpuKernels; + +GPUKernelStats &GetGPUKernelStats(std::type_index typeIndex, const char *description) { + auto iter = gpuKernels.find(typeIndex); + if (iter != gpuKernels.end()) { + CHECK_EQ(iter->second.description, std::string(description)); + return iter->second; + } + + gpuKernelLaunchOrder.push_back(typeIndex); + gpuKernels[typeIndex] = GPUKernelStats(description); + return gpuKernels.find(typeIndex)->second; +} + +void ReportKernelStats() { + CUDA_CHECK(cudaDeviceSynchronize()); + + // Compute total milliseconds over all kernels and launches + float totalms = 0.f; + for (const auto kernelTypeId : gpuKernelLaunchOrder) { + const GPUKernelStats &stats = gpuKernels[kernelTypeId]; + for (const auto &launch : stats.launchEvents) { + cudaEventSynchronize(launch.second); + float ms = 0; + cudaEventElapsedTime(&ms, launch.first, launch.second); + totalms += ms; + } + } + + printf("GPU Kernel Profile:\n"); + int otherLaunches = 0; + float otherms = 0; + const float otherCutoff = 0.001f * totalms; + for (const auto kernelTypeId : gpuKernelLaunchOrder) { + float summs = 0.f, minms = 1e30, maxms = 0; + const GPUKernelStats &stats = gpuKernels[kernelTypeId]; + for (const auto &launch : stats.launchEvents) { + float ms = 0; + cudaEventElapsedTime(&ms, launch.first, launch.second); + summs += ms; + minms = std::min(minms, ms); + maxms = std::max(maxms, ms); + } + + if (summs > otherCutoff) + Printf(" %-49s %5d launches %9.2f ms / %5.1f%s (avg %6.3f, min " + "%6.3f, max %7.3f)\n", + stats.description, stats.launchEvents.size(), summs, + 100.f * summs / totalms, "%", summs / stats.launchEvents.size(), minms, + maxms); + else { + otherms += summs; + otherLaunches += stats.launchEvents.size(); + } + } + Printf(" %-49s %5d launches %9.2f ms / %5.1f%s (avg %6.3f)\n", "Other", + otherLaunches, otherms, 100.f * otherms / totalms, "%", + otherms / otherLaunches); + Printf("\nTotal GPU time: %9.2f ms\n", totalms); + Printf("\n"); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/launch.h b/src/pbrt/gpu/launch.h new file mode 100644 index 00000000..0429296c --- /dev/null +++ b/src/pbrt/gpu/launch.h @@ -0,0 +1,101 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_LAUNCH_H +#define PBRT_GPU_LAUNCH_H + +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#ifdef NVTX +#include +#endif + +namespace pbrt { + +struct GPUKernelStats { + GPUKernelStats() = default; + GPUKernelStats(const char *description) : description(description) { + launchEvents.reserve(256); + } + + std::string description; + int blockSize = 0; + std::vector> launchEvents; +}; + +GPUKernelStats &GetGPUKernelStats(std::type_index typeIndex, const char *description); + +template +inline GPUKernelStats &GetGPUKernelStats(const char *description) { + return GetGPUKernelStats(std::type_index(typeid(T)), description); +} + +template +__global__ void Kernel(F func, int nItems) { + int tid = blockIdx.x * blockDim.x + threadIdx.x; + if (tid >= nItems) + return; + + func(tid); +} + +template +void GPUParallelFor(const char *description, int nItems, F func) { +#ifdef NVTX + nvtxRangePush(description); +#endif + auto kernel = &Kernel; + + GPUKernelStats &kernelStats = GetGPUKernelStats(description); + if (kernelStats.blockSize == 0) { + int minGridSize; + CUDA_CHECK(cudaOccupancyMaxPotentialBlockSize( + &minGridSize, &kernelStats.blockSize, kernel, 0, 0)); + + LOG_VERBOSE("[%s]: block size %d", description, kernelStats.blockSize); + } + + cudaEvent_t start, stop; + cudaEventCreate(&start); + cudaEventCreate(&stop); + +#ifndef NDEBUG + LOG_VERBOSE("Launching %s", description); +#endif + cudaEventRecord(start); + int gridSize = (nItems + kernelStats.blockSize - 1) / kernelStats.blockSize; + kernel<<>>(func, nItems); + cudaEventRecord(stop); + + kernelStats.launchEvents.push_back(std::make_pair(start, stop)); + +#ifndef NDEBUG + CUDA_CHECK(cudaDeviceSynchronize()); + LOG_VERBOSE("Post-sync %s", description); +#endif +#ifdef NVTX + nvtxRangePop(); +#endif +} + +template +void GPUDo(const char *description, F func) { + GPUParallelFor(description, 1, [=] PBRT_GPU(int) { func(); }); +} + +void ReportKernelStats(); + +} // namespace pbrt + +#endif // PBRT_GPU_LAUNCH_H diff --git a/src/pbrt/gpu/media.cpp b/src/pbrt/gpu/media.cpp new file mode 100644 index 00000000..150bd90e --- /dev/null +++ b/src/pbrt/gpu/media.cpp @@ -0,0 +1,334 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif // PBRT_GPU_DBG + +namespace pbrt { + +void GPUPathIntegrator::SampleMediumInteraction(int depth) { + ForAllQueued( + "Sample medium interaction", mediumSampleQueue, maxQueueSize, + [=] PBRT_GPU(MediumSampleWorkItem ms, int index) { + Ray ray = ms.ray; + Float tMax = ms.tMax; + + DBG("Sampling medium interaction ray index %d depth %d ray %f %f %f d %f %f " + "%f tMax %f\n", + ms.rayIndex, depth, ray.o.x, ray.o.y, ray.o.z, ray.d.x, ray.d.y, ray.d.z, + tMax); + + SampledWavelengths lambda = ms.lambda; + SampledSpectrum beta = ms.beta; + SampledSpectrum pdfUni = ms.pdfUni; + SampledSpectrum pdfNEE = ms.pdfNEE; + SampledSpectrum L(0.f); + RNG rng(Hash(tMax), Hash(ray.d)); + + DBG("Lambdas %f %f %f %f\n", lambda[0], lambda[1], lambda[2], lambda[3]); + DBG("Medium sample beta %f %f %f %f pdfUni %f %f %f %f pdfNEE %f %f %f %f\n", + beta[0], beta[1], beta[2], beta[3], pdfUni[0], pdfUni[1], pdfUni[2], + pdfUni[3], pdfNEE[0], pdfNEE[1], pdfNEE[2], pdfNEE[3]); + + // Sample the medium according to T_maj, the homogeneous + // transmission function based on the majorant. + bool scattered = false; + ray.medium.SampleTmaj( + ray, tMax, rng, lambda, [&](const MediumSample &mediumSample) { + if (!mediumSample.intr) { + // No interaction was sampled, but update the path + // throughput and unidirectional PDF to the end of + // the ray segment. + beta *= mediumSample.Tmaj; + pdfUni *= mediumSample.Tmaj; + DBG("No intr: beta %f %f %f %f pdfUni %f %f %f %f\n", beta[0], + beta[1], beta[2], beta[3], pdfUni[0], pdfUni[1], pdfUni[2], + pdfUni[3]); + return false; + } + + const MediumInteraction &intr = *mediumSample.intr; + const SampledSpectrum &sigma_a = intr.sigma_a; + const SampledSpectrum &sigma_s = intr.sigma_s; + const SampledSpectrum &Tmaj = mediumSample.Tmaj; + + DBG("Medium event Tmaj %f %f %f %f sigma_a %f %f %f %f sigma_s %f %f " + "%f %f\n", + Tmaj[0], Tmaj[1], Tmaj[2], Tmaj[3], sigma_a[0], sigma_a[1], + sigma_a[2], sigma_a[3], sigma_s[0], sigma_s[1], sigma_s[2], + sigma_s[3]); + + // Add emission, if present. Always do this and scale + // by sigma_a/sigma_maj rather than only doing it + // (without scaling) at absorption events. + if (depth < maxDepth && intr.Le) + L += beta * intr.Le * sigma_a / + (intr.sigma_maj[0] * pdfUni.Average()); + + // Compute probabilities for each type of scattering. + Float pAbsorb = sigma_a[0] / intr.sigma_maj[0]; + Float pScatter = sigma_s[0] / intr.sigma_maj[0]; + Float pNull = std::max(0, 1 - pAbsorb - pScatter); + DBG("Medium scattering probabilities: %f %f %f\n", pAbsorb, pScatter, + pNull); + + // And randomly choose one. + Float um = rng.Uniform(); + int mode = SampleDiscrete({pAbsorb, pScatter, pNull}, um); + + if (mode == 0) { + // Absorption--done. + DBG("absorbed\n"); + beta = SampledSpectrum(0.f); + // Tell the medium to stop traveral. + return false; + } else if (mode == 1) { + // Scattering. + DBG("scattered\n"); + beta *= Tmaj * sigma_s; + pdfUni *= Tmaj * sigma_s; + + // TODO: don't hard code a phase function. + const HGPhaseFunction *phase = + intr.phase.CastOrNullptr(); + // Enqueue medium scattering work. + mediumScatterQueue->Push(MediumScatterWorkItem{ + intr.p(), lambda, beta, pdfUni, ms.rayIndex, *phase, -ray.d, + ms.etaScale, ray.medium, ms.pixelIndex}); + scattered = true; + + return false; + } else { + // Null scattering. + DBG("null-scattered\n"); + SampledSpectrum sigma_n = intr.sigma_n(); + + beta *= Tmaj * sigma_n; + pdfUni *= Tmaj * sigma_n; + pdfNEE *= Tmaj * intr.sigma_maj; + + // It's not unususal for these values to have large + // magnitudes after multiple null scattering + // events, even though in the end ratios like + // beta/pdfUni are generally around 1. To avoid + // overflow, we rescale all three of them by the + // same factor when they become large. + if (beta.MaxComponentValue() > 0x1p24f || + pdfUni.MaxComponentValue() > 0x1p24f || + pdfNEE.MaxComponentValue() > 0x1p24f) { + // Note that no precision is lost in the + // rescaling since we're dividing by a power of + // 2. + beta *= 1.f / 0x1p24f; + pdfUni *= 1.f / 0x1p24f; + pdfNEE *= 1.f / 0x1p24f; + } + + return true; + } + }); + + DBG("Post ray medium sample L %f %f %f %f beta %f %f %f %f\n", L[0], L[1], + L[2], L[3], beta[0], beta[1], beta[2], beta[3]); + DBG("Post ray medium sample pdfUni %f %f %f %f pdfNEE %f %f %f %f\n", + pdfUni[0], pdfUni[1], pdfUni[2], pdfUni[3], pdfNEE[0], pdfNEE[1], + pdfNEE[2], pdfNEE[3]); + + // Add any emission found to its pixel sample's L value. + if (L) { + SampledSpectrum Lp = pixelSampleState.L[ms.pixelIndex]; + pixelSampleState.L[ms.pixelIndex] = Lp + L; + DBG("Added emitted radiance %f %f %f %f at pixel index %d ray index %d\n", + L[0], L[1], L[2], L[3], ms.pixelIndex, ms.rayIndex); + } + + // There's more work to do if there was a scattering event in + // the medium. + if (scattered) + return; + + // Otherwise, enqueue bump and medium stuff... + // FIXME: this is all basically duplicate code w/optix.cu + if (ms.tMax == Infinity) { + // no intersection + if (escapedRayQueue) { + DBG("Adding ray to escapedRayQueue pixel index %d depth %d\n", + ms.pixelIndex, depth); + escapedRayQueue->Push(EscapedRayWorkItem{ + beta, pdfUni, pdfNEE, lambda, ray.o, ray.d, ms.piPrev, ms.nPrev, + ms.nsPrev, (int)ms.isSpecularBounce, ms.pixelIndex}); + } + } + + MaterialHandle material = ms.material; + if (!material) { + Interaction intr(ms.pi, ms.n); + intr.mediumInterface = &ms.mediumInterface; + Ray newRay = intr.SpawnRay(ray.d); + mediumTransitionQueue->Push(MediumTransitionWorkItem{ + newRay, lambda, beta, pdfUni, pdfNEE, ms.piPrev, ms.nPrev, ms.nsPrev, + ms.isSpecularBounce, ms.anyNonSpecularBounces, ms.etaScale, + ms.pixelIndex}); +#if 0 + // WHY NOT THIS? + rayQueues[(depth + 1) & 1]->PushIndirect(newRay, ms.piPrev, ms.nPrev, ms.nsPrev, + beta, pdfUni, pdfNEE, lambda, ms.etaScale, + ms.isSpecularBounce, ms.anyNonSpecularBounces, + ms.pixelIndex); +#endif + return; + } + + if (ms.areaLight) { + DBG("Ray hit an area light: adding to hitAreaLightQueue pixel index %d " + "depth %d\n", + ms.pixelIndex, depth); + // TODO: intr.wo == -ray.d? + hitAreaLightQueue->Push(HitAreaLightWorkItem{ + ms.areaLight, lambda, beta, pdfUni, pdfNEE, Point3f(ms.pi), ms.n, + ms.uv, -ray.d, ms.piPrev, ray.d, ray.time, ms.nPrev, ms.nsPrev, + ms.isSpecularBounce, ms.pixelIndex}); + } + + FloatTextureHandle displacement = material.GetDisplacement(); + + MaterialEvalQueue *q = + (material.CanEvaluateTextures(BasicTextureEvaluator()) && + (!displacement || + BasicTextureEvaluator().CanEvaluate({displacement}, {}))) + ? basicEvalMaterialQueue + : universalEvalMaterialQueue; + + DBG("Enqueuing for material eval, mtl tag %d", material.Tag()); + + auto enqueue = [=](auto ptr) { + using Material = typename std::remove_reference_t; + q->Push(MaterialEvalWorkItem{ + ptr, lambda, beta, pdfUni, ms.pi, ms.n, ms.ns, ms.dpdus, ms.dpdvs, + ms.dndus, ms.dndvs, -ray.d, ms.uv, ray.time, ms.anyNonSpecularBounces, + ms.etaScale, ms.mediumInterface, ms.rayIndex, ms.pixelIndex}); + }; + material.Dispatch(enqueue); + }); + + using PhaseFunction = HGPhaseFunction; + std::string desc = std::string("Sample direct/indirect - Henyey Greenstein"); + ForAllQueued( + desc.c_str(), mediumScatterQueue, maxQueueSize, + [=] PBRT_GPU(MediumScatterWorkItem ms, int index) { + RaySamples raySamples = rayQueues[depth & 1]->raySamples[ms.rayIndex]; + Float time = 0; // TODO: FIXME + Vector3f wo = ms.wo; + + // Sample direct lighting at medium scattering event. First, + // choose a light source. + LightSampleContext ctx(Point3fi(ms.p), Normal3f(0, 0, 0), Normal3f(0, 0, 0)); + pstd::optional sampledLight = + lightSampler.Sample(ctx, raySamples.direct.uc); + + LightHandle light = sampledLight->light; + if (light) { + // And now sample a point on the light. + LightLiSample ls = light.SampleLi(ctx, raySamples.direct.u, ms.lambda, + LightSamplingMode::WithMIS); + if (ls && ls.L) { + Vector3f wi = ls.wi; + SampledSpectrum beta = ms.beta * ms.phase.p(wo, wi); + + DBG("Phase phase beta %f %f %f %f\n", beta[0], beta[1], beta[2], + beta[3]); + + // Compute PDFs for direct lighting MIS calculation. + Float lightPDF = ls.pdf * sampledLight->pdf; + Float phasePDF = + IsDeltaLight(light.Type()) ? 0.f : ms.phase.PDF(wo, wi); + SampledSpectrum pdfUni = ms.pdfUni * phasePDF; + SampledSpectrum pdfNEE = ms.pdfUni * lightPDF; + + SampledSpectrum Ld = beta * ls.L; + Ray ray(ms.p, ls.pLight.p() - ms.p, time, ms.medium); + + // Enqueue shadow ray + shadowRayQueue->Push(ShadowRayWorkItem{ray, 1 - ShadowEpsilon, + ms.lambda, Ld, pdfUni, pdfNEE, + ms.pixelIndex}); + + DBG("Enqueued medium shadow ray depth %d " + "Ld %f %f %f %f pdfUni %f %f %f %f " + "pdfNEE %f %f %f %f parent ray index %d parent pixel index %d\n", + depth, Ld[0], Ld[1], Ld[2], Ld[3], pdfUni[0], pdfUni[1], + pdfUni[2], pdfUni[3], pdfNEE[0], pdfNEE[1], pdfNEE[2], pdfNEE[3], + ms.rayIndex, ms.pixelIndex); + } + } + + // Sample indirect lighting. + PhaseFunctionSample phaseSample = + ms.phase.Sample_p(wo, raySamples.indirect.u); + if (!phaseSample) + return; + + SampledSpectrum beta = ms.beta * phaseSample.p; + SampledSpectrum pdfUni = ms.pdfUni * phaseSample.pdf; + SampledSpectrum pdfNEE = ms.pdfUni; + + // Russian roulette + SampledSpectrum rrBeta = beta * ms.etaScale / pdfUni.Average(); + if (rrBeta.MaxComponentValue() < 1 && depth > 1) { + Float q = std::max(0, 1 - rrBeta.MaxComponentValue()); + if (raySamples.indirect.rr < q) { + DBG("RR terminated medium indirect with q %f ray index %d\n", q, + ms.rayIndex); + return; + } + pdfUni *= 1 - q; + pdfNEE *= 1 - q; + } + + Ray ray(ms.p, phaseSample.wi, time, ms.medium); + bool isSpecularBounce = false; + bool anyNonSpecularBounces = true; + + // Spawn indirect ray. + rayQueues[(depth + 1) & 1]->PushIndirect( + ray, Point3fi(ms.p), Normal3f(0, 0, 0), Normal3f(0, 0, 0), beta, pdfUni, + pdfNEE, ms.lambda, ms.etaScale, isSpecularBounce, anyNonSpecularBounces, + ms.pixelIndex); + DBG("Enqueuing indirect medium ray at depth %d ray index %d pixel index %d\n", + depth + 1, ms.rayIndex, ms.pixelIndex); + }); +} + +void GPUPathIntegrator::HandleMediumTransitions(int depth) { + ForAllQueued( + "Handle medium transitions", mediumTransitionQueue, maxQueueSize, + [=] PBRT_GPU(MediumTransitionWorkItem mt, int index) { + // Have to do this here, later, since we can't be writing into + // the other ray queue in optix closest hit. (Wait--really? + // Why not? Basically boils down to current indirect enqueue (and other + // places?)) + // TODO: figure this out... + rayQueues[(depth + 1) & 1]->PushIndirect( + mt.ray, mt.piPrev, mt.nPrev, mt.nsPrev, mt.beta, mt.pdfUni, mt.pdfNEE, + mt.lambda, mt.etaScale, mt.isSpecularBounce, mt.anyNonSpecularBounces, + mt.pixelIndex); + DBG("Enqueuied ray after medium transition at depth %d pixel index %d", + depth + 1, mt.pixelIndex); + }); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/optix.cu b/src/pbrt/gpu/optix.cu new file mode 100644 index 00000000..65920a06 --- /dev/null +++ b/src/pbrt/gpu/optix.cu @@ -0,0 +1,700 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include // :-( +#include // :-( +#include // :-( +#include // :-( + +#include + +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif // PBRT_GPU_DBG + +using namespace pbrt; + +extern "C" { +extern __constant__ pbrt::RayIntersectParameters params; +} + +/////////////////////////////////////////////////////////////////////////// +// Utility functions + +// Payload management +__device__ inline uint32_t packPointer0(void *ptr) { + uint64_t uptr = reinterpret_cast(ptr); + return uptr >> 32; +} + +__device__ inline uint32_t packPointer1(void *ptr) { + uint64_t uptr = reinterpret_cast(ptr); + return uint32_t(uptr); +} + +template +static __forceinline__ __device__ T *getPayload() { + uint32_t p0 = optixGetPayload_0(), p1 = optixGetPayload_1(); + const uint64_t uptr = (uint64_t(p0) << 32) | p1; + return reinterpret_cast(uptr); +} + +template +__device__ inline void Trace(OptixTraversableHandle traversable, Ray ray, Float tMin, + Float tMax, OptixRayFlags flags, Args &&... payload) { + optixTrace(traversable, make_float3(ray.o.x, ray.o.y, ray.o.z), + make_float3(ray.d.x, ray.d.y, ray.d.z), tMin, tMax, ray.time, + OptixVisibilityMask(255), flags, 0, /* ray type */ + 1, /* number of ray types */ + 0, /* missSBTIndex */ + std::forward(payload)...); +} + +/////////////////////////////////////////////////////////////////////////// +// Closest hit + +struct ClosestHitContext { + PBRT_GPU + ClosestHitContext(MediumHandle rayMedium, bool shadowRay) + : rayMedium(rayMedium), shadowRay(shadowRay) {} + + MediumHandle rayMedium; + bool shadowRay; + + // out + Point3fi piHit; + Normal3f nHit; + MaterialHandle material; + MediumInterface mediumInterface; + + PBRT_GPU + Ray SpawnRayTo(const Point3f &p) const { + Interaction intr(piHit, nHit); + intr.mediumInterface = &mediumInterface; + return intr.SpawnRayTo(p); + } +}; + +extern "C" __global__ void __raygen__findClosest() { + int rayIndex(optixGetLaunchIndex().x); + if (rayIndex >= params.rayQueue->Size()) + return; + + RayWorkItem r = (*params.rayQueue)[rayIndex]; + Ray ray = r.ray; + Float tMax = 1e30f; + + ClosestHitContext ctx(ray.medium, false); + uint32_t p0 = packPointer0(&ctx), p1 = packPointer1(&ctx); + + DBG("ray o %f %f %f dir %f %f %f tmax %f\n", ray.o.x, ray.o.y, ray.o.z, ray.d.x, + ray.d.y, ray.d.z, tMax); + + uint32_t missed = 0; + Trace(params.traversable, ray, 0.f /* tMin */, tMax, OPTIX_RAY_FLAG_NONE, p0, p1, + missed); + + if (missed) { + if (ray.medium) { + DBG("Adding miss ray to mediumSampleQueue. " + "ray %f %f %f d %f %f %f beta %f %f %f %f\n", + r.ray.o.x, r.ray.o.y, r.ray.o.z, r.ray.d.x, r.ray.d.y, r.ray.d.z, + r.beta[0], r.beta[1], r.beta[2], r.beta[3]); + params.mediumSampleQueue->Push(r.ray, Infinity, r.lambda, r.beta, r.pdfUni, + r.pdfNEE, rayIndex, r.pixelIndex, r.piPrev, + r.nPrev, r.nsPrev, r.isSpecularBounce, + r.anyNonSpecularBounces, r.etaScale); + } else if (params.escapedRayQueue) { + DBG("Adding ray to escapedRayQueue ray index %d pixel index %d\n", rayIndex, + r.pixelIndex); + params.escapedRayQueue->Push(EscapedRayWorkItem{ + r.beta, r.pdfUni, r.pdfNEE, r.lambda, ray.o, ray.d, r.piPrev, r.nPrev, + r.nsPrev, (int)r.isSpecularBounce, r.pixelIndex}); + } + } +} + +extern "C" __global__ void __miss__noop() { + optixSetPayload_2(1); +} + +static __forceinline__ __device__ void ProcessClosestIntersection( + SurfaceInteraction intr) { + int rayIndex = optixGetLaunchIndex().x; + + MediumHandle rayMedium = getPayload()->rayMedium; + if (intr.mediumInterface) + getPayload()->mediumInterface = *intr.mediumInterface; + else + getPayload()->mediumInterface = MediumInterface(rayMedium); + + getPayload()->piHit = intr.pi; + getPayload()->nHit = intr.n; + getPayload()->material = intr.material; + + if (getPayload()->shadowRay) + return; + + // We only have the ray queue (and it only makes sense to access) for + // regular closest hit rays. + RayWorkItem r = (*params.rayQueue)[rayIndex]; + + if (rayMedium) { + assert(params.mediumSampleQueue); + DBG("Enqueuing into medium sample queue\n"); + params.mediumSampleQueue->Push( + MediumSampleWorkItem{r.ray, + optixGetRayTmax(), + r.lambda, + r.beta, + r.pdfUni, + r.pdfNEE, + rayIndex, + r.pixelIndex, + r.piPrev, + r.nPrev, + r.nsPrev, + r.isSpecularBounce, + r.anyNonSpecularBounces, + r.etaScale, + intr.areaLight, + intr.pi, + intr.n, + -r.ray.d, + intr.uv, + intr.material, + intr.shading.n, + intr.shading.dpdu, + intr.shading.dpdv, + intr.shading.dndu, + intr.shading.dndv, + getPayload()->mediumInterface}); + return; + } + + // FIXME: this is all basically duplicate code w/medium.cpp + MaterialHandle material = intr.material; + if (!material) { + DBG("Enqueuing into medium transition queue: ray index %d pixel index %d \n", + rayIndex, r.pixelIndex); + Ray newRay = intr.SpawnRay(r.ray.d); + params.mediumTransitionQueue->Push(MediumTransitionWorkItem{ + newRay, r.lambda, r.beta, r.pdfUni, r.pdfNEE, r.piPrev, r.nPrev, r.nsPrev, + r.isSpecularBounce, r.anyNonSpecularBounces, r.etaScale, r.pixelIndex}); + return; + } + + if (intr.areaLight) { + DBG("Ray hit an area light: adding to hitAreaLightQueue ray index %d pixel index " + "%d\n", + rayIndex, r.pixelIndex); + Ray ray = r.ray; + // TODO: intr.wo == -ray.d? + params.hitAreaLightQueue->Push(HitAreaLightWorkItem{ + intr.areaLight, r.lambda, r.beta, r.pdfUni, r.pdfNEE, intr.p(), intr.n, + intr.uv, intr.wo, r.piPrev, ray.d, ray.time, r.nPrev, r.nsPrev, + (int)r.isSpecularBounce, r.pixelIndex}); + } + + FloatTextureHandle displacement = material.GetDisplacement(); + + MaterialEvalQueue *q = + (material.CanEvaluateTextures(BasicTextureEvaluator()) && + (!displacement || BasicTextureEvaluator().CanEvaluate({displacement}, {}))) + ? params.basicEvalMaterialQueue + : params.universalEvalMaterialQueue; + + DBG("Enqueuing for material eval, mtl tag %d\n", material.Tag()); + + auto enqueue = [=](auto ptr) { + using Material = typename std::remove_reference_t; + q->Push(MaterialEvalWorkItem{ + ptr, r.lambda, r.beta, r.pdfUni, intr.pi, intr.n, intr.shading.n, + intr.shading.dpdu, intr.shading.dpdv, intr.shading.dndu, intr.shading.dndv, + intr.wo, intr.uv, intr.time, r.anyNonSpecularBounces, r.etaScale, + getPayload()->mediumInterface, rayIndex, r.pixelIndex}); + }; + material.Dispatch(enqueue); + + DBG("Closest hit found intersection at t %f\n", optixGetRayTmax()); +} + +/////////////////////////////////////////////////////////////////////////// +// Triangles + +static __forceinline__ __device__ pstd::optional +getTriangleIntersection() { + const TriangleMeshRecord &rec = *(const TriangleMeshRecord *)optixGetSbtDataPointer(); + + float b1 = optixGetTriangleBarycentrics().x; + float b2 = optixGetTriangleBarycentrics().y; + float b0 = 1 - b1 - b2; + + float3 rd = optixGetWorldRayDirection(); + Vector3f wo = -Vector3f(rd.x, rd.y, rd.z); + + assert(optixGetTransformListSize() == 1); + float worldFromObj[12], objFromWorld[12]; + optixGetObjectToWorldTransformMatrix(worldFromObj); + optixGetWorldToObjectTransformMatrix(objFromWorld); + SquareMatrix<4> worldFromObjM(worldFromObj[0], worldFromObj[1], worldFromObj[2], + worldFromObj[3], worldFromObj[4], worldFromObj[5], + worldFromObj[6], worldFromObj[7], worldFromObj[8], + worldFromObj[9], worldFromObj[10], worldFromObj[11], + 0.f, 0.f, 0.f, 1.f); + SquareMatrix<4> objFromWorldM(objFromWorld[0], objFromWorld[1], objFromWorld[2], + objFromWorld[3], objFromWorld[4], objFromWorld[5], + objFromWorld[6], objFromWorld[7], objFromWorld[8], + objFromWorld[9], objFromWorld[10], objFromWorld[11], + 0.f, 0.f, 0.f, 1.f); + + Transform worldFromInstance(worldFromObjM, objFromWorldM); + return Triangle::InteractionFromIntersection(rec.mesh, optixGetPrimitiveIndex(), + {b0, b1, b2}, optixGetRayTime(), wo, + worldFromInstance); +} + +static __forceinline__ __device__ bool alphaKilled(const TriangleMeshRecord &rec) { + if (!rec.alphaTexture) + return false; + + pstd::optional intr = getTriangleIntersection(); + if (!intr) + return true; + + BasicTextureEvaluator eval; + Float alpha = eval(rec.alphaTexture, *intr); + return alpha == 0; +} + +extern "C" __global__ void __closesthit__triangle() { + const TriangleMeshRecord &rec = *(const TriangleMeshRecord *)optixGetSbtDataPointer(); + // It's slightly dicey to assume intr is valid. But invalid would + // presumably mean that OptiX returned a hit with a degenerate + // triangle... + SurfaceInteraction intr = *getTriangleIntersection(); + + if (rec.mediumInterface && rec.mediumInterface->IsMediumTransition()) + intr.mediumInterface = rec.mediumInterface; + intr.material = rec.material; + if (!rec.areaLights.empty()) + intr.areaLight = rec.areaLights[optixGetPrimitiveIndex()]; + + ProcessClosestIntersection(intr); +} + +extern "C" __global__ void __anyhit__triangle() { + const TriangleMeshRecord &rec = *(const TriangleMeshRecord *)optixGetSbtDataPointer(); + + if (alphaKilled(rec)) + optixIgnoreIntersection(); +} + +extern "C" __global__ void __anyhit__shadowTriangle() { + const TriangleMeshRecord &rec = *(const TriangleMeshRecord *)optixGetSbtDataPointer(); + + if (rec.material && rec.material.IsTransparent()) + optixIgnoreIntersection(); + + if (alphaKilled(rec)) + optixIgnoreIntersection(); +} + +/////////////////////////////////////////////////////////////////////////// +// Shadow rays + +extern "C" __global__ void __raygen__shadow() { + int index = optixGetLaunchIndex().x; + if (index >= params.shadowRayQueue->Size()) + return; + + ShadowRayWorkItem sr = (*params.shadowRayQueue)[index]; + + uint32_t missed = 0; + Trace(params.traversable, sr.ray, 1e-5f /* tMin */, sr.tMax, OPTIX_RAY_FLAG_NONE, + missed); + + SampledSpectrum Ld; + if (missed) + Ld = sr.Ld / (sr.pdfUni + sr.pdfNEE).Average(); + else + Ld = SampledSpectrum(0.); + + params.shadowRayQueue->Ld[index] = Ld; +} + +extern "C" __global__ void __miss__shadow() { + optixSetPayload_0(1); +} + +extern "C" __global__ void __raygen__shadow_Tr() { + DBG("raygen sahadow tr %d\n", optixGetLaunchIndex().x); + int index = optixGetLaunchIndex().x; + if (index >= params.shadowRayQueue->Size()) + return; + + ShadowRayWorkItem sr = (*params.shadowRayQueue)[index]; + SampledWavelengths lambda = sr.lambda; + + SampledSpectrum Ld = sr.Ld; + DBG("Initial Ld %f %f %f %f shadow ray index %d pixel index %d\n", Ld[0], Ld[1], + Ld[2], Ld[3], index, sr.pixelIndex); + + SampledSpectrum pdfUni = sr.pdfUni, pdfNEE = sr.pdfNEE; + + Ray ray = sr.ray; + Float tMax = sr.tMax; + Point3f pLight = ray(tMax); + RNG rng(Hash(ray.o), Hash(ray.d)); + + while (true) { + ClosestHitContext ctx(ray.medium, true); + uint32_t p0 = packPointer0(&ctx), p1 = packPointer1(&ctx); + + DBG("Tracing shadow tr shadow ray index %d pixel index %d " + "ray %f %f %f d %f %f %f tMax %f\n", + index, sr.pixelIndex, ray.o.x, ray.o.y, ray.o.z, ray.d.x, ray.d.y, ray.d.z, + tMax); + + uint32_t missed = 0; + + Trace(params.traversable, ray, 1e-5f /* tMin */, tMax, OPTIX_RAY_FLAG_NONE, p0, + p1, missed); + + if (!missed && ctx.material) { + DBG("Hit opaque. Bye\n"); + // Hit opaque surface + Ld = SampledSpectrum(0.f); + break; + } + + if (ray.medium) { + DBG("Ray medium %p. Will sample tmaj...\n", ray.medium.ptr()); + + Float tEnd = + missed ? tMax : (Distance(ray.o, Point3f(ctx.piHit)) / Length(ray.d)); + ray.medium.SampleTmaj(ray, tEnd, rng, lambda, + [&](const MediumSample &mediumSample) { + if (!mediumSample.intr) + // FIXME: include last Tmaj? + return false; + + const SampledSpectrum &Tmaj = mediumSample.Tmaj; + const MediumInteraction &intr = *mediumSample.intr; + SampledSpectrum sigma_n = intr.sigma_n(); + + // ratio-tracking: only evaluate null scattering + Ld *= Tmaj * sigma_n; + pdfNEE *= Tmaj * intr.sigma_maj; + pdfUni *= Tmaj * sigma_n; + + if (!Ld) + return false; + + if (Ld.MaxComponentValue() > 0x1p24f || + pdfNEE.MaxComponentValue() > 0x1p24f || + pdfUni.MaxComponentValue() > 0x1p24f) { + Ld *= 1.f / 0x1p24f; + pdfNEE *= 1.f / 0x1p24f; + pdfUni *= 1.f / 0x1p24f; + } + + return true; + }); + } + + if (missed || !Ld) + // done + break; + + ray = ctx.SpawnRayTo(pLight); + + if (ray.d == Vector3f(0, 0, 0)) + break; + } + + Ld /= (pdfUni + pdfNEE).Average(); + DBG("Setting final Ld for shadow ray index %d pixel index %d = as %f %f %f %f\n", + index, sr.pixelIndex, Ld[0], Ld[1], Ld[2], Ld[3]); + + params.shadowRayQueue->Ld[index] = Ld; +} + +extern "C" __global__ void __miss__shadow_Tr() { + optixSetPayload_2(1); +} + +///////////////////////////////////////////////////////////////////////////////////// +// Quadrics + +static __device__ inline SurfaceInteraction getQuadricIntersection( + const QuadricIntersection &si) { + QuadricRecord &rec = *((QuadricRecord *)optixGetSbtDataPointer()); + + float3 rd = optixGetWorldRayDirection(); + Vector3f wo = -Vector3f(rd.x, rd.y, rd.z); + Float time = optixGetRayTime(); + + SurfaceInteraction intr; + if (const Sphere *sphere = rec.shape.CastOrNullptr()) + intr = sphere->InteractionFromIntersection(si, wo, time); + else if (const Cylinder *cylinder = rec.shape.CastOrNullptr()) + intr = cylinder->InteractionFromIntersection(si, wo, time); + else if (const Disk *disk = rec.shape.CastOrNullptr()) + intr = disk->InteractionFromIntersection(si, wo, time); + else + assert(!"unexpected quadric"); + + return intr; +} + +extern "C" __global__ void __closesthit__quadric() { + QuadricRecord &rec = *((QuadricRecord *)optixGetSbtDataPointer()); + QuadricIntersection qi; + qi.pObj = + Point3f(BitsToFloat(optixGetAttribute_0()), BitsToFloat(optixGetAttribute_1()), + BitsToFloat(optixGetAttribute_2())); + qi.phi = BitsToFloat(optixGetAttribute_3()); + + SurfaceInteraction intr = getQuadricIntersection(qi); + if (rec.mediumInterface && rec.mediumInterface->IsMediumTransition()) + intr.mediumInterface = rec.mediumInterface; + intr.material = rec.material; + if (rec.areaLight) + intr.areaLight = rec.areaLight; + + ProcessClosestIntersection(intr); +} + +extern "C" __global__ void __anyhit__shadowQuadric() { + QuadricRecord &rec = *((QuadricRecord *)optixGetSbtDataPointer()); + + if (rec.material && rec.material.IsTransparent()) + optixIgnoreIntersection(); +} + +extern "C" __global__ void __intersection__quadric() { + QuadricRecord &rec = *((QuadricRecord *)optixGetSbtDataPointer()); + + float3 org = optixGetObjectRayOrigin(); + float3 dir = optixGetObjectRayDirection(); + Float tMax = optixGetRayTmax(); + Ray ray(Point3f(org.x, org.y, org.z), Vector3f(dir.x, dir.y, dir.z)); + pstd::optional isect; + + if (const Sphere *sphere = rec.shape.CastOrNullptr()) + isect = sphere->BasicIntersect(ray, tMax); + else if (const Cylinder *cylinder = rec.shape.CastOrNullptr()) + isect = cylinder->BasicIntersect(ray, tMax); + else if (const Disk *disk = rec.shape.CastOrNullptr()) + isect = disk->BasicIntersect(ray, tMax); + + if (!isect) + return; + + if (rec.alphaTexture) { + SurfaceInteraction intr = getQuadricIntersection(*isect); + + BasicTextureEvaluator eval; + Float alpha = eval(rec.alphaTexture, intr); + if (alpha == 0) + // No hit + return; + } + + optixReportIntersection(isect->tHit, 0 /* hit kind */, FloatToBits(isect->pObj.x), + FloatToBits(isect->pObj.y), FloatToBits(isect->pObj.z), + FloatToBits(isect->phi)); +} + +/////////////////////////////////////////////////////////////////////////// +// Bilinear patches + +static __forceinline__ __device__ SurfaceInteraction +getBilinearPatchIntersection(Point2f uv) { + BilinearMeshRecord &rec = *((BilinearMeshRecord *)optixGetSbtDataPointer()); + + float3 rd = optixGetWorldRayDirection(); + Vector3f wo = -Vector3f(rd.x, rd.y, rd.z); + + return BilinearPatch::InteractionFromIntersection(rec.mesh, optixGetPrimitiveIndex(), + uv, optixGetRayTime(), wo); +} + +extern "C" __global__ void __closesthit__bilinearPatch() { + BilinearMeshRecord &rec = *((BilinearMeshRecord *)optixGetSbtDataPointer()); + + Point2f uv(BitsToFloat(optixGetAttribute_0()), BitsToFloat(optixGetAttribute_1())); + + SurfaceInteraction intr = getBilinearPatchIntersection(uv); + if (rec.mediumInterface && rec.mediumInterface->IsMediumTransition()) + intr.mediumInterface = rec.mediumInterface; + intr.material = rec.material; + if (!rec.areaLights.empty()) + intr.areaLight = rec.areaLights[optixGetPrimitiveIndex()]; + + ProcessClosestIntersection(intr); +} + +extern "C" __global__ void __anyhit__shadowBilinearPatch() { + BilinearMeshRecord &rec = *((BilinearMeshRecord *)optixGetSbtDataPointer()); + + if (rec.material && rec.material.IsTransparent()) + optixIgnoreIntersection(); +} + +extern "C" __global__ void __intersection__bilinearPatch() { + BilinearMeshRecord &rec = *((BilinearMeshRecord *)optixGetSbtDataPointer()); + + float3 org = optixGetObjectRayOrigin(); + float3 dir = optixGetObjectRayDirection(); + Float tMax = optixGetRayTmax(); + Ray ray(Point3f(org.x, org.y, org.z), Vector3f(dir.x, dir.y, dir.z)); + + int vertexIndex = 4 * optixGetPrimitiveIndex(); + Point3f p00 = rec.mesh->p[rec.mesh->vertexIndices[vertexIndex]]; + Point3f p10 = rec.mesh->p[rec.mesh->vertexIndices[vertexIndex + 1]]; + Point3f p01 = rec.mesh->p[rec.mesh->vertexIndices[vertexIndex + 2]]; + Point3f p11 = rec.mesh->p[rec.mesh->vertexIndices[vertexIndex + 3]]; + pstd::optional isect = + BilinearPatch::Intersect(ray, tMax, p00, p10, p01, p11); + + if (!isect) + return; + + if (rec.alphaTexture) { + SurfaceInteraction intr = getBilinearPatchIntersection(isect->uv); + BasicTextureEvaluator eval; + Float alpha = eval(rec.alphaTexture, intr); + if (alpha == 0) + // No intersection + return; + } + + optixReportIntersection(isect->t, 0 /* hit kind */, FloatToBits(isect->uv[0]), + FloatToBits(isect->uv[1])); +} + +/////////////////////////////////////////////////////////////////////////// +// Random hit (for subsurface scattering) + +struct RandomHitPayload { + WeightedReservoirSampler wrs; + MaterialHandle material; +}; + +extern "C" __global__ void __raygen__randomHit() { + // Keep as uint32_t so can pass directly to optixTrace. + uint32_t index = optixGetLaunchIndex().x; + if (index >= params.subsurfaceScatterQueue->Size()) + return; + + SubsurfaceScatterWorkItem s = (*params.subsurfaceScatterQueue)[index]; + + Ray ray(s.p0, s.p1 - s.p0); + Float tMax = 1.f; + + RandomHitPayload payload; + payload.wrs.Seed(Hash(s.p0, s.p1)); + payload.material = s.material; + + uint32_t ptr0 = packPointer0(&payload), ptr1 = packPointer1(&payload); + + DBG("Randomhit raygen ray.o %f %f %f ray.d %f %f %f tMax %f\n", ray.o.x, ray.o.y, + ray.o.z, ray.d.x, ray.d.y, ray.d.z, tMax); + + Trace(params.traversable, ray, 0.f /* tMin */, tMax, OPTIX_RAY_FLAG_NONE, ptr0, ptr1); + + if (payload.wrs.HasSample() && + payload.wrs.WeightSum() > 0) { // TODO: latter check shouldn't be needed... + const SubsurfaceInteraction &si = payload.wrs.GetSample(); + DBG("optix si p %f %f %f n %f %f %f\n", si.p().x, si.p().y, si.p().z, si.n.x, + si.n.y, si.n.z); + + params.subsurfaceScatterQueue->weight[index] = payload.wrs.WeightSum(); + params.subsurfaceScatterQueue->ssi[index] = payload.wrs.GetSample(); + } else + params.subsurfaceScatterQueue->weight[index] = 0; +} + +extern "C" __global__ void __anyhit__randomHitTriangle() { + const TriangleMeshRecord &rec = *(const TriangleMeshRecord *)optixGetSbtDataPointer(); + + RandomHitPayload *p = getPayload(); + + DBG("Anyhit triangle for random hit: rec.material %p params.materials %p\n", + rec.material.ptr(), p->material.ptr()); + + if (rec.material == p->material) + p->wrs.Add([&] PBRT_CPU_GPU() { return *getTriangleIntersection(); }, 1.f); + + optixIgnoreIntersection(); +} + +extern "C" __global__ void __anyhit__randomHitBilinearPatch() { + BilinearMeshRecord &rec = *(BilinearMeshRecord *)optixGetSbtDataPointer(); + + RandomHitPayload *p = getPayload(); + + DBG("Anyhit blp for random hit: rec.material %p params.materials %p\n", + rec.material.ptr(), p->material.ptr()); + + if (rec.material == p->material) + p->wrs.Add( + [&] PBRT_CPU_GPU() { + Point2f uv(BitsToFloat(optixGetAttribute_0()), + BitsToFloat(optixGetAttribute_1())); + return getBilinearPatchIntersection(uv); + }, + 1.f); + + optixIgnoreIntersection(); +} + +extern "C" __global__ void __anyhit__randomHitQuadric() { + QuadricRecord &rec = *((QuadricRecord *)optixGetSbtDataPointer()); + + RandomHitPayload *p = getPayload(); + + DBG("Anyhit quadric for random hit: rec.material %p params.materials %p\n", + rec.material.ptr(), p->material.ptr()); + + if (rec.material == p->material) { + p->wrs.Add( + [&] PBRT_CPU_GPU() { + QuadricIntersection qi; + qi.pObj = Point3f(BitsToFloat(optixGetAttribute_0()), + BitsToFloat(optixGetAttribute_1()), + BitsToFloat(optixGetAttribute_2())); + qi.phi = BitsToFloat(optixGetAttribute_3()); + + return getQuadricIntersection(qi); + }, + 1.f); + } + + optixIgnoreIntersection(); +} diff --git a/src/pbrt/gpu/optix.h b/src/pbrt/gpu/optix.h new file mode 100644 index 00000000..7bd86e90 --- /dev/null +++ b/src/pbrt/gpu/optix.h @@ -0,0 +1,71 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_OPTIX_H +#define PBRT_GPU_OPTIX_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +class TriangleMesh; +class BilinearPatchMesh; + +struct TriangleMeshRecord { + const TriangleMesh *mesh; + MaterialHandle material; + FloatTextureHandle alphaTexture; + pstd::span areaLights; + MediumInterface *mediumInterface; +}; + +struct BilinearMeshRecord { + const BilinearPatchMesh *mesh; + MaterialHandle material; + FloatTextureHandle alphaTexture; + pstd::span areaLights; + MediumInterface *mediumInterface; +}; + +struct QuadricRecord { + ShapeHandle shape; + MaterialHandle material; + FloatTextureHandle alphaTexture; + LightHandle areaLight; + MediumInterface *mediumInterface; +}; + +struct RayIntersectParameters { + OptixTraversableHandle traversable; + + RayQueue *rayQueue; + + // closest hit + EscapedRayQueue *escapedRayQueue; + HitAreaLightQueue *hitAreaLightQueue; + MaterialEvalQueue *basicEvalMaterialQueue, *universalEvalMaterialQueue; + MediumTransitionQueue *mediumTransitionQueue; + MediumSampleQueue *mediumSampleQueue; + + // shadow rays + ShadowRayQueue *shadowRayQueue; + + // Subsurface scattering... + SubsurfaceScatterQueue *subsurfaceScatterQueue; +}; + +} // namespace pbrt + +#endif // PBRT_GPU_OPTIX_H diff --git a/src/pbrt/gpu/pathintegrator.cpp b/src/pbrt/gpu/pathintegrator.cpp new file mode 100644 index 00000000..330b880d --- /dev/null +++ b/src/pbrt/gpu/pathintegrator.cpp @@ -0,0 +1,580 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#ifdef NVTX +#include "nvtx3/nvToolsExt.h" +#include "nvtx3/nvToolsExtCuda.h" +#endif + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif + +namespace pbrt { + +STAT_MEMORY_COUNTER("Memory/GPU path integrator pixel state", pathIntegratorBytes); + +GPUPathIntegrator::GPUPathIntegrator(Allocator alloc, const ParsedScene &scene) { + // Allocate all of the data structures that represent the scene... + std::map media = scene.CreateMedia(alloc); + + haveMedia = false; + // Check the shapes... + for (const auto &shape : scene.shapes) + if (!shape.insideMedium.empty() || !shape.outsideMedium.empty()) + haveMedia = true; + for (const auto &shape : scene.animatedShapes) + if (!shape.insideMedium.empty() || !shape.outsideMedium.empty()) + haveMedia = true; + + auto findMedium = [&](const std::string &s, const FileLoc *loc) -> MediumHandle { + if (s.empty()) + return nullptr; + + auto iter = media.find(s); + if (iter == media.end()) + ErrorExit(loc, "%s: medium not defined", s); + haveMedia = true; + return iter->second; + }; + + filter = FilterHandle::Create(scene.filter.name, scene.filter.parameters, + &scene.filter.loc, alloc); + + film = FilmHandle::Create(scene.film.name, scene.film.parameters, &scene.film.loc, + filter, alloc); + initializeVisibleSurface = film.UsesVisibleSurface(); + + sampler = SamplerHandle::Create(scene.sampler.name, scene.sampler.parameters, + film.FullResolution(), &scene.sampler.loc, alloc); + + MediumHandle cameraMedium = findMedium(scene.camera.medium, &scene.camera.loc); + camera = CameraHandle::Create(scene.camera.name, scene.camera.parameters, + cameraMedium, scene.camera.cameraTransform, film, + &scene.camera.loc, alloc); + + pstd::vector allLights; + + for (const auto &light : scene.lights) { + MediumHandle outsideMedium = findMedium(light.medium, &light.loc); + if (light.renderFromObject.IsAnimated()) + Warning(&light.loc, + "Animated lights aren't supported. Using the start transform."); + + LightHandle l = LightHandle::Create( + light.name, light.parameters, light.renderFromObject.startTransform, + scene.camera.cameraTransform, outsideMedium, &light.loc, alloc); + + if (l.Is() || l.Is() || + l.Is()) { + if (envLight) + Warning(&light.loc, + "Multiple infinite lights specified. Using this one."); + envLight = l; + } + + allLights.push_back(l); + } + + // Area lights... + std::map *> shapeIndexToAreaLights; + for (size_t i = 0; i < scene.shapes.size(); ++i) { + const auto &shape = scene.shapes[i]; + if (shape.lightIndex == -1) + continue; + CHECK_LT(shape.lightIndex, scene.areaLights.size()); + const auto &areaLightEntity = scene.areaLights[shape.lightIndex]; + AnimatedTransform renderFromLight(*shape.renderFromObject); + + pstd::vector shapeHandles = ShapeHandle::Create( + shape.name, shape.renderFromObject, shape.objectFromRender, + shape.reverseOrientation, shape.parameters, &shape.loc, alloc); + + if (shapeHandles.empty()) + continue; + + MediumHandle outsideMedium = findMedium(shape.outsideMedium, &shape.loc); + + pstd::vector *lightsForShape = + alloc.new_object>(alloc); + for (ShapeHandle sh : shapeHandles) { + if (renderFromLight.IsAnimated()) + Warning(&shape.loc, + "Animated lights aren't supported. Using the start transform."); + DiffuseAreaLight *area = DiffuseAreaLight::Create( + renderFromLight.startTransform, outsideMedium, areaLightEntity.parameters, + areaLightEntity.parameters.ColorSpace(), &areaLightEntity.loc, alloc, sh); + allLights.push_back(area); + lightsForShape->push_back(area); + } + shapeIndexToAreaLights[i] = lightsForShape; + } + + haveBasicEvalMaterial.fill(false); + haveUniversalEvalMaterial.fill(false); + haveSubsurface = false; + accel = new GPUAccel(scene, alloc, nullptr /* cuda stream */, shapeIndexToAreaLights, + media, &haveBasicEvalMaterial, &haveUniversalEvalMaterial, + &haveSubsurface); + + // Preprocess the light sources + for (LightHandle light : allLights) + light.Preprocess(accel->Bounds()); + + bool haveLights = !allLights.empty(); + for (const auto &m : media) + haveLights |= m.second.IsEmissive(); + if (!haveLights) + ErrorExit("No light sources specified"); + + std::string lightSamplerName = + scene.integrator.parameters.GetOneString("lightsampler", "bvh"); + if (allLights.size() == 1) + lightSamplerName = "uniform"; + lightSampler = LightSamplerHandle::Create(lightSamplerName, allLights, alloc); + + // Integrator parameters + regularize = scene.integrator.parameters.GetOneBool("regularize", false); + maxDepth = scene.integrator.parameters.GetOneInt("maxdepth", 5); + + /////////////////////////////////////////////////////////////////////////// + // Allocate storage for all of the queues/buffers... + + CUDATrackedMemoryResource *mr = + dynamic_cast(gpuMemoryAllocator.resource()); + CHECK(mr != nullptr); + size_t startSize = mr->BytesAllocated(); + + // Compute number of scanlines to render per pass. + Vector2i resolution = film.PixelBounds().Diagonal(); + // TODO: make this configurable. Base it on the amount of GPU memory? + int maxSamples = 1024 * 1024; + scanlinesPerPass = std::max(1, maxSamples / resolution.x); + int nPasses = (resolution.y + scanlinesPerPass - 1) / scanlinesPerPass; + scanlinesPerPass = (resolution.y + nPasses - 1) / nPasses; + maxQueueSize = resolution.x * scanlinesPerPass; + LOG_VERBOSE("Will render in %d passes %d scanlines per pass\n", nPasses, + scanlinesPerPass); + + pixelSampleState = SOA(maxQueueSize, alloc); + + rayQueues[0] = alloc.new_object(maxQueueSize, alloc); + rayQueues[1] = alloc.new_object(maxQueueSize, alloc); + + shadowRayQueue = alloc.new_object(maxQueueSize, alloc); + + if (haveSubsurface) { + bssrdfEvalQueue = + alloc.new_object(maxQueueSize, alloc); + subsurfaceScatterQueue = + alloc.new_object(maxQueueSize, alloc); + } + + if (envLight) + escapedRayQueue = alloc.new_object(maxQueueSize, alloc); + hitAreaLightQueue = alloc.new_object(maxQueueSize, alloc); + + basicEvalMaterialQueue = alloc.new_object( + maxQueueSize, alloc, + pstd::MakeConstSpan(&haveBasicEvalMaterial[1], haveBasicEvalMaterial.size() - 1)); + universalEvalMaterialQueue = alloc.new_object( + maxQueueSize, alloc, + pstd::MakeConstSpan(&haveUniversalEvalMaterial[1], + haveUniversalEvalMaterial.size() - 1)); + + // Always allocate this, even if no media + mediumTransitionQueue = alloc.new_object(maxQueueSize, alloc); + if (haveMedia) { + mediumSampleQueue = alloc.new_object(maxQueueSize, alloc); + mediumScatterQueue = alloc.new_object(maxQueueSize, alloc); + } + + stats = alloc.new_object(maxDepth, alloc); + + size_t endSize = mr->BytesAllocated(); + pathIntegratorBytes += endSize - startSize; +} + +void GPUPathIntegrator::TraceShadowRays(int depth) { + std::pair events; + if (haveMedia) + events = + accel->IntersectShadowTr(maxQueueSize, shadowRayQueue); + else + events = accel->IntersectShadow(maxQueueSize, shadowRayQueue); + struct IsectShadowHack {}; + GetGPUKernelStats("Tracing shadow rays") + .launchEvents.push_back(events); + + // Add contribution if light was visible + ForAllQueued("Incorporate shadow ray contribution", shadowRayQueue, maxQueueSize, + [=] PBRT_GPU(const ShadowRayWorkItem sr, int index) { + if (!sr.Ld) + return; + + SampledSpectrum Lpixel = pixelSampleState.L[sr.pixelIndex]; + + DBG("Adding shadow ray Ld %f %f %f %f at pixel index %d \n", + sr.Ld[0], sr.Ld[1], sr.Ld[2], sr.Ld[3], sr.pixelIndex); + + pixelSampleState.L[sr.pixelIndex] = Lpixel + sr.Ld; + }); + + GPUDo("Reset shadowRayQueue", [=] PBRT_GPU() { + stats->shadowRays[depth] += shadowRayQueue->Size(); + shadowRayQueue->Reset(); + }); +} + +void GPUPathIntegrator::Render(ImageMetadata *metadata) { + Vector2i resolution = film.PixelBounds().Diagonal(); + int spp = sampler.SamplesPerPixel(); + + RGB *displayRGB = nullptr, *displayRGBHost = nullptr; + std::atomic exitCopyThread{false}; + std::thread copyThread; + + if (!Options->displayServer.empty()) { + // Allocate staging memory on the GPU to store the current WIP + // image. + CUDA_CHECK(cudaMalloc(&displayRGB, resolution.x * resolution.y * sizeof(RGB))); + CUDA_CHECK(cudaMemset(displayRGB, 0, resolution.x * resolution.y * sizeof(RGB))); + + // Host-side memory for the WIP Image. We'll just let this leak so + // that the lambda passed to DisplayDynamic below doesn't access + // freed memory after Render() returns... + displayRGBHost = new RGB[resolution.x * resolution.y]; + + copyThread = std::thread([&]() { +#ifdef NVTX + nvtxNameOsThread(syscall(SYS_gettid), "DISPLAY_SERVER_COPY_THREAD"); +#endif + // Copy back to the CPU using a separate stream so that we can + // periodically but asynchronously pick up the latest results + // from the GPU. + cudaStream_t memcpyStream; + CUDA_CHECK(cudaStreamCreate(&memcpyStream)); +#ifdef NVTX + nvtxNameCuStream(memcpyStream, "DISPLAY_SERVER_COPY_STREAM"); +#endif + + // Copy back to the host from the GPU buffer, without any + // synthronization. + while (!exitCopyThread) { + CUDA_CHECK(cudaMemcpyAsync(displayRGBHost, displayRGB, + resolution.x * resolution.y * sizeof(RGB), + cudaMemcpyDeviceToHost, memcpyStream)); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + + CUDA_CHECK(cudaStreamSynchronize(memcpyStream)); + } + + // Copy one more time to get the final image before exiting. + CUDA_CHECK(cudaMemcpy(displayRGBHost, displayRGB, + resolution.x * resolution.y * sizeof(RGB), + cudaMemcpyDeviceToHost)); + CUDA_CHECK(cudaDeviceSynchronize()); + }); + + // Now on the CPU side, give the display system a lambda that + // copies values from |displayRGBHost| into its buffers used for + // sending messages to the display program (i.e., tev). + DisplayDynamic(film.GetFilename(), {resolution.x, resolution.y}, {"R", "G", "B"}, + [resolution, displayRGBHost]( + Bounds2i b, pstd::span> displayValue) { + int index = 0; + for (Point2i p : b) { + RGB rgb = displayRGBHost[p.x + p.y * resolution.x]; + displayValue[0][index] = rgb.r; + displayValue[1][index] = rgb.g; + displayValue[2][index] = rgb.b; + ++index; + } + }); + } + + ProgressReporter progress(spp, "Rendering", Options->quiet, true /* GPU */); + + for (int sampleIndex = 0; sampleIndex < spp; ++sampleIndex) { + for (int y0 = 0; y0 < resolution.y; y0 += scanlinesPerPass) { + GPUDo("Reset ray queue", [=] PBRT_GPU() { + DBG("Starting scanlines at y0 = %d, sample %d / %d\n", y0, sampleIndex, + spp); + rayQueues[0]->Reset(); + }); + + GenerateCameraRays(y0, sampleIndex); + + GPUDo("Update camera ray stats", + [=] PBRT_GPU() { stats->cameraRays += rayQueues[0]->Size(); }); + + for (int depth = 0; true; ++depth) { + GenerateRaySamples(depth, sampleIndex); + + GPUDo("Reset queues before tracing rays", [=] PBRT_GPU() { + hitAreaLightQueue->Reset(); + if (escapedRayQueue) + escapedRayQueue->Reset(); + + basicEvalMaterialQueue->Reset(); + universalEvalMaterialQueue->Reset(); + + if (bssrdfEvalQueue) + bssrdfEvalQueue->Reset(); + if (subsurfaceScatterQueue) + subsurfaceScatterQueue->Reset(); + + mediumTransitionQueue->Reset(); + if (mediumSampleQueue) + mediumSampleQueue->Reset(); + if (mediumScatterQueue) + mediumScatterQueue->Reset(); + + rayQueues[(depth + 1) & 1]->Reset(); + }); + + auto events = accel->IntersectClosest( + maxQueueSize, escapedRayQueue, hitAreaLightQueue, + basicEvalMaterialQueue, universalEvalMaterialQueue, + mediumTransitionQueue, mediumSampleQueue, rayQueues[depth & 1]); + struct IsectHack {}; + GetGPUKernelStats("Tracing closest hit rays") + .launchEvents.push_back(events); + + if (depth > 0) + GPUDo("Update indirect ray stats", [=] PBRT_GPU() { + stats->indirectRays[depth] += rayQueues[depth & 1]->Size(); + }); + + if (haveMedia) + SampleMediumInteraction(depth); + + if (escapedRayQueue) + HandleEscapedRays(depth); + + HandleRayFoundEmission(depth); + + if (depth == maxDepth) + break; + + EvaluateMaterialsAndBSDFs(depth); + + // Do immediately so that we have space for shadow rays for + // subsurface.. + TraceShadowRays(depth); + + HandleMediumTransitions(depth); + + if (haveSubsurface) + SampleSubsurface(depth); + } + + UpdateFilm(); + + if (!Options->displayServer.empty()) + GPUParallelFor("Update Display RGB Buffer", maxQueueSize, + [=] PBRT_GPU(int pixelIndex) { + Point2i pPixel = pixelSampleState.pPixel[pixelIndex]; + if (!InsideExclusive(pPixel, film.PixelBounds())) + return; + + Point2i p(pPixel - film.PixelBounds().pMin); + displayRGB[p.x + p.y * resolution.x] = + film.GetPixelRGB(pPixel); + }); + } + + progress.Update(); + } + progress.Done(); + + CUDA_CHECK(cudaDeviceSynchronize()); + + // Wait until rendering is all done before we start to shut down the + // display stuff.. + if (!Options->displayServer.empty()) { + exitCopyThread = true; + copyThread.join(); + } + + metadata->samplesPerPixel = sampler.SamplesPerPixel(); + camera.InitMetadata(metadata); +} + +void GPUPathIntegrator::HandleEscapedRays(int depth) { + ForAllQueued("Handle escaped rays", escapedRayQueue, maxQueueSize, + [=] PBRT_GPU(const EscapedRayWorkItem er, int index) { + Ray ray(er.rayo, er.rayd); + SampledSpectrum Le = envLight.Le(ray, er.lambda); + if (!Le) + return; + + SampledSpectrum L = pixelSampleState.L[er.pixelIndex]; + + if (depth == 0 || er.specularBounce) { + L += er.beta * Le / er.pdfUni.Average(); + } else { + Float time = 0; // FIXME + LightSampleContext ctx(er.piPrev, er.nPrev, er.nsPrev); + + Float lightChoicePDF = lightSampler.PDF(ctx, envLight); + Float lightPDF = + lightChoicePDF * + envLight.PDF_Li(ctx, ray.d, LightSamplingMode::WithMIS); + + SampledSpectrum pdfUni = er.pdfUni; + SampledSpectrum pdfNEE = er.pdfNEE * lightPDF; + + L += er.beta * Le / (pdfUni + pdfNEE).Average(); + } + + DBG("Added L %f %f %f %f for escaped ray pixel index %d\n", L[0], + L[1], L[2], L[3], er.pixelIndex); + pixelSampleState.L[er.pixelIndex] = L; + }); +} + +void GPUPathIntegrator::HandleRayFoundEmission(int depth) { + ForAllQueued( + "Handle emitters hit by indirect rays", hitAreaLightQueue, maxQueueSize, + [=] PBRT_GPU(const HitAreaLightWorkItem he, int index) { + LightHandle areaLight = he.areaLight; + SampledSpectrum Le = areaLight.L(he.p, he.n, he.uv, he.wo, he.lambda); + if (!Le) + return; + + DBG("Got Le %f %f %f %f from hit area light at depth %d\n", Le[0], Le[1], + Le[2], Le[3], depth); + + SampledSpectrum L = pixelSampleState.L[he.pixelIndex]; + + if (depth == 0 || he.isSpecularBounce) { + L += he.beta * Le / he.pdfUni.Average(); + } else { + Vector3f wi = he.rayd; + + LightSampleContext ctx(he.piPrev, he.nPrev, he.nsPrev); + + Float lightChoicePDF = lightSampler.PDF(ctx, areaLight); + Float lightPDF = lightChoicePDF * + areaLight.PDF_Li(ctx, wi, LightSamplingMode::WithMIS); + + SampledSpectrum pdfUni = he.pdfUni; + SampledSpectrum pdfNEE = he.pdfNEE * lightPDF; + + L += he.beta * Le / (pdfUni + pdfNEE).Average(); + } + + DBG("Added L %f %f %f %f for pixel index %d\n", L[0], L[1], L[2], L[3], + he.pixelIndex); + pixelSampleState.L[he.pixelIndex] = L; + }); +} + +void GPURender(ParsedScene &scene) { + GPUPathIntegrator *integrator = + gpuMemoryAllocator.new_object(gpuMemoryAllocator, scene); + + // Set things up so that we can still have read from the + // GPUPathIntegrator struct on the CPU without hurting + // performance. (This makes it possible to use the values of things + // like GPUPathIntegrator::haveSubsurface to conditionally launch + // kernels according to what's in the scene...) + int deviceIndex; + CUDA_CHECK(cudaGetDevice(&deviceIndex)); + CUDA_CHECK( + cudaMemAdvise(integrator, sizeof(*integrator), cudaMemAdviseSetReadMostly, 0)); + CUDA_CHECK(cudaMemAdvise(integrator, sizeof(*integrator), + cudaMemAdviseSetPreferredLocation, deviceIndex)); + + // Copy all of the scene data structures over to GPU memory. This + // ensures that there isn't a big performance hitch for the first batch + // of rays as that stuff is copied over on demand. + CUDATrackedMemoryResource *mr = + dynamic_cast(gpuMemoryAllocator.resource()); + CHECK(mr != nullptr); + mr->PrefetchToGPU(); + + /////////////////////////////////////////////////////////////////////////// + // Render! + Timer timer; + ImageMetadata metadata; + integrator->Render(&metadata); + + LOG_VERBOSE("Total rendering time: %.3f s", timer.ElapsedSeconds()); + + CUDA_CHECK(cudaProfilerStop()); + + if (!Options->quiet) { + ReportKernelStats(); + + Printf("GPU Statistics:\n"); + Printf("%s\n", integrator->stats->Print()); + } + + metadata.renderTimeSeconds = timer.ElapsedSeconds(); + metadata.samplesPerPixel = integrator->sampler.SamplesPerPixel(); + + std::vector logs = ReadGPULogs(); + for (const auto &item : logs) + Log(item.level, item.file, item.line, item.message); + + integrator->film.WriteImage(metadata); +} + +GPUPathIntegrator::Stats::Stats(int maxDepth, Allocator alloc) + : indirectRays(maxDepth + 1, alloc), shadowRays(maxDepth, alloc) {} + +std::string GPUPathIntegrator::Stats::Print() const { + std::string s; + s += StringPrintf(" %-42s %12" PRIu64 "\n", "Camera rays", + cameraRays); + for (int i = 1; i < indirectRays.size(); ++i) + s += StringPrintf(" %-42s %12" PRIu64 "\n", + StringPrintf("Indirect rays, depth %-3d", i), indirectRays[i]); + for (int i = 0; i < shadowRays.size(); ++i) + s += StringPrintf(" %-42s %12" PRIu64 "\n", + StringPrintf("Shadow rays, depth %-3d", i), shadowRays[i]); + return s; +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/pathintegrator.h b/src/pbrt/gpu/pathintegrator.h new file mode 100644 index 00000000..cb01f29c --- /dev/null +++ b/src/pbrt/gpu/pathintegrator.h @@ -0,0 +1,121 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_PATHINTEGRATOR_H +#define PBRT_GPU_PATHINTEGRATOR_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pbrt { + +class ParsedScene; +class GPUAccel; + +void GPUInit(); +void GPURender(ParsedScene &scene); + +class GPUPathIntegrator { + public: + GPUPathIntegrator(Allocator alloc, const ParsedScene &scene); + + void Render(ImageMetadata *metadata); + + void GenerateCameraRays(int y0, int sampleIndex); + template + void GenerateCameraRays(int y0, int sampleIndex); + + void GenerateRaySamples(int depth, int sampleIndex); + template + void GenerateRaySamples(int depth, int sampleIndex); + + void TraceShadowRays(int depth); + void SampleMediumInteraction(int depth); + void HandleMediumTransitions(int depth); + void SampleSubsurface(int depth); + + void HandleEscapedRays(int depth); + void HandleRayFoundEmission(int depth); + + void EvaluateMaterialsAndBSDFs(int depth); + template + void EvaluateMaterialAndBSDF(int depth); + template + void EvaluateMaterialAndBSDF(TextureEvaluator texEval, MaterialEvalQueue *evalQueue, + int depth); + + void SampleDirect(int depth); + template + void SampleDirect(int depth); + + void SampleIndirect(int depth); + template + void SampleIndirect(int depth); + + void UpdateFilm(); + + FilterHandle filter; + FilmHandle film; + SamplerHandle sampler; + CameraHandle camera; + LightHandle envLight; + LightSamplerHandle lightSampler; + + int maxDepth; + bool regularize; + int maxQueueSize, scanlinesPerPass; + + // Various properties of the scene + bool initializeVisibleSurface; + bool haveSubsurface; + bool haveMedia; + pstd::array haveBasicEvalMaterial; + pstd::array haveUniversalEvalMaterial; + + GPUAccel *accel = nullptr; + + SOA pixelSampleState; + + RayQueue *rayQueues[2] = {nullptr, nullptr}; + + ShadowRayQueue *shadowRayQueue = nullptr; + + EscapedRayQueue *escapedRayQueue = nullptr; + HitAreaLightQueue *hitAreaLightQueue = nullptr; + + MaterialEvalQueue *basicEvalMaterialQueue = nullptr; + MaterialEvalQueue *universalEvalMaterialQueue = nullptr; + + GetBSSRDFAndProbeRayQueue *bssrdfEvalQueue = nullptr; + SubsurfaceScatterQueue *subsurfaceScatterQueue = nullptr; + + MediumTransitionQueue *mediumTransitionQueue = nullptr; + MediumSampleQueue *mediumSampleQueue = nullptr; + MediumScatterQueue *mediumScatterQueue = nullptr; + + struct Stats { + Stats(int maxDepth, Allocator alloc); + + std::string Print() const; + + // Note: not atomics: tid 0 always updates them for everyone... + uint64_t cameraRays = 0; + pstd::vector indirectRays, shadowRays; + }; + Stats *stats; +}; + +} // namespace pbrt + +#endif // PBRT_GPU_PATHINTEGRATOR_H diff --git a/src/pbrt/gpu/samples.cpp b/src/pbrt/gpu/samples.cpp new file mode 100644 index 00000000..e75ec81f --- /dev/null +++ b/src/pbrt/gpu/samples.cpp @@ -0,0 +1,73 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include + +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif // PBRT_GPU_DBG + +namespace pbrt { + +template +void GPUPathIntegrator::GenerateRaySamples(int depth, int sampleIndex) { + std::string desc = std::string("Generate ray samples - ") + Sampler::Name(); + + ForAllQueued(desc.c_str(), rayQueues[depth & 1], maxQueueSize, + [=] PBRT_GPU(const RayWorkItem w, int index) { + // Figure out how many dimensions have been consumed so far: 5 + // are used for the initial camera sample and then either 7 or + // 10 per ray, depending on whether there's subsurface + // scattering. + int dimension = 5 + 7 * depth; + if (haveSubsurface) + dimension += 3 * depth; + + // Initialize a Sampler + Sampler pixelSampler = *sampler.Cast(); + Point2i pPixel = pixelSampleState.pPixel[w.pixelIndex]; + pixelSampler.StartPixelSample(pPixel, sampleIndex, dimension); + + // Generate the samples for the ray and store them with it in + // the ray queue. + RaySamples rs; + rs.direct.u = pixelSampler.Get2D(); + rs.direct.uc = pixelSampler.Get1D(); + rs.indirect.u = pixelSampler.Get2D(); + rs.indirect.uc = pixelSampler.Get1D(); + rs.indirect.rr = pixelSampler.Get1D(); + rs.haveSubsurface = haveSubsurface; + if (haveSubsurface) { + rs.subsurface.uc = pixelSampler.Get1D(); + rs.subsurface.u = pixelSampler.Get2D(); + } + + rayQueues[depth & 1]->raySamples[index] = rs; + }); +} + +void GPUPathIntegrator::GenerateRaySamples(int depth, int sampleIndex) { + auto generateSamples = [=](auto sampler) { + using Sampler = std::remove_reference_t; + if constexpr (!std::is_same_v && + !std::is_same_v) + GenerateRaySamples(depth, sampleIndex); + }; + // Call the appropriate GenerateRaySamples specialization based on the + // Sampler's actual type. + sampler.DispatchCPU(generateSamples); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/subsurface.cpp b/src/pbrt/gpu/subsurface.cpp new file mode 100644 index 00000000..1abd3b67 --- /dev/null +++ b/src/pbrt/gpu/subsurface.cpp @@ -0,0 +1,211 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif + +namespace pbrt { + +void GPUPathIntegrator::SampleSubsurface(int depth) { + ForAllQueued( + "Get BSSRDF and enqueue probe ray", bssrdfEvalQueue, maxQueueSize, + [=] PBRT_GPU(const GetBSSRDFAndProbeRayWorkItem be, int index) { + using BSSRDF = typename SubsurfaceMaterial::BSSRDF; + BSSRDF bssrdf; + const SubsurfaceMaterial *material = be.material.Cast(); + MaterialEvalContext ctx = be.GetMaterialEvalContext(); + SampledWavelengths lambda = be.lambda; + material->GetBSSRDF(BasicTextureEvaluator(), ctx, lambda, &bssrdf); + + RaySamples raySamples = rayQueues[depth & 1]->raySamples[be.rayIndex]; + Float uc = raySamples.subsurface.uc; + Point2f u = raySamples.subsurface.u; + + BSSRDFProbeSegment probeSeg = bssrdf.Sample(uc, u); + if (probeSeg) + subsurfaceScatterQueue->Push(probeSeg.p0, probeSeg.p1, material, bssrdf, + be.beta, be.pdfUni, be.mediumInterface, + be.rayIndex); + }); + + auto events = accel->IntersectOneRandom(maxQueueSize, subsurfaceScatterQueue); + struct IsectRandomHack {}; + GetGPUKernelStats("Tracing subsurface scattering probe rays") + .launchEvents.push_back(events); + + ForAllQueued( + "Handle out-scattering after SSS", subsurfaceScatterQueue, maxQueueSize, + [=] PBRT_GPU(SubsurfaceScatterWorkItem s, int index) { + if (s.weight == 0) + return; + + using BSSRDF = TabulatedBSSRDF; + BSSRDF bssrdf = s.bssrdf; + using BxDF = typename BSSRDF::BxDF; + BxDF bxdf; + + SubsurfaceInteraction &intr = s.ssi; + BSSRDFSample bssrdfSample = bssrdf.ProbeIntersectionToSample(intr, &bxdf); + + if (!bssrdfSample.S || bssrdfSample.pdf == 0) + return; + + SampledSpectrum betap = s.beta * bssrdfSample.S * s.weight / bssrdfSample.pdf; + SampledWavelengths lambda = rayQueues[depth & 1]->lambda[s.rayIndex]; + Float etaScale = rayQueues[depth & 1]->etaScale[s.rayIndex]; + RaySamples raySamples = rayQueues[depth & 1]->raySamples[s.rayIndex]; + Vector3f wo = bssrdfSample.wo; + BSDF &bsdf = bssrdfSample.bsdf; + Float time = 0; // TODO: pipe through + + // NOTE: the remainder is copied from the Material/BSDF eval method. + // Will unify into shared fragments in the book... + + // Indirect... + { + Point2f u = raySamples.indirect.u; + Float uc = raySamples.indirect.uc; + + BSDFSample bsdfSample = bsdf.Sample_f(wo, uc, u); + if (bsdfSample && bsdfSample.f) { + Vector3f wi = bsdfSample.wi; + SampledSpectrum beta = betap * bsdfSample.f * AbsDot(wi, intr.ns); + SampledSpectrum pdfUni = s.pdfUni, pdfNEE = pdfUni; + + DBG("%s f*cos[0] %f bsdfSample.pdf %f f*cos/pdf %f\n", BxDF::Name(), + bsdfSample.f[0] * AbsDot(wi, intr.ns), bsdfSample.pdf, + bsdfSample.f[0] * AbsDot(wi, intr.ns) / bsdfSample.pdf); + + if (bsdf.SampledPDFIsProportional()) { + Float pdf = bsdf.PDF(wo, wi); + beta *= pdf / bsdfSample.pdf; + pdfUni *= pdf; + DBG("Sampled PDF is proportional: pdf %f\n", pdf); + } else + pdfUni *= bsdfSample.pdf; + + if (bsdfSample.IsTransmission()) + etaScale *= Sqr(bsdf.eta); + + // Russian roulette + SampledSpectrum rrBeta = beta * etaScale / pdfUni.Average(); + if (rrBeta.MaxComponentValue() < 1 && depth > 1) { + Float q = std::max(0, 1 - rrBeta.MaxComponentValue()); + if (raySamples.indirect.rr < q) { + beta = SampledSpectrum(0.f); + DBG("Path terminated with RR\n"); + } + pdfUni *= 1 - q; + pdfNEE *= 1 - q; + } + + if (beta) { + Ray ray = SpawnRay(intr.pi, intr.n, time, wi); + if (haveMedia) + // TODO: should always just take outside in this case? + ray.medium = Dot(ray.d, intr.n) > 0 + ? s.mediumInterface.outside + : s.mediumInterface.inside; + + // || rather than | is intentional, to avoid the read if + // possible... + bool anyNonSpecularBounces = true; + int pixelIndex = rayQueues[depth & 1]->pixelIndex[s.rayIndex]; + + rayQueues[(depth + 1) & 1]->PushIndirect( + ray, intr.pi, intr.n, intr.ns, beta, pdfUni, pdfNEE, lambda, + etaScale, bsdfSample.IsSpecular(), anyNonSpecularBounces, + pixelIndex); + + DBG("Spawned indirect ray at depth %d from prev index %d. " + "Specular %d Beta %f %f %f %f pdfUni %f %f %f %f pdfNEE %f " + "%f %f %f " + "beta/pdfUni %f %f %f %f\n", + depth + 1, int(s.rayIndex), int(bsdfSample.IsSpecular()), + beta[0], beta[1], beta[2], beta[3], pdfUni[0], pdfUni[1], + pdfUni[2], pdfUni[3], pdfNEE[0], pdfNEE[1], pdfNEE[2], + pdfNEE[3], SafeDiv(beta, pdfUni)[0], SafeDiv(beta, pdfUni)[1], + SafeDiv(beta, pdfUni)[2], SafeDiv(beta, pdfUni)[3]); + } + } + } + + // Direct lighting... + if (!bsdf.IsSpecular()) { + LightSampleContext ctx(intr.pi, intr.n, intr.ns); + pstd::optional sampledLight = + lightSampler.Sample(ctx, raySamples.direct.uc); + LightHandle light = sampledLight->light; + if (!light) + return; + + LightLiSample ls = light.SampleLi(ctx, raySamples.direct.u, lambda, + LightSamplingMode::WithMIS); + if (!ls || !ls.L) + return; + + Vector3f wi = ls.wi; + SampledSpectrum f = bsdf.f(wo, wi); + if (!f) + return; + + SampledSpectrum beta = betap * f * AbsDot(wi, intr.ns); + + DBG("depth %d beta %f %f %f %f f %f %f %f %f ls.L %f %f %f %f ls.pdf " + "%f\n", + depth, beta[0], beta[1], beta[2], beta[3], f[0], f[1], f[2], f[3], + ls.L[0], ls.L[1], ls.L[2], ls.L[3], ls.pdf); + + Float lightPDF = ls.pdf * sampledLight->pdf; + // This causes pdfUni to be zero for the shadow ray, so that + // part of MIS just becomes a no-op. + Float bsdfPDF = IsDeltaLight(light.Type()) ? 0.f : bsdf.PDF(wo, wi); + SampledSpectrum pdfUni = s.pdfUni * bsdfPDF; + SampledSpectrum pdfNEE = s.pdfUni * lightPDF; + + SampledSpectrum Ld = beta * ls.L; + + DBG("depth %d Ld %f %f %f %f " + "new beta %f %f %f %f beta/uni %f %f %f %f Ld/uni %f %f %f %f\n", + depth, Ld[0], Ld[1], Ld[2], Ld[3], beta[0], beta[1], beta[2], beta[3], + SafeDiv(beta, pdfUni)[0], SafeDiv(beta, pdfUni)[1], + SafeDiv(beta, pdfUni)[2], SafeDiv(beta, pdfUni)[3], + SafeDiv(Ld, pdfUni)[0], SafeDiv(Ld, pdfUni)[1], + SafeDiv(Ld, pdfUni)[2], SafeDiv(Ld, pdfUni)[3]); + + Ray ray = SpawnRayTo(intr.pi, intr.n, time, ls.pLight.pi, ls.pLight.n); + if (haveMedia) + // TODO: as above, always take outside here? + ray.medium = Dot(ray.d, intr.n) > 0 ? s.mediumInterface.outside + : s.mediumInterface.inside; + + int pixelIndex = rayQueues[depth & 1]->pixelIndex[s.rayIndex]; + shadowRayQueue->Push(ShadowRayWorkItem{ray, 1 - ShadowEpsilon, lambda, Ld, + pdfUni, pdfNEE, pixelIndex}); + } + }); + + TraceShadowRays(depth); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/surfscatter.cpp b/src/pbrt/gpu/surfscatter.cpp new file mode 100644 index 00000000..9674216a --- /dev/null +++ b/src/pbrt/gpu/surfscatter.cpp @@ -0,0 +1,264 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#ifdef PBRT_GPU_DBG +#ifndef TO_STRING +#define TO_STRING(x) TO_STRING2(x) +#define TO_STRING2(x) #x +#endif // !TO_STRING +#define DBG(...) printf(__FILE__ ":" TO_STRING(__LINE__) ": " __VA_ARGS__) +#else +#define DBG(...) +#endif // PBRT_GPU_DBG + +namespace pbrt { + +template +void GPUPathIntegrator::EvaluateMaterialAndBSDF(TextureEvaluator texEval, + MaterialEvalQueue *evalQueue, int depth) { + std::string name = StringPrintf( + "%s + BxDF Eval (%s tex)", Material::Name(), + std::is_same_v ? "Basic" : "Universal"); + + ForAllQueued( + name.c_str(), evalQueue->Get(), maxQueueSize, + [=] PBRT_GPU(const MaterialEvalWorkItem me, int index) { + const Material *material = me.material; + + Normal3f ns = me.ns; + Vector3f dpdus = me.dpdus; + + FloatTextureHandle displacement = material->GetDisplacement(); + if (displacement) { + // Compute shading normal (and shading dpdu) via bump mapping. + DCHECK(texEval.CanEvaluate({displacement}, {})); + + BumpEvalContext bctx = me.GetBumpEvalContext(); + Vector3f dpdvs; + Bump(texEval, displacement, bctx, &dpdus, &dpdvs); + + ns = Normal3f(Normalize(Cross(dpdus, dpdvs))); + ns = FaceForward(ns, me.n); + } + + // Evaluate the material (and thence, its textures), to get the BSDF. + SampledWavelengths lambda = me.lambda; + MaterialEvalContext ctx = me.GetMaterialEvalContext(ns, dpdus); + using BxDF = typename Material::BxDF; + BxDF bxdf; + BSDF bsdf = material->GetBSDF(texEval, ctx, lambda, &bxdf); + + // BSDF regularization, if appropriate. + if (regularize && me.anyNonSpecularBounces) + bsdf.Regularize(); + + if (depth == 0 && initializeVisibleSurface) { + SurfaceInteraction intr; + intr.pi = me.pi; + intr.n = me.n; + intr.shading.n = ns; + intr.wo = me.wo; + // TODO: intr.time + + // Estimate BSDF's albedo + constexpr int nRhoSamples = 16; + SampledSpectrum rho(0.f); + for (int i = 0; i < nRhoSamples; ++i) { + // Generate sample for hemispherical-directional reflectance + Float uc = RadicalInverse(0, i + 1); + Point2f u(RadicalInverse(1, i + 1), RadicalInverse(2, i + 1)); + + // Estimate one term of $\rho_\roman{hd}$ + BSDFSample bs = bsdf.Sample_f(me.wo, uc, u); + if (bs && bs.pdf > 0) + rho += bs.f * AbsDot(bs.wi, ns) / bs.pdf; + } + SampledSpectrum albedo = rho / nRhoSamples; + + pixelSampleState.visibleSurface[me.pixelIndex] = + VisibleSurface(intr, camera.GetCameraTransform(), albedo, lambda); + } + + Vector3f wo = me.wo; + RaySamples raySamples = rayQueues[depth & 1]->raySamples[me.rayIndex]; + + // Sample indirect lighting + BSDFSample bsdfSample = + bsdf.Sample_f(wo, raySamples.indirect.uc, raySamples.indirect.u); + if (bsdfSample && bsdfSample.f) { + Vector3f wi = bsdfSample.wi; + SampledSpectrum beta = me.beta * bsdfSample.f * AbsDot(wi, ns); + SampledSpectrum pdfUni = me.pdfUni, pdfNEE = pdfUni; + + DBG("%s f*cos[0] %f bsdfSample.pdf %f f*cos/pdf %f\n", BxDF::Name(), + bsdfSample.f[0] * AbsDot(wi, ns), bsdfSample.pdf, + bsdfSample.f[0] * AbsDot(wi, ns) / bsdfSample.pdf); + + if (bsdf.SampledPDFIsProportional()) { + // The PDFs need to be handled slightly differently for + // stochastically-sampled layered materials.. + Float pdf = bsdf.PDF(wo, wi); + beta *= pdf / bsdfSample.pdf; + pdfUni *= pdf; + } else + pdfUni *= bsdfSample.pdf; + + Float etaScale = me.etaScale; + if (bsdfSample.IsTransmission()) + etaScale *= Sqr(bsdf.eta); + + // Russian roulette + SampledSpectrum rrBeta = beta * etaScale / pdfUni.Average(); + if (rrBeta.MaxComponentValue() < 1 && depth > 1) { + Float q = std::max(0, 1 - rrBeta.MaxComponentValue()); + if (raySamples.indirect.rr < q) { + beta = SampledSpectrum(0.f); + DBG("Path terminated with RR ray index %d\n", me.rayIndex); + } + pdfUni *= 1 - q; + pdfNEE *= 1 - q; + } + + if (beta) { + if (bsdfSample.IsTransmission() && + material->HasSubsurfaceScattering()) { + // There's a BSSRDF and sampled ray scattered into + // the surface; enqueue a work item for subsurface + // scattering rather than tracing the ray. + bssrdfEvalQueue->Push(GetBSSRDFAndProbeRayWorkItem{ + material, lambda, beta, pdfUni, Point3f(me.pi), wo, me.n, ns, + dpdus, me.uv, me.mediumInterface, me.rayIndex}); + } else { + Ray ray = SpawnRay(me.pi, me.n, me.time, wi); + if (haveMedia) + ray.medium = Dot(ray.d, me.n) > 0 ? me.mediumInterface.outside + : me.mediumInterface.inside; + + // || rather than | is intentional, to avoid the read if + // possible... + bool anyNonSpecularBounces = + !bsdfSample.IsSpecular() || me.anyNonSpecularBounces; + + // Spawn indriect ray. + rayQueues[(depth + 1) & 1]->PushIndirect( + ray, me.pi, me.n, ns, beta, pdfUni, pdfNEE, lambda, etaScale, + bsdfSample.IsSpecular(), anyNonSpecularBounces, + me.pixelIndex); + + DBG("Spawned indirect ray at depth %d from prev ray index %d. " + "Specular %d Beta %f %f %f %f pdfUni %f %f %f %f pdfNEE %f " + "%f %f %f " + "beta/pdfUni %f %f %f %f\n", + depth + 1, int(me.rayIndex), int(bsdfSample.IsSpecular()), + beta[0], beta[1], beta[2], beta[3], pdfUni[0], pdfUni[1], + pdfUni[2], pdfUni[3], pdfNEE[0], pdfNEE[1], pdfNEE[2], + pdfNEE[3], SafeDiv(beta, pdfUni)[0], SafeDiv(beta, pdfUni)[1], + SafeDiv(beta, pdfUni)[2], SafeDiv(beta, pdfUni)[3]); + } + } + } + + // Sample direct lighting. + if (!bsdf.IsSpecular()) { + // Choose a light source using the LightSampler. + LightSampleContext ctx(me.pi, me.n, ns); + pstd::optional sampledLight = + lightSampler.Sample(ctx, raySamples.direct.uc); + LightHandle light = sampledLight->light; + if (!light) + return; + + // Remarkably, this substantially improves L1 cache hits with + // CoatedDiffuseBxDF and gives about a 60% perf. benefit. + __syncthreads(); + + // And now sample the light source itself. + LightLiSample ls = light.SampleLi(ctx, raySamples.direct.u, lambda, + LightSamplingMode::WithMIS); + if (!ls || !ls.L) + return; + + Vector3f wi = ls.wi; + SampledSpectrum f = bsdf.f(wo, wi); + if (!f) + return; + + SampledSpectrum beta = me.beta * f * AbsDot(wi, ns); + + DBG("ray index %d depth %d beta %f %f %f %f f %f %f %f %f ls.L %f %f %f " + "%f ls.pdf %f\n", + me.rayIndex, depth, beta[0], beta[1], beta[2], beta[3], f[0], f[1], + f[2], f[3], ls.L[0], ls.L[1], ls.L[2], ls.L[3], ls.pdf); + + // Compute light and BSDF PDFs for MIS. + Float lightPDF = ls.pdf * sampledLight->pdf; + // This causes pdfUni to be zero for the shadow ray, so that + // part of MIS just becomes a no-op. + Float bsdfPDF = IsDeltaLight(light.Type()) ? 0.f : bsdf.PDF(wo, wi); + SampledSpectrum pdfUni = me.pdfUni * bsdfPDF; + SampledSpectrum pdfNEE = me.pdfUni * lightPDF; + + SampledSpectrum Ld = beta * ls.L; + + Ray ray = SpawnRayTo(me.pi, me.n, me.time, ls.pLight.pi, ls.pLight.n); + if (haveMedia) + ray.medium = Dot(ray.d, me.n) > 0 ? me.mediumInterface.outside + : me.mediumInterface.inside; + + shadowRayQueue->Push(ShadowRayWorkItem{ray, 1 - ShadowEpsilon, lambda, Ld, + pdfUni, pdfNEE, me.pixelIndex}); + DBG("ray index %d spawned shadow ray depth %d Ld %f %f %f %f " + "new beta %f %f %f %f beta/uni %f %f %f %f Ld/uni %f %f %f %f\n", + me.rayIndex, depth, Ld[0], Ld[1], Ld[2], Ld[3], beta[0], beta[1], + beta[2], beta[3], SafeDiv(beta, pdfUni)[0], SafeDiv(beta, pdfUni)[1], + SafeDiv(beta, pdfUni)[2], SafeDiv(beta, pdfUni)[3], + SafeDiv(Ld, pdfUni)[0], SafeDiv(Ld, pdfUni)[1], + SafeDiv(Ld, pdfUni)[2], SafeDiv(Ld, pdfUni)[3]); + } + }); +} + +template +void GPUPathIntegrator::EvaluateMaterialAndBSDF(int depth) { + if (haveBasicEvalMaterial[MaterialHandle::TypeIndex()]) + EvaluateMaterialAndBSDF(BasicTextureEvaluator(), basicEvalMaterialQueue, + depth); + + if (haveUniversalEvalMaterial[MaterialHandle::TypeIndex()]) + EvaluateMaterialAndBSDF(UniversalTextureEvaluator(), + universalEvalMaterialQueue, depth); +} + +struct EvaluateMaterialCallback { + int depth; + GPUPathIntegrator *integrator; + template + void operator()() { + integrator->EvaluateMaterialAndBSDF(depth); + } +}; + +void GPUPathIntegrator::EvaluateMaterialsAndBSDFs(int depth) { + MaterialHandle::ForEachType(EvaluateMaterialCallback{depth, this}); +} + +} // namespace pbrt diff --git a/src/pbrt/gpu/workitems.h b/src/pbrt/gpu/workitems.h new file mode 100644 index 00000000..12c27562 --- /dev/null +++ b/src/pbrt/gpu/workitems.h @@ -0,0 +1,411 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_WORKITEMS_H +#define PBRT_GPU_WORKITEMS_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace pbrt { + +struct RaySamples { + struct { + Point2f u; + Float uc; + } direct; + struct { + Float uc, rr; + Point2f u; + } indirect; + + bool haveSubsurface; + struct { + Float uc; + Point2f u; + } subsurface; +}; + +template <> +struct SOA { + public: + SOA() = default; + + SOA(int size, Allocator alloc) { + direct = alloc.allocate_object(size); + indirect = alloc.allocate_object(size); + subsurface = alloc.allocate_object(size); + } + + PBRT_CPU_GPU + RaySamples operator[](int i) const { + RaySamples rs; + Float4 dir = Load4(direct + i); + rs.direct.u = Point2f(dir.v[0], dir.v[1]); + rs.direct.uc = dir.v[2]; + + Float4 ind = Load4(indirect + i); + rs.indirect.uc = ind.v[0]; + rs.indirect.rr = ind.v[1]; + rs.indirect.u = Point2f(ind.v[2], ind.v[3]); + + rs.haveSubsurface = dir.v[3] != 0; + if (rs.haveSubsurface) { + Float4 ss = Load4(subsurface + i); + rs.subsurface.uc = ss.v[0]; + rs.subsurface.u = Point2f(ss.v[1], ss.v[2]); + } + + return rs; + } + + struct GetSetIndirector { + PBRT_CPU_GPU + operator RaySamples() const { return (*(const SOA *)soa)[index]; } + + PBRT_CPU_GPU + void operator=(RaySamples rs) { + soa->direct[index] = Float4{rs.direct.u[0], rs.direct.u[1], rs.direct.uc, + Float(rs.haveSubsurface)}; + soa->indirect[index] = Float4{rs.indirect.uc, rs.indirect.rr, + rs.indirect.u[0], rs.indirect.u[1]}; + if (rs.haveSubsurface) + soa->subsurface[index] = + Float4{rs.subsurface.uc, rs.subsurface.u.x, rs.subsurface.u.y, 0.f}; + } + + SOA *soa; + int index; + }; + + PBRT_CPU_GPU + GetSetIndirector operator[](int i) { return GetSetIndirector{this, i}; } + + private: + Float4 *__restrict__ direct; + Float4 *__restrict__ indirect; + Float4 *__restrict__ subsurface; +}; + +struct PixelSampleState { + Float filterWeight; + Point2i pPixel; + SampledWavelengths lambda; + SampledSpectrum L; + SampledSpectrum cameraRayWeight; + VisibleSurface visibleSurface; +}; + +struct RayWorkItem { + Ray ray; + int pixelIndex; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni, pdfNEE; + Point3fi piPrev; + Normal3f nPrev; + Normal3f nsPrev; + RaySamples raySamples; + Float etaScale; + int isSpecularBounce; + int anyNonSpecularBounces; +}; + +struct EscapedRayWorkItem { + SampledSpectrum beta, pdfUni, pdfNEE; + SampledWavelengths lambda; + Point3f rayo; + Vector3f rayd; + Point3fi piPrev; + Normal3f nPrev, nsPrev; + int specularBounce; + int pixelIndex; +}; + +using EscapedRayQueue = WorkQueue; + +struct HitAreaLightWorkItem { + LightHandle areaLight; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni, pdfNEE; + Point3f p; + Normal3f n; + Point2f uv; + Vector3f wo; + Point3fi piPrev; + Vector3f rayd; + Float time; + Normal3f nPrev, nsPrev; + int isSpecularBounce; + int pixelIndex; +}; + +using HitAreaLightQueue = WorkQueue; + +struct ShadowRayWorkItem { + Ray ray; + Float tMax; + SampledWavelengths lambda; + SampledSpectrum Ld, pdfUni, pdfNEE; + int pixelIndex; +}; + +using ShadowRayQueue = WorkQueue; + +template +struct MaterialEvalWorkItem { + PBRT_CPU_GPU + BumpEvalContext GetBumpEvalContext() const { + BumpEvalContext ctx; + ctx.p = Point3f(pi); + ctx.uv = uv; + ctx.shading.n = ns; + ctx.shading.dpdu = dpdus; + ctx.shading.dpdv = dpdvs; + ctx.shading.dndu = dndus; + ctx.shading.dndv = dndvs; + return ctx; + } + + PBRT_CPU_GPU + MaterialEvalContext GetMaterialEvalContext(Normal3f ns, Vector3f dpdus) const { + MaterialEvalContext ctx; + ctx.wo = wo; + ctx.n = n; + ctx.ns = ns; + ctx.dpdus = dpdus; + ctx.p = Point3f(pi); + ctx.uv = uv; + return ctx; + } + + const Material *material; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni; + Point3fi pi; + Normal3f n, ns; + Vector3f dpdus, dpdvs; + Normal3f dndus, dndvs; + Vector3f wo; + Point2f uv; + Float time; + int anyNonSpecularBounces; + Float etaScale; + MediumInterface mediumInterface; + int rayIndex; + int pixelIndex; +}; + +struct GetBSSRDFAndProbeRayWorkItem { + PBRT_CPU_GPU + MaterialEvalContext GetMaterialEvalContext() const { + MaterialEvalContext ctx; + ctx.wo = wo; + ctx.n = n; + ctx.ns = ns; + ctx.dpdus = dpdus; + ctx.p = p; + ctx.uv = uv; + return ctx; + } + + MaterialHandle material; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni; + Point3f p; + Vector3f wo; + Normal3f n, ns; + Vector3f dpdus; + Point2f uv; + MediumInterface mediumInterface; + int rayIndex; +}; + +using GetBSSRDFAndProbeRayQueue = WorkQueue; + +struct SubsurfaceScatterWorkItem { + Point3f p0, p1; + MaterialHandle material; + TabulatedBSSRDF bssrdf; + SampledSpectrum beta, pdfUni; + Float weight; + Float uLight; + SubsurfaceInteraction ssi; + MediumInterface mediumInterface; + int rayIndex; +}; + +struct MediumTransitionWorkItem { + Ray ray; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni, pdfNEE; + Point3fi piPrev; + Normal3f nPrev, nsPrev; + int isSpecularBounce; + int anyNonSpecularBounces; + Float etaScale; + int pixelIndex; +}; + +using MediumTransitionQueue = WorkQueue; + +struct MediumSampleWorkItem { + // Both enqueue types (have mtl and no hit) + Ray ray; + Float tMax; + SampledWavelengths lambda; + SampledSpectrum beta; + SampledSpectrum pdfUni; + SampledSpectrum pdfNEE; + int rayIndex; + int pixelIndex; + Point3fi piPrev; + Normal3f nPrev; + Normal3f nsPrev; + int isSpecularBounce; + int anyNonSpecularBounces; + Float etaScale; + + // Have a hit material as well + LightHandle areaLight; + Point3fi pi; + Normal3f n; + Vector3f wo; + Point2f uv; + MaterialHandle material; + Normal3f ns; + Vector3f dpdus; + Vector3f dpdvs; + Normal3f dndus; + Normal3f dndvs; + MediumInterface mediumInterface; +}; + +struct MediumScatterWorkItem { + Point3f p; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni; + int rayIndex; + HGPhaseFunction phase; + Vector3f wo; + Float etaScale; + MediumHandle medium; + int pixelIndex; +}; + +#include "gpu_workitems_soa.h" + +class RayQueue : public WorkQueue { + public: + using WorkQueue::WorkQueue; + + PBRT_CPU_GPU + int PushCameraRay(const Ray &ray, const SampledWavelengths &lambda, int pixelIndex) { + int index = size.fetch_add(1, cuda::std::memory_order_relaxed); + this->ray[index] = ray; + this->pixelIndex[index] = pixelIndex; + this->lambda[index] = lambda; + this->beta[index] = SampledSpectrum(1.f); + this->etaScale[index] = 1.f; + this->anyNonSpecularBounces[index] = false; + this->pdfUni[index] = SampledSpectrum(1.f); + this->pdfNEE[index] = SampledSpectrum(1.f); + this->isSpecularBounce[index] = false; + return index; + } + + PBRT_CPU_GPU + int PushIndirect(const Ray &ray, const Point3fi &piPrev, const Normal3f &nPrev, + const Normal3f &nsPrev, const SampledSpectrum &beta, + const SampledSpectrum &pdfUni, const SampledSpectrum &pdfNEE, + const SampledWavelengths &lambda, Float etaScale, + bool isSpecularBounce, bool anyNonSpecularBounces, int pixelIndex) { + int index = size.fetch_add(1, cuda::std::memory_order_relaxed); + this->ray[index] = ray; + this->pixelIndex[index] = pixelIndex; + this->piPrev[index] = piPrev; + this->nPrev[index] = nPrev; + this->nsPrev[index] = nsPrev; + this->beta[index] = beta; + this->pdfUni[index] = pdfUni; + this->pdfNEE[index] = pdfNEE; + this->lambda[index] = lambda; + this->anyNonSpecularBounces[index] = anyNonSpecularBounces; + this->isSpecularBounce[index] = isSpecularBounce; + this->etaScale[index] = etaScale; + return index; + } +}; + +class SubsurfaceScatterQueue : public WorkQueue { + public: + using WorkQueue::WorkQueue; + + PBRT_CPU_GPU + int Push(Point3f p0, Point3f p1, MaterialHandle material, TabulatedBSSRDF bssrdf, + SampledSpectrum beta, SampledSpectrum pdfUni, + MediumInterface mediumInterface, int rayIndex) { + int index = size.fetch_add(1, cuda::std::memory_order_relaxed); + this->p0[index] = p0; + this->p1[index] = p1; + this->material[index] = material; + this->bssrdf[index] = bssrdf; + this->beta[index] = beta; + this->pdfUni[index] = pdfUni; + this->mediumInterface[index] = mediumInterface; + this->rayIndex[index] = rayIndex; + return index; + } +}; + +class MediumSampleQueue : public WorkQueue { + public: + using WorkQueue::WorkQueue; + + using WorkQueue::Push; + + PBRT_CPU_GPU + int Push(Ray ray, Float tMax, SampledWavelengths lambda, SampledSpectrum beta, + SampledSpectrum pdfUni, SampledSpectrum pdfNEE, int rayIndex, int pixelIndex, + Point3fi piPrev, Normal3f nPrev, Normal3f nsPrev, int isSpecularBounce, + int anyNonSpecularBounces, Float etaScale) { + int index = size.fetch_add(1, cuda::std::memory_order_relaxed); + this->ray[index] = ray; + this->tMax[index] = tMax; + this->lambda[index] = lambda; + this->beta[index] = beta; + this->pdfUni[index] = pdfUni; + this->pdfNEE[index] = pdfNEE; + this->rayIndex[index] = rayIndex; + this->pixelIndex[index] = pixelIndex; + this->piPrev[index] = piPrev; + this->nPrev[index] = nPrev; + this->nsPrev[index] = nsPrev; + this->isSpecularBounce[index] = isSpecularBounce; + this->anyNonSpecularBounces[index] = anyNonSpecularBounces; + this->etaScale[index] = etaScale; + return index; + } +}; + +using MediumScatterQueue = WorkQueue; + +using MaterialEvalQueue = + MultiWorkQueue; + +} // namespace pbrt + +#endif // PBRT_GPU_WORKITEMS_H diff --git a/src/pbrt/gpu/workitems.soa b/src/pbrt/gpu/workitems.soa new file mode 100644 index 00000000..5965cc79 --- /dev/null +++ b/src/pbrt/gpu/workitems.soa @@ -0,0 +1,184 @@ +// -*- mode: c++ -*- +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +flat Float; +flat HGPhaseFunction; +flat LightHandle; +flat MaterialHandle; +flat MediumHandle; +flat int; + +soa BSDF; +soa MediumInterface; +soa Normal3f; +soa Point2f; +soa Point2i; +soa Point3f; +soa Point3fi; +soa Ray; +soa RaySamples; +soa SampledSpectrum; +soa SampledWavelengths; +soa SubsurfaceInteraction; +soa TabulatedBSSRDF; +soa Vector3f; +soa VisibleSurface; + +soa PixelSampleState { + Float filterWeight; + Point2i pPixel; + SampledWavelengths lambda; + SampledSpectrum L; + SampledSpectrum cameraRayWeight; + VisibleSurface visibleSurface; +}; + +soa RayWorkItem { + Ray ray; + int pixelIndex; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni, pdfNEE; + Point3fi piPrev; + Normal3f nPrev; + Normal3f nsPrev; + RaySamples raySamples; + Float etaScale; + int isSpecularBounce; + int anyNonSpecularBounces; +}; + +soa EscapedRayWorkItem { + SampledSpectrum beta, pdfUni, pdfNEE; + SampledWavelengths lambda; + Point3f rayo; + Vector3f rayd; + Point3fi piPrev; + Normal3f nPrev, nsPrev; + int specularBounce; + int pixelIndex; +}; + +soa HitAreaLightWorkItem { + LightHandle areaLight; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni, pdfNEE; + Point3f p; + Normal3f n; + Point2f uv; + Vector3f wo; + Point3fi piPrev; + Vector3f rayd; + Float time; + Normal3f nPrev, nsPrev; + int isSpecularBounce; + int pixelIndex; +}; + +soa ShadowRayWorkItem { + Ray ray; + Float tMax; + SampledWavelengths lambda; + SampledSpectrum Ld, pdfUni, pdfNEE; + int pixelIndex; +}; + +soa GetBSSRDFAndProbeRayWorkItem { + MaterialHandle material; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni; + Point3f p; + Vector3f wo; + Normal3f n, ns; + Vector3f dpdus; + Point2f uv; + MediumInterface mediumInterface; + int rayIndex; +}; + +soa SubsurfaceScatterWorkItem { + // Via eval/sample SSS kernel + Point3f p0, p1; + MaterialHandle material; + TabulatedBSSRDF bssrdf; + SampledSpectrum beta, pdfUni; + MediumInterface mediumInterface; + int rayIndex; + + // OptiX code initializes these. + Float weight; + Float uLight; + SubsurfaceInteraction ssi; +}; + +soa MediumTransitionWorkItem { + Ray ray; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni, pdfNEE; + Point3fi piPrev; + Normal3f nPrev, nsPrev; + int isSpecularBounce; + int anyNonSpecularBounces; + Float etaScale; + int pixelIndex; +}; + +soa MediumSampleWorkItem { + Ray ray; + Float tMax; + SampledWavelengths lambda; + SampledSpectrum beta; + SampledSpectrum pdfUni; + SampledSpectrum pdfNEE; + int rayIndex; + int pixelIndex; + LightHandle areaLight; + Point3fi pi; + Normal3f n; + Vector3f wo; + Point2f uv; + Point3fi piPrev; + Normal3f nPrev; + Normal3f nsPrev; + int isSpecularBounce; + MaterialHandle material; + Normal3f ns; + Vector3f dpdus; + Vector3f dpdvs; + Normal3f dndus; + Normal3f dndvs; + int anyNonSpecularBounces; + Float etaScale; + MediumInterface mediumInterface; +}; + +soa MediumScatterWorkItem { + Point3f p; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni; + int rayIndex; + HGPhaseFunction phase; + Vector3f wo; + Float etaScale; + MediumHandle medium; + int pixelIndex; +}; + +soa MaterialEvalWorkItem { + const Material *material; + SampledWavelengths lambda; + SampledSpectrum beta, pdfUni; + Point3fi pi; + Normal3f n, ns; + Vector3f dpdus, dpdvs; + Normal3f dndus, dndvs; + Vector3f wo; + Point2f uv; + Float time; + int anyNonSpecularBounces; + Float etaScale; + MediumInterface mediumInterface; + int rayIndex; + int pixelIndex; +}; diff --git a/src/pbrt/gpu/workqueue.h b/src/pbrt/gpu/workqueue.h new file mode 100644 index 00000000..50b5914d --- /dev/null +++ b/src/pbrt/gpu/workqueue.h @@ -0,0 +1,134 @@ +// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. +// The pbrt source code is licensed under the Apache License, Version 2.0. +// SPDX: Apache-2.0 + +#ifndef PBRT_GPU_WORKQUEUE_H +#define PBRT_GPU_WORKQUEUE_H + +#include + +#include +#include + +#include +#include + +namespace pbrt { + +template +class WorkQueue : public SOA { + public: + WorkQueue(int n, Allocator alloc) : SOA(n, alloc) {} + + PBRT_CPU_GPU + int Size() const { return size.load(cuda::std::memory_order_relaxed); } + + PBRT_CPU_GPU + void Reset() { size.store(0, cuda::std::memory_order_relaxed); } + + PBRT_CPU_GPU + int Push(WorkItem w) { + int index = size.fetch_add(1, cuda::std::memory_order_relaxed); + (*this)[index] = w; + return index; + } + + protected: + cuda::atomic size{0}; +}; + +template +void ForAllQueued(const char *desc, WorkQueue *q, int maxQueued, F func) { + GPUParallelFor(desc, maxQueued, [=] PBRT_GPU(int index) { + if (index >= q->Size()) + return; + func((*q)[index], index); + }); +} + +template