"atomic bomb" commit. Reorganized OpenCV directory structure

This commit is contained in:
Vadim Pisarevsky 2010-05-11 17:44:00 +00:00
commit 127d6649a1
1761 changed files with 1622326 additions and 0 deletions

15
3rdparty/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,15 @@
add_subdirectory(flann)
add_subdirectory(lapack)
add_subdirectory(zlib)
if(WITH_JASPER AND NOT JASPER_FOUND)
add_subdirectory(libjasper)
endif()
if(WITH_JPEG AND NOT JPEG_FOUND)
add_subdirectory(libjpeg)
endif()
if(WITH_PNG AND NOT PNG_FOUND)
add_subdirectory(libpng)
endif()
if(WITH_TIFF AND NOT TIFF_FOUND)
add_subdirectory(libtiff)
endif()

107
3rdparty/flann/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,107 @@
if (DEFINED OPENCV_VERSION)
# ----------------------------------------------------------------------------
# CMake file for libflann. See root CMakeLists.txt
#
# ----------------------------------------------------------------------------
project(flann)
# List of C++ files:
#set(CMAKE_BUILD_TYPE Debug)
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/algorithms
${CMAKE_CURRENT_SOURCE_DIR}/util
${CMAKE_CURRENT_SOURCE_DIR}/nn
"${CMAKE_CURRENT_SOURCE_DIR}/../include/flann"
)
# The .cpp files:
file(GLOB_RECURSE flann_sources_cpp *.cpp)
file(GLOB_RECURSE flann_sources_h1 "${CMAKE_CURRENT_SOURCE_DIR}/../include/flann/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/../include/flann/*.hpp")
file(GLOB_RECURSE flann_sources_h2 *.h *.hpp)
source_group("Src" FILES ${flann_sources_cpp})
source_group("Include\\External" FILES ${flann_sources_h1})
source_group("Include\\Internal" FILES ${flann_sources_h2})
set(flann_sources ${flann_sources_cpp} ${flann_sources_h1} ${flann_sources_h2})
# ----------------------------------------------------------------------------------
# Define the library target:
# ----------------------------------------------------------------------------------
set(the_target "flann")
add_library(${the_target} STATIC ${flann_sources})
add_definitions(-Dflann_EXPORTS)
if(MSVC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3")
add_definitions(-DJAS_WIN_MSVC_BUILD)
endif()
if(UNIX)
if(CMAKE_COMPILER_IS_GNUCXX OR CV_ICC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
endif()
endif()
set_target_properties(${the_target}
PROPERTIES
OUTPUT_NAME "${the_target}"
DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/3rdparty/lib"
)
ELSE()
INCLUDE_DIRECTORIES(algorithms util nn .)
ADD_SUBDIRECTORY( tests )
file(GLOB_RECURSE SOURCES *.cpp)
#SET(SOURCES flann.cpp util/Random.cpp nn/Testing.cpp algorithms/NNIndex.cpp algorithms/dist.cpp util/Logger.cpp util/Saving.cpp)
ADD_LIBRARY(flann ${SOURCES})
#ADD_LIBRARY(flann SHARED ${SOURCES}) #JL: Why the two versions??
#ADD_LIBRARY(flann_s STATIC ${SOURCES})
IF(WIN32)
INSTALL (
TARGETS flann
RUNTIME DESTINATION matlab
)
INSTALL (
TARGETS flann
RUNTIME DESTINATION python/pyflann/bindings
)
ELSE(WIN32)
INSTALL (
TARGETS flann
LIBRARY DESTINATION python/pyflann/bindings
)
ENDIF(WIN32)
INSTALL (
TARGETS flann # flann_s
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
)
# INSTALL (
# TARGETS flann flann_s
# ARCHIVE DESTINATION ${PROJECT_SOURCE_DIR}/python
# LIBRARY DESTINATION ${PROJECT_SOURCE_DIR}/python
# )
INSTALL (
FILES flann.h constants.h
DESTINATION include
)
ENDIF()

View File

@ -0,0 +1,571 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef AUTOTUNEDINDEX_H_
#define AUTOTUNEDINDEX_H_
#include "constants.h"
#include "nn_index.h"
#include "ground_truth.h"
#include "index_testing.h"
namespace flann
{
class AutotunedIndex : public NNIndex
{
NNIndex* bestIndex;
IndexParams* bestParams;
SearchParams bestSearchParams;
Matrix<float>* sampledDataset;
Matrix<float>* testDataset;
Matrix<int>* gt_matches;
float speedup;
/**
* The dataset used by this index
*/
const Matrix<float> dataset;
/**
* Index parameters
*/
const AutotunedIndexParams& params;
/**
* Number of features in the dataset.
*/
int size_;
/**
* Length of each feature.
*/
int veclen_;
public:
AutotunedIndex(const Matrix<float>& inputData, const AutotunedIndexParams& params_ = AutotunedIndexParams() ) :
dataset(inputData), params(params_)
{
size_ = dataset.rows;
veclen_ = dataset.cols;
bestIndex = NULL;
}
virtual ~AutotunedIndex()
{
delete bestIndex;
delete bestParams;
};
/**
Method responsible with building the index.
*/
virtual void buildIndex()
{
bestParams = estimateBuildParams();
bestIndex = bestParams->createIndex(dataset);
bestIndex->buildIndex();
speedup = estimateSearchParams(bestSearchParams);
}
/**
Saves the index to a stream
*/
virtual void saveIndex(FILE* stream)
{
bestIndex->saveIndex(stream);
}
/**
Loads the index from a stream
*/
virtual void loadIndex(FILE* stream)
{
bestIndex->loadIndex(stream);
}
/**
Method that searches for nearest-neighbors
*/
virtual void findNeighbors(ResultSet& result, const float* vec, const SearchParams& /*searchParams*/)
{
bestIndex->findNeighbors(result, vec, bestSearchParams);
}
/**
Number of features in this index.
*/
virtual int size() const
{
return bestIndex->size();
}
/**
The length of each vector in this index.
*/
virtual int veclen() const
{
return bestIndex->veclen();
}
/**
The amount of memory (in bytes) this index uses.
*/
virtual int usedMemory() const
{
return bestIndex->usedMemory();
}
/**
* Algorithm name
*/
virtual flann_algorithm_t getType() const
{
return bestIndex->getType();
}
/**
Estimates the search parameters required in order to get a certain precision.
If testset is not given it uses cross-validation.
*/
// virtual Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
// {
// Params params;
//
// return params;
// }
private:
struct CostData {
float searchTimeCost;
float buildTimeCost;
float timeCost;
float memoryCost;
float totalCost;
};
typedef pair<CostData, KDTreeIndexParams> KDTreeCostData;
typedef pair<CostData, KMeansIndexParams> KMeansCostData;
void evaluate_kmeans(CostData& cost, const KMeansIndexParams& kmeans_params)
{
StartStopTimer t;
int checks;
const int nn = 1;
logger.info("KMeansTree using params: max_iterations=%d, branching=%d\n", kmeans_params.iterations, kmeans_params.branching);
KMeansIndex kmeans(*sampledDataset, kmeans_params);
// measure index build time
t.start();
kmeans.buildIndex();
t.stop();
float buildTime = (float)t.value;
// measure search time
float searchTime = test_index_precision(kmeans, *sampledDataset, *testDataset, *gt_matches, params.target_precision, checks, nn);;
float datasetMemory = (float)(sampledDataset->rows*sampledDataset->cols*sizeof(float));
cost.memoryCost = (kmeans.usedMemory()+datasetMemory)/datasetMemory;
cost.searchTimeCost = searchTime;
cost.buildTimeCost = buildTime;
cost.timeCost = (buildTime*params.build_weight+searchTime);
logger.info("KMeansTree buildTime=%g, searchTime=%g, timeCost=%g, buildTimeFactor=%g\n",buildTime, searchTime, cost.timeCost, params.build_weight);
}
void evaluate_kdtree(CostData& cost, const KDTreeIndexParams& kdtree_params)
{
StartStopTimer t;
int checks;
const int nn = 1;
logger.info("KDTree using params: trees=%d\n",kdtree_params.trees);
KDTreeIndex kdtree(*sampledDataset, kdtree_params);
t.start();
kdtree.buildIndex();
t.stop();
float buildTime = (float)t.value;
//measure search time
float searchTime = test_index_precision(kdtree, *sampledDataset, *testDataset, *gt_matches, params.target_precision, checks, nn);
float datasetMemory = (float)(sampledDataset->rows*sampledDataset->cols*sizeof(float));
cost.memoryCost = (kdtree.usedMemory()+datasetMemory)/datasetMemory;
cost.searchTimeCost = searchTime;
cost.buildTimeCost = buildTime;
cost.timeCost = (buildTime*params.build_weight+searchTime);
logger.info("KDTree buildTime=%g, searchTime=%g, timeCost=%g\n",buildTime, searchTime, cost.timeCost);
}
// struct KMeansSimpleDownhillFunctor {
//
// Autotune& autotuner;
// KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {};
//
// float operator()(int* params) {
//
// float maxFloat = numeric_limits<float>::max();
//
// if (params[0]<2) return maxFloat;
// if (params[1]<0) return maxFloat;
//
// CostData c;
// c.params["algorithm"] = KMEANS;
// c.params["centers-init"] = CENTERS_RANDOM;
// c.params["branching"] = params[0];
// c.params["max-iterations"] = params[1];
//
// autotuner.evaluate_kmeans(c);
//
// return c.timeCost;
//
// }
// };
//
// struct KDTreeSimpleDownhillFunctor {
//
// Autotune& autotuner;
// KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {};
//
// float operator()(int* params) {
// float maxFloat = numeric_limits<float>::max();
//
// if (params[0]<1) return maxFloat;
//
// CostData c;
// c.params["algorithm"] = KDTREE;
// c.params["trees"] = params[0];
//
// autotuner.evaluate_kdtree(c);
//
// return c.timeCost;
//
// }
// };
KMeansCostData optimizeKMeans()
{
logger.info("KMEANS, Step 1: Exploring parameter space\n");
// explore kmeans parameters space using combinations of the parameters below
int maxIterations[] = { 1, 5, 10, 15 };
int branchingFactors[] = { 16, 32, 64, 128, 256 };
int kmeansParamSpaceSize = ARRAY_LEN(maxIterations)*ARRAY_LEN(branchingFactors);
vector<KMeansCostData> kmeansCosts(kmeansParamSpaceSize);
// CostData* kmeansCosts = new CostData[kmeansParamSpaceSize];
// evaluate kmeans for all parameter combinations
int cnt = 0;
for (size_t i=0; i<ARRAY_LEN(maxIterations); ++i) {
for (size_t j=0; j<ARRAY_LEN(branchingFactors); ++j) {
kmeansCosts[cnt].second.centers_init = CENTERS_RANDOM;
kmeansCosts[cnt].second.branching = branchingFactors[j];
kmeansCosts[cnt].second.iterations = maxIterations[j];
evaluate_kmeans(kmeansCosts[cnt].first, kmeansCosts[cnt].second);
int k = cnt;
// order by time cost
while (k>0 && kmeansCosts[k].first.timeCost < kmeansCosts[k-1].first.timeCost) {
swap(kmeansCosts[k],kmeansCosts[k-1]);
--k;
}
++cnt;
}
}
// logger.info("KMEANS, Step 2: simplex-downhill optimization\n");
//
// const int n = 2;
// // choose initial simplex points as the best parameters so far
// int kmeansNMPoints[n*(n+1)];
// float kmeansVals[n+1];
// for (int i=0;i<n+1;++i) {
// kmeansNMPoints[i*n] = (int)kmeansCosts[i].params["branching"];
// kmeansNMPoints[i*n+1] = (int)kmeansCosts[i].params["max-iterations"];
// kmeansVals[i] = kmeansCosts[i].timeCost;
// }
// KMeansSimpleDownhillFunctor kmeans_cost_func(*this);
// // run optimization
// optimizeSimplexDownhill(kmeansNMPoints,n,kmeans_cost_func,kmeansVals);
// // store results
// for (int i=0;i<n+1;++i) {
// kmeansCosts[i].params["branching"] = kmeansNMPoints[i*2];
// kmeansCosts[i].params["max-iterations"] = kmeansNMPoints[i*2+1];
// kmeansCosts[i].timeCost = kmeansVals[i];
// }
float optTimeCost = kmeansCosts[0].first.timeCost;
// recompute total costs factoring in the memory costs
for (int i=0;i<kmeansParamSpaceSize;++i) {
kmeansCosts[i].first.totalCost = (kmeansCosts[i].first.timeCost/optTimeCost + params.memory_weight * kmeansCosts[i].first.memoryCost);
int k = i;
while (k>0 && kmeansCosts[k].first.totalCost < kmeansCosts[k-1].first.totalCost) {
swap(kmeansCosts[k],kmeansCosts[k-1]);
k--;
}
}
// display the costs obtained
for (int i=0;i<kmeansParamSpaceSize;++i) {
logger.info("KMeans, branching=%d, iterations=%d, time_cost=%g[%g] (build=%g, search=%g), memory_cost=%g, cost=%g\n",
kmeansCosts[i].second.branching, kmeansCosts[i].second.iterations,
kmeansCosts[i].first.timeCost,kmeansCosts[i].first.timeCost/optTimeCost,
kmeansCosts[i].first.buildTimeCost, kmeansCosts[i].first.searchTimeCost,
kmeansCosts[i].first.memoryCost,kmeansCosts[i].first.totalCost);
}
return kmeansCosts[0];
}
KDTreeCostData optimizeKDTree()
{
logger.info("KD-TREE, Step 1: Exploring parameter space\n");
// explore kd-tree parameters space using the parameters below
int testTrees[] = { 1, 4, 8, 16, 32 };
size_t kdtreeParamSpaceSize = ARRAY_LEN(testTrees);
vector<KDTreeCostData> kdtreeCosts(kdtreeParamSpaceSize);
// evaluate kdtree for all parameter combinations
int cnt = 0;
for (size_t i=0; i<ARRAY_LEN(testTrees); ++i) {
kdtreeCosts[cnt].second.trees = testTrees[i];
evaluate_kdtree(kdtreeCosts[cnt].first, kdtreeCosts[cnt].second);
int k = cnt;
// order by time cost
while (k>0 && kdtreeCosts[k].first.timeCost < kdtreeCosts[k-1].first.timeCost) {
swap(kdtreeCosts[k],kdtreeCosts[k-1]);
--k;
}
++cnt;
}
// logger.info("KD-TREE, Step 2: simplex-downhill optimization\n");
//
// const int n = 1;
// // choose initial simplex points as the best parameters so far
// int kdtreeNMPoints[n*(n+1)];
// float kdtreeVals[n+1];
// for (int i=0;i<n+1;++i) {
// kdtreeNMPoints[i] = (int)kdtreeCosts[i].params["trees"];
// kdtreeVals[i] = kdtreeCosts[i].timeCost;
// }
// KDTreeSimpleDownhillFunctor kdtree_cost_func(*this);
// // run optimization
// optimizeSimplexDownhill(kdtreeNMPoints,n,kdtree_cost_func,kdtreeVals);
// // store results
// for (int i=0;i<n+1;++i) {
// kdtreeCosts[i].params["trees"] = kdtreeNMPoints[i];
// kdtreeCosts[i].timeCost = kdtreeVals[i];
// }
float optTimeCost = kdtreeCosts[0].first.timeCost;
// recompute costs for kd-tree factoring in memory cost
for (size_t i=0;i<kdtreeParamSpaceSize;++i) {
kdtreeCosts[i].first.totalCost = (kdtreeCosts[i].first.timeCost/optTimeCost + params.memory_weight * kdtreeCosts[i].first.memoryCost);
int k = i;
while (k>0 && kdtreeCosts[k].first.totalCost < kdtreeCosts[k-1].first.totalCost) {
swap(kdtreeCosts[k],kdtreeCosts[k-1]);
k--;
}
}
// display costs obtained
for (size_t i=0;i<kdtreeParamSpaceSize;++i) {
logger.info("kd-tree, trees=%d, time_cost=%g[%g] (build=%g, search=%g), memory_cost=%g, cost=%g\n",
kdtreeCosts[i].second.trees,kdtreeCosts[i].first.timeCost,kdtreeCosts[i].first.timeCost/optTimeCost,
kdtreeCosts[i].first.buildTimeCost, kdtreeCosts[i].first.searchTimeCost,
kdtreeCosts[i].first.memoryCost,kdtreeCosts[i].first.totalCost);
}
return kdtreeCosts[0];
}
/**
Chooses the best nearest-neighbor algorithm and estimates the optimal
parameters to use when building the index (for a given precision).
Returns a dictionary with the optimal parameters.
*/
IndexParams* estimateBuildParams()
{
int sampleSize = int(params.sample_fraction*dataset.rows);
int testSampleSize = min(sampleSize/10, 1000);
logger.info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d\n",dataset.rows, sampleSize, testSampleSize);
// For a very small dataset, it makes no sense to build any fancy index, just
// use linear search
if (testSampleSize<10) {
logger.info("Choosing linear, dataset too small\n");
return new LinearIndexParams();
}
// We use a fraction of the original dataset to speedup the autotune algorithm
sampledDataset = dataset.sample(sampleSize);
// We use a cross-validation approach, first we sample a testset from the dataset
testDataset = sampledDataset->sample(testSampleSize,true);
// We compute the ground truth using linear search
logger.info("Computing ground truth... \n");
gt_matches = new Matrix<int>(testDataset->rows, 1);
StartStopTimer t;
t.start();
compute_ground_truth(*sampledDataset, *testDataset, *gt_matches, 0);
t.stop();
float bestCost = (float)t.value;
IndexParams* bestParams = new LinearIndexParams();
// Start parameter autotune process
logger.info("Autotuning parameters...\n");
KMeansCostData kmeansCost = optimizeKMeans();
if (kmeansCost.first.totalCost<bestCost) {
bestParams = new KMeansIndexParams(kmeansCost.second);
bestCost = kmeansCost.first.totalCost;
}
KDTreeCostData kdtreeCost = optimizeKDTree();
if (kdtreeCost.first.totalCost<bestCost) {
bestParams = new KDTreeIndexParams(kdtreeCost.second);
bestCost = kdtreeCost.first.totalCost;
}
// free the memory used by the datasets we sampled
delete sampledDataset;
delete testDataset;
delete gt_matches;
return bestParams;
}
/**
Estimates the search time parameters needed to get the desired precision.
Precondition: the index is built
Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search.
*/
float estimateSearchParams(SearchParams& searchParams)
{
const int nn = 1;
const long SAMPLE_COUNT = 1000;
assert(bestIndex!=NULL); // must have a valid index
float speedup = 0;
int samples = min(dataset.rows/10, SAMPLE_COUNT);
if (samples>0) {
Matrix<float>* testDataset = dataset.sample(samples);
logger.info("Computing ground truth\n");
// we need to compute the ground truth first
Matrix<int> gt_matches(testDataset->rows,1);
StartStopTimer t;
t.start();
compute_ground_truth(dataset, *testDataset, gt_matches,1);
t.stop();
float linear = (float)t.value;
int checks;
logger.info("Estimating number of checks\n");
float searchTime;
float cb_index;
if (bestIndex->getType() == KMEANS) {
logger.info("KMeans algorithm, estimating cluster border factor\n");
KMeansIndex* kmeans = (KMeansIndex*)bestIndex;
float bestSearchTime = -1;
float best_cb_index = -1;
int best_checks = -1;
for (cb_index = 0;cb_index<1.1f; cb_index+=0.2f) {
kmeans->set_cb_index(cb_index);
searchTime = test_index_precision(*kmeans, dataset, *testDataset, gt_matches, params.target_precision, checks, nn, 1);
if (searchTime<bestSearchTime || bestSearchTime == -1) {
bestSearchTime = searchTime;
best_cb_index = cb_index;
best_checks = checks;
}
}
searchTime = bestSearchTime;
cb_index = best_cb_index;
checks = best_checks;
kmeans->set_cb_index(best_cb_index);
logger.info("Optimum cb_index: %g\n",cb_index);
((KMeansIndexParams*)bestParams)->cb_index = cb_index;
}
else {
searchTime = test_index_precision(*bestIndex, dataset, *testDataset, gt_matches, params.target_precision, checks, nn, 1);
}
logger.info("Required number of checks: %d \n",checks);;
searchParams.checks = checks;
delete testDataset;
speedup = linear/searchTime;
}
return speedup;
}
};
}
#endif /* AUTOTUNEDINDEX_H_ */

View File

@ -0,0 +1,128 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef COMPOSITETREE_H
#define COMPOSITETREE_H
#include "constants.h"
#include "nn_index.h"
namespace flann
{
class CompositeIndex : public NNIndex
{
KMeansIndex* kmeans;
KDTreeIndex* kdtree;
const Matrix<float> dataset;
public:
CompositeIndex(const Matrix<float>& inputData, const CompositeIndexParams& params = CompositeIndexParams() ) : dataset(inputData)
{
KDTreeIndexParams kdtree_params(params.trees);
KMeansIndexParams kmeans_params(params.branching, params.iterations, params.centers_init, params.cb_index);
kdtree = new KDTreeIndex(inputData,kdtree_params);
kmeans = new KMeansIndex(inputData,kmeans_params);
}
virtual ~CompositeIndex()
{
delete kdtree;
delete kmeans;
}
flann_algorithm_t getType() const
{
return COMPOSITE;
}
int size() const
{
return dataset.rows;
}
int veclen() const
{
return dataset.cols;
}
int usedMemory() const
{
return kmeans->usedMemory()+kdtree->usedMemory();
}
void buildIndex()
{
logger.info("Building kmeans tree...\n");
kmeans->buildIndex();
logger.info("Building kdtree tree...\n");
kdtree->buildIndex();
}
void saveIndex(FILE* /*stream*/)
{
}
void loadIndex(FILE* /*stream*/)
{
}
void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams)
{
kmeans->findNeighbors(result,vec,searchParams);
kdtree->findNeighbors(result,vec,searchParams);
}
// Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
// {
// Params params;
//
// return params;
// }
};
}
#endif //COMPOSITETREE_H

51
3rdparty/flann/algorithms/dist.cpp vendored Normal file
View File

@ -0,0 +1,51 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include "dist.h"
namespace flann
{
/** Global variable indicating the distance metric
* to be used.
*/
flann_distance_t flann_distance_type = EUCLIDEAN;
/**
* Zero iterator that emulates a zero feature.
*/
ZeroIterator<float> zero;
/**
* Order of Minkowski distance to use.
*/
int flann_minkowski_order;
}

211
3rdparty/flann/algorithms/dist.h vendored Normal file
View File

@ -0,0 +1,211 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef DIST_H
#define DIST_H
#include <cmath>
using namespace std;
#include "constants.h"
namespace flann
{
/**
* Distance function by default set to the custom distance
* function. This can be set to a specific distance function
* for further efficiency.
*/
#define flann_dist custom_dist
//#define flann_dist euclidean_dist
/**
* Compute the squared Euclidean distance between two vectors.
*
* This is highly optimised, with loop unrolling, as it is one
* of the most expensive inner loops.
*
* The computation of squared root at the end is omitted for
* efficiency.
*/
template <typename Iterator1, typename Iterator2>
double euclidean_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
{
double distsq = acc;
double diff0, diff1, diff2, diff3;
Iterator1 lastgroup = last1 - 3;
/* Process 4 items with each loop for efficiency. */
while (first1 < lastgroup) {
diff0 = first1[0] - first2[0];
diff1 = first1[1] - first2[1];
diff2 = first1[2] - first2[2];
diff3 = first1[3] - first2[3];
distsq += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
first1 += 4;
first2 += 4;
}
/* Process last 0-3 pixels. Not needed for standard vector lengths. */
while (first1 < last1) {
diff0 = *first1++ - *first2++;
distsq += diff0 * diff0;
}
return distsq;
}
/**
* Compute the Manhattan (L_1) distance between two vectors.
*
* This is highly optimised, with loop unrolling, as it is one
* of the most expensive inner loops.
*/
template <typename Iterator1, typename Iterator2>
double manhattan_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
{
double distsq = acc;
double diff0, diff1, diff2, diff3;
Iterator1 lastgroup = last1 - 3;
/* Process 4 items with each loop for efficiency. */
while (first1 < lastgroup) {
diff0 = fabs(first1[0] - first2[0]);
diff1 = fabs(first1[1] - first2[1]);
diff2 = fabs(first1[2] - first2[2]);
diff3 = fabs(first1[3] - first2[3]);
distsq += diff0 + diff1 + diff2 + diff3;
first1 += 4;
first2 += 4;
}
/* Process last 0-3 pixels. Not needed for standard vector lengths. */
while (first1 < last1) {
diff0 = fabs(*first1++ - *first2++);
distsq += diff0;
}
return distsq;
}
extern int flann_minkowski_order;
/**
* Compute the Minkowski (L_p) distance between two vectors.
*
* This is highly optimised, with loop unrolling, as it is one
* of the most expensive inner loops.
*
* The computation of squared root at the end is omitted for
* efficiency.
*/
template <typename Iterator1, typename Iterator2>
double minkowski_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
{
double distsq = acc;
double diff0, diff1, diff2, diff3;
Iterator1 lastgroup = last1 - 3;
int p = flann_minkowski_order;
/* Process 4 items with each loop for efficiency. */
while (first1 < lastgroup) {
diff0 = fabs(first1[0] - first2[0]);
diff1 = fabs(first1[1] - first2[1]);
diff2 = fabs(first1[2] - first2[2]);
diff3 = fabs(first1[3] - first2[3]);
distsq += pow(diff0,p) + pow(diff1,p) + pow(diff2,p) + pow(diff3,p);
first1 += 4;
first2 += 4;
}
/* Process last 0-3 pixels. Not needed for standard vector lengths. */
while (first1 < last1) {
diff0 = fabs(*first1++ - *first2++);
distsq += pow(diff0,p);
}
return distsq;
}
extern flann_distance_t flann_distance_type;
/**
* Custom distance function. The distance computed is dependent on the value
* of the 'flann_distance_type' global variable.
*
* If the last argument 'acc' is passed, the result is accumulated to the value
* of this argument.
*/
template <typename Iterator1, typename Iterator2>
float custom_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
{
switch (flann_distance_type) {
case EUCLIDEAN:
return (float)euclidean_dist(first1, last1, first2, acc);
case MANHATTAN:
return (float)manhattan_dist(first1, last1, first2, acc);
case MINKOWSKI:
return (float)minkowski_dist(first1, last1, first2, acc);
default:
return (float)euclidean_dist(first1, last1, first2, acc);
}
}
/*
* This is a "zero iterator". It basically behaves like a zero filled
* array to all algorithms that use arrays as iterators (STL style).
* It's useful when there's a need to compute the distance between feature
* and origin it and allows for better compiler optimisation than using a
* zero-filled array.
*/
template <typename T>
struct ZeroIterator {
T operator*() {
return 0;
}
T operator[](int /*index*/) {
return 0;
}
ZeroIterator<T>& operator ++(int) {
return *this;
}
ZeroIterator<T>& operator+=(int) {
return *this;
}
};
extern ZeroIterator<float> zero;
}
#endif //DIST_H

653
3rdparty/flann/algorithms/kdtree_index.h vendored Normal file
View File

@ -0,0 +1,653 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef KDTREE_H
#define KDTREE_H
#include <algorithm>
#include <map>
#include <cassert>
#include "heap.h"
#include "common.h"
#include "constants.h"
#include "allocator.h"
#include "matrix.h"
#include "result_set.h"
#include "random.h"
#include "nn_index.h"
#include "saving.h"
using namespace std;
namespace flann
{
/**
* Randomized kd-tree index
*
* Contains the k-d trees and other information for indexing a set of points
* for nearest-neighbor matching.
*/
class KDTreeIndex : public NNIndex
{
enum {
/**
* To improve efficiency, only SAMPLE_MEAN random values are used to
* compute the mean and variance at each level when building a tree.
* A value of 100 seems to perform as well as using all values.
*/
SAMPLE_MEAN = 100,
/**
* Top random dimensions to consider
*
* When creating random trees, the dimension on which to subdivide is
* selected at random from among the top RAND_DIM dimensions with the
* highest variance. A value of 5 works well.
*/
RAND_DIM=5
};
/**
* Number of randomized trees that are used
*/
int numTrees;
/**
* Array of indices to vectors in the dataset. When doing lookup,
* this is used instead to mark checkID.
*/
int* vind;
/**
* An unique ID for each lookup.
*/
int checkID;
/**
* The dataset used by this index
*/
const Matrix<float> dataset;
int size_;
int veclen_;
float* mean;
float* var;
/*--------------------- Internal Data Structures --------------------------*/
/**
* A node of the binary k-d tree.
*
* This is All nodes that have vec[divfeat] < divval are placed in the
* child1 subtree, else child2., A leaf node is indicated if both children are NULL.
*/
struct TreeSt {
/**
* Index of the vector feature used for subdivision.
* If this is a leaf node (both children are NULL) then
* this holds vector index for this leaf.
*/
int divfeat;
/**
* The value used for subdivision.
*/
float divval;
/**
* The child nodes.
*/
TreeSt *child1, *child2;
};
typedef TreeSt* Tree;
/**
* Array of k-d trees used to find neighbors.
*/
Tree* trees;
typedef BranchStruct<Tree> BranchSt;
typedef BranchSt* Branch;
/**
* Priority queue storing intermediate branches in the best-bin-first search
*/
Heap<BranchSt>* heap;
/**
* Pooled memory allocator.
*
* Using a pooled memory allocator is more efficient
* than allocating memory directly when there is a large
* number small of memory allocations.
*/
PooledAllocator pool;
public:
flann_algorithm_t getType() const
{
return KDTREE;
}
/**
* KDTree constructor
*
* Params:
* inputData = dataset with the input features
* params = parameters passed to the kdtree algorithm
*/
KDTreeIndex(const Matrix<float>& inputData, const KDTreeIndexParams& params = KDTreeIndexParams() ) : dataset(inputData)
{
size_ = dataset.rows;
veclen_ = dataset.cols;
numTrees = params.trees;
trees = new Tree[numTrees];
// get the parameters
// if (params.find("trees") != params.end()) {
// numTrees = (int)params["trees"];
// trees = new Tree[numTrees];
// }
// else {
// numTrees = -1;
// trees = NULL;
// }
heap = new Heap<BranchSt>(size_);
checkID = -1000;
// Create a permutable array of indices to the input vectors.
vind = new int[size_];
for (int i = 0; i < size_; i++) {
vind[i] = i;
}
mean = new float[veclen_];
var = new float[veclen_];
}
/**
* Standard destructor
*/
~KDTreeIndex()
{
delete[] vind;
if (trees!=NULL) {
delete[] trees;
}
delete heap;
delete[] mean;
delete[] var;
}
/**
* Builds the index
*/
void buildIndex()
{
/* Construct the randomized trees. */
for (int i = 0; i < numTrees; i++) {
/* Randomize the order of vectors to allow for unbiased sampling. */
for (int j = size_; j > 0; --j) {
// int rand = cast(int) (drand48() * size);
int rnd = rand_int(j);
assert(rnd >=0 && rnd < size_);
swap(vind[j-1], vind[rnd]);
}
trees[i] = NULL;
divideTree(&trees[i], 0, size_ - 1);
}
}
void saveIndex(FILE* stream)
{
save_header(stream, *this);
save_value(stream, numTrees);
for (int i=0;i<numTrees;++i) {
save_tree(stream, trees[i]);
}
}
void loadIndex(FILE* stream)
{
IndexHeader header = load_header(stream);
if (header.rows!=size() || header.cols!=veclen()) {
throw FLANNException("The index saved belongs to a different dataset");
}
load_value(stream, numTrees);
if (trees!=NULL) {
delete[] trees;
}
trees = new Tree[numTrees];
for (int i=0;i<numTrees;++i) {
load_tree(stream,trees[i]);
}
}
/**
* Returns size of index.
*/
int size() const
{
return size_;
}
/**
* Returns the length of an index feature.
*/
int veclen() const
{
return veclen_;
}
/**
* Computes the inde memory usage
* Returns: memory used by the index
*/
int usedMemory() const
{
return pool.usedMemory+pool.wastedMemory+dataset.rows*sizeof(int); // pool memory and vind array memory
}
/**
* Find set of nearest neighbors to vec. Their indices are stored inside
* the result object.
*
* Params:
* result = the result object in which the indices of the nearest-neighbors are stored
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams)
{
int maxChecks = searchParams.checks;
if (maxChecks<0) {
getExactNeighbors(result, vec);
} else {
getNeighbors(result, vec, maxChecks);
}
}
void continueSearch(ResultSet& result, float* vec, int maxCheck)
{
BranchSt branch;
int checkCount = 0;
/* Keep searching other branches from heap until finished. */
while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) {
searchLevel(result, vec, branch.node,branch.mindistsq, checkCount, maxCheck);
}
assert(result.full());
}
// Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
// {
// Params params;
//
// return params;
// }
private:
void save_tree(FILE* stream, Tree tree)
{
save_value(stream, *tree);
if (tree->child1!=NULL) {
save_tree(stream, tree->child1);
}
if (tree->child2!=NULL) {
save_tree(stream, tree->child2);
}
}
void load_tree(FILE* stream, Tree& tree)
{
tree = pool.allocate<TreeSt>();
load_value(stream, *tree);
if (tree->child1!=NULL) {
load_tree(stream, tree->child1);
}
if (tree->child2!=NULL) {
load_tree(stream, tree->child2);
}
}
/**
* Create a tree node that subdivides the list of vecs from vind[first]
* to vind[last]. The routine is called recursively on each sublist.
* Place a pointer to this new tree node in the location pTree.
*
* Params: pTree = the new node to create
* first = index of the first vector
* last = index of the last vector
*/
void divideTree(Tree* pTree, int first, int last)
{
Tree node;
node = pool.allocate<TreeSt>(); // allocate memory
*pTree = node;
/* If only one exemplar remains, then make this a leaf node. */
if (first == last) {
node->child1 = node->child2 = NULL; /* Mark as leaf node. */
node->divfeat = vind[first]; /* Store index of this vec. */
} else {
chooseDivision(node, first, last);
subdivide(node, first, last);
}
}
/**
* Choose which feature to use in order to subdivide this set of vectors.
* Make a random choice among those with the highest variance, and use
* its variance as the threshold value.
*/
void chooseDivision(Tree node, int first, int last)
{
memset(mean,0,veclen_*sizeof(float));
memset(var,0,veclen_*sizeof(float));
/* Compute mean values. Only the first SAMPLE_MEAN values need to be
sampled to get a good estimate.
*/
int end = min(first + SAMPLE_MEAN, last);
int count = end - first + 1;
for (int j = first; j <= end; ++j) {
float* v = dataset[vind[j]];
for (int k=0; k<veclen_; ++k) {
mean[k] += v[k];
}
}
for (int k=0; k<veclen_; ++k) {
mean[k] /= count;
}
/* Compute variances (no need to divide by count). */
for (int j = first; j <= end; ++j) {
float* v = dataset[vind[j]];
for (int k=0; k<veclen_; ++k) {
float dist = v[k] - mean[k];
var[k] += dist * dist;
}
}
/* Select one of the highest variance indices at random. */
node->divfeat = selectDivision(var);
node->divval = mean[node->divfeat];
}
/**
* Select the top RAND_DIM largest values from v and return the index of
* one of these selected at random.
*/
int selectDivision(float* v)
{
int num = 0;
int topind[RAND_DIM];
/* Create a list of the indices of the top RAND_DIM values. */
for (int i = 0; i < veclen_; ++i) {
if (num < RAND_DIM || v[i] > v[topind[num-1]]) {
/* Put this element at end of topind. */
if (num < RAND_DIM) {
topind[num++] = i; /* Add to list. */
}
else {
topind[num-1] = i; /* Replace last element. */
}
/* Bubble end value down to right location by repeated swapping. */
int j = num - 1;
while (j > 0 && v[topind[j]] > v[topind[j-1]]) {
swap(topind[j], topind[j-1]);
--j;
}
}
}
/* Select a random integer in range [0,num-1], and return that index. */
// int rand = cast(int) (drand48() * num);
int rnd = rand_int(num);
assert(rnd >=0 && rnd < num);
return topind[rnd];
}
/**
* Subdivide the list of exemplars using the feature and division
* value given in this node. Call divideTree recursively on each list.
*/
void subdivide(Tree node, int first, int last)
{
/* Move vector indices for left subtree to front of list. */
int i = first;
int j = last;
while (i <= j) {
int ind = vind[i];
float val = dataset[ind][node->divfeat];
if (val < node->divval) {
++i;
} else {
/* Move to end of list by swapping vind i and j. */
swap(vind[i], vind[j]);
--j;
}
}
/* If either list is empty, it means we have hit the unlikely case
in which all remaining features are identical. Split in the middle
to maintain a balanced tree.
*/
if ( (i == first) || (i == last+1)) {
i = (first+last+1)/2;
}
divideTree(& node->child1, first, i - 1);
divideTree(& node->child2, i, last);
}
/**
* Performs an exact nearest neighbor search. The exact search performs a full
* traversal of the tree.
*/
void getExactNeighbors(ResultSet& result, const float* vec)
{
checkID -= 1; /* Set a different unique ID for each search. */
if (numTrees > 1) {
fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search");
}
if (numTrees>0) {
searchLevelExact(result, vec, trees[0], 0.0);
}
assert(result.full());
}
/**
* Performs the approximate nearest-neighbor search. The search is approximate
* because the tree traversal is abandoned after a given number of descends in
* the tree.
*/
void getNeighbors(ResultSet& result, const float* vec, int maxCheck)
{
int i;
BranchSt branch;
int checkCount = 0;
heap->clear();
checkID -= 1; /* Set a different unique ID for each search. */
/* Search once through each tree down to root. */
for (i = 0; i < numTrees; ++i) {
searchLevel(result, vec, trees[i], 0.0, checkCount, maxCheck);
}
/* Keep searching other branches from heap until finished. */
while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) {
searchLevel(result, vec, branch.node,branch.mindistsq, checkCount, maxCheck);
}
assert(result.full());
}
/**
* Search starting from a given node of the tree. Based on any mismatches at
* higher levels, all exemplars below this level must have a distance of
* at least "mindistsq".
*/
void searchLevel(ResultSet& result, const float* vec, Tree node, float mindistsq, int& checkCount, int maxCheck)
{
if (result.worstDist()<mindistsq) {
// printf("Ignoring branch, too far\n");
return;
}
float val, diff;
Tree bestChild, otherChild;
/* If this is a leaf node, then do check and return. */
if (node->child1 == NULL && node->child2 == NULL) {
/* Do not check same node more than once when searching multiple trees.
Once a vector is checked, we set its location in vind to the
current checkID.
*/
if (vind[node->divfeat] == checkID || checkCount>=maxCheck) {
if (result.full()) return;
}
checkCount++;
vind[node->divfeat] = checkID;
result.addPoint(dataset[node->divfeat],node->divfeat);
return;
}
/* Which child branch should be taken first? */
val = vec[node->divfeat];
diff = val - node->divval;
bestChild = (diff < 0) ? node->child1 : node->child2;
otherChild = (diff < 0) ? node->child2 : node->child1;
/* Create a branch record for the branch not taken. Add distance
of this feature boundary (we don't attempt to correct for any
use of this feature in a parent node, which is unlikely to
happen and would have only a small effect). Don't bother
adding more branches to heap after halfway point, as cost of
adding exceeds their value.
*/
float new_distsq = flann_dist(&val, &val+1, &node->divval, mindistsq);
// if (2 * checkCount < maxCheck || !result.full()) {
if (new_distsq < result.worstDist() || !result.full()) {
heap->insert( BranchSt::make_branch(otherChild, new_distsq) );
}
/* Call recursively to search next level down. */
searchLevel(result, vec, bestChild, mindistsq, checkCount, maxCheck);
}
/**
* Performs an exact search in the tree starting from a node.
*/
void searchLevelExact(ResultSet& result, const float* vec, Tree node, float mindistsq)
{
if (mindistsq>result.worstDist()) {
return;
}
float val, diff;
Tree bestChild, otherChild;
/* If this is a leaf node, then do check and return. */
if (node->child1 == NULL && node->child2 == NULL) {
/* Do not check same node more than once when searching multiple trees.
Once a vector is checked, we set its location in vind to the
current checkID.
*/
if (vind[node->divfeat] == checkID)
return;
vind[node->divfeat] = checkID;
result.addPoint(dataset[node->divfeat],node->divfeat);
return;
}
/* Which child branch should be taken first? */
val = vec[node->divfeat];
diff = val - node->divval;
bestChild = (diff < 0) ? node->child1 : node->child2;
otherChild = (diff < 0) ? node->child2 : node->child1;
/* Call recursively to search next level down. */
searchLevelExact(result, vec, bestChild, mindistsq);
float new_distsq = flann_dist(&val, &val+1, &node->divval, mindistsq);
searchLevelExact(result, vec, otherChild, new_distsq);
}
}; // class KDTree
}
#endif //KDTREE_H

1119
3rdparty/flann/algorithms/kmeans_index.h vendored Normal file

File diff suppressed because it is too large Load Diff

105
3rdparty/flann/algorithms/linear_index.h vendored Normal file
View File

@ -0,0 +1,105 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef LINEARSEARCH_H
#define LINEARSEARCH_H
#include "constants.h"
#include "nn_index.h"
namespace flann
{
class LinearIndex : public NNIndex {
const Matrix<float> dataset;
public:
LinearIndex(const Matrix<float>& inputData, const LinearIndexParams& params = LinearIndexParams() ) : dataset(inputData)
{
}
flann_algorithm_t getType() const
{
return LINEAR;
}
int size() const
{
return dataset.rows;
}
int veclen() const
{
return dataset.cols;
}
int usedMemory() const
{
return 0;
}
void buildIndex()
{
/* nothing to do here for linear search */
}
void saveIndex(FILE* /*stream*/)
{
/* nothing to do here for linear search */
}
void loadIndex(FILE* /*stream*/)
{
/* nothing to do here for linear search */
}
void findNeighbors(ResultSet& resultSet, const float* /*vec*/, const SearchParams& /*searchParams*/)
{
for (int i=0;i<dataset.rows;++i) {
resultSet.addPoint(dataset[i],i);
}
}
// Params estimateSearchParams(float precision, Matrix<float>* testset = NULL)
// {
// Params params;
// return params;
// }
};
}
#endif // LINEARSEARCH_H

109
3rdparty/flann/algorithms/nn_index.h vendored Normal file
View File

@ -0,0 +1,109 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef NNINDEX_H
#define NNINDEX_H
#include "flann.hpp"
#include "constants.h"
#include "common.h"
#include "matrix.h"
#include <string>
#include <string.h>
using namespace std;
namespace flann
{
class ResultSet;
/**
* Nearest-neighbor index base class
*/
class NNIndex
{
public:
virtual ~NNIndex() {};
/**
Method responsible with building the index.
*/
virtual void buildIndex() = 0;
/**
Saves the index to a stream
*/
virtual void saveIndex(FILE* stream) = 0;
/**
Loads the index from a stream
*/
virtual void loadIndex(FILE* stream) = 0;
/**
Method that searches for nearest-neighbors
*/
virtual void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams) = 0;
/**
Number of features in this index.
*/
virtual int size() const = 0;
/**
The length of each vector in this index.
*/
virtual int veclen() const = 0;
/**
The amount of memory (in bytes) this index uses.
*/
virtual int usedMemory() const = 0;
/**
* Algorithm name
*/
virtual flann_algorithm_t getType() const = 0;
/**
Estimates the search parameters required in order to get a certain precision.
If testset is not given it uses cross-validation.
*/
// virtual Params estimateSearchParams(float precision, Matrix<float>* testset = NULL) = 0;
};
}
#endif //NNINDEX_H

68
3rdparty/flann/constants.h vendored Normal file
View File

@ -0,0 +1,68 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef CONSTANTS_H
#define CONSTANTS_H
const double FLANN_VERSION = 1.20;
/* Nearest neighbor index algorithms */
enum flann_algorithm_t {
LINEAR = 0,
KDTREE = 1,
KMEANS = 2,
COMPOSITE = 3,
SAVED = 254,
AUTOTUNED = 255,
};
enum flann_centers_init_t {
CENTERS_RANDOM = 0,
CENTERS_GONZALES = 1,
CENTERS_KMEANSPP = 2
};
enum flann_log_level_t {
LOG_NONE = 0,
LOG_FATAL = 1,
LOG_ERROR = 2,
LOG_WARN = 3,
LOG_INFO = 4
};
enum flann_distance_t {
EUCLIDEAN = 1,
MANHATTAN = 2,
MINKOWSKI = 3
};
#endif // CONSTANTS_H

476
3rdparty/flann/flann.cpp vendored Normal file
View File

@ -0,0 +1,476 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include <stdexcept>
#include <vector>
#include "flann.h"
#include "timer.h"
#include "common.h"
#include "logger.h"
#include "index_testing.h"
#include "saving.h"
#include "object_factory.h"
// index types
#include "kdtree_index.h"
#include "kmeans_index.h"
#include "composite_index.h"
#include "linear_index.h"
#include "autotuned_index.h"
#include <typeinfo>
using namespace std;
#include "flann.h"
#ifdef WIN32
#define EXPORTED extern "C" __declspec(dllexport)
#else
#define EXPORTED extern "C"
#endif
namespace flann
{
typedef ObjectFactory<IndexParams, flann_algorithm_t> ParamsFactory;
IndexParams* IndexParams::createFromParameters(const FLANNParameters& p)
{
IndexParams* params = ParamsFactory::instance().create(p.algorithm);
params->fromParameters(p);
return params;
}
NNIndex* LinearIndexParams::createIndex(const Matrix<float>& dataset) const
{
return new LinearIndex(dataset, *this);
}
NNIndex* KDTreeIndexParams::createIndex(const Matrix<float>& dataset) const
{
return new KDTreeIndex(dataset, *this);
}
NNIndex* KMeansIndexParams::createIndex(const Matrix<float>& dataset) const
{
return new KMeansIndex(dataset, *this);
}
NNIndex* CompositeIndexParams::createIndex(const Matrix<float>& dataset) const
{
return new CompositeIndex(dataset, *this);
}
NNIndex* AutotunedIndexParams::createIndex(const Matrix<float>& dataset) const
{
return new AutotunedIndex(dataset, *this);
}
NNIndex* SavedIndexParams::createIndex(const Matrix<float>& dataset) const
{
FILE* fin = fopen(filename.c_str(), "rb");
if (fin==NULL) {
return NULL;
}
IndexHeader header = load_header(fin);
rewind(fin);
IndexParams* params = ParamsFactory::instance().create(header.index_type);
NNIndex* nnIndex = params->createIndex(dataset);
nnIndex->loadIndex(fin);
fclose(fin);
delete params; //?
return nnIndex;
}
class StaticInit
{
public:
StaticInit()
{
ParamsFactory::instance().register_<LinearIndexParams>(LINEAR);
ParamsFactory::instance().register_<KDTreeIndexParams>(KDTREE);
ParamsFactory::instance().register_<KMeansIndexParams>(KMEANS);
ParamsFactory::instance().register_<CompositeIndexParams>(COMPOSITE);
ParamsFactory::instance().register_<AutotunedIndexParams>(AUTOTUNED);
ParamsFactory::instance().register_<SavedIndexParams>(SAVED);
}
};
StaticInit __init;
Index::Index(const Matrix<float>& dataset, const IndexParams& params)
{
nnIndex = params.createIndex(dataset);
nnIndex->buildIndex();
}
Index::~Index()
{
delete nnIndex;
}
void Index::knnSearch(const Matrix<float>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& searchParams)
{
assert(queries.cols==nnIndex->veclen());
assert(indices.rows>=queries.rows);
assert(dists.rows>=queries.rows);
assert(indices.cols>=knn);
assert(dists.cols>=knn);
search_for_neighbors(*nnIndex, queries, indices, dists, searchParams);
}
int Index::radiusSearch(const Matrix<float>& query, Matrix<int> indices, Matrix<float> dists, float radius, const SearchParams& searchParams)
{
if (query.rows!=1) {
printf("I can only search one feature at a time for range search\n");
return -1;
}
assert(query.cols==nnIndex->veclen());
RadiusResultSet resultSet(radius);
resultSet.init(query.data, query.cols);
nnIndex->findNeighbors(resultSet,query.data,searchParams);
// TODO: optimize here
int* neighbors = resultSet.getNeighbors();
float* distances = resultSet.getDistances();
int count_nn = min((long)resultSet.size(), indices.cols);
assert (dists.cols>=count_nn);
for (int i=0;i<count_nn;++i) {
indices[0][i] = neighbors[i];
dists[0][i] = distances[i];
}
return count_nn;
}
void Index::save(string filename)
{
FILE* fout = fopen(filename.c_str(), "wb");
if (fout==NULL) {
logger.error("Cannot open file: %s", filename.c_str());
throw FLANNException("Cannot open file");
}
nnIndex->saveIndex(fout);
fclose(fout);
}
int Index::size() const
{
return nnIndex->size();
}
int Index::veclen() const
{
return nnIndex->veclen();
}
int hierarchicalClustering(const Matrix<float>& features, Matrix<float>& centers, const KMeansIndexParams& params)
{
KMeansIndex kmeans(features, params);
kmeans.buildIndex();
int clusterNum = kmeans.getClusterCenters(centers);
return clusterNum;
}
} // namespace FLANN
using namespace flann;
typedef NNIndex* NNIndexPtr;
typedef Matrix<float>* MatrixPtr;
void init_flann_parameters(FLANNParameters* p)
{
if (p != NULL) {
flann_log_verbosity(p->log_level);
if (p->random_seed>0) {
seed_random(p->random_seed);
}
}
}
EXPORTED void flann_log_verbosity(int level)
{
if (level>=0) {
logger.setLevel(level);
}
}
EXPORTED void flann_set_distance_type(flann_distance_t distance_type, int order)
{
flann_distance_type = distance_type;
flann_minkowski_order = order;
}
EXPORTED flann_index_t flann_build_index(float* dataset, int rows, int cols, float* /*speedup*/, FLANNParameters* flann_params)
{
try {
init_flann_parameters(flann_params);
if (flann_params == NULL) {
throw FLANNException("The flann_params argument must be non-null");
}
IndexParams* params = IndexParams::createFromParameters(*flann_params);
Index* index = new Index(Matrix<float>(rows,cols,dataset), *params);
return index;
}
catch (runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return NULL;
}
}
EXPORTED int flann_save_index(flann_index_t index_ptr, char* filename)
{
try {
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
Index* index = (Index*)index_ptr;
index->save(filename);
return 0;
}
catch(runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
}
EXPORTED FLANN_INDEX flann_load_index(char* filename, float* dataset, int rows, int cols)
{
try {
Index* index = new Index(Matrix<float>(rows,cols,dataset), SavedIndexParams(filename));
return index;
}
catch(runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return NULL;
}
}
EXPORTED int flann_find_nearest_neighbors(float* dataset, int rows, int cols, float* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params)
{
int _result = 0;
try {
init_flann_parameters(flann_params);
IndexParams* params = IndexParams::createFromParameters(*flann_params);
Index* index = new Index(Matrix<float>(rows,cols,dataset), *params);
Matrix<int> m_indices(tcount, nn, result);
Matrix<float> m_dists(tcount, nn, dists);
index->knnSearch(Matrix<float>(tcount, index->veclen(), testset),
m_indices,
m_dists, nn, SearchParams(flann_params->checks) );
}
catch(runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
_result = -1;
}
return _result;
}
EXPORTED int flann_find_nearest_neighbors_index(flann_index_t index_ptr, float* testset, int tcount, int* result, float* dists, int nn, int checks, FLANNParameters* flann_params)
{
try {
init_flann_parameters(flann_params);
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
Index* index = (Index*) index_ptr;
Matrix<int> m_indices(tcount, nn, result);
Matrix<float> m_dists(tcount, nn, dists);
index->knnSearch(Matrix<float>(tcount, index->veclen(), testset),
m_indices,
m_dists, nn, SearchParams(checks) );
}
catch(runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
return -1;
}
EXPORTED int flann_radius_search(FLANN_INDEX index_ptr,
float* query,
int* indices,
float* dists,
int max_nn,
float radius,
int checks,
FLANNParameters* flann_params)
{
try {
init_flann_parameters(flann_params);
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
Index* index = (Index*) index_ptr;
Matrix<int> m_indices(1, max_nn, indices);
Matrix<float> m_dists(1, max_nn, dists);
int count = index->radiusSearch(Matrix<float>(1, index->veclen(), query),
m_indices,
m_dists, radius, SearchParams(checks) );
return count;
}
catch(runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
}
EXPORTED int flann_free_index(FLANN_INDEX index_ptr, FLANNParameters* flann_params)
{
try {
init_flann_parameters(flann_params);
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
Index* index = (Index*) index_ptr;
delete index;
return 0;
}
catch(runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
}
EXPORTED int flann_compute_cluster_centers(float* dataset, int rows, int cols, int clusters, float* result, FLANNParameters* flann_params)
{
try {
init_flann_parameters(flann_params);
MatrixPtr inputData = new Matrix<float>(rows,cols,dataset);
KMeansIndexParams params(flann_params->branching, flann_params->iterations, flann_params->centers_init, flann_params->cb_index);
Matrix<float> centers(clusters, cols, result);
int clusterNum = hierarchicalClustering(*inputData,centers, params);
return clusterNum;
} catch (runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
}
EXPORTED void compute_ground_truth_float(float* dataset, int dshape[], float* testset, int tshape[], int* match, int mshape[], int skip)
{
assert(dshape[1]==tshape[1]);
assert(tshape[0]==mshape[0]);
Matrix<int> _match(mshape[0], mshape[1], match);
compute_ground_truth(Matrix<float>(dshape[0], dshape[1], dataset), Matrix<float>(tshape[0], tshape[1], testset), _match, skip);
}
EXPORTED float test_with_precision(FLANN_INDEX index_ptr, float* dataset, int dshape[], float* testset, int tshape[], int* matches, int mshape[],
int nn, float precision, int* checks, int skip = 0)
{
assert(dshape[1]==tshape[1]);
assert(tshape[0]==mshape[0]);
try {
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
NNIndexPtr index = (NNIndexPtr)index_ptr;
return test_index_precision(*index, Matrix<float>(dshape[0], dshape[1],dataset), Matrix<float>(tshape[0], tshape[1], testset),
Matrix<int>(mshape[0],mshape[1],matches), precision, *checks, nn, skip);
} catch (runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
}
EXPORTED float test_with_checks(FLANN_INDEX index_ptr, float* dataset, int dshape[], float* testset, int tshape[], int* matches, int mshape[],
int nn, int checks, float* precision, int skip = 0)
{
assert(dshape[1]==tshape[1]);
assert(tshape[0]==mshape[0]);
try {
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
NNIndexPtr index = (NNIndexPtr)index_ptr;
return test_index_checks(*index, Matrix<float>(dshape[0], dshape[1],dataset), Matrix<float>(tshape[0], tshape[1], testset),
Matrix<int>(mshape[0],mshape[1],matches), checks, *precision, nn, skip);
} catch (runtime_error& e) {
logger.error("Caught exception: %s\n",e.what());
return -1;
}
}

278
3rdparty/flann/flann.h vendored Normal file
View File

@ -0,0 +1,278 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef FLANN_H
#define FLANN_H
#include "constants.h"
#ifdef WIN32
/* win32 dll export/import directives */
#ifdef flann_EXPORTS
#define LIBSPEC __declspec(dllexport)
#else
#define LIBSPEC __declspec(dllimport)
#endif
#else
/* unix needs nothing */
#define LIBSPEC
#endif
struct FLANNParameters {
flann_algorithm_t algorithm; // the algorithm to use (see constants.h)
int checks; // how many leafs (features) to check in one search
float cb_index; // cluster boundary index. Used when searching the kmeans tree
int trees; // number of randomized trees to use (for kdtree)
int branching; // branching factor (for kmeans tree)
int iterations; // max iterations to perform in one kmeans cluetering (kmeans tree)
flann_centers_init_t centers_init; // algorithm used for picking the initial cluetr centers for kmeans tree
float target_precision; // precision desired (used for autotuning, -1 otherwise)
float build_weight; // build tree time weighting factor
float memory_weight; // index memory weigthing factor
float sample_fraction; // what fraction of the dataset to use for autotuning
flann_log_level_t log_level; // determines the verbosity of each flann function
char* log_destination; // file where the output should go, NULL for the console
long random_seed; // random seed to use
};
typedef void* FLANN_INDEX; // deprecated
typedef void* flann_index_t;
#ifdef __cplusplus
extern "C" {
#endif
/**
Sets the log level used for all flann functions (unless
specified in FLANNParameters for each call
Params:
level = verbosity level (defined in constants.h)
*/
LIBSPEC void flann_log_verbosity(int level);
/**
* Sets the distance type to use throughout FLANN.
* If distance type specified is MINKOWSKI, the second argument
* specifies which order the minkowski distance should have.
*/
LIBSPEC void flann_set_distance_type(flann_distance_t distance_type, int order);
/**
Builds and returns an index. It uses autotuning if the target_precision field of index_params
is between 0 and 1, or the parameters specified if it's -1.
Params:
dataset = pointer to a data set stored in row major order
rows = number of rows (features) in the dataset
cols = number of columns in the dataset (feature dimensionality)
speedup = speedup over linear search, estimated if using autotuning, output parameter
index_params = index related parameters
flann_params = generic flann parameters
Returns: the newly created index or a number <0 for error
*/
LIBSPEC FLANN_INDEX flann_build_index(float* dataset,
int rows,
int cols,
float* speedup,
struct FLANNParameters* flann_params);
/**
* Saves the index to a file. Only the index is saved into the file, the dataset corresponding to the index is not saved.
*
* @param index_id The index that should be saved
* @param filename The filename the index should be saved to
* @return Returns 0 on success, negative value on error.
*/
LIBSPEC int flann_save_index(FLANN_INDEX index_id,
char* filename);
/**
* Loads an index from a file.
*
* @param filename File to load the index from.
* @param dataset The dataset corresponding to the index.
* @param rows Dataset tors
* @param cols Dataset columns
* @return
*/
LIBSPEC FLANN_INDEX flann_load_index(char* filename,
float* dataset,
int rows,
int cols);
/**
Builds an index and uses it to find nearest neighbors.
Params:
dataset = pointer to a data set stored in row major order
rows = number of rows (features) in the dataset
cols = number of columns in the dataset (feature dimensionality)
testset = pointer to a query set stored in row major order
trows = number of rows (features) in the query dataset (same dimensionality as features in the dataset)
indices = pointer to matrix for the indices of the nearest neighbors of the testset features in the dataset
(must have trows number of rows and nn number of columns)
nn = how many nearest neighbors to return
index_params = index related parameters
flann_params = generic flann parameters
Returns: zero or -1 for error
*/
LIBSPEC int flann_find_nearest_neighbors(float* dataset,
int rows,
int cols,
float* testset,
int trows,
int* indices,
float* dists,
int nn,
struct FLANNParameters* flann_params);
/**
Searches for nearest neighbors using the index provided
Params:
index_id = the index (constructed previously using flann_build_index).
testset = pointer to a query set stored in row major order
trows = number of rows (features) in the query dataset (same dimensionality as features in the dataset)
indices = pointer to matrix for the indices of the nearest neighbors of the testset features in the dataset
(must have trows number of rows and nn number of columns)
nn = how many nearest neighbors to return
checks = number of checks to perform before the search is stopped
flann_params = generic flann parameters
Returns: zero or a number <0 for error
*/
LIBSPEC int flann_find_nearest_neighbors_index(FLANN_INDEX index_id,
float* testset,
int trows,
int* indices,
float* dists,
int nn,
int checks,
struct FLANNParameters* flann_params);
/**
* Performs an radius search using an already constructed index.
*
* In case of radius search, instead of always returning a predetermined
* number of nearest neighbours (for example the 10 nearest neighbours), the
* search will return all the neighbours found within a search radius
* of the query point.
*
* The check parameter in the function below sets the level of approximation
* for the search by only visiting "checks" number of features in the index
* (the same way as for the KNN search). A lower value for checks will give
* a higher search speedup at the cost of potentially not returning all the
* neighbours in the specified radius.
*/
LIBSPEC int flann_radius_search(FLANN_INDEX index_ptr, /* the index */
float* query, /* query point */
int* indices, /* array for storing the indices found (will be modified) */
float* dists, /* similar, but for storing distances */
int max_nn, /* size of arrays indices and dists */
float radius, /* search radius (squared radius for euclidian metric) */
int checks, /* number of features to check, sets the level of approximation */
FLANNParameters* flann_params);
/**
Deletes an index and releases the memory used by it.
Params:
index_id = the index (constructed previously using flann_build_index).
flann_params = generic flann parameters
Returns: zero or a number <0 for error
*/
LIBSPEC int flann_free_index(FLANN_INDEX index_id,
struct FLANNParameters* flann_params);
/**
Clusters the features in the dataset using a hierarchical kmeans clustering approach.
This is significantly faster than using a flat kmeans clustering for a large number
of clusters.
Params:
dataset = pointer to a data set stored in row major order
rows = number of rows (features) in the dataset
cols = number of columns in the dataset (feature dimensionality)
clusters = number of cluster to compute
result = memory buffer where the output cluster centers are storred
index_params = used to specify the kmeans tree parameters (branching factor, max number of iterations to use)
flann_params = generic flann parameters
Returns: number of clusters computed or a number <0 for error. This number can be different than the number of clusters requested, due to the
way hierarchical clusters are computed. The number of clusters returned will be the highest number of the form
(branch_size-1)*K+1 smaller than the number of clusters requested.
*/
LIBSPEC int flann_compute_cluster_centers(float* dataset,
int rows,
int cols,
int clusters,
float* result,
struct FLANNParameters* flann_params);
#ifdef __cplusplus
};
#include "flann.hpp"
#endif
#endif /*FLANN_H*/

247
3rdparty/flann/flann.hpp vendored Normal file
View File

@ -0,0 +1,247 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef FLANN_HPP_
#define FLANN_HPP_
#include <vector>
#include <string>
#include "constants.h"
#include "common.h"
#include "matrix.h"
#include "flann.h"
namespace flann
{
class NNIndex;
class IndexFactory
{
public:
virtual ~IndexFactory() {}
virtual NNIndex* createIndex(const Matrix<float>& dataset) const = 0;
};
struct IndexParams : public IndexFactory {
protected:
IndexParams() {};
public:
static IndexParams* createFromParameters(const FLANNParameters& p);
virtual void fromParameters(const FLANNParameters&) {};
virtual void toParameters(FLANNParameters&) { };
};
struct LinearIndexParams : public IndexParams {
LinearIndexParams() {};
NNIndex* createIndex(const Matrix<float>& dataset) const;
};
struct KDTreeIndexParams : public IndexParams {
KDTreeIndexParams(int trees_ = 4) : trees(trees_) {};
int trees; // number of randomized trees to use (for kdtree)
NNIndex* createIndex(const Matrix<float>& dataset) const;
void fromParameters(const FLANNParameters& p)
{
trees = p.trees;
}
void toParameters(FLANNParameters& p)
{
p.algorithm = KDTREE;
p.trees = trees;
};
};
struct KMeansIndexParams : public IndexParams {
KMeansIndexParams(int branching_ = 32, int iterations_ = 11,
flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
branching(branching_),
iterations(iterations_),
centers_init(centers_init_),
cb_index(cb_index_) {};
int branching; // branching factor (for kmeans tree)
int iterations; // max iterations to perform in one kmeans clustering (kmeans tree)
flann_centers_init_t centers_init; // algorithm used for picking the initial cluster centers for kmeans tree
float cb_index; // cluster boundary index. Used when searching the kmeans tree
NNIndex* createIndex(const Matrix<float>& dataset) const;
void fromParameters(const FLANNParameters& p)
{
branching = p.branching;
iterations = p.iterations;
centers_init = p.centers_init;
cb_index = p.cb_index;
}
void toParameters(FLANNParameters& p)
{
p.algorithm = KMEANS;
p.branching = branching;
p.iterations = iterations;
p.centers_init = centers_init;
p.cb_index = cb_index;
};
};
struct CompositeIndexParams : public IndexParams {
CompositeIndexParams(int trees_ = 4, int branching_ = 32, int iterations_ = 11,
flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
trees(trees_),
branching(branching_),
iterations(iterations_),
centers_init(centers_init_),
cb_index(cb_index_) {};
int trees; // number of randomized trees to use (for kdtree)
int branching; // branching factor (for kmeans tree)
int iterations; // max iterations to perform in one kmeans clustering (kmeans tree)
flann_centers_init_t centers_init; // algorithm used for picking the initial cluster centers for kmeans tree
float cb_index; // cluster boundary index. Used when searching the kmeans tree
NNIndex* createIndex(const Matrix<float>& dataset) const;
void fromParameters(const FLANNParameters& p)
{
trees = p.trees;
branching = p.branching;
iterations = p.iterations;
centers_init = p.centers_init;
cb_index = p.cb_index;
}
void toParameters(FLANNParameters& p)
{
p.algorithm = COMPOSITE;
p.trees = trees;
p.branching = branching;
p.iterations = iterations;
p.centers_init = centers_init;
p.cb_index = cb_index;
};
};
struct AutotunedIndexParams : public IndexParams {
AutotunedIndexParams( float target_precision_ = 0.9, float build_weight_ = 0.01,
float memory_weight_ = 0, float sample_fraction_ = 0.1) :
target_precision(target_precision_),
build_weight(build_weight_),
memory_weight(memory_weight_),
sample_fraction(sample_fraction_) {};
float target_precision; // precision desired (used for autotuning, -1 otherwise)
float build_weight; // build tree time weighting factor
float memory_weight; // index memory weighting factor
float sample_fraction; // what fraction of the dataset to use for autotuning
NNIndex* createIndex(const Matrix<float>& dataset) const;
void fromParameters(const FLANNParameters& p)
{
target_precision = p.target_precision;
build_weight = p.build_weight;
memory_weight = p.memory_weight;
sample_fraction = p.sample_fraction;
}
void toParameters(FLANNParameters& p)
{
p.algorithm = AUTOTUNED;
p.target_precision = target_precision;
p.build_weight = build_weight;
p.memory_weight = memory_weight;
p.sample_fraction = sample_fraction;
};
};
struct SavedIndexParams : public IndexParams {
SavedIndexParams() {
throw FLANNException("I don't know which index to load");
}
SavedIndexParams(std::string filename_) : filename(filename_) {}
std::string filename; // filename of the stored index
NNIndex* createIndex(const Matrix<float>& dataset) const;
};
struct SearchParams {
SearchParams(int checks_ = 32) :
checks(checks_) {};
int checks;
};
class Index {
NNIndex* nnIndex;
public:
Index(const Matrix<float>& features, const IndexParams& params);
~Index();
void knnSearch(const Matrix<float>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& params);
int radiusSearch(const Matrix<float>& query, Matrix<int> indices, Matrix<float> dists, float radius, const SearchParams& params);
void save(std::string filename);
int veclen() const;
int size() const;
};
int hierarchicalClustering(const Matrix<float>& features, Matrix<float>& centers, const KMeansIndexParams& params);
}
#endif /* FLANN_HPP_ */

95
3rdparty/flann/nn/ground_truth.h vendored Normal file
View File

@ -0,0 +1,95 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef GROUND_TRUTH_H
#define GROUND_TRUTH_H
#include "matrix.h"
#include "dist.h"
namespace flann
{
template <typename T>
void find_nearest(const Matrix<T>& dataset, T* query, int* matches, int nn, int skip = 0)
{
int n = nn + skip;
T* query_end = query + dataset.cols;
long* match = new long[n];
T* dists = new T[n];
dists[0] = flann_dist(query, query_end, dataset[0]);
match[0] = 0;
int dcnt = 1;
for (int i=1;i<dataset.rows;++i) {
T tmp = flann_dist(query, query_end, dataset[i]);
if (dcnt<n) {
match[dcnt] = i;
dists[dcnt++] = tmp;
}
else if (tmp < dists[dcnt-1]) {
dists[dcnt-1] = tmp;
match[dcnt-1] = i;
}
int j = dcnt-1;
// bubble up
while (j>=1 && dists[j]<dists[j-1]) {
swap(dists[j],dists[j-1]);
swap(match[j],match[j-1]);
j--;
}
}
for (int i=0;i<nn;++i) {
matches[i] = match[i+skip];
}
delete[] match;
delete[] dists;
}
template <typename T>
void compute_ground_truth(const Matrix<T>& dataset, const Matrix<T>& testset, Matrix<int>& matches, int skip=0)
{
for (int i=0;i<testset.rows;++i) {
find_nearest(dataset, testset[i], matches[i], matches.cols, skip);
}
}
}
#endif //GROUND_TRUTH_H

314
3rdparty/flann/nn/index_testing.cpp vendored Normal file
View File

@ -0,0 +1,314 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include "index_testing.h"
#include "result_set.h"
#include "timer.h"
#include "logger.h"
#include "dist.h"
#include "common.h"
#include <algorithm>
#include <math.h>
#include <string.h>
#include <stdlib.h>
namespace flann
{
const float SEARCH_EPS = 0.001f;
int countCorrectMatches(int* neighbors, int* groundTruth, int n)
{
int count = 0;
for (int i=0;i<n;++i) {
for (int k=0;k<n;++k) {
if (neighbors[i]==groundTruth[k]) {
count++;
break;
}
}
}
return count;
}
float computeDistanceRaport(const Matrix<float>& inputData, float* target, int* neighbors, int* groundTruth, int veclen, int n)
{
float* target_end = target + veclen;
float ret = 0;
for (int i=0;i<n;++i) {
float den = (float)flann_dist(target,target_end, inputData[groundTruth[i]]);
float num = (float)flann_dist(target,target_end, inputData[neighbors[i]]);
// printf("den=%g,num=%g\n",den,num);
if (den==0 && num==0) {
ret += 1;
} else {
ret += num/den;
}
}
return ret;
}
float search_with_ground_truth(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches, int nn, int checks, float& time, float& dist, int skipMatches)
{
if (matches.cols<nn) {
logger.info("matches.cols=%d, nn=%d\n",matches.cols,nn);
throw FLANNException("Ground truth is not computed for as many neighbors as requested");
}
KNNResultSet resultSet(nn+skipMatches);
SearchParams searchParams(checks);
int correct = 0;
float distR = 0;
StartStopTimer t;
int repeats = 0;
while (t.value<0.2) {
repeats++;
t.start();
correct = 0;
distR = 0;
for (int i = 0; i < testData.rows; i++) {
float* target = testData[i];
resultSet.init(target, testData.cols);
index.findNeighbors(resultSet,target, searchParams);
int* neighbors = resultSet.getNeighbors();
neighbors = neighbors+skipMatches;
correct += countCorrectMatches(neighbors,matches[i], nn);
distR += computeDistanceRaport(inputData, target,neighbors,matches[i], testData.cols, nn);
}
t.stop();
}
time = (float)(t.value/repeats);
float precicion = (float)correct/(nn*testData.rows);
dist = distR/(testData.rows*nn);
logger.info("%8d %10.4g %10.5g %10.5g %10.5g\n",
checks, precicion, time, 1000.0 * time / testData.rows, dist);
return precicion;
}
void search_for_neighbors(NNIndex& index, const Matrix<float>& testset, Matrix<int>& result, Matrix<float>& dists, const SearchParams& searchParams, int skip)
{
assert(testset.rows == result.rows);
int nn = result.cols;
KNNResultSet resultSet(nn+skip);
for (int i = 0; i < testset.rows; i++) {
float* target = testset[i];
resultSet.init(target, testset.cols);
index.findNeighbors(resultSet,target, searchParams);
int* neighbors = resultSet.getNeighbors();
float* distances = resultSet.getDistances();
memcpy(result[i], neighbors+skip, nn*sizeof(int));
memcpy(dists[i], distances+skip, nn*sizeof(float));
}
}
float test_index_checks(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches, int checks, float& precision, int nn, int skipMatches)
{
logger.info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n");
logger.info("---------------------------------------------------------\n");
float time = 0;
float dist = 0;
precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, skipMatches);
return time;
}
float test_index_precision(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
float precision, int& checks, int nn, int skipMatches)
{
logger.info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n");
logger.info("---------------------------------------------------------\n");
int c2 = 1;
float p2;
int c1 = 1;
float p1;
float time;
float dist;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, skipMatches);
if (p2>precision) {
logger.info("Got as close as I can\n");
checks = c2;
return time;
}
while (p2<precision) {
c1 = c2;
p1 = p2;
c2 *=2;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, skipMatches);
}
int cx;
float realPrecision;
if (fabs(p2-precision)>SEARCH_EPS) {
logger.info("Start linear estimation\n");
// after we got to values in the vecinity of the desired precision
// use linear approximation get a better estimation
cx = (c1+c2)/2;
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, skipMatches);
while (fabs(realPrecision-precision)>SEARCH_EPS) {
if (realPrecision<precision) {
c1 = cx;
}
else {
c2 = cx;
}
cx = (c1+c2)/2;
if (cx==c1) {
logger.info("Got as close as I can\n");
break;
}
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, skipMatches);
}
c2 = cx;
p2 = realPrecision;
} else {
logger.info("No need for linear estimation\n");
cx = c2;
realPrecision = p2;
}
checks = cx;
return time;
}
float test_index_precisions(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
float* precisions, int precisions_length, int nn, int skipMatches, float maxTime)
{
// make sure precisions array is sorted
sort(precisions, precisions+precisions_length);
int pindex = 0;
float precision = precisions[pindex];
logger.info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist");
logger.info("---------------------------------------------------------");
int c2 = 1;
float p2;
int c1 = 1;
float p1;
float time;
float dist;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, skipMatches);
// if precision for 1 run down the tree is already
// better then some of the requested precisions, then
// skip those
while (precisions[pindex]<p2 && pindex<precisions_length) {
pindex++;
}
if (pindex==precisions_length) {
logger.info("Got as close as I can\n");
return time;
}
for (int i=pindex;i<precisions_length;++i) {
precision = precisions[i];
while (p2<precision) {
c1 = c2;
p1 = p2;
c2 *=2;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, skipMatches);
if (maxTime> 0 && time > maxTime && p2<precision) return time;
}
int cx;
float realPrecision;
if (fabs(p2-precision)>SEARCH_EPS) {
logger.info("Start linear estimation\n");
// after we got to values in the vecinity of the desired precision
// use linear approximation get a better estimation
cx = (c1+c2)/2;
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, skipMatches);
while (fabs(realPrecision-precision)>SEARCH_EPS) {
if (realPrecision<precision) {
c1 = cx;
}
else {
c2 = cx;
}
cx = (c1+c2)/2;
if (cx==c1) {
logger.info("Got as close as I can\n");
break;
}
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, skipMatches);
}
c2 = cx;
p2 = realPrecision;
} else {
logger.info("No need for linear estimation\n");
cx = c2;
realPrecision = p2;
}
}
return time;
}
}

57
3rdparty/flann/nn/index_testing.h vendored Normal file
View File

@ -0,0 +1,57 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef TESTING_H
#define TESTING_H
#include "nn_index.h"
#include "matrix.h"
using namespace std;
namespace flann
{
void search_for_neighbors(NNIndex& index, const Matrix<float>& testset, Matrix<int>& result, Matrix<float>& dists, const SearchParams &searchParams, int skip = 0);
float test_index_checks(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
int checks, float& precision, int nn = 1, int skipMatches = 0);
float test_index_precision(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
float precision, int& checks, int nn = 1, int skipMatches = 0);
float test_index_precisions(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
float* precisions, int precisions_length, int nn = 1, int skipMatches = 0, float maxTime = 0);
}
#endif //TESTING_H

186
3rdparty/flann/nn/simplex_downhill.h vendored Normal file
View File

@ -0,0 +1,186 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef SIMPLEX_DOWNHILL_H
#define SIMPLEX_DOWNHILL_H
namespace flann
{
/**
Adds val to array vals (and point to array points) and keeping the arrays sorted by vals.
*/
template <typename T>
void addValue(int pos, float val, float* vals, T* point, T* points, int n)
{
vals[pos] = val;
for (int i=0;i<n;++i) {
points[pos*n+i] = point[i];
}
// bubble down
int j=pos;
while (j>0 && vals[j]<vals[j-1]) {
swap(vals[j],vals[j-1]);
for (int i=0;i<n;++i) {
swap(points[j*n+i],points[(j-1)*n+i]);
}
--j;
}
}
/**
Simplex downhill optimization function.
Preconditions: points is a 2D mattrix of size (n+1) x n
func is the cost function taking n an array of n params and returning float
vals is the cost function in the n+1 simplex points, if NULL it will be computed
Postcondition: returns optimum value and points[0..n] are the optimum parameters
*/
template <typename T, typename F>
float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL )
{
const int MAX_ITERATIONS = 10;
assert(n>0);
T* p_o = new T[n];
T* p_r = new T[n];
T* p_e = new T[n];
int alpha = 1;
int iterations = 0;
bool ownVals = false;
if (vals == NULL) {
ownVals = true;
vals = new float[n+1];
for (int i=0;i<n+1;++i) {
float val = func(points+i*n);
addValue(i, val, vals, points+i*n, points, n);
}
}
int nn = n*n;
while (true) {
if (iterations++ > MAX_ITERATIONS) break;
// compute average of simplex points (except the highest point)
for (int j=0;j<n;++j) {
p_o[j] = 0;
for (int i=0;i<n;++i) {
p_o[i] += points[j*n+i];
}
}
for (int i=0;i<n;++i) {
p_o[i] /= n;
}
bool converged = true;
for (int i=0;i<n;++i) {
if (p_o[i] != points[nn+i]) {
converged = false;
}
}
if (converged) break;
// trying a reflection
for (int i=0;i<n;++i) {
p_r[i] = p_o[i] + alpha*(p_o[i]-points[nn+i]);
}
float val_r = func(p_r);
if (val_r>=vals[0] && val_r<vals[n]) {
// reflection between second highest and lowest
// add it to the simplex
logger.info("Choosing reflection\n");
addValue(n, val_r,vals, p_r, points, n);
continue;
}
if (val_r<vals[0]) {
// value is smaller than smalest in simplex
// expand some more to see if it drops further
for (int i=0;i<n;++i) {
p_e[i] = 2*p_r[i]-p_o[i];
}
float val_e = func(p_e);
if (val_e<val_r) {
logger.info("Choosing reflection and expansion\n");
addValue(n, val_e,vals,p_e,points,n);
}
else {
logger.info("Choosing reflection\n");
addValue(n, val_r,vals,p_r,points,n);
}
continue;
}
if (val_r>=vals[n]) {
for (int i=0;i<n;++i) {
p_e[i] = (p_o[i]+points[nn+i])/2;
}
float val_e = func(p_e);
if (val_e<vals[n]) {
logger.info("Choosing contraction\n");
addValue(n,val_e,vals,p_e,points,n);
continue;
}
}
{
logger.info("Full contraction\n");
for (int j=1;j<=n;++j) {
for (int i=0;i<n;++i) {
points[j*n+i] = (points[j*n+i]+points[i])/2;
}
float val = func(points+j*n);
addValue(j,val,vals,points+j*n,points,n);
}
}
}
float bestVal = vals[0];
delete[] p_r;
delete[] p_o;
delete[] p_e;
if (ownVals) delete[] vals;
return bestVal;
}
}
#endif //SIMPLEX_DOWNHILL_H

188
3rdparty/flann/util/allocator.h vendored Normal file
View File

@ -0,0 +1,188 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef ALLOCATOR_H
#define ALLOCATOR_H
#include <stdlib.h>
#include <stdio.h>
namespace flann
{
/**
* Allocates (using C's malloc) a generic type T.
*
* Params:
* count = number of instances to allocate.
* Returns: pointer (of type T*) to memory buffer
*/
template <typename T>
T* allocate(size_t count = 1)
{
T* mem = (T*) ::malloc(sizeof(T)*count);
return mem;
}
/**
* Pooled storage allocator
*
* The following routines allow for the efficient allocation of storage in
* small chunks from a specified pool. Rather than allowing each structure
* to be freed individually, an entire pool of storage is freed at once.
* This method has two advantages over just using malloc() and free(). First,
* it is far more efficient for allocating small objects, as there is
* no overhead for remembering all the information needed to free each
* object or consolidating fragmented memory. Second, the decision about
* how long to keep an object is made at the time of allocation, and there
* is no need to track down all the objects to free them.
*
*/
const size_t WORDSIZE=16;
const size_t BLOCKSIZE=8192;
class PooledAllocator
{
/* We maintain memory alignment to word boundaries by requiring that all
allocations be in multiples of the machine wordsize. */
/* Size of machine word in bytes. Must be power of 2. */
/* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */
int remaining; /* Number of bytes left in current block of storage. */
void* base; /* Pointer to base of current block of storage. */
void* loc; /* Current location in block to next allocate memory. */
int blocksize;
public:
int usedMemory;
int wastedMemory;
/**
Default constructor. Initializes a new pool.
*/
PooledAllocator(int blocksize = BLOCKSIZE)
{
this->blocksize = blocksize;
remaining = 0;
base = NULL;
usedMemory = 0;
wastedMemory = 0;
}
/**
* Destructor. Frees all the memory allocated in this pool.
*/
~PooledAllocator()
{
void *prev;
while (base != NULL) {
prev = *((void **) base); /* Get pointer to prev block. */
::free(base);
base = prev;
}
}
/**
* Returns a pointer to a piece of new memory of the given size in bytes
* allocated from the pool.
*/
void* malloc(int size)
{
int blocksize;
/* Round size up to a multiple of wordsize. The following expression
only works for WORDSIZE that is a power of 2, by masking last bits of
incremented size to zero.
*/
size = (size + (WORDSIZE - 1)) & ~(WORDSIZE - 1);
/* Check whether a new block must be allocated. Note that the first word
of a block is reserved for a pointer to the previous block.
*/
if (size > remaining) {
wastedMemory += remaining;
/* Allocate new storage. */
blocksize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ?
size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE;
// use the standard C malloc to allocate memory
void* m = ::malloc(blocksize);
if (!m) {
fprintf(stderr,"Failed to allocate memory.");
exit(1);
}
/* Fill first word of new block with pointer to previous block. */
((void **) m)[0] = base;
base = m;
int shift = 0;
//int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1);
remaining = blocksize - sizeof(void*) - shift;
loc = ((char*)m + sizeof(void*) + shift);
}
void* rloc = loc;
loc = (char*)loc + size;
remaining -= size;
usedMemory += size;
return rloc;
}
/**
* Allocates (using this pool) a generic type T.
*
* Params:
* count = number of instances to allocate.
* Returns: pointer (of type T*) to memory buffer
*/
template <typename T>
T* allocate(size_t count = 1)
{
T* mem = (T*) this->malloc(sizeof(T)*count);
return mem;
}
};
}
#endif //ALLOCATOR_H

48
3rdparty/flann/util/common.h vendored Normal file
View File

@ -0,0 +1,48 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef COMMOM_H
#define COMMOM_H
#define ARRAY_LEN(a) (sizeof(a)/sizeof(a[0]))
#include <stdexcept>
namespace flann
{
class FLANNException : public std::runtime_error {
public:
FLANNException(const char* message) : std::runtime_error(message) { }
};
}
#endif //COMMOM_H

209
3rdparty/flann/util/heap.h vendored Normal file
View File

@ -0,0 +1,209 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef HEAP_H
#define HEAP_H
#include <algorithm>
using namespace std;
namespace flann
{
/**
* Priority Queue Implementation
*
* The priority queue is implemented with a heap. A heap is a complete
* (full) binary tree in which each parent is less than both of its
* children, but the order of the children is unspecified.
* Note that a heap uses 1-based indexing to allow for power-of-2
* location of parents and children. We ignore element 0 of Heap array.
*/
template <typename T>
class Heap {
/**
* Storage array for the heap.
* Type T must be comparable.
*/
T* heap;
int length;
/**
* Number of element in the heap
*/
int count;
public:
/**
* Constructor.
*
* Params:
* size = heap size
*/
Heap(int size)
{
length = size+1;
heap = new T[length]; // heap uses 1-based indexing
count = 0;
}
/**
* Destructor.
*
*/
~Heap()
{
delete[] heap;
}
/**
*
* Returns: heap size
*/
int size()
{
return count;
}
/**
* Tests if the heap is empty
*
* Returns: true is heap empty, false otherwise
*/
bool empty()
{
return size()==0;
}
/**
* Clears the heap.
*/
void clear()
{
count = 0;
}
/**
* Insert a new element in the heap.
*
* We select the next empty leaf node, and then keep moving any larger
* parents down until the right location is found to store this element.
*
* Params:
* value = the new element to be inserted in the heap
*/
void insert(T value)
{
/* If heap is full, then return without adding this element. */
if (count == length-1) {
return;
}
int loc = ++(count); /* Remember 1-based indexing. */
/* Keep moving parents down until a place is found for this node. */
int par = loc / 2; /* Location of parent. */
while (par > 0 && value < heap[par]) {
heap[loc] = heap[par]; /* Move parent down to loc. */
loc = par;
par = loc / 2;
}
/* Insert the element at the determined location. */
heap[loc] = value;
}
/**
* Returns the node of minimum value from the heap (top of the heap).
*
* Params:
* value = out parameter used to return the min element
* Returns: false if heap empty
*/
bool popMin(T& value)
{
if (count == 0) {
return false;
}
/* Switch first node with last. */
swap(heap[1],heap[count]);
count -= 1;
heapify(1); /* Move new node 1 to right position. */
value = heap[count + 1];
return true; /* Return old last node. */
}
/**
* Reorganizes the heap (a parent is smaller than its children)
* starting with a node.
*
* Params:
* parent = node form which to start heap reorganization.
*/
void heapify(int parent)
{
int minloc = parent;
/* Check the left child */
int left = 2 * parent;
if (left <= count && heap[left] < heap[parent]) {
minloc = left;
}
/* Check the right child */
int right = left + 1;
if (right <= count && heap[right] < heap[minloc]) {
minloc = right;
}
/* If a child was smaller, than swap parent with it and Heapify. */
if (minloc != parent) {
swap(heap[parent],heap[minloc]);
heapify(minloc);
}
}
};
}
#endif //HEAP_H

85
3rdparty/flann/util/logger.cpp vendored Normal file
View File

@ -0,0 +1,85 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include "logger.h"
#include <cstdio>
#include <cstdarg>
#include <sstream>
using namespace std;
namespace flann
{
Logger logger;
int Logger::log(int level, const char* fmt, ...)
{
if (level > logLevel ) return -1;
int ret;
va_list arglist;
va_start(arglist, fmt);
ret = vfprintf(stream, fmt, arglist);
va_end(arglist);
return ret;
}
int Logger::log(int level, const char* fmt, va_list arglist)
{
if (level > logLevel ) return -1;
int ret;
ret = vfprintf(stream, fmt, arglist);
return ret;
}
#define LOG_METHOD(NAME,LEVEL) \
int Logger::NAME(const char* fmt, ...) \
{ \
int ret; \
va_list ap; \
va_start(ap, fmt); \
ret = log(LEVEL, fmt, ap); \
va_end(ap); \
return ret; \
}
LOG_METHOD(fatal, LOG_FATAL)
LOG_METHOD(error, LOG_ERROR)
LOG_METHOD(warn, LOG_WARN)
LOG_METHOD(info, LOG_INFO)
}

93
3rdparty/flann/util/logger.h vendored Normal file
View File

@ -0,0 +1,93 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef LOGGER_H
#define LOGGER_H
#include <cstdio>
#include <stdarg.h>
#include "common.h"
#include "flann.h"
using namespace std;
namespace flann
{
class Logger
{
FILE* stream;
int logLevel;
public:
Logger() : stream(stdout), logLevel(LOG_WARN) {};
~Logger()
{
if (stream!=NULL && stream!=stdout) {
fclose(stream);
}
}
void setDestination(const char* name)
{
if (name==NULL) {
stream = stdout;
}
else {
stream = fopen(name,"w");
if (stream == NULL) {
stream = stdout;
}
}
}
void setLevel(int level) { logLevel = level; }
int log(int level, const char* fmt, ...);
int log(int level, const char* fmt, va_list arglist);
int fatal(const char* fmt, ...);
int error(const char* fmt, ...);
int warn(const char* fmt, ...);
int info(const char* fmt, ...);
};
extern Logger logger;
}
#endif //LOGGER_H

163
3rdparty/flann/util/matrix.h vendored Normal file
View File

@ -0,0 +1,163 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef DATASET_H
#define DATASET_H
#include <stdio.h>
#include <random.h>
namespace flann
{
/**
* Class implementing a generic rectangular dataset.
*/
template <typename T>
class Matrix {
/**
* Flag showing if the class owns its data storage.
*/
bool ownData;
void shallow_copy(const Matrix& rhs)
{
data = rhs.data;
rows = rhs.rows;
cols = rhs.cols;
ownData = false;
}
public:
long rows;
long cols;
T* data;
Matrix(long rows_, long cols_, T* data_ = NULL) :
ownData(false), rows(rows_), cols(cols_), data(data_)
{
if (data_==NULL) {
data = new T[rows*cols];
ownData = true;
}
}
Matrix(const Matrix& d)
{
shallow_copy(d);
}
const Matrix& operator=(const Matrix& rhs)
{
if (this!=&rhs) {
shallow_copy(rhs);
}
return *this;
}
~Matrix()
{
if (ownData) {
delete[] data;
}
}
/**
* Operator that return a (pointer to a) row of the data.
*/
T* operator[](long index)
{
return data+index*cols;
}
T* operator[](long index) const
{
return data+index*cols;
}
Matrix<T>* sample(long size, bool remove = false)
{
UniqueRandom rand(rows);
Matrix<T> *newSet = new Matrix<T>(size,cols);
T *src,*dest;
for (long i=0;i<size;++i) {
long r = rand.next();
dest = (*newSet)[i];
src = (*this)[r];
for (long j=0;j<cols;++j) {
dest[j] = src[j];
}
if (remove) {
dest = (*this)[rows-i-1];
src = (*this)[r];
for (long j=0;j<cols;++j) {
swap(*src,*dest);
src++;
dest++;
}
}
}
if (remove) {
rows -= size;
}
return newSet;
}
Matrix<T>* sample(long size) const
{
UniqueRandom rand(rows);
Matrix<T> *newSet = new Matrix<T>(size,cols);
T *src,*dest;
for (long i=0;i<size;++i) {
long r = rand.next();
dest = (*newSet)[i];
src = (*this)[r];
for (long j=0;j<cols;++j) {
dest[j] = src[j];
}
}
return newSet;
}
};
}
#endif //DATASET_H

93
3rdparty/flann/util/object_factory.h vendored Normal file
View File

@ -0,0 +1,93 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef OBJECT_FACTORY_H_
#define OBJECT_FACTORY_H_
#include <map>
namespace flann
{
template<typename BaseClass, typename DerivedClass>
BaseClass* createObject()
{
return new DerivedClass();
}
template<typename BaseClass, typename UniqueIdType>
class ObjectFactory
{
typedef BaseClass* (*CreateObjectFunc)();
std::map<UniqueIdType, CreateObjectFunc> object_registry;
// singleton class, private constructor
ObjectFactory() {};
public:
typedef typename std::map<UniqueIdType, CreateObjectFunc>::iterator Iterator;
template<typename DerivedClass>
bool register_(UniqueIdType id)
{
if (object_registry.find(id) != object_registry.end())
return false;
object_registry[id] = &createObject<BaseClass, DerivedClass>;
return true;
}
bool unregister(UniqueIdType id)
{
return (object_registry.erase(id) == 1);
}
BaseClass* create(UniqueIdType id)
{
Iterator iter = object_registry.find(id);
if (iter == object_registry.end())
return NULL;
return ((*iter).second)();
}
static ObjectFactory<BaseClass,UniqueIdType>& instance()
{
static ObjectFactory<BaseClass,UniqueIdType> the_factory;
return the_factory;
}
};
}
#endif /* OBJECT_FACTORY_H_ */

53
3rdparty/flann/util/random.cpp vendored Normal file
View File

@ -0,0 +1,53 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include "random.h"
namespace flann
{
void seed_random(unsigned int seed)
{
srand(seed);
}
double rand_double(double high, double low)
{
return low + ((high-low) * (std::rand() / (RAND_MAX + 1.0)));
}
int rand_int(int high, int low)
{
return low + (int) ( double(high-low) * (std::rand() / (RAND_MAX + 1.0)));
}
}

134
3rdparty/flann/util/random.h vendored Normal file
View File

@ -0,0 +1,134 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef RANDOM_H
#define RANDOM_H
#include <algorithm>
#include <cstdlib>
#include <cassert>
using namespace std;
namespace flann
{
/**
* Seeds the random number generator
*/
void seed_random(unsigned int seed);
/*
* Generates a random double value.
*/
double rand_double(double high = 1.0, double low=0);
/*
* Generates a random integer value.
*/
int rand_int(int high = RAND_MAX, int low = 0);
/**
* Random number generator that returns a distinct number from
* the [0,n) interval each time.
*
* TODO: improve on this to use a generator function instead of an
* array of randomly permuted numbers
*/
class UniqueRandom
{
int* vals;
int size;
int counter;
public:
/**
* Constructor.
* Params:
* n = the size of the interval from which to generate
* random numbers.
*/
UniqueRandom(int n) : vals(NULL) {
init(n);
}
~UniqueRandom()
{
delete[] vals;
}
/**
* Initializes the number generator.
* Params:
* n = the size of the interval from which to generate
* random numbers.
*/
void init(int n)
{
// create and initialize an array of size n
if (vals == NULL || n!=size) {
delete[] vals;
size = n;
vals = new int[size];
}
for(int i=0;i<size;++i) {
vals[i] = i;
}
// shuffle the elements in the array
// Fisher-Yates shuffle
for (int i=size;i>0;--i) {
// int rand = cast(int) (drand48() * n);
int rnd = rand_int(i);
assert(rnd >=0 && rnd < i);
swap(vals[i-1], vals[rnd]);
}
counter = 0;
}
/**
* Return a distinct random integer in greater or equal to 0 and less
* than 'n' on each call. It should be called maximum 'n' times.
* Returns: a random integer
*/
int next() {
if (counter==size) {
return -1;
} else {
return vals[counter++];
}
}
};
}
#endif //RANDOM_H

314
3rdparty/flann/util/result_set.h vendored Normal file
View File

@ -0,0 +1,314 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef RESULTSET_H
#define RESULTSET_H
#include <algorithm>
#include <limits>
#include <vector>
#include "dist.h"
using namespace std;
namespace flann
{
/* This record represents a branch point when finding neighbors in
the tree. It contains a record of the minimum distance to the query
point, as well as the node at which the search resumes.
*/
template <typename T>
struct BranchStruct {
T node; /* Tree node at which search resumes */
float mindistsq; /* Minimum distance to query for all nodes below. */
bool operator<(const BranchStruct<T>& rhs)
{
return mindistsq<rhs.mindistsq;
}
static BranchStruct<T> make_branch(T aNode, float dist)
{
BranchStruct<T> branch;
branch.node = aNode;
branch.mindistsq = dist;
return branch;
}
};
class ResultSet
{
protected:
const float* target;
const float* target_end;
int veclen;
public:
ResultSet(float* target_ = NULL, int veclen_ = 0) :
target(target_), veclen(veclen_) { target_end = target + veclen;}
virtual ~ResultSet() {}
virtual void init(const float* target_, int veclen_) = 0;
virtual int* getNeighbors() = 0;
virtual float* getDistances() = 0;
virtual int size() const = 0;
virtual bool full() const = 0;
virtual bool addPoint(float* point, int index) = 0;
virtual float worstDist() const = 0;
};
class KNNResultSet : public ResultSet
{
int* indices;
float* dists;
int capacity;
int count;
public:
KNNResultSet(int capacity_, float* target_ = NULL, int veclen_ = 0 ) :
ResultSet(target_, veclen_), capacity(capacity_), count(0)
{
indices = new int[capacity_];
dists = new float[capacity_];
}
~KNNResultSet()
{
delete[] indices;
delete[] dists;
}
void init(const float* target_, int veclen_)
{
target = target_;
veclen = veclen_;
target_end = target + veclen;
count = 0;
}
int* getNeighbors()
{
return indices;
}
float* getDistances()
{
return dists;
}
int size() const
{
return count;
}
bool full() const
{
return count == capacity;
}
bool addPoint(float* point, int index)
{
for (int i=0;i<count;++i) {
if (indices[i]==index) return false;
}
float dist = (float)flann_dist(target, target_end, point);
if (count<capacity) {
indices[count] = index;
dists[count] = dist;
++count;
}
else if (dist < dists[count-1] || (dist == dists[count-1] && index < indices[count-1])) {
// else if (dist < dists[count-1]) {
indices[count-1] = index;
dists[count-1] = dist;
}
else {
return false;
}
int i = count-1;
// bubble up
while (i>=1 && (dists[i]<dists[i-1] || (dists[i]==dists[i-1] && indices[i]<indices[i-1]) ) ) {
// while (i>=1 && (dists[i]<dists[i-1]) ) {
swap(indices[i],indices[i-1]);
swap(dists[i],dists[i-1]);
i--;
}
return true;
}
float worstDist() const
{
return (count<capacity) ? numeric_limits<float>::max() : dists[count-1];
}
};
/**
* A result-set class used when performing a radius based search.
*/
class RadiusResultSet : public ResultSet
{
struct Item {
int index;
float dist;
bool operator<(Item rhs) {
return dist<rhs.dist;
}
};
vector<Item> items;
float radius;
bool sorted;
int* indices;
float* dists;
size_t count;
private:
void resize_vecs()
{
if (items.size()>count) {
if (indices!=NULL) delete[] indices;
if (dists!=NULL) delete[] dists;
count = items.size();
indices = new int[count];
dists = new float[count];
}
}
public:
RadiusResultSet(float radius_) :
radius(radius_), indices(NULL), dists(NULL)
{
sorted = false;
items.reserve(16);
count = 0;
}
~RadiusResultSet()
{
if (indices!=NULL) delete[] indices;
if (dists!=NULL) delete[] dists;
}
void init(const float* target_, int veclen_)
{
target = target_;
veclen = veclen_;
target_end = target + veclen;
items.clear();
sorted = false;
}
int* getNeighbors()
{
if (!sorted) {
sorted = true;
sort_heap(items.begin(), items.end());
}
resize_vecs();
for (size_t i=0;i<items.size();++i) {
indices[i] = items[i].index;
}
return indices;
}
float* getDistances()
{
if (!sorted) {
sorted = true;
sort_heap(items.begin(), items.end());
}
resize_vecs();
for (size_t i=0;i<items.size();++i) {
dists[i] = items[i].dist;
}
return dists;
}
int size() const
{
return items.size();
}
bool full() const
{
return true;
}
bool addPoint(float* point, int index)
{
Item it;
it.index = index;
it.dist = (float)flann_dist(target, target_end, point);
if (it.dist<=radius) {
items.push_back(it);
push_heap(items.begin(), items.end());
return true;
}
return false;
}
float worstDist() const
{
return radius;
}
};
}
#endif //RESULTSET_H

73
3rdparty/flann/util/saving.cpp vendored Normal file
View File

@ -0,0 +1,73 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include "common.h"
#include "saving.h"
#include "nn_index.h"
#include <cstdio>
namespace flann
{
const char FLANN_SIGNATURE[] = "FLANN_INDEX";
void save_header(FILE* stream, const NNIndex& index)
{
IndexHeader header;
memset(header.signature, 0 , sizeof(header.signature));
strcpy(header.signature, FLANN_SIGNATURE);
header.flann_version = (int)FLANN_VERSION;
header.index_type = index.getType();
header.rows = index.size();
header.cols = index.veclen();
std::fwrite(&header, sizeof(header),1,stream);
}
IndexHeader load_header(FILE* stream)
{
IndexHeader header;
int read_size = fread(&header,sizeof(header),1,stream);
if (read_size!=1) {
throw FLANNException("Invalid index file, cannot read");
}
if (strcmp(header.signature,FLANN_SIGNATURE)!=0) {
throw FLANNException("Invalid index file, wrong signature");
}
return header;
}
}

87
3rdparty/flann/util/saving.h vendored Normal file
View File

@ -0,0 +1,87 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef SAVING_H_
#define SAVING_H_
#include "constants.h"
#include "nn_index.h"
namespace flann
{
/**
* Structure representing the index header.
*/
struct IndexHeader
{
char signature[16];
int flann_version;
flann_algorithm_t index_type;
int rows;
int cols;
};
/**
* Saves index header to stream
*
* @param stream - Stream to save to
* @param index - The index to save
*/
void save_header(FILE* stream, const NNIndex& index);
/**
*
* @param stream - Stream to load from
* @return Index header
*/
IndexHeader load_header(FILE* stream);
template<typename T>
void save_value(FILE* stream, const T& value, int count = 1)
{
fwrite(&value, sizeof(value),count, stream);
}
template<typename T>
void load_value(FILE* stream, T& value, int count = 1)
{
int read_cnt = fread(&value, sizeof(value),count, stream);
if (read_cnt!=count) {
throw FLANNException("Cannot read from file");
}
}
}
#endif /* SAVING_H_ */

90
3rdparty/flann/util/timer.h vendored Normal file
View File

@ -0,0 +1,90 @@
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef TIMER_H
#define TIMER_H
#include <time.h>
namespace flann
{
/**
* A start-stop timer class.
*
* Can be used to time portions of code.
*/
class StartStopTimer
{
clock_t startTime;
public:
/**
* Value of the timer.
*/
double value;
/**
* Constructor.
*/
StartStopTimer()
{
reset();
}
/**
* Starts the timer.
*/
void start() {
startTime = clock();
}
/**
* Stops the timer and updates timer value.
*/
void stop() {
clock_t stopTime = clock();
value += ( (double)stopTime - startTime) / CLOCKS_PER_SEC;
}
/**
* Resets the timer value to 0.
*/
void reset() {
value = 0;
}
};
}
#endif // TIMER_H

34
3rdparty/ilmimf/LICENSE vendored Normal file
View File

@ -0,0 +1,34 @@
Copyright (c) 2004, Industrial Light & Magic, a division of Lucasfilm
Entertainment Company Ltd. Portions contributed and copyright held by
others as indicated. 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 Industrial Light & Magic nor the names of
any other contributors to this software 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.

123
3rdparty/ilmimf/README vendored Normal file
View File

@ -0,0 +1,123 @@
ABOUT THE OPENEXR LIBRARIES
----------------------------
Half is a class that encapsulates our 16-bit floating-point format.
IlmThread is a thread abstraction library for use with IlmImf. It
currently supports pthreads and Windows threads.
IlmImf is our "EXR" file format for storing 16-bit FP images.
Imath is a math library. IlmImf only uses a subset of it,
but we're releasing the full library because it's easier for us to
maintain, and we think it'll be useful to others.
Iex is an exception-handling library.
See the IlmImfExamples directory for some code that demonstrates how
to use the IlmImf library to read and write OpenEXR files. The doc
directory contains some high-level documentation and history about the
OpenEXR format.
If you have questions about using the OpenEXR libraries, you may want
to join our developer mailing list. See http://www.openexr.com for
details.
LICENSE
-------
The OpenEXR source code distribution is free software. See the file
named COPYING (included in this distribution) for details.
WHAT'S INCLUDED
---------------
Besides the core OpenEXR libraries, the release includes several
utilities for reading, writing, viewing, and manipulating OpenEXR
images. These include:
* exrdisplay, an image viewer.
* exrheader, a utility for dumping header information.
* exrstdattr, a utility for modifying OpenEXR standard attributes.
* exrmaketiled, for generating tiled and rip/mipmapped images.
* exrenvmap, for creating OpenEXR environment maps.
* exrmakepreview, for creating preview images for OpenEXR files.
exrdisplay requires FLTK 1.1 or greater and OpenGL. exrdisplay
supports fragment shaders if you have the Nvidia Cg SDK and a graphics
card capable of running fp30 profile fragment shaders. See
exrdisplay/README for details.
We have also released an OpenEXR display driver for Renderman, a file
I/O plugin for Shake, and a file I/O plugin for Adobe Photoshop (on
both Windows and MacOS). These are packaged separately. Go to
http://www.openexr.com to download them. NOTE: the most recent
versions of these applications now have native support for OpenEXR, so
you should only use our open-source versions of the plugins if you
have an older version of the application.
BUILDING OPENEXR
----------------
Building OpenEXR requires the zlib library. If you want to build the
'exrdisplay' image viewer, you'll also need FLTK 1.1, but this program
is not required to use OpenEXR's libraries in your application.
exrdisplay can also accelerate the display of OpenEXR images if you
have the NVIDIA Cg SDK.
Your OS distribution may already include these libraries, or supply
packages for them. That is the preferred way to obtain them for use
with OpenEXR. If not, you can obtain the source code for zlib and
FLTK from:
http://www.zlib.net
http://www.fltk.org
and you can download the NVIDIA Cg SDK from
http://developer.nvidia.com.
If you're building OpenEXR on a Windows platform, see README.win32 for
instructions on how to build OpenEXR. The remainder of this file
applies only to GNU/Linux or other UNIX-like systems.
After installing the required libraries, to build OpenEXR on
GNU/Linux or other UNIX-like systems, do this:
./configure
make
make install
unless you obtained OpenEXR directly from CVS, in which case you
should first read README.CVS.
If you have the Nvidia Cg SDK and you want to build support for
fragment shaders into exrdisplay, specify the path to the SDK using
the "--with-cg-prefix" flag. There are some additional compile-time
configuration options available; type `./configure --help` for more
information.
See README.OSX for details on building OpenEXR in MacOS X.
Do `make check` to run the OpenEXR confidence tests. They should all
pass; if you find a test that does not pass on your system, please let
us know.
Other UNIX variants haven't been tested, but should be easy to build.
Let us know if you're having problems porting OpenEXR to a particular
platform.
All include files needed to use the OpenEXR libraries are installed in the
OpenEXR subdirectory of the install prefix, e.g. /usr/local/include/OpenEXR.
USING OPENEXR IN YOUR APPLICATIONS
----------------------------------
On systems with support for pkg-config, use `pkg-config --cflags
OpenEXR` for the C++ flags required to compile against OpenEXR
headers; and `pkg-config --libs OpenEXR` for the linker flags required
to link against OpenEXR libraries.

60
3rdparty/include/OpenEXR/Iex.h vendored Normal file
View File

@ -0,0 +1,60 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEX_H
#define INCLUDED_IEX_H
//--------------------------------
//
// Exception handling
//
//--------------------------------
#include "IexMacros.h"
#include "IexBaseExc.h"
#include "IexMathExc.h"
#include "IexThrowErrnoExc.h"
// Note that we do not include file IexErrnoExc.h here. That file
// defines over 150 classes and significantly slows down compilation.
// If you throw ErrnoExc exceptions using the throwErrnoExc() function,
// you don't need IexErrnoExc.h. You have to include IexErrnoExc.h
// only if you want to catch specific subclasses of ErrnoExc.
#endif

266
3rdparty/include/OpenEXR/IexBaseExc.h vendored Normal file
View File

@ -0,0 +1,266 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXBASEEXC_H
#define INCLUDED_IEXBASEEXC_H
//----------------------------------------------------------
//
// A general exception base class, and a few
// useful exceptions derived from the base class.
//
//----------------------------------------------------------
#include <string>
#include <exception>
#include <sstream>
namespace Iex {
#if (defined _WIN32 || defined _WIN64) && defined _MSC_VER
// Tell MS VC++ to suppress exception specification warnings
#pragma warning(disable:4290)
#endif
//-------------------------------
// Our most basic exception class
//-------------------------------
class BaseExc: public std::string, public std::exception
{
public:
//----------------------------
// Constructors and destructor
//----------------------------
BaseExc (const char *s = 0) throw(); // std::string (s)
BaseExc (const std::string &s) throw(); // std::string (s)
BaseExc (std::stringstream &s) throw(); // std::string (s.str())
BaseExc (const BaseExc &be) throw();
virtual ~BaseExc () throw ();
//--------------------------------------------
// what() method -- e.what() returns e.c_str()
//--------------------------------------------
virtual const char * what () const throw ();
//--------------------------------------------------
// Convenient methods to change the exception's text
//--------------------------------------------------
BaseExc & assign (std::stringstream &s); // assign (s.str())
BaseExc & operator = (std::stringstream &s);
BaseExc & append (std::stringstream &s); // append (s.str())
BaseExc & operator += (std::stringstream &s);
//--------------------------------------------------
// These methods from the base class get obscured by
// the definitions above.
//--------------------------------------------------
BaseExc & assign (const char *s);
BaseExc & operator = (const char *s);
BaseExc & append (const char *s);
BaseExc & operator += (const char *s);
//--------------------------------------------------
// Stack trace for the point at which the exception
// was thrown. The stack trace will be an empty
// string unless a working stack-tracing routine
// has been installed (see below, setStackTracer()).
//--------------------------------------------------
const std::string & stackTrace () const;
private:
std::string _stackTrace;
};
//-----------------------------------------------------
// A macro to save typing when declararing an exception
// class derived directly or indirectly from BaseExc:
//-----------------------------------------------------
#define DEFINE_EXC(name, base) \
class name: public base \
{ \
public: \
name (const char* text=0) throw(): base (text) {} \
name (const std::string &text) throw(): base (text) {} \
name (std::stringstream &text) throw(): base (text) {} \
};
//--------------------------------------------------------
// Some exceptions which should be useful in most programs
//--------------------------------------------------------
DEFINE_EXC (ArgExc, BaseExc) // Invalid arguments to a function call
DEFINE_EXC (LogicExc, BaseExc) // General error in a program's logic,
// for example, a function was called
// in a context where the call does
// not make sense.
DEFINE_EXC (InputExc, BaseExc) // Invalid input data, e.g. from a file
DEFINE_EXC (IoExc, BaseExc) // Input or output operation failed
DEFINE_EXC (MathExc, BaseExc) // Arithmetic exception; more specific
// exceptions derived from this class
// are defined in ExcMath.h
DEFINE_EXC (ErrnoExc, BaseExc) // Base class for exceptions corresponding
// to errno values (see errno.h); more
// specific exceptions derived from this
// class are defined in ExcErrno.h
DEFINE_EXC (NoImplExc, BaseExc) // Missing method exception e.g. from a
// call to a method that is only partially
// or not at all implemented. A reminder
// to lazy software people to get back
// to work.
DEFINE_EXC (NullExc, BaseExc) // A pointer is inappropriately null.
DEFINE_EXC (TypeExc, BaseExc) // An object is an inappropriate type,
// i.e. a dynamnic_cast failed.
//----------------------------------------------------------------------
// Stack-tracing support:
//
// setStackTracer(st)
//
// installs a stack-tracing routine, st, which will be called from
// class BaseExc's constructor every time an exception derived from
// BaseExc is thrown. The stack-tracing routine should return a
// string that contains a printable representation of the program's
// current call stack. This string will be stored in the BaseExc
// object; the string is accesible via the BaseExc::stackTrace()
// method.
//
// setStackTracer(0)
//
// removes the current stack tracing routine. When an exception
// derived from BaseExc is thrown, the stack trace string stored
// in the BaseExc object will be empty.
//
// stackTracer()
//
// returns a pointer to the current stack-tracing routine, or 0
// if there is no current stack stack-tracing routine.
//
//----------------------------------------------------------------------
typedef std::string (* StackTracer) ();
void setStackTracer (StackTracer stackTracer);
StackTracer stackTracer ();
//-----------------
// Inline functions
//-----------------
inline BaseExc &
BaseExc::operator = (std::stringstream &s)
{
return assign (s);
}
inline BaseExc &
BaseExc::operator += (std::stringstream &s)
{
return append (s);
}
inline BaseExc &
BaseExc::assign (const char *s)
{
std::string::assign(s);
return *this;
}
inline BaseExc &
BaseExc::operator = (const char *s)
{
return assign(s);
}
inline BaseExc &
BaseExc::append (const char *s)
{
std::string::append(s);
return *this;
}
inline BaseExc &
BaseExc::operator += (const char *s)
{
return append(s);
}
inline const std::string &
BaseExc::stackTrace () const
{
return _stackTrace;
}
#if (defined _WIN32 || defined _WIN64) && defined _MSC_VER
#pragma warning(default:4290)
#endif
} // namespace Iex
#endif

210
3rdparty/include/OpenEXR/IexErrnoExc.h vendored Normal file
View File

@ -0,0 +1,210 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXERRNOEXC_H
#define INCLUDED_IEXERRNOEXC_H
//----------------------------------------------------------------
//
// Exceptions which correspond to "errno" error codes.
//
//----------------------------------------------------------------
#include "IexBaseExc.h"
namespace Iex {
DEFINE_EXC (EpermExc, ErrnoExc)
DEFINE_EXC (EnoentExc, ErrnoExc)
DEFINE_EXC (EsrchExc, ErrnoExc)
DEFINE_EXC (EintrExc, ErrnoExc)
DEFINE_EXC (EioExc, ErrnoExc)
DEFINE_EXC (EnxioExc, ErrnoExc)
DEFINE_EXC (E2bigExc, ErrnoExc)
DEFINE_EXC (EnoexecExc, ErrnoExc)
DEFINE_EXC (EbadfExc, ErrnoExc)
DEFINE_EXC (EchildExc, ErrnoExc)
DEFINE_EXC (EagainExc, ErrnoExc)
DEFINE_EXC (EnomemExc, ErrnoExc)
DEFINE_EXC (EaccesExc, ErrnoExc)
DEFINE_EXC (EfaultExc, ErrnoExc)
DEFINE_EXC (EnotblkExc, ErrnoExc)
DEFINE_EXC (EbusyExc, ErrnoExc)
DEFINE_EXC (EexistExc, ErrnoExc)
DEFINE_EXC (ExdevExc, ErrnoExc)
DEFINE_EXC (EnodevExc, ErrnoExc)
DEFINE_EXC (EnotdirExc, ErrnoExc)
DEFINE_EXC (EisdirExc, ErrnoExc)
DEFINE_EXC (EinvalExc, ErrnoExc)
DEFINE_EXC (EnfileExc, ErrnoExc)
DEFINE_EXC (EmfileExc, ErrnoExc)
DEFINE_EXC (EnottyExc, ErrnoExc)
DEFINE_EXC (EtxtbsyExc, ErrnoExc)
DEFINE_EXC (EfbigExc, ErrnoExc)
DEFINE_EXC (EnospcExc, ErrnoExc)
DEFINE_EXC (EspipeExc, ErrnoExc)
DEFINE_EXC (ErofsExc, ErrnoExc)
DEFINE_EXC (EmlinkExc, ErrnoExc)
DEFINE_EXC (EpipeExc, ErrnoExc)
DEFINE_EXC (EdomExc, ErrnoExc)
DEFINE_EXC (ErangeExc, ErrnoExc)
DEFINE_EXC (EnomsgExc, ErrnoExc)
DEFINE_EXC (EidrmExc, ErrnoExc)
DEFINE_EXC (EchrngExc, ErrnoExc)
DEFINE_EXC (El2nsyncExc, ErrnoExc)
DEFINE_EXC (El3hltExc, ErrnoExc)
DEFINE_EXC (El3rstExc, ErrnoExc)
DEFINE_EXC (ElnrngExc, ErrnoExc)
DEFINE_EXC (EunatchExc, ErrnoExc)
DEFINE_EXC (EnocsiExc, ErrnoExc)
DEFINE_EXC (El2hltExc, ErrnoExc)
DEFINE_EXC (EdeadlkExc, ErrnoExc)
DEFINE_EXC (EnolckExc, ErrnoExc)
DEFINE_EXC (EbadeExc, ErrnoExc)
DEFINE_EXC (EbadrExc, ErrnoExc)
DEFINE_EXC (ExfullExc, ErrnoExc)
DEFINE_EXC (EnoanoExc, ErrnoExc)
DEFINE_EXC (EbadrqcExc, ErrnoExc)
DEFINE_EXC (EbadsltExc, ErrnoExc)
DEFINE_EXC (EdeadlockExc, ErrnoExc)
DEFINE_EXC (EbfontExc, ErrnoExc)
DEFINE_EXC (EnostrExc, ErrnoExc)
DEFINE_EXC (EnodataExc, ErrnoExc)
DEFINE_EXC (EtimeExc, ErrnoExc)
DEFINE_EXC (EnosrExc, ErrnoExc)
DEFINE_EXC (EnonetExc, ErrnoExc)
DEFINE_EXC (EnopkgExc, ErrnoExc)
DEFINE_EXC (EremoteExc, ErrnoExc)
DEFINE_EXC (EnolinkExc, ErrnoExc)
DEFINE_EXC (EadvExc, ErrnoExc)
DEFINE_EXC (EsrmntExc, ErrnoExc)
DEFINE_EXC (EcommExc, ErrnoExc)
DEFINE_EXC (EprotoExc, ErrnoExc)
DEFINE_EXC (EmultihopExc, ErrnoExc)
DEFINE_EXC (EbadmsgExc, ErrnoExc)
DEFINE_EXC (EnametoolongExc, ErrnoExc)
DEFINE_EXC (EoverflowExc, ErrnoExc)
DEFINE_EXC (EnotuniqExc, ErrnoExc)
DEFINE_EXC (EbadfdExc, ErrnoExc)
DEFINE_EXC (EremchgExc, ErrnoExc)
DEFINE_EXC (ElibaccExc, ErrnoExc)
DEFINE_EXC (ElibbadExc, ErrnoExc)
DEFINE_EXC (ElibscnExc, ErrnoExc)
DEFINE_EXC (ElibmaxExc, ErrnoExc)
DEFINE_EXC (ElibexecExc, ErrnoExc)
DEFINE_EXC (EilseqExc, ErrnoExc)
DEFINE_EXC (EnosysExc, ErrnoExc)
DEFINE_EXC (EloopExc, ErrnoExc)
DEFINE_EXC (ErestartExc, ErrnoExc)
DEFINE_EXC (EstrpipeExc, ErrnoExc)
DEFINE_EXC (EnotemptyExc, ErrnoExc)
DEFINE_EXC (EusersExc, ErrnoExc)
DEFINE_EXC (EnotsockExc, ErrnoExc)
DEFINE_EXC (EdestaddrreqExc, ErrnoExc)
DEFINE_EXC (EmsgsizeExc, ErrnoExc)
DEFINE_EXC (EprototypeExc, ErrnoExc)
DEFINE_EXC (EnoprotooptExc, ErrnoExc)
DEFINE_EXC (EprotonosupportExc, ErrnoExc)
DEFINE_EXC (EsocktnosupportExc, ErrnoExc)
DEFINE_EXC (EopnotsuppExc, ErrnoExc)
DEFINE_EXC (EpfnosupportExc, ErrnoExc)
DEFINE_EXC (EafnosupportExc, ErrnoExc)
DEFINE_EXC (EaddrinuseExc, ErrnoExc)
DEFINE_EXC (EaddrnotavailExc, ErrnoExc)
DEFINE_EXC (EnetdownExc, ErrnoExc)
DEFINE_EXC (EnetunreachExc, ErrnoExc)
DEFINE_EXC (EnetresetExc, ErrnoExc)
DEFINE_EXC (EconnabortedExc, ErrnoExc)
DEFINE_EXC (EconnresetExc, ErrnoExc)
DEFINE_EXC (EnobufsExc, ErrnoExc)
DEFINE_EXC (EisconnExc, ErrnoExc)
DEFINE_EXC (EnotconnExc, ErrnoExc)
DEFINE_EXC (EshutdownExc, ErrnoExc)
DEFINE_EXC (EtoomanyrefsExc, ErrnoExc)
DEFINE_EXC (EtimedoutExc, ErrnoExc)
DEFINE_EXC (EconnrefusedExc, ErrnoExc)
DEFINE_EXC (EhostdownExc, ErrnoExc)
DEFINE_EXC (EhostunreachExc, ErrnoExc)
DEFINE_EXC (EalreadyExc, ErrnoExc)
DEFINE_EXC (EinprogressExc, ErrnoExc)
DEFINE_EXC (EstaleExc, ErrnoExc)
DEFINE_EXC (EioresidExc, ErrnoExc)
DEFINE_EXC (EucleanExc, ErrnoExc)
DEFINE_EXC (EnotnamExc, ErrnoExc)
DEFINE_EXC (EnavailExc, ErrnoExc)
DEFINE_EXC (EisnamExc, ErrnoExc)
DEFINE_EXC (EremoteioExc, ErrnoExc)
DEFINE_EXC (EinitExc, ErrnoExc)
DEFINE_EXC (EremdevExc, ErrnoExc)
DEFINE_EXC (EcanceledExc, ErrnoExc)
DEFINE_EXC (EnolimfileExc, ErrnoExc)
DEFINE_EXC (EproclimExc, ErrnoExc)
DEFINE_EXC (EdisjointExc, ErrnoExc)
DEFINE_EXC (EnologinExc, ErrnoExc)
DEFINE_EXC (EloginlimExc, ErrnoExc)
DEFINE_EXC (EgrouploopExc, ErrnoExc)
DEFINE_EXC (EnoattachExc, ErrnoExc)
DEFINE_EXC (EnotsupExc, ErrnoExc)
DEFINE_EXC (EnoattrExc, ErrnoExc)
DEFINE_EXC (EdircorruptedExc, ErrnoExc)
DEFINE_EXC (EdquotExc, ErrnoExc)
DEFINE_EXC (EnfsremoteExc, ErrnoExc)
DEFINE_EXC (EcontrollerExc, ErrnoExc)
DEFINE_EXC (EnotcontrollerExc, ErrnoExc)
DEFINE_EXC (EenqueuedExc, ErrnoExc)
DEFINE_EXC (EnotenqueuedExc, ErrnoExc)
DEFINE_EXC (EjoinedExc, ErrnoExc)
DEFINE_EXC (EnotjoinedExc, ErrnoExc)
DEFINE_EXC (EnoprocExc, ErrnoExc)
DEFINE_EXC (EmustrunExc, ErrnoExc)
DEFINE_EXC (EnotstoppedExc, ErrnoExc)
DEFINE_EXC (EclockcpuExc, ErrnoExc)
DEFINE_EXC (EinvalstateExc, ErrnoExc)
DEFINE_EXC (EnoexistExc, ErrnoExc)
DEFINE_EXC (EendofminorExc, ErrnoExc)
DEFINE_EXC (EbufsizeExc, ErrnoExc)
DEFINE_EXC (EemptyExc, ErrnoExc)
DEFINE_EXC (EnointrgroupExc, ErrnoExc)
DEFINE_EXC (EinvalmodeExc, ErrnoExc)
DEFINE_EXC (EcantextentExc, ErrnoExc)
DEFINE_EXC (EinvaltimeExc, ErrnoExc)
DEFINE_EXC (EdestroyedExc, ErrnoExc)
} // namespace Iex
#endif

148
3rdparty/include/OpenEXR/IexMacros.h vendored Normal file
View File

@ -0,0 +1,148 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXMACROS_H
#define INCLUDED_IEXMACROS_H
//--------------------------------------------------------------------
//
// Macros which make throwing exceptions more convenient
//
//--------------------------------------------------------------------
#include <sstream>
//----------------------------------------------------------------------------
// A macro to throw exceptions whose text is assembled using stringstreams.
//
// Example:
//
// THROW (InputExc, "Syntax error in line " << line ", " << file << ".");
//
//----------------------------------------------------------------------------
#define THROW(type, text) \
do \
{ \
std::stringstream s; \
s << text; \
throw type (s); \
} \
while (0)
//----------------------------------------------------------------------------
// Macros to add to or to replace the text of an exception.
// The new text is assembled using stringstreams.
//
// Examples:
//
// Append to end of an exception's text:
//
// catch (BaseExc &e)
// {
// APPEND_EXC (e, " Directory " << name << " does not exist.");
// throw;
// }
//
// Replace an exception's text:
//
// catch (BaseExc &e)
// {
// REPLACE_EXC (e, "Directory " << name << " does not exist. " << e);
// throw;
// }
//----------------------------------------------------------------------------
#define APPEND_EXC(exc, text) \
do \
{ \
std::stringstream s; \
s << text; \
exc.append (s); \
} \
while (0)
#define REPLACE_EXC(exc, text) \
do \
{ \
std::stringstream s; \
s << text; \
exc.assign (s); \
} \
while (0)
//-------------------------------------------------------------
// A macro to throw ErrnoExc exceptions whose text is assembled
// using stringstreams:
//
// Example:
//
// THROW_ERRNO ("Cannot open file " << name << " (%T).");
//
//-------------------------------------------------------------
#define THROW_ERRNO(text) \
do \
{ \
std::stringstream s; \
s << text; \
::Iex::throwErrnoExc (s.str()); \
} \
while (0)
//-------------------------------------------------------------
// A macro to throw exceptions if an assertion is false.
//
// Example:
//
// ASSERT (NullExc, ptr != NULL, "Null pointer" );
//
//-------------------------------------------------------------
#define ASSERT(assertion, type, text) \
do \
{ \
if( (assertion) == false ) \
THROW( type, text ); \
} \
while (0)
#endif

58
3rdparty/include/OpenEXR/IexMathExc.h vendored Normal file
View File

@ -0,0 +1,58 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXMATHEXC_H
#define INCLUDED_IEXMATHEXC_H
#include "IexBaseExc.h"
namespace Iex {
//---------------------------------------------------------
// Exception classess which correspond to specific floating
// point exceptions.
//---------------------------------------------------------
DEFINE_EXC (OverflowExc, MathExc) // Overflow
DEFINE_EXC (UnderflowExc, MathExc) // Underflow
DEFINE_EXC (DivzeroExc, MathExc) // Division by zero
DEFINE_EXC (InexactExc, MathExc) // Inexact result
DEFINE_EXC (InvalidFpOpExc, MathExc) // Invalid operation
} // namespace Iex
#endif

View File

@ -0,0 +1,96 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IEXTHROWERRNOEXC_H
#define INCLUDED_IEXTHROWERRNOEXC_H
//----------------------------------------------------------
//
// A function which throws ExcErrno exceptions
//
//----------------------------------------------------------
#include "IexBaseExc.h"
namespace Iex {
//--------------------------------------------------------------------------
//
// Function throwErrnoExc() throws an exception which corresponds to
// error code errnum. The exception text is initialized with a copy
// of the string passed to throwErrnoExc(), where all occurrences of
// "%T" have been replaced with the output of strerror(oserror()).
//
// Example:
//
// If opening file /tmp/output failed with an ENOENT error code,
// calling
//
// throwErrnoExc ();
//
// or
//
// throwErrnoExc ("%T.");
//
// will throw an EnoentExc whose text reads
//
// No such file or directory.
//
// More detailed messages can be assembled using stringstreams:
//
// std::stringstream s;
// s << "Cannot open file " << name << " (%T).";
// throwErrnoExc (s);
//
// The resulting exception contains the following text:
//
// Cannot open file /tmp/output (No such file or directory).
//
// Alternatively, you may want to use the THROW_ERRNO macro defined
// in IexMacros.h:
//
// THROW_ERRNO ("Cannot open file " << name << " (%T).")
//
//--------------------------------------------------------------------------
void throwErrnoExc (const std::string &txt, int errnum);
void throwErrnoExc (const std::string &txt = "%T." /*, int errnum = oserror() */);
} // namespace Iex
#endif

141
3rdparty/include/OpenEXR/IlmThread.h vendored Normal file
View File

@ -0,0 +1,141 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_ILM_THREAD_H
#define INCLUDED_ILM_THREAD_H
//-----------------------------------------------------------------------------
//
// class Thread
//
// Class Thread is a portable interface to a system-dependent thread
// primitive. In order to make a thread actually do something useful,
// you must derive a subclass from class Thread and implement the
// run() function. If the operating system supports threading then
// the run() function will be executed int a new thread.
//
// The actual creation of the thread is done by the start() routine
// which then calls the run() function. In general the start()
// routine should be called from the constructor of the derived class.
//
// The base-class thread destructor will join/destroy the thread.
//
// IMPORTANT: Due to the mechanisms that encapsulate the low-level
// threading primitives in a C++ class there is a race condition
// with code resembling the following:
//
// {
// WorkerThread myThread;
// } // myThread goes out of scope, is destroyed
// // and the thread is joined
//
// The race is between the parent thread joining the child thread
// in the destructor of myThread, and the run() function in the
// child thread. If the destructor gets executed first then run()
// will be called with an invalid "this" pointer.
//
// This issue can be fixed by using a Semaphore to keep track of
// whether the run() function has already been called. You can
// include a Semaphore member variable within your derived class
// which you post() on in the run() function, and wait() on in the
// destructor before the thread is joined. Alternatively you could
// do something like this:
//
// Semaphore runStarted;
//
// void WorkerThread::run ()
// {
// runStarted.post()
// // do some work
// ...
// }
//
// {
// WorkerThread myThread;
// runStarted.wait (); // ensure that we have started
// // the run function
// } // myThread goes out of scope, is destroyed
// // and the thread is joined
//
//-----------------------------------------------------------------------------
#include "OpenEXRConfig.h"
#if defined _WIN32 || defined _WIN64
#ifdef NOMINMAX
#undef NOMINMAX
#endif
#define NOMINMAX
#include <windows.h>
#include <process.h>
#elif HAVE_PTHREAD
#include <pthread.h>
#endif
namespace IlmThread {
//
// Query function to determine if the current platform supports
// threads AND this library was compiled with threading enabled.
//
bool supportsThreads ();
class Thread
{
public:
Thread ();
virtual ~Thread ();
void start ();
virtual void run () = 0;
private:
#if defined _WIN32 || defined _WIN64
HANDLE _thread;
#elif HAVE_PTHREAD
pthread_t _thread;
#endif
void operator = (const Thread& t); // not implemented
Thread (const Thread& t); // not implemented
};
} // namespace IlmThread
#endif

View File

@ -0,0 +1,158 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_ILM_THREAD_MUTEX_H
#define INCLUDED_ILM_THREAD_MUTEX_H
//-----------------------------------------------------------------------------
//
// class Mutex, class Lock
//
// Class Mutex is a wrapper for a system-dependent mutual exclusion
// mechanism. Actual locking and unlocking of a Mutex object must
// be performed using an instance of a Lock (defined below).
//
// Class lock provides safe locking and unlocking of mutexes even in
// the presence of C++ exceptions. Constructing a Lock object locks
// the mutex; destroying the Lock unlocks the mutex.
//
// Lock objects are not themselves thread-safe. You should never
// share a Lock object among multiple threads.
//
// Typical usage:
//
// Mutex mtx; // Create a Mutex object that is visible
// //to multiple threads
//
// ... // create some threads
//
// // Then, within each thread, construct a critical section like so:
//
// {
// Lock lock (mtx); // Lock constructor locks the mutex
// ... // do some computation on shared data
// } // leaving the block unlocks the mutex
//
//-----------------------------------------------------------------------------
#include "OpenEXRConfig.h"
#if defined _WIN32 || defined _WIN64
#ifdef NOMINMAX
#undef NOMINMAX
#endif
#define NOMINMAX
#include <windows.h>
#elif HAVE_PTHREAD
#include <pthread.h>
#endif
namespace IlmThread {
class Lock;
class Mutex
{
public:
Mutex ();
virtual ~Mutex ();
private:
void lock () const;
void unlock () const;
#if defined _WIN32 || defined _WIN64
mutable CRITICAL_SECTION _mutex;
#elif HAVE_PTHREAD
mutable pthread_mutex_t _mutex;
#endif
void operator = (const Mutex& M); // not implemented
Mutex (const Mutex& M); // not implemented
friend class Lock;
};
class Lock
{
public:
Lock (const Mutex& m, bool autoLock = true):
_mutex (m),
_locked (false)
{
if (autoLock)
{
_mutex.lock();
_locked = true;
}
}
~Lock ()
{
if (_locked)
_mutex.unlock();
}
void acquire ()
{
_mutex.lock();
_locked = true;
}
void release ()
{
_mutex.unlock();
_locked = false;
}
bool locked ()
{
return _locked;
}
private:
const Mutex & _mutex;
bool _locked;
};
} // namespace IlmThread
#endif

156
3rdparty/include/OpenEXR/IlmThreadPool.h vendored Normal file
View File

@ -0,0 +1,156 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_ILM_THREAD_POOL_H
#define INCLUDED_ILM_THREAD_POOL_H
//-----------------------------------------------------------------------------
//
// class Task, class ThreadPool, class TaskGroup
//
// Class ThreadPool manages a set of worker threads and accepts
// tasks for processing. Tasks added to the thread pool are
// executed concurrently by the worker threads.
//
// Class Thread provides an abstract interface for a task which
// a ThreadPool works on. Derived classes need to implement the
// execute() function which performs the actual task.
//
// Class TaskTroup allows synchronization on the completion of a set
// of tasks. Every task that is added to a ThreadPool belongs to a
// single TaskGroup. The destructor of the TaskGroup waits for all
// tasks in the group to finish.
//
// Note: if you plan to use the ThreadPool interface in your own
// applications note that the implementation of the ThreadPool calls
// opertor delete on tasks as they complete. If you define a custom
// operator new for your tasks, for instance to use a custom heap,
// then you must also write an appropriate operator delete.
//
//-----------------------------------------------------------------------------
namespace IlmThread {
class TaskGroup;
class Task;
class ThreadPool
{
public:
//-------------------------------------------------------
// Constructor -- creates numThreads worker threads which
// wait until a task is available.
//-------------------------------------------------------
ThreadPool (unsigned numThreads = 0);
//-----------------------------------------------------------
// Destructor -- waits for all tasks to complete, joins all
// the threads to the calling thread, and then destroys them.
//-----------------------------------------------------------
virtual ~ThreadPool ();
//--------------------------------------------------------
// Query and set the number of worker threads in the pool.
//
// Warning: never call setNumThreads from within a worker
// thread as this will almost certainly cause a deadlock
// or crash.
//--------------------------------------------------------
int numThreads () const;
void setNumThreads (int count);
//------------------------------------------------------------
// Add a task for processing. The ThreadPool can handle any
// number of tasks regardless of the number of worker threads.
// The tasks are first added onto a queue, and are executed
// by threads as they become available, in FIFO order.
//------------------------------------------------------------
void addTask (Task* task);
//-------------------------------------------
// Access functions for the global threadpool
//-------------------------------------------
static ThreadPool& globalThreadPool ();
static void addGlobalTask (Task* task);
struct Data;
protected:
Data * _data;
};
class Task
{
public:
Task (TaskGroup* g);
virtual ~Task ();
virtual void execute () = 0;
TaskGroup * group();
protected:
TaskGroup * _group;
};
class TaskGroup
{
public:
TaskGroup();
~TaskGroup();
struct Data;
Data* const _data;
};
} // namespace IlmThread
#endif

View File

@ -0,0 +1,109 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_ILM_THREAD_SEMAPHORE_H
#define INCLUDED_ILM_THREAD_SEMAPHORE_H
//-----------------------------------------------------------------------------
//
// class Semaphore -- a wrapper class for
// system-dependent counting semaphores
//
//-----------------------------------------------------------------------------
#include "OpenEXRConfig.h"
#if defined _WIN32 || defined _WIN64
#ifdef NOMINMAX
#undef NOMINMAX
#endif
#define NOMINMAX
#include <windows.h>
#elif HAVE_PTHREAD && !HAVE_POSIX_SEMAPHORES
#include <pthread.h>
#elif HAVE_PTHREAD && HAVE_POSIX_SEMAPHORES
#include <semaphore.h>
#endif
namespace IlmThread {
class Semaphore
{
public:
Semaphore (unsigned int value = 0);
virtual ~Semaphore();
void wait();
void post();
int value() const;
private:
#if defined _WIN32 || defined _WIN64
mutable HANDLE _semaphore;
#elif HAVE_PTHREAD && !HAVE_POSIX_SEMAPHORES
//
// If the platform has Posix threads but no semapohores,
// then we implement them ourselves using condition variables
//
struct sema_t
{
unsigned int count;
unsigned long numWaiting;
pthread_mutex_t mutex;
pthread_cond_t nonZero;
};
mutable sema_t _semaphore;
#elif HAVE_PTHREAD && HAVE_POSIX_SEMAPHORES
mutable sem_t _semaphore;
#endif
void operator = (const Semaphore& s); // not implemented
Semaphore (const Semaphore& s); // not implemented
};
} // namespace IlmThread
#endif

277
3rdparty/include/OpenEXR/ImathBox.h vendored Normal file
View File

@ -0,0 +1,277 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHBOX_H
#define INCLUDED_IMATHBOX_H
//-------------------------------------------------------------------
//
// class Imath::Box<class T>
// --------------------------------
//
// This class imposes the following requirements on its
// parameter class:
//
// 1) The class T must implement these operators:
// + - < > <= >= =
// with the signature (T,T) and the expected
// return values for a numeric type.
//
// 2) The class T must implement operator=
// with the signature (T,float and/or double)
//
// 3) The class T must have a constructor which takes
// a float (and/or double) for use in initializing the box.
//
// 4) The class T must have a function T::dimensions()
// which returns the number of dimensions in the class
// (since its assumed its a vector) -- preferably, this
// returns a constant expression.
//
//-------------------------------------------------------------------
#include "ImathVec.h"
namespace Imath {
template <class T>
class Box
{
public:
//-------------------------
// Data Members are public
//-------------------------
T min;
T max;
//-----------------------------------------------------
// Constructors - an "empty" box is created by default
//-----------------------------------------------------
Box();
Box(const T& point);
Box(const T& minT, const T& maxT);
//--------------------
// Operators: ==, !=
//--------------------
bool operator == (const Box<T> &src) const;
bool operator != (const Box<T> &src) const;
//------------------
// Box manipulation
//------------------
void makeEmpty();
void extendBy(const T& point);
void extendBy(const Box<T>& box);
//---------------------------------------------------
// Query functions - these compute results each time
//---------------------------------------------------
T size() const;
T center() const;
bool intersects(const T &point) const;
bool intersects(const Box<T> &box) const;
unsigned int majorAxis() const;
//----------------
// Classification
//----------------
bool isEmpty() const;
bool hasVolume() const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Box <V2s> Box2s;
typedef Box <V2i> Box2i;
typedef Box <V2f> Box2f;
typedef Box <V2d> Box2d;
typedef Box <V3s> Box3s;
typedef Box <V3i> Box3i;
typedef Box <V3f> Box3f;
typedef Box <V3d> Box3d;
//----------------
// Implementation
//----------------
template <class T>
inline Box<T>::Box()
{
makeEmpty();
}
template <class T>
inline Box<T>::Box(const T& point)
{
min = point;
max = point;
}
template <class T>
inline Box<T>::Box(const T& minV, const T& maxV)
{
min = minV;
max = maxV;
}
template <class T>
inline bool
Box<T>::operator == (const Box<T> &src) const
{
return (min == src.min && max == src.max);
}
template <class T>
inline bool
Box<T>::operator != (const Box<T> &src) const
{
return (min != src.min || max != src.max);
}
template <class T>
inline void Box<T>::makeEmpty()
{
min = T(T::baseTypeMax());
max = T(T::baseTypeMin());
}
template <class T>
inline void Box<T>::extendBy(const T& point)
{
for (unsigned int i=0; i<min.dimensions(); i++)
{
if ( point[i] < min[i] ) min[i] = point[i];
if ( point[i] > max[i] ) max[i] = point[i];
}
}
template <class T>
inline void Box<T>::extendBy(const Box<T>& box)
{
for (unsigned int i=0; i<min.dimensions(); i++)
{
if ( box.min[i] < min[i] ) min[i] = box.min[i];
if ( box.max[i] > max[i] ) max[i] = box.max[i];
}
}
template <class T>
inline bool Box<T>::intersects(const T& point) const
{
for (unsigned int i=0; i<min.dimensions(); i++)
{
if (point[i] < min[i] || point[i] > max[i]) return false;
}
return true;
}
template <class T>
inline bool Box<T>::intersects(const Box<T>& box) const
{
for (unsigned int i=0; i<min.dimensions(); i++)
{
if (box.max[i] < min[i] || box.min[i] > max[i]) return false;
}
return true;
}
template <class T>
inline T Box<T>::size() const
{
if (isEmpty())
return T (0);
return max-min;
}
template <class T>
inline T Box<T>::center() const
{
return (max+min)/2;
}
template <class T>
inline bool Box<T>::isEmpty() const
{
for (unsigned int i=0; i<min.dimensions(); i++)
{
if (max[i] < min[i]) return true;
}
return false;
}
template <class T>
inline bool Box<T>::hasVolume() const
{
for (unsigned int i=0; i<min.dimensions(); i++)
{
if (max[i] <= min[i]) return false;
}
return true;
}
template<class T>
inline unsigned int Box<T>::majorAxis() const
{
unsigned int major = 0;
T s = size();
for (unsigned int i=1; i<min.dimensions(); i++)
{
if ( s[i] > s[major] ) major = i;
}
return major;
}
} // namespace Imath
#endif

611
3rdparty/include/OpenEXR/ImathBoxAlgo.h vendored Normal file
View File

@ -0,0 +1,611 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHBOXALGO_H
#define INCLUDED_IMATHBOXALGO_H
//---------------------------------------------------------------------------
//
// This file contains algorithms applied to or in conjunction
// with bounding boxes (Imath::Box). These algorithms require
// more headers to compile. The assumption made is that these
// functions are called much less often than the basic box
// functions or these functions require more support classes.
//
// Contains:
//
// T clip<T>(const T& in, const Box<T>& box)
//
// Vec3<T> closestPointOnBox(const Vec3<T>&, const Box<Vec3<T>>& )
//
// Vec3<T> closestPointInBox(const Vec3<T>&, const Box<Vec3<T>>& )
//
// void transform(Box<Vec3<T>>&, const Matrix44<T>&)
//
// bool findEntryAndExitPoints(const Line<T> &line,
// const Box< Vec3<T> > &box,
// Vec3<T> &enterPoint,
// Vec3<T> &exitPoint)
//
// bool intersects(const Box<Vec3<T>> &box,
// const Line3<T> &line,
// Vec3<T> result)
//
// bool intersects(const Box<Vec3<T>> &box, const Line3<T> &line)
//
//---------------------------------------------------------------------------
#include "ImathBox.h"
#include "ImathMatrix.h"
#include "ImathLineAlgo.h"
#include "ImathPlane.h"
namespace Imath {
template <class T>
inline T clip(const T& in, const Box<T>& box)
{
//
// Clip a point so that it lies inside the given bbox
//
T out;
for (int i=0; i<(int)box.min.dimensions(); i++)
{
if (in[i] < box.min[i]) out[i] = box.min[i];
else if (in[i] > box.max[i]) out[i] = box.max[i];
else out[i] = in[i];
}
return out;
}
//
// Return p if p is inside the box.
//
template <class T>
Vec3<T>
closestPointInBox(const Vec3<T>& p, const Box< Vec3<T> >& box )
{
Imath::V3f b;
if (p.x < box.min.x)
b.x = box.min.x;
else if (p.x > box.max.x)
b.x = box.max.x;
else
b.x = p.x;
if (p.y < box.min.y)
b.y = box.min.y;
else if (p.y > box.max.y)
b.y = box.max.y;
else
b.y = p.y;
if (p.z < box.min.z)
b.z = box.min.z;
else if (p.z > box.max.z)
b.z = box.max.z;
else
b.z = p.z;
return b;
}
template <class T>
Vec3<T> closestPointOnBox(const Vec3<T>& pt, const Box< Vec3<T> >& box )
{
//
// This sucker is specialized to work with a Vec3f and a box
// made of Vec3fs.
//
Vec3<T> result;
// trivial cases first
if (box.isEmpty())
return pt;
else if (pt == box.center())
{
// middle of z side
result[0] = (box.max[0] + box.min[0])/2.0;
result[1] = (box.max[1] + box.min[1])/2.0;
result[2] = box.max[2];
}
else
{
// Find the closest point on a unit box (from -1 to 1),
// then scale up.
// Find the vector from center to the point, then scale
// to a unit box.
Vec3<T> vec = pt - box.center();
T sizeX = box.max[0]-box.min[0];
T sizeY = box.max[1]-box.min[1];
T sizeZ = box.max[2]-box.min[2];
T halfX = sizeX/2.0;
T halfY = sizeY/2.0;
T halfZ = sizeZ/2.0;
if (halfX > 0.0)
vec[0] /= halfX;
if (halfY > 0.0)
vec[1] /= halfY;
if (halfZ > 0.0)
vec[2] /= halfZ;
// Side to snap side that has greatest magnitude in the vector.
Vec3<T> mag;
mag[0] = fabs(vec[0]);
mag[1] = fabs(vec[1]);
mag[2] = fabs(vec[2]);
result = mag;
// Check if beyond corners
if (result[0] > 1.0)
result[0] = 1.0;
if (result[1] > 1.0)
result[1] = 1.0;
if (result[2] > 1.0)
result[2] = 1.0;
// snap to appropriate side
if ((mag[0] > mag[1]) && (mag[0] > mag[2]))
{
result[0] = 1.0;
}
else if ((mag[1] > mag[0]) && (mag[1] > mag[2]))
{
result[1] = 1.0;
}
else if ((mag[2] > mag[0]) && (mag[2] > mag[1]))
{
result[2] = 1.0;
}
else if ((mag[0] == mag[1]) && (mag[0] == mag[2]))
{
// corner
result = Vec3<T>(1,1,1);
}
else if (mag[0] == mag[1])
{
// edge parallel with z
result[0] = 1.0;
result[1] = 1.0;
}
else if (mag[0] == mag[2])
{
// edge parallel with y
result[0] = 1.0;
result[2] = 1.0;
}
else if (mag[1] == mag[2])
{
// edge parallel with x
result[1] = 1.0;
result[2] = 1.0;
}
// Now make everything point the right way
for (int i=0; i < 3; i++)
{
if (vec[i] < 0.0)
result[i] = -result[i];
}
// scale back up and move to center
result[0] *= halfX;
result[1] *= halfY;
result[2] *= halfZ;
result += box.center();
}
return result;
}
template <class S, class T>
Box< Vec3<S> >
transform(const Box< Vec3<S> >& box, const Matrix44<T>& m)
{
// Transforms Box3f by matrix, enlarging Box3f to contain result.
// Clever method courtesy of Graphics Gems, pp. 548-550
//
// This works for projection matrices as well as simple affine
// transformations. Coordinates of the box are rehomogenized if there
// is a projection matrix
// a transformed empty box is still empty
if (box.isEmpty())
return box;
// If the last column is close enuf to ( 0 0 0 1 ) then we use the
// fast, affine version. The tricky affine method could maybe be
// extended to deal with the projection case as well, but its not
// worth it right now.
if (m[0][3] * m[0][3] + m[1][3] * m[1][3] + m[2][3] * m[2][3]
+ (1.0 - m[3][3]) * (1.0 - m[3][3]) < 0.00001)
{
// Affine version, use the Graphics Gems hack
int i, j;
Box< Vec3<S> > newBox;
for (i = 0; i < 3; i++)
{
newBox.min[i] = newBox.max[i] = (S) m[3][i];
for (j = 0; j < 3; j++)
{
float a, b;
a = (S) m[j][i] * box.min[j];
b = (S) m[j][i] * box.max[j];
if (a < b)
{
newBox.min[i] += a;
newBox.max[i] += b;
}
else
{
newBox.min[i] += b;
newBox.max[i] += a;
}
}
}
return newBox;
}
// This is a projection matrix. Do things the naive way.
Vec3<S> points[8];
/* Set up the eight points at the corners of the extent */
points[0][0] = points[1][0] = points[2][0] = points[3][0] = box.min[0];
points[4][0] = points[5][0] = points[6][0] = points[7][0] = box.max[0];
points[0][1] = points[1][1] = points[4][1] = points[5][1] = box.min[1];
points[2][1] = points[3][1] = points[6][1] = points[7][1] = box.max[1];
points[0][2] = points[2][2] = points[4][2] = points[6][2] = box.min[2];
points[1][2] = points[3][2] = points[5][2] = points[7][2] = box.max[2];
Box< Vec3<S> > newBox;
for (int i = 0; i < 8; i++)
newBox.extendBy(points[i] * m);
return newBox;
}
template <class T>
Box< Vec3<T> >
affineTransform(const Box< Vec3<T> > &bbox, const Matrix44<T> &M)
{
float min0, max0, min1, max1, min2, max2, a, b;
float min0new, max0new, min1new, max1new, min2new, max2new;
min0 = bbox.min[0];
max0 = bbox.max[0];
min1 = bbox.min[1];
max1 = bbox.max[1];
min2 = bbox.min[2];
max2 = bbox.max[2];
min0new = max0new = M[3][0];
a = M[0][0] * min0;
b = M[0][0] * max0;
if (a < b) {
min0new += a;
max0new += b;
} else {
min0new += b;
max0new += a;
}
a = M[1][0] * min1;
b = M[1][0] * max1;
if (a < b) {
min0new += a;
max0new += b;
} else {
min0new += b;
max0new += a;
}
a = M[2][0] * min2;
b = M[2][0] * max2;
if (a < b) {
min0new += a;
max0new += b;
} else {
min0new += b;
max0new += a;
}
min1new = max1new = M[3][1];
a = M[0][1] * min0;
b = M[0][1] * max0;
if (a < b) {
min1new += a;
max1new += b;
} else {
min1new += b;
max1new += a;
}
a = M[1][1] * min1;
b = M[1][1] * max1;
if (a < b) {
min1new += a;
max1new += b;
} else {
min1new += b;
max1new += a;
}
a = M[2][1] * min2;
b = M[2][1] * max2;
if (a < b) {
min1new += a;
max1new += b;
} else {
min1new += b;
max1new += a;
}
min2new = max2new = M[3][2];
a = M[0][2] * min0;
b = M[0][2] * max0;
if (a < b) {
min2new += a;
max2new += b;
} else {
min2new += b;
max2new += a;
}
a = M[1][2] * min1;
b = M[1][2] * max1;
if (a < b) {
min2new += a;
max2new += b;
} else {
min2new += b;
max2new += a;
}
a = M[2][2] * min2;
b = M[2][2] * max2;
if (a < b) {
min2new += a;
max2new += b;
} else {
min2new += b;
max2new += a;
}
Box< Vec3<T> > xbbox;
xbbox.min[0] = min0new;
xbbox.max[0] = max0new;
xbbox.min[1] = min1new;
xbbox.max[1] = max1new;
xbbox.min[2] = min2new;
xbbox.max[2] = max2new;
return xbbox;
}
template <class T>
bool findEntryAndExitPoints(const Line3<T>& line,
const Box<Vec3<T> >& box,
Vec3<T> &enterPoint,
Vec3<T> &exitPoint)
{
if ( box.isEmpty() ) return false;
if ( line.distanceTo(box.center()) > box.size().length()/2. ) return false;
Vec3<T> points[8], inter, bary;
Plane3<T> plane;
int i, v0, v1, v2;
bool front = false, valid, validIntersection = false;
// set up the eight coords of the corners of the box
for(i = 0; i < 8; i++)
{
points[i].setValue( i & 01 ? box.min[0] : box.max[0],
i & 02 ? box.min[1] : box.max[1],
i & 04 ? box.min[2] : box.max[2]);
}
// intersect the 12 triangles.
for(i = 0; i < 12; i++)
{
switch(i)
{
case 0: v0 = 2; v1 = 1; v2 = 0; break; // +z
case 1: v0 = 2; v1 = 3; v2 = 1; break;
case 2: v0 = 4; v1 = 5; v2 = 6; break; // -z
case 3: v0 = 6; v1 = 5; v2 = 7; break;
case 4: v0 = 0; v1 = 6; v2 = 2; break; // -x
case 5: v0 = 0; v1 = 4; v2 = 6; break;
case 6: v0 = 1; v1 = 3; v2 = 7; break; // +x
case 7: v0 = 1; v1 = 7; v2 = 5; break;
case 8: v0 = 1; v1 = 4; v2 = 0; break; // -y
case 9: v0 = 1; v1 = 5; v2 = 4; break;
case 10: v0 = 2; v1 = 7; v2 = 3; break; // +y
case 11: v0 = 2; v1 = 6; v2 = 7; break;
}
if((valid=intersect (line, points[v0], points[v1], points[v2],
inter, bary, front)) == true)
{
if(front == true)
{
enterPoint = inter;
validIntersection = valid;
}
else
{
exitPoint = inter;
validIntersection = valid;
}
}
}
return validIntersection;
}
template<class T>
bool intersects(const Box< Vec3<T> > &box,
const Line3<T> &line,
Vec3<T> &result)
{
/*
Fast Ray-Box Intersection
by Andrew Woo
from "Graphics Gems", Academic Press, 1990
*/
const int right = 0;
const int left = 1;
const int middle = 2;
const Vec3<T> &minB = box.min;
const Vec3<T> &maxB = box.max;
const Vec3<T> &origin = line.pos;
const Vec3<T> &dir = line.dir;
bool inside = true;
char quadrant[3];
int whichPlane;
float maxT[3];
float candidatePlane[3];
/* Find candidate planes; this loop can be avoided if
rays cast all from the eye(assume perpsective view) */
for (int i=0; i<3; i++)
{
if(origin[i] < minB[i])
{
quadrant[i] = left;
candidatePlane[i] = minB[i];
inside = false;
}
else if (origin[i] > maxB[i])
{
quadrant[i] = right;
candidatePlane[i] = maxB[i];
inside = false;
}
else
{
quadrant[i] = middle;
}
}
/* Ray origin inside bounding box */
if ( inside )
{
result = origin;
return true;
}
/* Calculate T distances to candidate planes */
for (int i = 0; i < 3; i++)
{
if (quadrant[i] != middle && dir[i] !=0.)
{
maxT[i] = (candidatePlane[i]-origin[i]) / dir[i];
}
else
{
maxT[i] = -1.;
}
}
/* Get largest of the maxT's for final choice of intersection */
whichPlane = 0;
for (int i = 1; i < 3; i++)
{
if (maxT[whichPlane] < maxT[i])
{
whichPlane = i;
}
}
/* Check final candidate actually inside box */
if (maxT[whichPlane] < 0.) return false;
for (int i = 0; i < 3; i++)
{
if (whichPlane != i)
{
result[i] = origin[i] + maxT[whichPlane] *dir[i];
if ((quadrant[i] == right && result[i] < minB[i]) ||
(quadrant[i] == left && result[i] > maxB[i]))
{
return false; /* outside box */
}
}
else
{
result[i] = candidatePlane[i];
}
}
return true;
}
template<class T>
bool intersects(const Box< Vec3<T> > &box, const Line3<T> &line)
{
Vec3<T> ignored;
return intersects(box,line,ignored);
}
} // namespace Imath
#endif

734
3rdparty/include/OpenEXR/ImathColor.h vendored Normal file
View File

@ -0,0 +1,734 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHCOLOR_H
#define INCLUDED_IMATHCOLOR_H
//----------------------------------------------------
//
// A three and four component color class template.
//
//----------------------------------------------------
#include "ImathVec.h"
#include "half.h"
namespace Imath {
template <class T>
class Color3: public Vec3 <T>
{
public:
//-------------
// Constructors
//-------------
Color3 (); // no initialization
explicit Color3 (T a); // (a a a)
Color3 (T a, T b, T c); // (a b c)
//---------------------------------
// Copy constructors and assignment
//---------------------------------
Color3 (const Color3 &c);
template <class S> Color3 (const Vec3<S> &v);
const Color3 & operator = (const Color3 &c);
//------------------------
// Component-wise addition
//------------------------
const Color3 & operator += (const Color3 &c);
Color3 operator + (const Color3 &c) const;
//---------------------------
// Component-wise subtraction
//---------------------------
const Color3 & operator -= (const Color3 &c);
Color3 operator - (const Color3 &c) const;
//------------------------------------
// Component-wise multiplication by -1
//------------------------------------
Color3 operator - () const;
const Color3 & negate ();
//------------------------------
// Component-wise multiplication
//------------------------------
const Color3 & operator *= (const Color3 &c);
const Color3 & operator *= (T a);
Color3 operator * (const Color3 &c) const;
Color3 operator * (T a) const;
//------------------------
// Component-wise division
//------------------------
const Color3 & operator /= (const Color3 &c);
const Color3 & operator /= (T a);
Color3 operator / (const Color3 &c) const;
Color3 operator / (T a) const;
};
template <class T> class Color4
{
public:
//-------------------
// Access to elements
//-------------------
T r, g, b, a;
T & operator [] (int i);
const T & operator [] (int i) const;
//-------------
// Constructors
//-------------
Color4 (); // no initialization
explicit Color4 (T a); // (a a a a)
Color4 (T a, T b, T c, T d); // (a b c d)
//---------------------------------
// Copy constructors and assignment
//---------------------------------
Color4 (const Color4 &v);
template <class S> Color4 (const Color4<S> &v);
const Color4 & operator = (const Color4 &v);
//----------------------
// Compatibility with Sb
//----------------------
template <class S>
void setValue (S a, S b, S c, S d);
template <class S>
void setValue (const Color4<S> &v);
template <class S>
void getValue (S &a, S &b, S &c, S &d) const;
template <class S>
void getValue (Color4<S> &v) const;
T * getValue();
const T * getValue() const;
//---------
// Equality
//---------
template <class S>
bool operator == (const Color4<S> &v) const;
template <class S>
bool operator != (const Color4<S> &v) const;
//------------------------
// Component-wise addition
//------------------------
const Color4 & operator += (const Color4 &v);
Color4 operator + (const Color4 &v) const;
//---------------------------
// Component-wise subtraction
//---------------------------
const Color4 & operator -= (const Color4 &v);
Color4 operator - (const Color4 &v) const;
//------------------------------------
// Component-wise multiplication by -1
//------------------------------------
Color4 operator - () const;
const Color4 & negate ();
//------------------------------
// Component-wise multiplication
//------------------------------
const Color4 & operator *= (const Color4 &v);
const Color4 & operator *= (T a);
Color4 operator * (const Color4 &v) const;
Color4 operator * (T a) const;
//------------------------
// Component-wise division
//------------------------
const Color4 & operator /= (const Color4 &v);
const Color4 & operator /= (T a);
Color4 operator / (const Color4 &v) const;
Color4 operator / (T a) const;
//----------------------------------------------------------
// Number of dimensions, i.e. number of elements in a Color4
//----------------------------------------------------------
static unsigned int dimensions() {return 4;}
//-------------------------------------------------
// Limitations of type T (see also class limits<T>)
//-------------------------------------------------
static T baseTypeMin() {return limits<T>::min();}
static T baseTypeMax() {return limits<T>::max();}
static T baseTypeSmallest() {return limits<T>::smallest();}
static T baseTypeEpsilon() {return limits<T>::epsilon();}
//--------------------------------------------------------------
// Base type -- in templates, which accept a parameter, V, which
// could be a Color4<T>, you can refer to T as
// V::BaseType
//--------------------------------------------------------------
typedef T BaseType;
};
//--------------
// Stream output
//--------------
template <class T>
std::ostream & operator << (std::ostream &s, const Color4<T> &v);
//----------------------------------------------------
// Reverse multiplication: S * Color4<T>
//----------------------------------------------------
template <class S, class T> Color4<T> operator * (S a, const Color4<T> &v);
//-------------------------
// Typedefs for convenience
//-------------------------
typedef Color3<float> Color3f;
typedef Color3<half> Color3h;
typedef Color3<unsigned char> Color3c;
typedef Color3<half> C3h;
typedef Color3<float> C3f;
typedef Color3<unsigned char> C3c;
typedef Color4<float> Color4f;
typedef Color4<half> Color4h;
typedef Color4<unsigned char> Color4c;
typedef Color4<float> C4f;
typedef Color4<half> C4h;
typedef Color4<unsigned char> C4c;
typedef unsigned int PackedColor;
//-------------------------
// Implementation of Color3
//-------------------------
template <class T>
inline
Color3<T>::Color3 (): Vec3 <T> ()
{
// empty
}
template <class T>
inline
Color3<T>::Color3 (T a): Vec3 <T> (a)
{
// empty
}
template <class T>
inline
Color3<T>::Color3 (T a, T b, T c): Vec3 <T> (a, b, c)
{
// empty
}
template <class T>
inline
Color3<T>::Color3 (const Color3 &c): Vec3 <T> (c)
{
// empty
}
template <class T>
template <class S>
inline
Color3<T>::Color3 (const Vec3<S> &v): Vec3 <T> (v)
{
//empty
}
template <class T>
inline const Color3<T> &
Color3<T>::operator = (const Color3 &c)
{
*((Vec3<T> *) this) = c;
return *this;
}
template <class T>
inline const Color3<T> &
Color3<T>::operator += (const Color3 &c)
{
*((Vec3<T> *) this) += c;
return *this;
}
template <class T>
inline Color3<T>
Color3<T>::operator + (const Color3 &c) const
{
return Color3 (*(Vec3<T> *)this + (const Vec3<T> &)c);
}
template <class T>
inline const Color3<T> &
Color3<T>::operator -= (const Color3 &c)
{
*((Vec3<T> *) this) -= c;
return *this;
}
template <class T>
inline Color3<T>
Color3<T>::operator - (const Color3 &c) const
{
return Color3 (*(Vec3<T> *)this - (const Vec3<T> &)c);
}
template <class T>
inline Color3<T>
Color3<T>::operator - () const
{
return Color3 (-(*(Vec3<T> *)this));
}
template <class T>
inline const Color3<T> &
Color3<T>::negate ()
{
((Vec3<T> *) this)->negate();
return *this;
}
template <class T>
inline const Color3<T> &
Color3<T>::operator *= (const Color3 &c)
{
*((Vec3<T> *) this) *= c;
return *this;
}
template <class T>
inline const Color3<T> &
Color3<T>::operator *= (T a)
{
*((Vec3<T> *) this) *= a;
return *this;
}
template <class T>
inline Color3<T>
Color3<T>::operator * (const Color3 &c) const
{
return Color3 (*(Vec3<T> *)this * (const Vec3<T> &)c);
}
template <class T>
inline Color3<T>
Color3<T>::operator * (T a) const
{
return Color3 (*(Vec3<T> *)this * a);
}
template <class T>
inline const Color3<T> &
Color3<T>::operator /= (const Color3 &c)
{
*((Vec3<T> *) this) /= c;
return *this;
}
template <class T>
inline const Color3<T> &
Color3<T>::operator /= (T a)
{
*((Vec3<T> *) this) /= a;
return *this;
}
template <class T>
inline Color3<T>
Color3<T>::operator / (const Color3 &c) const
{
return Color3 (*(Vec3<T> *)this / (const Vec3<T> &)c);
}
template <class T>
inline Color3<T>
Color3<T>::operator / (T a) const
{
return Color3 (*(Vec3<T> *)this / a);
}
//-----------------------
// Implementation of Color4
//-----------------------
template <class T>
inline T &
Color4<T>::operator [] (int i)
{
return (&r)[i];
}
template <class T>
inline const T &
Color4<T>::operator [] (int i) const
{
return (&r)[i];
}
template <class T>
inline
Color4<T>::Color4 ()
{
// empty
}
template <class T>
inline
Color4<T>::Color4 (T x)
{
r = g = b = a = x;
}
template <class T>
inline
Color4<T>::Color4 (T x, T y, T z, T w)
{
r = x;
g = y;
b = z;
a = w;
}
template <class T>
inline
Color4<T>::Color4 (const Color4 &v)
{
r = v.r;
g = v.g;
b = v.b;
a = v.a;
}
template <class T>
template <class S>
inline
Color4<T>::Color4 (const Color4<S> &v)
{
r = T (v.r);
g = T (v.g);
b = T (v.b);
a = T (v.a);
}
template <class T>
inline const Color4<T> &
Color4<T>::operator = (const Color4 &v)
{
r = v.r;
g = v.g;
b = v.b;
a = v.a;
return *this;
}
template <class T>
template <class S>
inline void
Color4<T>::setValue (S x, S y, S z, S w)
{
r = T (x);
g = T (y);
b = T (z);
a = T (w);
}
template <class T>
template <class S>
inline void
Color4<T>::setValue (const Color4<S> &v)
{
r = T (v.r);
g = T (v.g);
b = T (v.b);
a = T (v.a);
}
template <class T>
template <class S>
inline void
Color4<T>::getValue (S &x, S &y, S &z, S &w) const
{
x = S (r);
y = S (g);
z = S (b);
w = S (a);
}
template <class T>
template <class S>
inline void
Color4<T>::getValue (Color4<S> &v) const
{
v.r = S (r);
v.g = S (g);
v.b = S (b);
v.a = S (a);
}
template <class T>
inline T *
Color4<T>::getValue()
{
return (T *) &r;
}
template <class T>
inline const T *
Color4<T>::getValue() const
{
return (const T *) &r;
}
template <class T>
template <class S>
inline bool
Color4<T>::operator == (const Color4<S> &v) const
{
return r == v.r && g == v.g && b == v.b && a == v.a;
}
template <class T>
template <class S>
inline bool
Color4<T>::operator != (const Color4<S> &v) const
{
return r != v.r || g != v.g || b != v.b || a != v.a;
}
template <class T>
inline const Color4<T> &
Color4<T>::operator += (const Color4 &v)
{
r += v.r;
g += v.g;
b += v.b;
a += v.a;
return *this;
}
template <class T>
inline Color4<T>
Color4<T>::operator + (const Color4 &v) const
{
return Color4 (r + v.r, g + v.g, b + v.b, a + v.a);
}
template <class T>
inline const Color4<T> &
Color4<T>::operator -= (const Color4 &v)
{
r -= v.r;
g -= v.g;
b -= v.b;
a -= v.a;
return *this;
}
template <class T>
inline Color4<T>
Color4<T>::operator - (const Color4 &v) const
{
return Color4 (r - v.r, g - v.g, b - v.b, a - v.a);
}
template <class T>
inline Color4<T>
Color4<T>::operator - () const
{
return Color4 (-r, -g, -b, -a);
}
template <class T>
inline const Color4<T> &
Color4<T>::negate ()
{
r = -r;
g = -g;
b = -b;
a = -a;
return *this;
}
template <class T>
inline const Color4<T> &
Color4<T>::operator *= (const Color4 &v)
{
r *= v.r;
g *= v.g;
b *= v.b;
a *= v.a;
return *this;
}
template <class T>
inline const Color4<T> &
Color4<T>::operator *= (T x)
{
r *= x;
g *= x;
b *= x;
a *= x;
return *this;
}
template <class T>
inline Color4<T>
Color4<T>::operator * (const Color4 &v) const
{
return Color4 (r * v.r, g * v.g, b * v.b, a * v.a);
}
template <class T>
inline Color4<T>
Color4<T>::operator * (T x) const
{
return Color4 (r * x, g * x, b * x, a * x);
}
template <class T>
inline const Color4<T> &
Color4<T>::operator /= (const Color4 &v)
{
r /= v.r;
g /= v.g;
b /= v.b;
a /= v.a;
return *this;
}
template <class T>
inline const Color4<T> &
Color4<T>::operator /= (T x)
{
r /= x;
g /= x;
b /= x;
a /= x;
return *this;
}
template <class T>
inline Color4<T>
Color4<T>::operator / (const Color4 &v) const
{
return Color4 (r / v.r, g / v.g, b / v.b, a / v.a);
}
template <class T>
inline Color4<T>
Color4<T>::operator / (T x) const
{
return Color4 (r / x, g / x, b / x, a / x);
}
template <class T>
std::ostream &
operator << (std::ostream &s, const Color4<T> &v)
{
return s << '(' << v.r << ' ' << v.g << ' ' << v.b << ' ' << v.a << ')';
}
//-----------------------------------------
// Implementation of reverse multiplication
//-----------------------------------------
template <class S, class T>
inline Color4<T>
operator * (S x, const Color4<T> &v)
{
return Color4<T> (x * v.r, x * v.g, x * v.b, x * v.a);
}
} // namespace Imath
#endif

View File

@ -0,0 +1,256 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHCOLORALGO_H
#define INCLUDED_IMATHCOLORALGO_H
#include "ImathColor.h"
#include "ImathMath.h"
#include "ImathLimits.h"
namespace Imath {
//
// Non-templated helper routines for color conversion.
// These routines eliminate type warnings under g++.
//
Vec3<double> hsv2rgb_d(const Vec3<double> &hsv);
Color4<double> hsv2rgb_d(const Color4<double> &hsv);
Vec3<double> rgb2hsv_d(const Vec3<double> &rgb);
Color4<double> rgb2hsv_d(const Color4<double> &rgb);
//
// Color conversion functions and general color algorithms
//
// hsv2rgb(), rgb2hsv(), rgb2packed(), packed2rgb()
// see each funtion definition for details.
//
template<class T>
Vec3<T>
hsv2rgb(const Vec3<T> &hsv)
{
if ( limits<T>::isIntegral() )
{
Vec3<double> v = Vec3<double>(hsv.x / double(limits<T>::max()),
hsv.y / double(limits<T>::max()),
hsv.z / double(limits<T>::max()));
Vec3<double> c = hsv2rgb_d(v);
return Vec3<T>((T) (c.x * limits<T>::max()),
(T) (c.y * limits<T>::max()),
(T) (c.z * limits<T>::max()));
}
else
{
Vec3<double> v = Vec3<double>(hsv.x, hsv.y, hsv.z);
Vec3<double> c = hsv2rgb_d(v);
return Vec3<T>((T) c.x, (T) c.y, (T) c.z);
}
}
template<class T>
Color4<T>
hsv2rgb(const Color4<T> &hsv)
{
if ( limits<T>::isIntegral() )
{
Color4<double> v = Color4<double>(hsv.r / float(limits<T>::max()),
hsv.g / float(limits<T>::max()),
hsv.b / float(limits<T>::max()),
hsv.a / float(limits<T>::max()));
Color4<double> c = hsv2rgb_d(v);
return Color4<T>((T) (c.r * limits<T>::max()),
(T) (c.g * limits<T>::max()),
(T) (c.b * limits<T>::max()),
(T) (c.a * limits<T>::max()));
}
else
{
Color4<double> v = Color4<double>(hsv.r, hsv.g, hsv.g, hsv.a);
Color4<double> c = hsv2rgb_d(v);
return Color4<T>((T) c.r, (T) c.g, (T) c.b, (T) c.a);
}
}
template<class T>
Vec3<T>
rgb2hsv(const Vec3<T> &rgb)
{
if ( limits<T>::isIntegral() )
{
Vec3<double> v = Vec3<double>(rgb.x / double(limits<T>::max()),
rgb.y / double(limits<T>::max()),
rgb.z / double(limits<T>::max()));
Vec3<double> c = rgb2hsv_d(v);
return Vec3<T>((T) (c.x * limits<T>::max()),
(T) (c.y * limits<T>::max()),
(T) (c.z * limits<T>::max()));
}
else
{
Vec3<double> v = Vec3<double>(rgb.x, rgb.y, rgb.z);
Vec3<double> c = rgb2hsv_d(v);
return Vec3<T>((T) c.x, (T) c.y, (T) c.z);
}
}
template<class T>
Color4<T>
rgb2hsv(const Color4<T> &rgb)
{
if ( limits<T>::isIntegral() )
{
Color4<double> v = Color4<double>(rgb.r / float(limits<T>::max()),
rgb.g / float(limits<T>::max()),
rgb.b / float(limits<T>::max()),
rgb.a / float(limits<T>::max()));
Color4<double> c = rgb2hsv_d(v);
return Color4<T>((T) (c.r * limits<T>::max()),
(T) (c.g * limits<T>::max()),
(T) (c.b * limits<T>::max()),
(T) (c.a * limits<T>::max()));
}
else
{
Color4<double> v = Color4<double>(rgb.r, rgb.g, rgb.g, rgb.a);
Color4<double> c = rgb2hsv_d(v);
return Color4<T>((T) c.r, (T) c.g, (T) c.b, (T) c.a);
}
}
template <class T>
PackedColor
rgb2packed(const Vec3<T> &c)
{
if ( limits<T>::isIntegral() )
{
float x = c.x / float(limits<T>::max());
float y = c.y / float(limits<T>::max());
float z = c.z / float(limits<T>::max());
return rgb2packed( V3f(x,y,z) );
}
else
{
return ( (PackedColor) (c.x * 255) |
(((PackedColor) (c.y * 255)) << 8) |
(((PackedColor) (c.z * 255)) << 16) | 0xFF000000 );
}
}
template <class T>
PackedColor
rgb2packed(const Color4<T> &c)
{
if ( limits<T>::isIntegral() )
{
float r = c.r / float(limits<T>::max());
float g = c.g / float(limits<T>::max());
float b = c.b / float(limits<T>::max());
float a = c.a / float(limits<T>::max());
return rgb2packed( C4f(r,g,b,a) );
}
else
{
return ( (PackedColor) (c.r * 255) |
(((PackedColor) (c.g * 255)) << 8) |
(((PackedColor) (c.b * 255)) << 16) |
(((PackedColor) (c.a * 255)) << 24));
}
}
//
// This guy can't return the result because the template
// parameter would not be in the function signiture. So instead,
// its passed in as an argument.
//
template <class T>
void
packed2rgb(PackedColor packed, Vec3<T> &out)
{
if ( limits<T>::isIntegral() )
{
T f = limits<T>::max() / ((PackedColor)0xFF);
out.x = (packed & 0xFF) * f;
out.y = ((packed & 0xFF00) >> 8) * f;
out.z = ((packed & 0xFF0000) >> 16) * f;
}
else
{
T f = T(1) / T(255);
out.x = (packed & 0xFF) * f;
out.y = ((packed & 0xFF00) >> 8) * f;
out.z = ((packed & 0xFF0000) >> 16) * f;
}
}
template <class T>
void
packed2rgb(PackedColor packed, Color4<T> &out)
{
if ( limits<T>::isIntegral() )
{
T f = limits<T>::max() / ((PackedColor)0xFF);
out.r = (packed & 0xFF) * f;
out.g = ((packed & 0xFF00) >> 8) * f;
out.b = ((packed & 0xFF0000) >> 16) * f;
out.a = ((packed & 0xFF000000) >> 24) * f;
}
else
{
T f = T(1) / T(255);
out.r = (packed & 0xFF) * f;
out.g = ((packed & 0xFF00) >> 8) * f;
out.b = ((packed & 0xFF0000) >> 16) * f;
out.a = ((packed & 0xFF000000) >> 24) * f;
}
}
} // namespace Imath
#endif

903
3rdparty/include/OpenEXR/ImathEuler.h vendored Normal file
View File

@ -0,0 +1,903 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHEULER_H
#define INCLUDED_IMATHEULER_H
//----------------------------------------------------------------------
//
// template class Euler<T>
//
// This class represents euler angle orientations. The class
// inherits from Vec3 to it can be freely cast. The additional
// information is the euler priorities rep. This class is
// essentially a rip off of Ken Shoemake's GemsIV code. It has
// been modified minimally to make it more understandable, but
// hardly enough to make it easy to grok completely.
//
// There are 24 possible combonations of Euler angle
// representations of which 12 are common in CG and you will
// probably only use 6 of these which in this scheme are the
// non-relative-non-repeating types.
//
// The representations can be partitioned according to two
// criteria:
//
// 1) Are the angles measured relative to a set of fixed axis
// or relative to each other (the latter being what happens
// when rotation matrices are multiplied together and is
// almost ubiquitous in the cg community)
//
// 2) Is one of the rotations repeated (ala XYX rotation)
//
// When you construct a given representation from scratch you
// must order the angles according to their priorities. So, the
// easiest is a softimage or aerospace (yaw/pitch/roll) ordering
// of ZYX.
//
// float x_rot = 1;
// float y_rot = 2;
// float z_rot = 3;
//
// Eulerf angles(z_rot, y_rot, x_rot, Eulerf::ZYX);
// -or-
// Eulerf angles( V3f(z_rot,y_rot,z_rot), Eulerf::ZYX );
//
// If instead, the order was YXZ for instance you would have to
// do this:
//
// float x_rot = 1;
// float y_rot = 2;
// float z_rot = 3;
//
// Eulerf angles(y_rot, x_rot, z_rot, Eulerf::YXZ);
// -or-
// Eulerf angles( V3f(y_rot,x_rot,z_rot), Eulerf::YXZ );
//
// Notice how the order you put the angles into the three slots
// should correspond to the enum (YXZ) ordering. The input angle
// vector is called the "ijk" vector -- not an "xyz" vector. The
// ijk vector order is the same as the enum. If you treat the
// Euler<> as a Vec<> (which it inherts from) you will find the
// angles are ordered in the same way, i.e.:
//
// V3f v = angles;
// // v.x == y_rot, v.y == x_rot, v.z == z_rot
//
// If you just want the x, y, and z angles stored in a vector in
// that order, you can do this:
//
// V3f v = angles.toXYZVector()
// // v.x == x_rot, v.y == y_rot, v.z == z_rot
//
// If you want to set the Euler with an XYZVector use the
// optional layout argument:
//
// Eulerf angles(x_rot, y_rot, z_rot,
// Eulerf::YXZ,
// Eulerf::XYZLayout);
//
// This is the same as:
//
// Eulerf angles(y_rot, x_rot, z_rot, Eulerf::YXZ);
//
// Note that this won't do anything intelligent if you have a
// repeated axis in the euler angles (e.g. XYX)
//
// If you need to use the "relative" versions of these, you will
// need to use the "r" enums.
//
// The units of the rotation angles are assumed to be radians.
//
//----------------------------------------------------------------------
#include "ImathMath.h"
#include "ImathVec.h"
#include "ImathQuat.h"
#include "ImathMatrix.h"
#include "ImathLimits.h"
#include <iostream>
namespace Imath {
#if (defined _WIN32 || defined _WIN64) && defined _MSC_VER
// Disable MS VC++ warnings about conversion from double to float
#pragma warning(disable:4244)
#endif
template <class T>
class Euler : public Vec3<T>
{
public:
using Vec3<T>::x;
using Vec3<T>::y;
using Vec3<T>::z;
enum Order
{
//
// All 24 possible orderings
//
XYZ = 0x0101, // "usual" orderings
XZY = 0x0001,
YZX = 0x1101,
YXZ = 0x1001,
ZXY = 0x2101,
ZYX = 0x2001,
XZX = 0x0011, // first axis repeated
XYX = 0x0111,
YXY = 0x1011,
YZY = 0x1111,
ZYZ = 0x2011,
ZXZ = 0x2111,
XYZr = 0x2000, // relative orderings -- not common
XZYr = 0x2100,
YZXr = 0x1000,
YXZr = 0x1100,
ZXYr = 0x0000,
ZYXr = 0x0100,
XZXr = 0x2110, // relative first axis repeated
XYXr = 0x2010,
YXYr = 0x1110,
YZYr = 0x1010,
ZYZr = 0x0110,
ZXZr = 0x0010,
// ||||
// VVVV
// Legend: ABCD
// A -> Initial Axis (0==x, 1==y, 2==z)
// B -> Parity Even (1==true)
// C -> Initial Repeated (1==true)
// D -> Frame Static (1==true)
//
Legal = XYZ | XZY | YZX | YXZ | ZXY | ZYX |
XZX | XYX | YXY | YZY | ZYZ | ZXZ |
XYZr| XZYr| YZXr| YXZr| ZXYr| ZYXr|
XZXr| XYXr| YXYr| YZYr| ZYZr| ZXZr,
Min = 0x0000,
Max = 0x2111,
Default = XYZ
};
enum Axis { X = 0, Y = 1, Z = 2 };
enum InputLayout { XYZLayout, IJKLayout };
//----------------------------------------------------------------
// Constructors -- all default to ZYX non-relative ala softimage
// (where there is no argument to specify it)
//----------------------------------------------------------------
Euler();
Euler(const Euler&);
Euler(Order p);
Euler(const Vec3<T> &v, Order o = Default, InputLayout l = IJKLayout);
Euler(T i, T j, T k, Order o = Default, InputLayout l = IJKLayout);
Euler(const Euler<T> &euler, Order newp);
Euler(const Matrix33<T> &, Order o = Default);
Euler(const Matrix44<T> &, Order o = Default);
//---------------------------------
// Algebraic functions/ Operators
//---------------------------------
const Euler<T>& operator= (const Euler<T>&);
const Euler<T>& operator= (const Vec3<T>&);
//--------------------------------------------------------
// Set the euler value
// This does NOT convert the angles, but setXYZVector()
// does reorder the input vector.
//--------------------------------------------------------
static bool legal(Order);
void setXYZVector(const Vec3<T> &);
Order order() const;
void setOrder(Order);
void set(Axis initial,
bool relative,
bool parityEven,
bool firstRepeats);
//---------------------------------------------------------
// Conversions, toXYZVector() reorders the angles so that
// the X rotation comes first, followed by the Y and Z
// in cases like XYX ordering, the repeated angle will be
// in the "z" component
//---------------------------------------------------------
void extract(const Matrix33<T>&);
void extract(const Matrix44<T>&);
void extract(const Quat<T>&);
Matrix33<T> toMatrix33() const;
Matrix44<T> toMatrix44() const;
Quat<T> toQuat() const;
Vec3<T> toXYZVector() const;
//---------------------------------------------------
// Use this function to unpack angles from ijk form
//---------------------------------------------------
void angleOrder(int &i, int &j, int &k) const;
//---------------------------------------------------
// Use this function to determine mapping from xyz to ijk
// - reshuffles the xyz to match the order
//---------------------------------------------------
void angleMapping(int &i, int &j, int &k) const;
//----------------------------------------------------------------------
//
// Utility methods for getting continuous rotations. None of these
// methods change the orientation given by its inputs (or at least
// that is the intent).
//
// angleMod() converts an angle to its equivalent in [-PI, PI]
//
// simpleXYZRotation() adjusts xyzRot so that its components differ
// from targetXyzRot by no more than +-PI
//
// nearestRotation() adjusts xyzRot so that its components differ
// from targetXyzRot by as little as possible.
// Note that xyz here really means ijk, because
// the order must be provided.
//
// makeNear() adjusts "this" Euler so that its components differ
// from target by as little as possible. This method
// might not make sense for Eulers with different order
// and it probably doesn't work for repeated axis and
// relative orderings (TODO).
//
//-----------------------------------------------------------------------
static float angleMod (T angle);
static void simpleXYZRotation (Vec3<T> &xyzRot,
const Vec3<T> &targetXyzRot);
static void nearestRotation (Vec3<T> &xyzRot,
const Vec3<T> &targetXyzRot,
Order order = XYZ);
void makeNear (const Euler<T> &target);
bool frameStatic() const { return _frameStatic; }
bool initialRepeated() const { return _initialRepeated; }
bool parityEven() const { return _parityEven; }
Axis initialAxis() const { return _initialAxis; }
protected:
bool _frameStatic : 1; // relative or static rotations
bool _initialRepeated : 1; // init axis repeated as last
bool _parityEven : 1; // "parity of axis permutation"
#if defined _WIN32 || defined _WIN64
Axis _initialAxis ; // First axis of rotation
#else
Axis _initialAxis : 2; // First axis of rotation
#endif
};
//--------------------
// Convenient typedefs
//--------------------
typedef Euler<float> Eulerf;
typedef Euler<double> Eulerd;
//---------------
// Implementation
//---------------
template<class T>
inline void
Euler<T>::angleOrder(int &i, int &j, int &k) const
{
i = _initialAxis;
j = _parityEven ? (i+1)%3 : (i > 0 ? i-1 : 2);
k = _parityEven ? (i > 0 ? i-1 : 2) : (i+1)%3;
}
template<class T>
inline void
Euler<T>::angleMapping(int &i, int &j, int &k) const
{
int m[3];
m[_initialAxis] = 0;
m[(_initialAxis+1) % 3] = _parityEven ? 1 : 2;
m[(_initialAxis+2) % 3] = _parityEven ? 2 : 1;
i = m[0];
j = m[1];
k = m[2];
}
template<class T>
inline void
Euler<T>::setXYZVector(const Vec3<T> &v)
{
int i,j,k;
angleMapping(i,j,k);
(*this)[i] = v.x;
(*this)[j] = v.y;
(*this)[k] = v.z;
}
template<class T>
inline Vec3<T>
Euler<T>::toXYZVector() const
{
int i,j,k;
angleMapping(i,j,k);
return Vec3<T>((*this)[i],(*this)[j],(*this)[k]);
}
template<class T>
Euler<T>::Euler() :
Vec3<T>(0,0,0),
_frameStatic(true),
_initialRepeated(false),
_parityEven(true),
_initialAxis(X)
{}
template<class T>
Euler<T>::Euler(typename Euler<T>::Order p) :
Vec3<T>(0,0,0),
_frameStatic(true),
_initialRepeated(false),
_parityEven(true),
_initialAxis(X)
{
setOrder(p);
}
template<class T>
inline Euler<T>::Euler( const Vec3<T> &v,
typename Euler<T>::Order p,
typename Euler<T>::InputLayout l )
{
setOrder(p);
if ( l == XYZLayout ) setXYZVector(v);
else { x = v.x; y = v.y; z = v.z; }
}
template<class T>
inline Euler<T>::Euler(const Euler<T> &euler)
{
operator=(euler);
}
template<class T>
inline Euler<T>::Euler(const Euler<T> &euler,Order p)
{
setOrder(p);
Matrix33<T> M = euler.toMatrix33();
extract(M);
}
template<class T>
inline Euler<T>::Euler( T xi, T yi, T zi,
typename Euler<T>::Order p,
typename Euler<T>::InputLayout l)
{
setOrder(p);
if ( l == XYZLayout ) setXYZVector(Vec3<T>(xi,yi,zi));
else { x = xi; y = yi; z = zi; }
}
template<class T>
inline Euler<T>::Euler( const Matrix33<T> &M, typename Euler::Order p )
{
setOrder(p);
extract(M);
}
template<class T>
inline Euler<T>::Euler( const Matrix44<T> &M, typename Euler::Order p )
{
setOrder(p);
extract(M);
}
template<class T>
inline void Euler<T>::extract(const Quat<T> &q)
{
extract(q.toMatrix33());
}
template<class T>
void Euler<T>::extract(const Matrix33<T> &M)
{
int i,j,k;
angleOrder(i,j,k);
if (_initialRepeated)
{
//
// Extract the first angle, x.
//
x = Math<T>::atan2 (M[j][i], M[k][i]);
//
// Remove the x rotation from M, so that the remaining
// rotation, N, is only around two axes, and gimbal lock
// cannot occur.
//
Vec3<T> r (0, 0, 0);
r[i] = (_parityEven? -x: x);
Matrix44<T> N;
N.rotate (r);
N = N * Matrix44<T> (M[0][0], M[0][1], M[0][2], 0,
M[1][0], M[1][1], M[1][2], 0,
M[2][0], M[2][1], M[2][2], 0,
0, 0, 0, 1);
//
// Extract the other two angles, y and z, from N.
//
T sy = Math<T>::sqrt (N[j][i]*N[j][i] + N[k][i]*N[k][i]);
y = Math<T>::atan2 (sy, N[i][i]);
z = Math<T>::atan2 (N[j][k], N[j][j]);
}
else
{
//
// Extract the first angle, x.
//
x = Math<T>::atan2 (M[j][k], M[k][k]);
//
// Remove the x rotation from M, so that the remaining
// rotation, N, is only around two axes, and gimbal lock
// cannot occur.
//
Vec3<T> r (0, 0, 0);
r[i] = (_parityEven? -x: x);
Matrix44<T> N;
N.rotate (r);
N = N * Matrix44<T> (M[0][0], M[0][1], M[0][2], 0,
M[1][0], M[1][1], M[1][2], 0,
M[2][0], M[2][1], M[2][2], 0,
0, 0, 0, 1);
//
// Extract the other two angles, y and z, from N.
//
T cy = Math<T>::sqrt (N[i][i]*N[i][i] + N[i][j]*N[i][j]);
y = Math<T>::atan2 (-N[i][k], cy);
z = Math<T>::atan2 (-N[j][i], N[j][j]);
}
if (!_parityEven)
*this *= -1;
if (!_frameStatic)
{
T t = x;
x = z;
z = t;
}
}
template<class T>
void Euler<T>::extract(const Matrix44<T> &M)
{
int i,j,k;
angleOrder(i,j,k);
if (_initialRepeated)
{
//
// Extract the first angle, x.
//
x = Math<T>::atan2 (M[j][i], M[k][i]);
//
// Remove the x rotation from M, so that the remaining
// rotation, N, is only around two axes, and gimbal lock
// cannot occur.
//
Vec3<T> r (0, 0, 0);
r[i] = (_parityEven? -x: x);
Matrix44<T> N;
N.rotate (r);
N = N * M;
//
// Extract the other two angles, y and z, from N.
//
T sy = Math<T>::sqrt (N[j][i]*N[j][i] + N[k][i]*N[k][i]);
y = Math<T>::atan2 (sy, N[i][i]);
z = Math<T>::atan2 (N[j][k], N[j][j]);
}
else
{
//
// Extract the first angle, x.
//
x = Math<T>::atan2 (M[j][k], M[k][k]);
//
// Remove the x rotation from M, so that the remaining
// rotation, N, is only around two axes, and gimbal lock
// cannot occur.
//
Vec3<T> r (0, 0, 0);
r[i] = (_parityEven? -x: x);
Matrix44<T> N;
N.rotate (r);
N = N * M;
//
// Extract the other two angles, y and z, from N.
//
T cy = Math<T>::sqrt (N[i][i]*N[i][i] + N[i][j]*N[i][j]);
y = Math<T>::atan2 (-N[i][k], cy);
z = Math<T>::atan2 (-N[j][i], N[j][j]);
}
if (!_parityEven)
*this *= -1;
if (!_frameStatic)
{
T t = x;
x = z;
z = t;
}
}
template<class T>
Matrix33<T> Euler<T>::toMatrix33() const
{
int i,j,k;
angleOrder(i,j,k);
Vec3<T> angles;
if ( _frameStatic ) angles = (*this);
else angles = Vec3<T>(z,y,x);
if ( !_parityEven ) angles *= -1.0;
T ci = Math<T>::cos(angles.x);
T cj = Math<T>::cos(angles.y);
T ch = Math<T>::cos(angles.z);
T si = Math<T>::sin(angles.x);
T sj = Math<T>::sin(angles.y);
T sh = Math<T>::sin(angles.z);
T cc = ci*ch;
T cs = ci*sh;
T sc = si*ch;
T ss = si*sh;
Matrix33<T> M;
if ( _initialRepeated )
{
M[i][i] = cj; M[j][i] = sj*si; M[k][i] = sj*ci;
M[i][j] = sj*sh; M[j][j] = -cj*ss+cc; M[k][j] = -cj*cs-sc;
M[i][k] = -sj*ch; M[j][k] = cj*sc+cs; M[k][k] = cj*cc-ss;
}
else
{
M[i][i] = cj*ch; M[j][i] = sj*sc-cs; M[k][i] = sj*cc+ss;
M[i][j] = cj*sh; M[j][j] = sj*ss+cc; M[k][j] = sj*cs-sc;
M[i][k] = -sj; M[j][k] = cj*si; M[k][k] = cj*ci;
}
return M;
}
template<class T>
Matrix44<T> Euler<T>::toMatrix44() const
{
int i,j,k;
angleOrder(i,j,k);
Vec3<T> angles;
if ( _frameStatic ) angles = (*this);
else angles = Vec3<T>(z,y,x);
if ( !_parityEven ) angles *= -1.0;
T ci = Math<T>::cos(angles.x);
T cj = Math<T>::cos(angles.y);
T ch = Math<T>::cos(angles.z);
T si = Math<T>::sin(angles.x);
T sj = Math<T>::sin(angles.y);
T sh = Math<T>::sin(angles.z);
T cc = ci*ch;
T cs = ci*sh;
T sc = si*ch;
T ss = si*sh;
Matrix44<T> M;
if ( _initialRepeated )
{
M[i][i] = cj; M[j][i] = sj*si; M[k][i] = sj*ci;
M[i][j] = sj*sh; M[j][j] = -cj*ss+cc; M[k][j] = -cj*cs-sc;
M[i][k] = -sj*ch; M[j][k] = cj*sc+cs; M[k][k] = cj*cc-ss;
}
else
{
M[i][i] = cj*ch; M[j][i] = sj*sc-cs; M[k][i] = sj*cc+ss;
M[i][j] = cj*sh; M[j][j] = sj*ss+cc; M[k][j] = sj*cs-sc;
M[i][k] = -sj; M[j][k] = cj*si; M[k][k] = cj*ci;
}
return M;
}
template<class T>
Quat<T> Euler<T>::toQuat() const
{
Vec3<T> angles;
int i,j,k;
angleOrder(i,j,k);
if ( _frameStatic ) angles = (*this);
else angles = Vec3<T>(z,y,x);
if ( !_parityEven ) angles.y = -angles.y;
T ti = angles.x*0.5;
T tj = angles.y*0.5;
T th = angles.z*0.5;
T ci = Math<T>::cos(ti);
T cj = Math<T>::cos(tj);
T ch = Math<T>::cos(th);
T si = Math<T>::sin(ti);
T sj = Math<T>::sin(tj);
T sh = Math<T>::sin(th);
T cc = ci*ch;
T cs = ci*sh;
T sc = si*ch;
T ss = si*sh;
T parity = _parityEven ? 1.0 : -1.0;
Quat<T> q;
Vec3<T> a;
if ( _initialRepeated )
{
a[i] = cj*(cs + sc);
a[j] = sj*(cc + ss) * parity,
a[k] = sj*(cs - sc);
q.r = cj*(cc - ss);
}
else
{
a[i] = cj*sc - sj*cs,
a[j] = (cj*ss + sj*cc) * parity,
a[k] = cj*cs - sj*sc;
q.r = cj*cc + sj*ss;
}
q.v = a;
return q;
}
template<class T>
inline bool
Euler<T>::legal(typename Euler<T>::Order order)
{
return (order & ~Legal) ? false : true;
}
template<class T>
typename Euler<T>::Order
Euler<T>::order() const
{
int foo = (_initialAxis == Z ? 0x2000 : (_initialAxis == Y ? 0x1000 : 0));
if (_parityEven) foo |= 0x0100;
if (_initialRepeated) foo |= 0x0010;
if (_frameStatic) foo++;
return (Order)foo;
}
template<class T>
inline void Euler<T>::setOrder(typename Euler<T>::Order p)
{
set( p & 0x2000 ? Z : (p & 0x1000 ? Y : X), // initial axis
!(p & 0x1), // static?
!!(p & 0x100), // permutation even?
!!(p & 0x10)); // initial repeats?
}
template<class T>
void Euler<T>::set(typename Euler<T>::Axis axis,
bool relative,
bool parityEven,
bool firstRepeats)
{
_initialAxis = axis;
_frameStatic = !relative;
_parityEven = parityEven;
_initialRepeated = firstRepeats;
}
template<class T>
const Euler<T>& Euler<T>::operator= (const Euler<T> &euler)
{
x = euler.x;
y = euler.y;
z = euler.z;
_initialAxis = euler._initialAxis;
_frameStatic = euler._frameStatic;
_parityEven = euler._parityEven;
_initialRepeated = euler._initialRepeated;
return *this;
}
template<class T>
const Euler<T>& Euler<T>::operator= (const Vec3<T> &v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
template<class T>
std::ostream& operator << (std::ostream &o, const Euler<T> &euler)
{
char a[3] = { 'X', 'Y', 'Z' };
const char* r = euler.frameStatic() ? "" : "r";
int i,j,k;
euler.angleOrder(i,j,k);
if ( euler.initialRepeated() ) k = i;
return o << "("
<< euler.x << " "
<< euler.y << " "
<< euler.z << " "
<< a[i] << a[j] << a[k] << r << ")";
}
template <class T>
float
Euler<T>::angleMod (T angle)
{
angle = fmod(T (angle), T (2 * M_PI));
if (angle < -M_PI) angle += 2 * M_PI;
if (angle > +M_PI) angle -= 2 * M_PI;
return angle;
}
template <class T>
void
Euler<T>::simpleXYZRotation (Vec3<T> &xyzRot, const Vec3<T> &targetXyzRot)
{
Vec3<T> d = xyzRot - targetXyzRot;
xyzRot[0] = targetXyzRot[0] + angleMod(d[0]);
xyzRot[1] = targetXyzRot[1] + angleMod(d[1]);
xyzRot[2] = targetXyzRot[2] + angleMod(d[2]);
}
template <class T>
void
Euler<T>::nearestRotation (Vec3<T> &xyzRot, const Vec3<T> &targetXyzRot,
Order order)
{
int i,j,k;
Euler<T> e (0,0,0, order);
e.angleOrder(i,j,k);
simpleXYZRotation(xyzRot, targetXyzRot);
Vec3<T> otherXyzRot;
otherXyzRot[i] = M_PI+xyzRot[i];
otherXyzRot[j] = M_PI-xyzRot[j];
otherXyzRot[k] = M_PI+xyzRot[k];
simpleXYZRotation(otherXyzRot, targetXyzRot);
Vec3<T> d = xyzRot - targetXyzRot;
Vec3<T> od = otherXyzRot - targetXyzRot;
T dMag = d.dot(d);
T odMag = od.dot(od);
if (odMag < dMag)
{
xyzRot = otherXyzRot;
}
}
template <class T>
void
Euler<T>::makeNear (const Euler<T> &target)
{
Vec3<T> xyzRot = toXYZVector();
Euler<T> targetSameOrder = Euler<T>(target, order());
Vec3<T> targetXyz = targetSameOrder.toXYZVector();
nearestRotation(xyzRot, targetXyz, order());
setXYZVector(xyzRot);
}
#if (defined _WIN32 || defined _WIN64) && defined _MSC_VER
#pragma warning(default:4244)
#endif
} // namespace Imath
#endif

70
3rdparty/include/OpenEXR/ImathExc.h vendored Normal file
View File

@ -0,0 +1,70 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHEXC_H
#define INCLUDED_IMATHEXC_H
//-----------------------------------------------
//
// Imath library-specific exceptions
//
//-----------------------------------------------
#include "IexBaseExc.h"
namespace Imath {
DEFINE_EXC (NullVecExc, ::Iex::MathExc) // Attempt to normalize
// null vector
DEFINE_EXC (NullQuatExc, ::Iex::MathExc) // Attempt to normalize
// null quaternion
DEFINE_EXC (SingMatrixExc, ::Iex::MathExc) // Attempt to invert
// singular matrix
DEFINE_EXC (ZeroScaleExc, ::Iex::MathExc) // Attempt to remove zero
// scaling from matrix
DEFINE_EXC (IntVecNormalizeExc, ::Iex::MathExc) // Attempt to normalize
// a vector of whose elements
// are an integer type
} // namespace Imath
#endif

190
3rdparty/include/OpenEXR/ImathFrame.h vendored Normal file
View File

@ -0,0 +1,190 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHFRAME_H
#define INCLUDED_IMATHFRAME_H
namespace Imath {
template<class T> class Vec3;
template<class T> class Matrix44;
//
// These methods compute a set of reference frames, defined by their
// transformation matrix, along a curve. It is designed so that the
// array of points and the array of matrices used to fetch these routines
// don't need to be ordered as the curve.
//
// A typical usage would be :
//
// m[0] = Imath::firstFrame( p[0], p[1], p[2] );
// for( int i = 1; i < n - 1; i++ )
// {
// m[i] = Imath::nextFrame( m[i-1], p[i-1], p[i], t[i-1], t[i] );
// }
// m[n-1] = Imath::lastFrame( m[n-2], p[n-2], p[n-1] );
//
// See Graphics Gems I for the underlying algorithm.
//
template<class T> Matrix44<T> firstFrame( const Vec3<T>&, // First point
const Vec3<T>&, // Second point
const Vec3<T>& ); // Third point
template<class T> Matrix44<T> nextFrame( const Matrix44<T>&, // Previous matrix
const Vec3<T>&, // Previous point
const Vec3<T>&, // Current point
Vec3<T>&, // Previous tangent
Vec3<T>& ); // Current tangent
template<class T> Matrix44<T> lastFrame( const Matrix44<T>&, // Previous matrix
const Vec3<T>&, // Previous point
const Vec3<T>& ); // Last point
//
// firstFrame - Compute the first reference frame along a curve.
//
// This function returns the transformation matrix to the reference frame
// defined by the three points 'pi', 'pj' and 'pk'. Note that if the two
// vectors <pi,pj> and <pi,pk> are colinears, an arbitrary twist value will
// be choosen.
//
// Throw 'NullVecExc' if 'pi' and 'pj' are equals.
//
template<class T> Matrix44<T> firstFrame
(
const Vec3<T>& pi, // First point
const Vec3<T>& pj, // Second point
const Vec3<T>& pk ) // Third point
{
Vec3<T> t = pj - pi; t.normalizeExc();
Vec3<T> n = t.cross( pk - pi ); n.normalize();
if( n.length() == 0.0f )
{
int i = fabs( t[0] ) < fabs( t[1] ) ? 0 : 1;
if( fabs( t[2] ) < fabs( t[i] )) i = 2;
Vec3<T> v( 0.0, 0.0, 0.0 ); v[i] = 1.0;
n = t.cross( v ); n.normalize();
}
Vec3<T> b = t.cross( n );
Matrix44<T> M;
M[0][0] = t[0]; M[0][1] = t[1]; M[0][2] = t[2]; M[0][3] = 0.0,
M[1][0] = n[0]; M[1][1] = n[1]; M[1][2] = n[2]; M[1][3] = 0.0,
M[2][0] = b[0]; M[2][1] = b[1]; M[2][2] = b[2]; M[2][3] = 0.0,
M[3][0] = pi[0]; M[3][1] = pi[1]; M[3][2] = pi[2]; M[3][3] = 1.0;
return M;
}
//
// nextFrame - Compute the next reference frame along a curve.
//
// This function returns the transformation matrix to the next reference
// frame defined by the previously computed transformation matrix and the
// new point and tangent vector along the curve.
//
template<class T> Matrix44<T> nextFrame
(
const Matrix44<T>& Mi, // Previous matrix
const Vec3<T>& pi, // Previous point
const Vec3<T>& pj, // Current point
Vec3<T>& ti, // Previous tangent vector
Vec3<T>& tj ) // Current tangent vector
{
Vec3<T> a(0.0, 0.0, 0.0); // Rotation axis.
T r = 0.0; // Rotation angle.
if( ti.length() != 0.0 && tj.length() != 0.0 )
{
ti.normalize(); tj.normalize();
T dot = ti.dot( tj );
//
// This is *really* necessary :
//
if( dot > 1.0 ) dot = 1.0;
else if( dot < -1.0 ) dot = -1.0;
r = acosf( dot );
a = ti.cross( tj );
}
if( a.length() != 0.0 && r != 0.0 )
{
Matrix44<T> R; R.setAxisAngle( a, r );
Matrix44<T> Tj; Tj.translate( pj );
Matrix44<T> Ti; Ti.translate( -pi );
return Mi * Ti * R * Tj;
}
else
{
Matrix44<T> Tr; Tr.translate( pj - pi );
return Mi * Tr;
}
}
//
// lastFrame - Compute the last reference frame along a curve.
//
// This function returns the transformation matrix to the last reference
// frame defined by the previously computed transformation matrix and the
// last point along the curve.
//
template<class T> Matrix44<T> lastFrame
(
const Matrix44<T>& Mi, // Previous matrix
const Vec3<T>& pi, // Previous point
const Vec3<T>& pj ) // Last point
{
Matrix44<T> Tr; Tr.translate( pj - pi );
return Mi * Tr;
}
} // namespace Imath
#endif

697
3rdparty/include/OpenEXR/ImathFrustum.h vendored Normal file
View File

@ -0,0 +1,697 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHFRUSTUM_H
#define INCLUDED_IMATHFRUSTUM_H
#include "ImathVec.h"
#include "ImathPlane.h"
#include "ImathLine.h"
#include "ImathMatrix.h"
#include "ImathLimits.h"
#include "ImathFun.h"
#include "IexMathExc.h"
#if defined _WIN32 || defined _WIN64
#ifdef near
#undef near
#endif
#ifdef far
#undef far
#endif
#endif
namespace Imath {
//
// template class Frustum<T>
//
// The frustum is always located with the eye point at the
// origin facing down -Z. This makes the Frustum class
// compatable with OpenGL (or anything that assumes a camera
// looks down -Z, hence with a right-handed coordinate system)
// but not with RenderMan which assumes the camera looks down
// +Z. Additional functions are provided for conversion from
// and from various camera coordinate spaces.
//
template<class T>
class Frustum
{
public:
Frustum();
Frustum(const Frustum &);
Frustum(T near, T far, T left, T right, T top, T bottom, bool ortho=false);
Frustum(T near, T far, T fovx, T fovy, T aspect);
virtual ~Frustum();
//--------------------
// Assignment operator
//--------------------
const Frustum &operator = (const Frustum &);
//--------------------
// Operators: ==, !=
//--------------------
bool operator == (const Frustum<T> &src) const;
bool operator != (const Frustum<T> &src) const;
//--------------------------------------------------------
// Set functions change the entire state of the Frustum
//--------------------------------------------------------
void set(T near, T far,
T left, T right,
T top, T bottom,
bool ortho=false);
void set(T near, T far, T fovx, T fovy, T aspect);
//------------------------------------------------------
// These functions modify an already valid frustum state
//------------------------------------------------------
void modifyNearAndFar(T near, T far);
void setOrthographic(bool);
//--------------
// Access
//--------------
bool orthographic() const { return _orthographic; }
T near() const { return _near; }
T far() const { return _far; }
T left() const { return _left; }
T right() const { return _right; }
T bottom() const { return _bottom; }
T top() const { return _top; }
//-----------------------------------------------------------------------
// Sets the planes in p to be the six bounding planes of the frustum, in
// the following order: top, right, bottom, left, near, far.
// Note that the planes have normals that point out of the frustum.
// The version of this routine that takes a matrix applies that matrix
// to transform the frustum before setting the planes.
//-----------------------------------------------------------------------
void planes(Plane3<T> p[6]);
void planes(Plane3<T> p[6], const Matrix44<T> &M);
//----------------------
// Derived Quantities
//----------------------
T fovx() const;
T fovy() const;
T aspect() const;
Matrix44<T> projectionMatrix() const;
//-----------------------------------------------------------------------
// Takes a rectangle in the screen space (i.e., -1 <= left <= right <= 1
// and -1 <= bottom <= top <= 1) of this Frustum, and returns a new
// Frustum whose near clipping-plane window is that rectangle in local
// space.
//-----------------------------------------------------------------------
Frustum<T> window(T left, T right, T top, T bottom) const;
//----------------------------------------------------------
// Projection is in screen space / Conversion from Z-Buffer
//----------------------------------------------------------
Line3<T> projectScreenToRay( const Vec2<T> & ) const;
Vec2<T> projectPointToScreen( const Vec3<T> & ) const;
T ZToDepth(long zval, long min, long max) const;
T normalizedZToDepth(T zval) const;
long DepthToZ(T depth, long zmin, long zmax) const;
T worldRadius(const Vec3<T> &p, T radius) const;
T screenRadius(const Vec3<T> &p, T radius) const;
protected:
Vec2<T> screenToLocal( const Vec2<T> & ) const;
Vec2<T> localToScreen( const Vec2<T> & ) const;
protected:
T _near;
T _far;
T _left;
T _right;
T _top;
T _bottom;
bool _orthographic;
};
template<class T>
inline Frustum<T>::Frustum()
{
set(T (0.1),
T (1000.0),
T (-1.0),
T (1.0),
T (1.0),
T (-1.0),
false);
}
template<class T>
inline Frustum<T>::Frustum(const Frustum &f)
{
*this = f;
}
template<class T>
inline Frustum<T>::Frustum(T n, T f, T l, T r, T t, T b, bool o)
{
set(n,f,l,r,t,b,o);
}
template<class T>
inline Frustum<T>::Frustum(T near, T far, T fovx, T fovy, T aspect)
{
set(near,far,fovx,fovy,aspect);
}
template<class T>
Frustum<T>::~Frustum()
{
}
template<class T>
const Frustum<T> &
Frustum<T>::operator = (const Frustum &f)
{
_near = f._near;
_far = f._far;
_left = f._left;
_right = f._right;
_top = f._top;
_bottom = f._bottom;
_orthographic = f._orthographic;
return *this;
}
template <class T>
bool
Frustum<T>::operator == (const Frustum<T> &src) const
{
return
_near == src._near &&
_far == src._far &&
_left == src._left &&
_right == src._right &&
_top == src._top &&
_bottom == src._bottom &&
_orthographic == src._orthographic;
}
template <class T>
inline bool
Frustum<T>::operator != (const Frustum<T> &src) const
{
return !operator== (src);
}
template<class T>
void Frustum<T>::set(T n, T f, T l, T r, T t, T b, bool o)
{
_near = n;
_far = f;
_left = l;
_right = r;
_bottom = b;
_top = t;
_orthographic = o;
}
template<class T>
void Frustum<T>::modifyNearAndFar(T n, T f)
{
if ( _orthographic )
{
_near = n;
}
else
{
Line3<T> lowerLeft( Vec3<T>(0,0,0), Vec3<T>(_left,_bottom,-_near) );
Line3<T> upperRight( Vec3<T>(0,0,0), Vec3<T>(_right,_top,-_near) );
Plane3<T> nearPlane( Vec3<T>(0,0,-1), n );
Vec3<T> ll,ur;
nearPlane.intersect(lowerLeft,ll);
nearPlane.intersect(upperRight,ur);
_left = ll.x;
_right = ur.x;
_top = ur.y;
_bottom = ll.y;
_near = n;
_far = f;
}
_far = f;
}
template<class T>
void Frustum<T>::setOrthographic(bool ortho)
{
_orthographic = ortho;
}
template<class T>
void Frustum<T>::set(T near, T far, T fovx, T fovy, T aspect)
{
if (fovx != 0 && fovy != 0)
throw Iex::ArgExc ("fovx and fovy cannot both be non-zero.");
if (fovx != 0)
{
_right = near * Math<T>::tan(fovx/2.0);
_left = -_right;
_top = ((_right - _left)/aspect)/2.0;
_bottom = -_top;
}
else
{
_top = near * Math<T>::tan(fovy/2.0);
_bottom = -_top;
_right = (_top - _bottom) * aspect / 2.0;
_left = -_right;
}
_near = near;
_far = far;
_orthographic = false;
}
template<class T>
T Frustum<T>::fovx() const
{
return Math<T>::atan2(_right,_near) - Math<T>::atan2(_left,_near);
}
template<class T>
T Frustum<T>::fovy() const
{
return Math<T>::atan2(_top,_near) - Math<T>::atan2(_bottom,_near);
}
template<class T>
T Frustum<T>::aspect() const
{
T rightMinusLeft = _right-_left;
T topMinusBottom = _top-_bottom;
if (abs(topMinusBottom) < 1 &&
abs(rightMinusLeft) > limits<T>::max() * abs(topMinusBottom))
{
throw Iex::DivzeroExc ("Bad viewing frustum: "
"aspect ratio cannot be computed.");
}
return rightMinusLeft / topMinusBottom;
}
template<class T>
Matrix44<T> Frustum<T>::projectionMatrix() const
{
T rightPlusLeft = _right+_left;
T rightMinusLeft = _right-_left;
T topPlusBottom = _top+_bottom;
T topMinusBottom = _top-_bottom;
T farPlusNear = _far+_near;
T farMinusNear = _far-_near;
if ((abs(rightMinusLeft) < 1 &&
abs(rightPlusLeft) > limits<T>::max() * abs(rightMinusLeft)) ||
(abs(topMinusBottom) < 1 &&
abs(topPlusBottom) > limits<T>::max() * abs(topMinusBottom)) ||
(abs(farMinusNear) < 1 &&
abs(farPlusNear) > limits<T>::max() * abs(farMinusNear)))
{
throw Iex::DivzeroExc ("Bad viewing frustum: "
"projection matrix cannot be computed.");
}
if ( _orthographic )
{
T tx = -rightPlusLeft / rightMinusLeft;
T ty = -topPlusBottom / topMinusBottom;
T tz = -farPlusNear / farMinusNear;
if ((abs(rightMinusLeft) < 1 &&
2 > limits<T>::max() * abs(rightMinusLeft)) ||
(abs(topMinusBottom) < 1 &&
2 > limits<T>::max() * abs(topMinusBottom)) ||
(abs(farMinusNear) < 1 &&
2 > limits<T>::max() * abs(farMinusNear)))
{
throw Iex::DivzeroExc ("Bad viewing frustum: "
"projection matrix cannot be computed.");
}
T A = 2 / rightMinusLeft;
T B = 2 / topMinusBottom;
T C = -2 / farMinusNear;
return Matrix44<T>( A, 0, 0, 0,
0, B, 0, 0,
0, 0, C, 0,
tx, ty, tz, 1.f );
}
else
{
T A = rightPlusLeft / rightMinusLeft;
T B = topPlusBottom / topMinusBottom;
T C = -farPlusNear / farMinusNear;
T farTimesNear = -2 * _far * _near;
if (abs(farMinusNear) < 1 &&
abs(farTimesNear) > limits<T>::max() * abs(farMinusNear))
{
throw Iex::DivzeroExc ("Bad viewing frustum: "
"projection matrix cannot be computed.");
}
T D = farTimesNear / farMinusNear;
T twoTimesNear = 2 * _near;
if ((abs(rightMinusLeft) < 1 &&
abs(twoTimesNear) > limits<T>::max() * abs(rightMinusLeft)) ||
(abs(topMinusBottom) < 1 &&
abs(twoTimesNear) > limits<T>::max() * abs(topMinusBottom)))
{
throw Iex::DivzeroExc ("Bad viewing frustum: "
"projection matrix cannot be computed.");
}
T E = twoTimesNear / rightMinusLeft;
T F = twoTimesNear / topMinusBottom;
return Matrix44<T>( E, 0, 0, 0,
0, F, 0, 0,
A, B, C, -1,
0, 0, D, 0 );
}
}
template<class T>
Frustum<T> Frustum<T>::window(T l, T r, T t, T b) const
{
// move it to 0->1 space
Vec2<T> bl = screenToLocal( Vec2<T>(l,b) );
Vec2<T> tr = screenToLocal( Vec2<T>(r,t) );
return Frustum<T>(_near, _far, bl.x, tr.x, tr.y, bl.y, _orthographic);
}
template<class T>
Vec2<T> Frustum<T>::screenToLocal(const Vec2<T> &s) const
{
return Vec2<T>( _left + (_right-_left) * (1.f+s.x) / 2.f,
_bottom + (_top-_bottom) * (1.f+s.y) / 2.f );
}
template<class T>
Vec2<T> Frustum<T>::localToScreen(const Vec2<T> &p) const
{
T leftPlusRight = _left - 2 * p.x + _right;
T leftMinusRight = _left-_right;
T bottomPlusTop = _bottom - 2 * p.y + _top;
T bottomMinusTop = _bottom-_top;
if ((abs(leftMinusRight) < 1 &&
abs(leftPlusRight) > limits<T>::max() * abs(leftMinusRight)) ||
(abs(bottomMinusTop) < 1 &&
abs(bottomPlusTop) > limits<T>::max() * abs(bottomMinusTop)))
{
throw Iex::DivzeroExc
("Bad viewing frustum: "
"local-to-screen transformation cannot be computed");
}
return Vec2<T>( leftPlusRight / leftMinusRight,
bottomPlusTop / bottomMinusTop );
}
template<class T>
Line3<T> Frustum<T>::projectScreenToRay(const Vec2<T> &p) const
{
Vec2<T> point = screenToLocal(p);
if (orthographic())
return Line3<T>( Vec3<T>(point.x,point.y, 0.0),
Vec3<T>(point.x,point.y,-_near));
else
return Line3<T>( Vec3<T>(0, 0, 0), Vec3<T>(point.x,point.y,-_near));
}
template<class T>
Vec2<T> Frustum<T>::projectPointToScreen(const Vec3<T> &point) const
{
if (orthographic() || point.z == 0)
return localToScreen( Vec2<T>( point.x, point.y ) );
else
return localToScreen( Vec2<T>( point.x * _near / -point.z,
point.y * _near / -point.z ) );
}
template<class T>
T Frustum<T>::ZToDepth(long zval,long zmin,long zmax) const
{
int zdiff = zmax - zmin;
if (zdiff == 0)
{
throw Iex::DivzeroExc
("Bad call to Frustum::ZToDepth: zmax == zmin");
}
if ( zval > zmax+1 ) zval -= zdiff;
T fzval = (T(zval) - T(zmin)) / T(zdiff);
return normalizedZToDepth(fzval);
}
template<class T>
T Frustum<T>::normalizedZToDepth(T zval) const
{
T Zp = zval * 2.0 - 1;
if ( _orthographic )
{
return -(Zp*(_far-_near) + (_far+_near))/2;
}
else
{
T farTimesNear = 2 * _far * _near;
T farMinusNear = Zp * (_far - _near) - _far - _near;
if (abs(farMinusNear) < 1 &&
abs(farTimesNear) > limits<T>::max() * abs(farMinusNear))
{
throw Iex::DivzeroExc
("Frustum::normalizedZToDepth cannot be computed. The "
"near and far clipping planes of the viewing frustum "
"may be too close to each other");
}
return farTimesNear / farMinusNear;
}
}
template<class T>
long Frustum<T>::DepthToZ(T depth,long zmin,long zmax) const
{
long zdiff = zmax - zmin;
T farMinusNear = _far-_near;
if ( _orthographic )
{
T farPlusNear = 2*depth + _far + _near;
if (abs(farMinusNear) < 1 &&
abs(farPlusNear) > limits<T>::max() * abs(farMinusNear))
{
throw Iex::DivzeroExc
("Bad viewing frustum: near and far clipping planes "
"are too close to each other");
}
T Zp = -farPlusNear/farMinusNear;
return long(0.5*(Zp+1)*zdiff) + zmin;
}
else
{
// Perspective
T farTimesNear = 2*_far*_near;
if (abs(depth) < 1 &&
abs(farTimesNear) > limits<T>::max() * abs(depth))
{
throw Iex::DivzeroExc
("Bad call to DepthToZ function: value of `depth' "
"is too small");
}
T farPlusNear = farTimesNear/depth + _far + _near;
if (abs(farMinusNear) < 1 &&
abs(farPlusNear) > limits<T>::max() * abs(farMinusNear))
{
throw Iex::DivzeroExc
("Bad viewing frustum: near and far clipping planes "
"are too close to each other");
}
T Zp = farPlusNear/farMinusNear;
return long(0.5*(Zp+1)*zdiff) + zmin;
}
}
template<class T>
T Frustum<T>::screenRadius(const Vec3<T> &p, T radius) const
{
// Derivation:
// Consider X-Z plane.
// X coord of projection of p = xp = p.x * (-_near / p.z)
// Let q be p + (radius, 0, 0).
// X coord of projection of q = xq = (p.x - radius) * (-_near / p.z)
// X coord of projection of segment from p to q = r = xp - xq
// = radius * (-_near / p.z)
// A similar analysis holds in the Y-Z plane.
// So r is the quantity we want to return.
if (abs(p.z) > 1 || abs(-_near) < limits<T>::max() * abs(p.z))
{
return radius * (-_near / p.z);
}
else
{
throw Iex::DivzeroExc
("Bad call to Frustum::screenRadius: the magnitude of `p' "
"is too small");
}
return radius * (-_near / p.z);
}
template<class T>
T Frustum<T>::worldRadius(const Vec3<T> &p, T radius) const
{
if (abs(-_near) > 1 || abs(p.z) < limits<T>::max() * abs(-_near))
{
return radius * (p.z / -_near);
}
else
{
throw Iex::DivzeroExc
("Bad viewing frustum: the near clipping plane is too "
"close to zero");
}
}
template<class T>
void Frustum<T>::planes(Plane3<T> p[6])
{
//
// Plane order: Top, Right, Bottom, Left, Near, Far.
// Normals point outwards.
//
Vec3<T> a( _left, _bottom, -_near);
Vec3<T> b( _left, _top, -_near);
Vec3<T> c( _right, _top, -_near);
Vec3<T> d( _right, _bottom, -_near);
Vec3<T> o(0,0,0);
p[0].set( o, c, b );
p[1].set( o, d, c );
p[2].set( o, a, d );
p[3].set( o, b, a );
p[4].set( Vec3<T>(0, 0, 1), -_near );
p[5].set( Vec3<T>(0, 0,-1), _far );
}
template<class T>
void Frustum<T>::planes(Plane3<T> p[6], const Matrix44<T> &M)
{
//
// Plane order: Top, Right, Bottom, Left, Near, Far.
// Normals point outwards.
//
Vec3<T> a = Vec3<T>( _left, _bottom, -_near) * M;
Vec3<T> b = Vec3<T>( _left, _top, -_near) * M;
Vec3<T> c = Vec3<T>( _right, _top, -_near) * M;
Vec3<T> d = Vec3<T>( _right, _bottom, -_near) * M;
double s = _far / double(_near);
T farLeft = (T) (s * _left);
T farRight = (T) (s * _right);
T farTop = (T) (s * _top);
T farBottom = (T) (s * _bottom);
Vec3<T> e = Vec3<T>( farLeft, farBottom, -_far) * M;
Vec3<T> f = Vec3<T>( farLeft, farTop, -_far) * M;
Vec3<T> g = Vec3<T>( farRight, farTop, -_far) * M;
Vec3<T> o = Vec3<T>(0,0,0) * M;
p[0].set( o, c, b );
p[1].set( o, d, c );
p[2].set( o, a, d );
p[3].set( o, b, a );
p[4].set( a, d, c );
p[5].set( e, f, g );
}
typedef Frustum<float> Frustumf;
typedef Frustum<double> Frustumd;
} // namespace Imath
#endif

272
3rdparty/include/OpenEXR/ImathFun.h vendored Normal file
View File

@ -0,0 +1,272 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHFUN_H
#define INCLUDED_IMATHFUN_H
//-----------------------------------------------------------------------------
//
// Miscellaneous utility functions
//
//-----------------------------------------------------------------------------
#include "ImathLimits.h"
namespace Imath {
template <class T>
inline T
abs (T a)
{
return (a > 0) ? a : -a;
}
template <class T>
inline int
sign (T a)
{
return (a > 0)? 1 : ((a < 0) ? -1 : 0);
}
template <class T, class Q>
inline T
lerp (T a, T b, Q t)
{
return (T) (a + (b - a) * t);
}
template <class T, class Q>
inline T
ulerp (T a, T b, Q t)
{
return (T) ((a > b)? (a - (a - b) * t): (a + (b - a) * t));
}
template <class T>
inline T
lerpfactor(T m, T a, T b)
{
//
// Return how far m is between a and b, that is return t such that
// if:
// t = lerpfactor(m, a, b);
// then:
// m = lerp(a, b, t);
//
// If a==b, return 0.
//
T d = b - a;
T n = m - a;
if (abs(d) > T(1) || abs(n) < limits<T>::max() * abs(d))
return n / d;
return T(0);
}
template <class T>
inline T
clamp (T a, T l, T h)
{
return (a < l)? l : ((a > h)? h : a);
}
template <class T>
inline int
cmp (T a, T b)
{
return Imath::sign (a - b);
}
template <class T>
inline int
cmpt (T a, T b, T t)
{
return (Imath::abs (a - b) <= t)? 0 : cmp (a, b);
}
template <class T>
inline bool
iszero (T a, T t)
{
return (Imath::abs (a) <= t) ? 1 : 0;
}
template <class T1, class T2, class T3>
inline bool
equal (T1 a, T2 b, T3 t)
{
return Imath::abs (a - b) <= t;
}
template <class T>
inline int
floor (T x)
{
return (x >= 0)? int (x): -(int (-x) + (-x > int (-x)));
}
template <class T>
inline int
ceil (T x)
{
return -floor (-x);
}
template <class T>
inline int
trunc (T x)
{
return (x >= 0) ? int(x) : -int(-x);
}
//
// Integer division and remainder where the
// remainder of x/y has the same sign as x:
//
// divs(x,y) == (abs(x) / abs(y)) * (sign(x) * sign(y))
// mods(x,y) == x - y * divs(x,y)
//
inline int
divs (int x, int y)
{
return (x >= 0)? ((y >= 0)? ( x / y): -( x / -y)):
((y >= 0)? -(-x / y): (-x / -y));
}
inline int
mods (int x, int y)
{
return (x >= 0)? ((y >= 0)? ( x % y): ( x % -y)):
((y >= 0)? -(-x % y): -(-x % -y));
}
//
// Integer division and remainder where the
// remainder of x/y is always positive:
//
// divp(x,y) == floor (double(x) / double (y))
// modp(x,y) == x - y * divp(x,y)
//
inline int
divp (int x, int y)
{
return (x >= 0)? ((y >= 0)? ( x / y): -( x / -y)):
((y >= 0)? -((y-1-x) / y): ((-y-1-x) / -y));
}
inline int
modp (int x, int y)
{
return x - y * divp (x, y);
}
//----------------------------------------------------------
// Successor and predecessor for floating-point numbers:
//
// succf(f) returns float(f+e), where e is the smallest
// positive number such that float(f+e) != f.
//
// predf(f) returns float(f-e), where e is the smallest
// positive number such that float(f-e) != f.
//
// succd(d) returns double(d+e), where e is the smallest
// positive number such that double(d+e) != d.
//
// predd(d) returns double(d-e), where e is the smallest
// positive number such that double(d-e) != d.
//
// Exceptions: If the input value is an infinity or a nan,
// succf(), predf(), succd(), and predd() all
// return the input value without changing it.
//
//----------------------------------------------------------
float succf (float f);
float predf (float f);
double succd (double d);
double predd (double d);
//
// Return true if the number is not a NaN or Infinity.
//
inline bool
finitef (float f)
{
union {float f; int i;} u;
u.f = f;
return (u.i & 0x7f800000) != 0x7f800000;
}
inline bool
finited (double d)
{
#if ULONG_MAX == 18446744073709551615LU
typedef long unsigned int Int64;
#else
typedef long long unsigned int Int64;
#endif
union {double d; Int64 i;} u;
u.d = d;
return (u.i & 0x7ff0000000000000LL) != 0x7ff0000000000000LL;
}
} // namespace Imath
#endif

159
3rdparty/include/OpenEXR/ImathGL.h vendored Normal file
View File

@ -0,0 +1,159 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHGL_H
#define INCLUDED_IMATHGL_H
#include <GL/gl.h>
#include "ImathVec.h"
#include "ImathMatrix.h"
#include "IexMathExc.h"
#include "ImathFun.h"
inline void glVertex ( const Imath::V3f &v ) { glVertex3f(v.x,v.y,v.z); }
inline void glVertex ( const Imath::V2f &v ) { glVertex2f(v.x,v.y); }
inline void glNormal ( const Imath::V3f &n ) { glNormal3f(n.x,n.y,n.z); }
inline void glColor ( const Imath::V3f &c ) { glColor3f(c.x,c.y,c.z); }
inline void glTranslate ( const Imath::V3f &t ) { glTranslatef(t.x,t.y,t.z); }
inline void glTexCoord( const Imath::V2f &t )
{
glTexCoord2f(t.x,t.y);
}
inline void glDisableTexture()
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
}
namespace {
const float GL_FLOAT_MAX = 1.8e+19; // sqrt (FLT_MAX)
inline bool
badFloat (float f)
{
return !Imath::finitef (f) || f < - GL_FLOAT_MAX || f > GL_FLOAT_MAX;
}
} // namespace
inline void
throwBadMatrix (const Imath::M44f& m)
{
if (badFloat (m[0][0]) ||
badFloat (m[0][1]) ||
badFloat (m[0][2]) ||
badFloat (m[0][3]) ||
badFloat (m[1][0]) ||
badFloat (m[1][1]) ||
badFloat (m[1][2]) ||
badFloat (m[1][3]) ||
badFloat (m[2][0]) ||
badFloat (m[2][1]) ||
badFloat (m[2][2]) ||
badFloat (m[2][3]) ||
badFloat (m[3][0]) ||
badFloat (m[3][1]) ||
badFloat (m[3][2]) ||
badFloat (m[3][3]))
throw Iex::OverflowExc ("GL matrix overflow");
}
inline void
glMultMatrix( const Imath::M44f& m )
{
throwBadMatrix (m);
glMultMatrixf( (GLfloat*)m[0] );
}
inline void
glMultMatrix( const Imath::M44f* m )
{
throwBadMatrix (*m);
glMultMatrixf( (GLfloat*)(*m)[0] );
}
inline void
glLoadMatrix( const Imath::M44f& m )
{
throwBadMatrix (m);
glLoadMatrixf( (GLfloat*)m[0] );
}
inline void
glLoadMatrix( const Imath::M44f* m )
{
throwBadMatrix (*m);
glLoadMatrixf( (GLfloat*)(*m)[0] );
}
namespace Imath {
//
// Class objects that push/pop the GL state. These objects assist with
// proper cleanup of the state when exceptions are thrown.
//
class GLPushMatrix {
public:
GLPushMatrix () { glPushMatrix(); }
~GLPushMatrix() { glPopMatrix(); }
};
class GLPushAttrib {
public:
GLPushAttrib (GLbitfield mask) { glPushAttrib (mask); }
~GLPushAttrib() { glPopAttrib(); }
};
class GLBegin {
public:
GLBegin (GLenum mode) { glBegin (mode); }
~GLBegin() { glEnd(); }
};
} // namespace Imath
#endif

54
3rdparty/include/OpenEXR/ImathGLU.h vendored Normal file
View File

@ -0,0 +1,54 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHGLU_H
#define INCLUDED_IMATHGLU_H
#include <GL/gl.h>
#include <GL/glu.h>
#include "ImathVec.h"
inline
void
gluLookAt(const Imath::V3f &pos, const Imath::V3f &interest, const Imath::V3f &up)
{
gluLookAt(pos.x, pos.y, pos.z,
interest.x, interest.y, interest.z,
up.x, up.y, up.z);
}
#endif

View File

@ -0,0 +1,66 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHHALFLIMITS_H
#define INCLUDED_IMATHHALFLIMITS_H
//--------------------------------------------------
//
// Imath-style limits for class half.
//
//--------------------------------------------------
#include "ImathLimits.h"
#include "half.h"
namespace Imath {
template <>
struct limits <half>
{
static float min() {return -HALF_MAX;}
static float max() {return HALF_MAX;}
static float smallest() {return HALF_MIN;}
static float epsilon() {return HALF_EPSILON;}
static bool isIntegral() {return false;}
static bool isSigned() {return true;}
};
} // namespace Imath
#endif

224
3rdparty/include/OpenEXR/ImathInterval.h vendored Normal file
View File

@ -0,0 +1,224 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHINTERVAL_H
#define INCLUDED_IMATHINTERVAL_H
//-------------------------------------------------------------------
//
// class Imath::Interval<class T>
// --------------------------------
//
// An Interval has a min and a max and some miscellaneous
// functions. It is basically a Box<T> that allows T to be
// a scalar.
//
//-------------------------------------------------------------------
#include "ImathVec.h"
namespace Imath {
template <class T>
class Interval
{
public:
//-------------------------
// Data Members are public
//-------------------------
T min;
T max;
//-----------------------------------------------------
// Constructors - an "empty" Interval is created by default
//-----------------------------------------------------
Interval();
Interval(const T& point);
Interval(const T& minT, const T& maxT);
//--------------------------------
// Operators: we get != from STL
//--------------------------------
bool operator == (const Interval<T> &src) const;
//------------------
// Interval manipulation
//------------------
void makeEmpty();
void extendBy(const T& point);
void extendBy(const Interval<T>& interval);
//---------------------------------------------------
// Query functions - these compute results each time
//---------------------------------------------------
T size() const;
T center() const;
bool intersects(const T &point) const;
bool intersects(const Interval<T> &interval) const;
//----------------
// Classification
//----------------
bool hasVolume() const;
bool isEmpty() const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Interval <float> Intervalf;
typedef Interval <double> Intervald;
typedef Interval <short> Intervals;
typedef Interval <int> Intervali;
//----------------
// Implementation
//----------------
template <class T>
inline Interval<T>::Interval()
{
makeEmpty();
}
template <class T>
inline Interval<T>::Interval(const T& point)
{
min = point;
max = point;
}
template <class T>
inline Interval<T>::Interval(const T& minV, const T& maxV)
{
min = minV;
max = maxV;
}
template <class T>
inline bool
Interval<T>::operator == (const Interval<T> &src) const
{
return (min == src.min && max == src.max);
}
template <class T>
inline void
Interval<T>::makeEmpty()
{
min = limits<T>::max();
max = limits<T>::min();
}
template <class T>
inline void
Interval<T>::extendBy(const T& point)
{
if ( point < min )
min = point;
if ( point > max )
max = point;
}
template <class T>
inline void
Interval<T>::extendBy(const Interval<T>& interval)
{
if ( interval.min < min )
min = interval.min;
if ( interval.max > max )
max = interval.max;
}
template <class T>
inline bool
Interval<T>::intersects(const T& point) const
{
return point >= min && point <= max;
}
template <class T>
inline bool
Interval<T>::intersects(const Interval<T>& interval) const
{
return interval.max >= min && interval.min <= max;
}
template <class T>
inline T
Interval<T>::size() const
{
return max-min;
}
template <class T>
inline T
Interval<T>::center() const
{
return (max+min)/2;
}
template <class T>
inline bool
Interval<T>::isEmpty() const
{
return max < min;
}
template <class T>
inline bool Interval<T>::hasVolume() const
{
return max > min;
}
} // namespace Imath
#endif

265
3rdparty/include/OpenEXR/ImathLimits.h vendored Normal file
View File

@ -0,0 +1,265 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHLIMITS_H
#define INCLUDED_IMATHLIMITS_H
//----------------------------------------------------------------
//
// Limitations of the basic C++ numerical data types
//
//----------------------------------------------------------------
#include <float.h>
#include <limits.h>
//------------------------------------------
// In Windows, min and max are macros. Yay.
//------------------------------------------
#if defined _WIN32 || defined _WIN64
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#endif
namespace Imath {
//-----------------------------------------------------------------
//
// Template class limits<T> returns information about the limits
// of numerical data type T:
//
// min() largest possible negative value of type T
//
// max() largest possible positive value of type T
//
// smallest() smallest possible positive value of type T
//
// epsilon() smallest possible e of type T, for which
// 1 + e != 1
//
// isIntegral() returns true if T is an integral type
//
// isSigned() returns true if T is signed
//
// Class limits<T> is useful to implement template classes or
// functions which depend on the limits of a numerical type
// which is not known in advance; for example:
//
// template <class T> max (T x[], int n)
// {
// T m = limits<T>::min();
//
// for (int i = 0; i < n; i++)
// if (m < x[i])
// m = x[i];
//
// return m;
// }
//
// Class limits<T> has been implemented for the following types:
//
// char, signed char, unsigned char
// short, unsigned short
// int, unsigned int
// long, unsigned long
// float
// double
// long double
//
// Class limits<T> has only static member functions, all of which
// are implemented as inlines. No objects of type limits<T> are
// ever created.
//
//-----------------------------------------------------------------
template <class T> struct limits
{
static T min();
static T max();
static T smallest();
static T epsilon();
static bool isIntegral();
static bool isSigned();
};
//---------------
// Implementation
//---------------
template <>
struct limits <char>
{
static char min() {return CHAR_MIN;}
static char max() {return CHAR_MAX;}
static char smallest() {return 1;}
static char epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return (char) ~0 < 0;}
};
template <>
struct limits <signed char>
{
static signed char min() {return SCHAR_MIN;}
static signed char max() {return SCHAR_MAX;}
static signed char smallest() {return 1;}
static signed char epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return true;}
};
template <>
struct limits <unsigned char>
{
static unsigned char min() {return 0;}
static unsigned char max() {return UCHAR_MAX;}
static unsigned char smallest() {return 1;}
static unsigned char epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return false;}
};
template <>
struct limits <short>
{
static short min() {return SHRT_MIN;}
static short max() {return SHRT_MAX;}
static short smallest() {return 1;}
static short epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return true;}
};
template <>
struct limits <unsigned short>
{
static unsigned short min() {return 0;}
static unsigned short max() {return USHRT_MAX;}
static unsigned short smallest() {return 1;}
static unsigned short epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return false;}
};
template <>
struct limits <int>
{
static int min() {return INT_MIN;}
static int max() {return INT_MAX;}
static int smallest() {return 1;}
static int epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return true;}
};
template <>
struct limits <unsigned int>
{
static unsigned int min() {return 0;}
static unsigned int max() {return UINT_MAX;}
static unsigned int smallest() {return 1;}
static unsigned int epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return false;}
};
template <>
struct limits <long>
{
static long min() {return LONG_MIN;}
static long max() {return LONG_MAX;}
static long smallest() {return 1;}
static long epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return true;}
};
template <>
struct limits <unsigned long>
{
static unsigned long min() {return 0;}
static unsigned long max() {return ULONG_MAX;}
static unsigned long smallest() {return 1;}
static unsigned long epsilon() {return 1;}
static bool isIntegral() {return true;}
static bool isSigned() {return false;}
};
template <>
struct limits <float>
{
static float min() {return -FLT_MAX;}
static float max() {return FLT_MAX;}
static float smallest() {return FLT_MIN;}
static float epsilon() {return FLT_EPSILON;}
static bool isIntegral() {return false;}
static bool isSigned() {return true;}
};
template <>
struct limits <double>
{
static double min() {return -DBL_MAX;}
static double max() {return DBL_MAX;}
static double smallest() {return DBL_MIN;}
static double epsilon() {return DBL_EPSILON;}
static bool isIntegral() {return false;}
static bool isSigned() {return true;}
};
template <>
struct limits <long double>
{
static long double min() {return -LDBL_MAX;}
static long double max() {return LDBL_MAX;}
static long double smallest() {return LDBL_MIN;}
static long double epsilon() {return LDBL_EPSILON;}
static bool isIntegral() {return false;}
static bool isSigned() {return true;}
};
} // namespace Imath
#endif

184
3rdparty/include/OpenEXR/ImathLine.h vendored Normal file
View File

@ -0,0 +1,184 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHLINE_H
#define INCLUDED_IMATHLINE_H
//-------------------------------------
//
// A 3D line class template
//
//-------------------------------------
#include "ImathVec.h"
#include "ImathLimits.h"
#include "ImathMatrix.h"
namespace Imath {
template <class T>
class Line3
{
public:
Vec3<T> pos;
Vec3<T> dir;
//-------------------------------------------------------------
// Constructors - default is normalized units along direction
//-------------------------------------------------------------
Line3() {}
Line3(const Vec3<T>& point1, const Vec3<T>& point2);
//------------------
// State Query/Set
//------------------
void set(const Vec3<T>& point1,
const Vec3<T>& point2);
//-------
// F(t)
//-------
Vec3<T> operator() (T parameter) const;
//---------
// Query
//---------
T distanceTo(const Vec3<T>& point) const;
T distanceTo(const Line3<T>& line) const;
Vec3<T> closestPointTo(const Vec3<T>& point) const;
Vec3<T> closestPointTo(const Line3<T>& line) const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Line3<float> Line3f;
typedef Line3<double> Line3d;
//---------------
// Implementation
//---------------
template <class T>
inline Line3<T>::Line3(const Vec3<T> &p0, const Vec3<T> &p1)
{
set(p0,p1);
}
template <class T>
inline void Line3<T>::set(const Vec3<T> &p0, const Vec3<T> &p1)
{
pos = p0; dir = p1-p0;
dir.normalize();
}
template <class T>
inline Vec3<T> Line3<T>::operator()(T parameter) const
{
return pos + dir * parameter;
}
template <class T>
inline T Line3<T>::distanceTo(const Vec3<T>& point) const
{
return (closestPointTo(point)-point).length();
}
template <class T>
inline Vec3<T> Line3<T>::closestPointTo(const Vec3<T>& point) const
{
return ((point - pos) ^ dir) * dir + pos;
}
template <class T>
inline T Line3<T>::distanceTo(const Line3<T>& line) const
{
T d = (dir % line.dir) ^ (line.pos - pos);
return (d >= 0)? d: -d;
}
template <class T>
inline Vec3<T>
Line3<T>::closestPointTo(const Line3<T>& line) const
{
// Assumes the lines are normalized
Vec3<T> posLpos = pos - line.pos ;
T c = dir ^ posLpos;
T a = line.dir ^ dir;
T f = line.dir ^ posLpos ;
T num = c - a * f;
T denom = a*a - 1;
T absDenom = ((denom >= 0)? denom: -denom);
if (absDenom < 1)
{
T absNum = ((num >= 0)? num: -num);
if (absNum >= absDenom * limits<T>::max())
return pos;
}
return pos + dir * (num / denom);
}
template<class T>
std::ostream& operator<< (std::ostream &o, const Line3<T> &line)
{
return o << "(" << line.pos << ", " << line.dir << ")";
}
template<class S, class T>
inline Line3<S> operator * (const Line3<S> &line, const Matrix44<T> &M)
{
return Line3<S>( line.pos * M, (line.pos + line.dir) * M );
}
} // namespace Imath
#endif

333
3rdparty/include/OpenEXR/ImathLineAlgo.h vendored Normal file
View File

@ -0,0 +1,333 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHLINEALGO_H
#define INCLUDED_IMATHLINEALGO_H
//------------------------------------------------------------------
//
// This file contains algorithms applied to or in conjunction
// with lines (Imath::Line). These algorithms may require
// more headers to compile. The assumption made is that these
// functions are called much less often than the basic line
// functions or these functions require more support classes
//
// Contains:
//
// bool closestPoints(const Line<T>& line1,
// const Line<T>& line2,
// Vec3<T>& point1,
// Vec3<T>& point2)
//
// bool intersect( const Line3<T> &line,
// const Vec3<T> &v0,
// const Vec3<T> &v1,
// const Vec3<T> &v2,
// Vec3<T> &pt,
// Vec3<T> &barycentric,
// bool &front)
//
// V3f
// closestVertex(const Vec3<T> &v0,
// const Vec3<T> &v1,
// const Vec3<T> &v2,
// const Line3<T> &l)
//
// V3f
// nearestPointOnTriangle(const Vec3<T> &v0,
// const Vec3<T> &v1,
// const Vec3<T> &v2,
// const Line3<T> &l)
//
// V3f
// rotatePoint(const Vec3<T> p, Line3<T> l, float angle)
//
//------------------------------------------------------------------
#include "ImathLine.h"
#include "ImathVecAlgo.h"
namespace Imath {
template <class T>
bool closestPoints(const Line3<T>& line1,
const Line3<T>& line2,
Vec3<T>& point1,
Vec3<T>& point2)
{
//
// Compute the closest points on two lines. This was originally
// lifted from inventor. This function assumes that the line
// directions are normalized. The original math has been collapsed.
//
T A = line1.dir ^ line2.dir;
if ( A == 1 ) return false;
T denom = A * A - 1;
T B = (line1.dir ^ line1.pos) - (line1.dir ^ line2.pos);
T C = (line2.dir ^ line1.pos) - (line2.dir ^ line2.pos);
point1 = line1(( B - A * C ) / denom);
point2 = line2(( B * A - C ) / denom);
return true;
}
template <class T>
bool intersect( const Line3<T> &line,
const Vec3<T> &v0,
const Vec3<T> &v1,
const Vec3<T> &v2,
Vec3<T> &pt,
Vec3<T> &barycentric,
bool &front)
{
// Intersect the line with a triangle.
// 1. find plane of triangle
// 2. find intersection point of ray and plane
// 3. pick plane to project point and triangle into
// 4. check each edge of triangle to see if point is inside it
//
// XXX TODO - this routine is way too long
// - the value of EPSILON is dubious
// - there should be versions of this
// routine that do not calculate the
// barycentric coordinates or the
// front flag
const float EPSILON = 1e-6;
T d, t, d01, d12, d20, vd0, vd1, vd2, ax, ay, az, sense;
Vec3<T> v01, v12, v20, c;
int axis0, axis1;
// calculate plane for polygon
v01 = v1 - v0;
v12 = v2 - v1;
// c is un-normalized normal
c = v12.cross(v01);
d = c.length();
if(d < EPSILON)
return false; // cant hit a triangle with no area
c = c * (1. / d);
// calculate distance to plane along ray
d = line.dir.dot(c);
if (d < EPSILON && d > -EPSILON)
return false; // line is parallel to plane containing triangle
t = (v0 - line.pos).dot(c) / d;
if(t < 0)
return false;
// calculate intersection point
pt = line.pos + t * line.dir;
// is point inside triangle? Project to 2d to find out
// use the plane that has the largest absolute value
// component in the normal
ax = c[0] < 0 ? -c[0] : c[0];
ay = c[1] < 0 ? -c[1] : c[1];
az = c[2] < 0 ? -c[2] : c[2];
if(ax > ay && ax > az)
{
// project on x=0 plane
axis0 = 1;
axis1 = 2;
sense = c[0] < 0 ? -1 : 1;
}
else if(ay > az)
{
axis0 = 2;
axis1 = 0;
sense = c[1] < 0 ? -1 : 1;
}
else
{
axis0 = 0;
axis1 = 1;
sense = c[2] < 0 ? -1 : 1;
}
// distance from v0-v1 must be less than distance from v2 to v0-v1
d01 = sense * ((pt[axis0] - v0[axis0]) * v01[axis1]
- (pt[axis1] - v0[axis1]) * v01[axis0]);
if(d01 < 0) return false;
vd2 = sense * ((v2[axis0] - v0[axis0]) * v01[axis1]
- (v2[axis1] - v0[axis1]) * v01[axis0]);
if(d01 > vd2) return false;
// distance from v1-v2 must be less than distance from v1 to v2-v0
d12 = sense * ((pt[axis0] - v1[axis0]) * v12[axis1]
- (pt[axis1] - v1[axis1]) * v12[axis0]);
if(d12 < 0) return false;
vd0 = sense * ((v0[axis0] - v1[axis0]) * v12[axis1]
- (v0[axis1] - v1[axis1]) * v12[axis0]);
if(d12 > vd0) return false;
// calculate v20, and do check on final side of triangle
v20 = v0 - v2;
d20 = sense * ((pt[axis0] - v2[axis0]) * v20[axis1]
- (pt[axis1] - v2[axis1]) * v20[axis0]);
if(d20 < 0) return false;
vd1 = sense * ((v1[axis0] - v2[axis0]) * v20[axis1]
- (v1[axis1] - v2[axis1]) * v20[axis0]);
if(d20 > vd1) return false;
// vd0, vd1, and vd2 will always be non-zero for a triangle
// that has non-zero area (we return before this for
// zero area triangles)
barycentric = Vec3<T>(d12 / vd0, d20 / vd1, d01 / vd2);
front = line.dir.dot(c) < 0;
return true;
}
template <class T>
Vec3<T>
closestVertex(const Vec3<T> &v0,
const Vec3<T> &v1,
const Vec3<T> &v2,
const Line3<T> &l)
{
Vec3<T> nearest = v0;
T neardot = (v0 - l.closestPointTo(v0)).length2();
T tmp = (v1 - l.closestPointTo(v1)).length2();
if (tmp < neardot)
{
neardot = tmp;
nearest = v1;
}
tmp = (v2 - l.closestPointTo(v2)).length2();
if (tmp < neardot)
{
neardot = tmp;
nearest = v2;
}
return nearest;
}
template <class T>
Vec3<T>
nearestPointOnTriangle(const Vec3<T> &v0,
const Vec3<T> &v1,
const Vec3<T> &v2,
const Line3<T> &l)
{
Vec3<T> pt, barycentric;
bool front;
if (intersect (l, v0, v1, v2, pt, barycentric, front))
return pt;
//
// The line did not intersect the triangle, so to be picky, you should
// find the closest edge that it passed over/under, but chances are that
// 1) another triangle will be closer
// 2) the app does not need this much precision for a ray that does not
// intersect the triangle
// 3) the expense of the calculation is not worth it since this is the
// common case
//
// XXX TODO This is bogus -- nearestPointOnTriangle() should do
// what its name implies; it should return a point
// on an edge if some edge is closer to the line than
// any vertex. If the application does not want the
// extra calculations, it should be possible to specify
// that; it is not up to this nearestPointOnTriangle()
// to make the decision.
return closestVertex(v0, v1, v2, l);
}
template <class T>
Vec3<T>
rotatePoint(const Vec3<T> p, Line3<T> l, T angle)
{
//
// Rotate the point p around the line l by the given angle.
//
//
// Form a coordinate frame with <x,y,a>. The rotation is the in xy
// plane.
//
Vec3<T> q = l.closestPointTo(p);
Vec3<T> x = p - q;
T radius = x.length();
x.normalize();
Vec3<T> y = (x % l.dir).normalize();
T cosangle = Math<T>::cos(angle);
T sinangle = Math<T>::sin(angle);
Vec3<T> r = q + x * radius * cosangle + y * radius * sinangle;
return r;
}
} // namespace Imath
#endif

191
3rdparty/include/OpenEXR/ImathMath.h vendored Normal file
View File

@ -0,0 +1,191 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHMATH_H
#define INCLUDED_IMATHMATH_H
//----------------------------------------------------------------------------
//
// ImathMath.h
//
// This file contains template functions which call the double-
// precision math functions defined in math.h (sin(), sqrt(),
// exp() etc.), with specializations that call the faster
// single-precision versions (sinf(), sqrtf(), expf() etc.)
// when appropriate.
//
// Example:
//
// double x = Math<double>::sqrt (3); // calls ::sqrt(double);
// float y = Math<float>::sqrt (3); // calls ::sqrtf(float);
//
// When would I want to use this?
//
// You may be writing a template which needs to call some function
// defined in math.h, for example to extract a square root, but you
// don't know whether to call the single- or the double-precision
// version of this function (sqrt() or sqrtf()):
//
// template <class T>
// T
// glorp (T x)
// {
// return sqrt (x + 1); // should call ::sqrtf(float)
// } // if x is a float, but we
// // don't know if it is
//
// Using the templates in this file, you can make sure that
// the appropriate version of the math function is called:
//
// template <class T>
// T
// glorp (T x, T y)
// {
// return Math<T>::sqrt (x + 1); // calls ::sqrtf(float) if x
// } // is a float, ::sqrt(double)
// // otherwise
//
//----------------------------------------------------------------------------
#include "ImathPlatform.h"
#include <math.h>
namespace Imath {
template <class T>
struct Math
{
static T acos (T x) {return ::acos (double(x));}
static T asin (T x) {return ::asin (double(x));}
static T atan (T x) {return ::atan (double(x));}
static T atan2 (T x, T y) {return ::atan2 (double(x), double(y));}
static T cos (T x) {return ::cos (double(x));}
static T sin (T x) {return ::sin (double(x));}
static T tan (T x) {return ::tan (double(x));}
static T cosh (T x) {return ::cosh (double(x));}
static T sinh (T x) {return ::sinh (double(x));}
static T tanh (T x) {return ::tanh (double(x));}
static T exp (T x) {return ::exp (double(x));}
static T log (T x) {return ::log (double(x));}
static T log10 (T x) {return ::log10 (double(x));}
static T modf (T x, T *iptr)
{
double ival;
T rval( ::modf (double(x),&ival));
*iptr = ival;
return rval;
}
static T pow (T x, T y) {return ::pow (double(x), double(y));}
static T sqrt (T x) {return ::sqrt (double(x));}
static T ceil (T x) {return ::ceil (double(x));}
static T fabs (T x) {return ::fabs (double(x));}
static T floor (T x) {return ::floor (double(x));}
static T fmod (T x, T y) {return ::fmod (double(x), double(y));}
static T hypot (T x, T y) {return ::hypot (double(x), double(y));}
};
template <>
struct Math<float>
{
static float acos (float x) {return ::acosf (x);}
static float asin (float x) {return ::asinf (x);}
static float atan (float x) {return ::atanf (x);}
static float atan2 (float x, float y) {return ::atan2f (x, y);}
static float cos (float x) {return ::cosf (x);}
static float sin (float x) {return ::sinf (x);}
static float tan (float x) {return ::tanf (x);}
static float cosh (float x) {return ::coshf (x);}
static float sinh (float x) {return ::sinhf (x);}
static float tanh (float x) {return ::tanhf (x);}
static float exp (float x) {return ::expf (x);}
static float log (float x) {return ::logf (x);}
static float log10 (float x) {return ::log10f (x);}
static float modf (float x, float *y) {return ::modff (x, y);}
static float pow (float x, float y) {return ::powf (x, y);}
static float sqrt (float x) {return ::sqrtf (x);}
static float ceil (float x) {return ::ceilf (x);}
static float fabs (float x) {return ::fabsf (x);}
static float floor (float x) {return ::floorf (x);}
static float fmod (float x, float y) {return ::fmodf (x, y);}
#if !defined(_MSC_VER)
static float hypot (float x, float y) {return ::hypotf (x, y);}
#else
static float hypot (float x, float y) {return ::sqrtf(x*x + y*y);}
#endif
};
//--------------------------------------------------------------------------
// Compare two numbers and test if they are "approximately equal":
//
// equalWithAbsError (x1, x2, e)
//
// Returns true if x1 is the same as x2 with an absolute error of
// no more than e,
//
// abs (x1 - x2) <= e
//
// equalWithRelError (x1, x2, e)
//
// Returns true if x1 is the same as x2 with an relative error of
// no more than e,
//
// abs (x1 - x2) <= e * x1
//
//--------------------------------------------------------------------------
template <class T>
inline bool
equalWithAbsError (T x1, T x2, T e)
{
return ((x1 > x2)? x1 - x2: x2 - x1) <= e;
}
template <class T>
inline bool
equalWithRelError (T x1, T x2, T e)
{
return ((x1 > x2)? x1 - x2: x2 - x1) <= e * ((x1 > 0)? x1: -x1);
}
} // namespace Imath
#endif

3249
3rdparty/include/OpenEXR/ImathMatrix.h vendored Normal file

File diff suppressed because it is too large Load Diff

1114
3rdparty/include/OpenEXR/ImathMatrixAlgo.h vendored Normal file

File diff suppressed because it is too large Load Diff

256
3rdparty/include/OpenEXR/ImathPlane.h vendored Normal file
View File

@ -0,0 +1,256 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHPLANE_H
#define INCLUDED_IMATHPLANE_H
//----------------------------------------------------------------------
//
// template class Plane3
//
// The Imath::Plane3<> class represents a half space, so the
// normal may point either towards or away from origin. The
// plane P can be represented by Imath::Plane3 as either p or -p
// corresponding to the two half-spaces on either side of the
// plane. Any function which computes a distance will return
// either negative or positive values for the distance indicating
// which half-space the point is in. Note that reflection, and
// intersection functions will operate as expected.
//
//----------------------------------------------------------------------
#include "ImathVec.h"
#include "ImathLine.h"
namespace Imath {
template <class T>
class Plane3
{
public:
Vec3<T> normal;
T distance;
Plane3() {}
Plane3(const Vec3<T> &normal, T distance);
Plane3(const Vec3<T> &point, const Vec3<T> &normal);
Plane3(const Vec3<T> &point1,
const Vec3<T> &point2,
const Vec3<T> &point3);
//----------------------
// Various set methods
//----------------------
void set(const Vec3<T> &normal,
T distance);
void set(const Vec3<T> &point,
const Vec3<T> &normal);
void set(const Vec3<T> &point1,
const Vec3<T> &point2,
const Vec3<T> &point3 );
//----------------------
// Utilities
//----------------------
bool intersect(const Line3<T> &line,
Vec3<T> &intersection) const;
bool intersectT(const Line3<T> &line,
T &parameter) const;
T distanceTo(const Vec3<T> &) const;
Vec3<T> reflectPoint(const Vec3<T> &) const;
Vec3<T> reflectVector(const Vec3<T> &) const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Plane3<float> Plane3f;
typedef Plane3<double> Plane3d;
//---------------
// Implementation
//---------------
template <class T>
inline Plane3<T>::Plane3(const Vec3<T> &p0,
const Vec3<T> &p1,
const Vec3<T> &p2)
{
set(p0,p1,p2);
}
template <class T>
inline Plane3<T>::Plane3(const Vec3<T> &n, T d)
{
set(n, d);
}
template <class T>
inline Plane3<T>::Plane3(const Vec3<T> &p, const Vec3<T> &n)
{
set(p, n);
}
template <class T>
inline void Plane3<T>::set(const Vec3<T>& point1,
const Vec3<T>& point2,
const Vec3<T>& point3)
{
normal = (point2 - point1) % (point3 - point1);
normal.normalize();
distance = normal ^ point1;
}
template <class T>
inline void Plane3<T>::set(const Vec3<T>& point, const Vec3<T>& n)
{
normal = n;
normal.normalize();
distance = normal ^ point;
}
template <class T>
inline void Plane3<T>::set(const Vec3<T>& n, T d)
{
normal = n;
normal.normalize();
distance = d;
}
template <class T>
inline T Plane3<T>::distanceTo(const Vec3<T> &point) const
{
return (point ^ normal) - distance;
}
template <class T>
inline Vec3<T> Plane3<T>::reflectPoint(const Vec3<T> &point) const
{
return normal * distanceTo(point) * -2.0 + point;
}
template <class T>
inline Vec3<T> Plane3<T>::reflectVector(const Vec3<T> &v) const
{
return normal * (normal ^ v) * 2.0 - v;
}
template <class T>
inline bool Plane3<T>::intersect(const Line3<T>& line, Vec3<T>& point) const
{
T d = normal ^ line.dir;
if ( d == 0.0 ) return false;
T t = - ((normal ^ line.pos) - distance) / d;
point = line(t);
return true;
}
template <class T>
inline bool Plane3<T>::intersectT(const Line3<T>& line, T &t) const
{
T d = normal ^ line.dir;
if ( d == 0.0 ) return false;
t = - ((normal ^ line.pos) - distance) / d;
return true;
}
template<class T>
std::ostream &operator<< (std::ostream &o, const Plane3<T> &plane)
{
return o << "(" << plane.normal << ", " << plane.distance
<< ")";
}
template<class T>
Plane3<T> operator* (const Plane3<T> &plane, const Matrix44<T> &M)
{
// T
// -1
// Could also compute M but that would suck.
//
Vec3<T> dir1 = Vec3<T> (1, 0, 0) % plane.normal;
T dir1Len = dir1 ^ dir1;
Vec3<T> tmp = Vec3<T> (0, 1, 0) % plane.normal;
T tmpLen = tmp ^ tmp;
if (tmpLen > dir1Len)
{
dir1 = tmp;
dir1Len = tmpLen;
}
tmp = Vec3<T> (0, 0, 1) % plane.normal;
tmpLen = tmp ^ tmp;
if (tmpLen > dir1Len)
{
dir1 = tmp;
}
Vec3<T> dir2 = dir1 % plane.normal;
Vec3<T> point = plane.distance * plane.normal;
return Plane3<T> ( point * M,
(point + dir2) * M,
(point + dir1) * M );
}
template<class T>
Plane3<T> operator- (const Plane3<T> &plane)
{
return Plane3<T>(-plane.normal,-plane.distance);
}
} // namespace Imath
#endif

View File

@ -0,0 +1,92 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHPLATFORM_H
#define INCLUDED_IMATHPLATFORM_H
//----------------------------------------------------------------------------
//
// ImathPlatform.h
//
// This file contains functions and constants which aren't
// provided by the system libraries, compilers, or includes on
// certain platforms.
//----------------------------------------------------------------------------
#include <math.h>
#if defined _WIN32 || defined _WIN64
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#endif
//-----------------------------------------------------------------------------
//
// Fixes for the "restrict" keyword. These #ifdef's for detecting
// compiler versions courtesy of Boost's select_compiler_config.hpp;
// here is the copyright notice for that file:
//
// (C) Copyright Boost.org 2001. Permission to copy, use, modify, sell and
// and distribute this software is granted provided this copyright notice
// appears in all copies. This software is provided "as is" without express
// or implied warranty, and with no claim as to its suitability for any
// purpose.
//
// Some compilers support "restrict", in which case we do nothing.
// Other compilers support some variant of it (e.g. "__restrict").
// If we don't know anything about the compiler, we define "restrict"
// to be a no-op.
//
//-----------------------------------------------------------------------------
#if defined __GNUC__
#if !defined(restrict)
#define restrict __restrict
#endif
#elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)
// supports restrict, do nothing.
#elif defined __sgi
// supports restrict, do nothing.
#else
#define restrict
#endif
#endif // INCLUDED_IMATHPLATFORM_H

690
3rdparty/include/OpenEXR/ImathQuat.h vendored Normal file
View File

@ -0,0 +1,690 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHQUAT_H
#define INCLUDED_IMATHQUAT_H
//----------------------------------------------------------------------
//
// template class Quat<T>
//
// "Quaternions came from Hamilton ... and have been an unmixed
// evil to those who have touched them in any way. Vector is a
// useless survival ... and has never been of the slightest use
// to any creature."
//
// - Lord Kelvin
//
// This class implements the quaternion numerical type -- you
// will probably want to use this class to represent orientations
// in R3 and to convert between various euler angle reps. You
// should probably use Imath::Euler<> for that.
//
//----------------------------------------------------------------------
#include "ImathExc.h"
#include "ImathMatrix.h"
#include <iostream>
namespace Imath {
#if (defined _WIN32 || defined _WIN64) && defined _MSC_VER
// Disable MS VC++ warnings about conversion from double to float
#pragma warning(disable:4244)
#endif
template <class T>
class Quat;
template<class T>
Quat<T> slerp (const Quat<T> &q1,const Quat<T> &q2, T t);
template<class T>
Quat<T> squad (const Quat<T> &q1,const Quat<T> &q2,
const Quat<T> &qa,const Quat<T> &qb, T t);
template<class T>
void intermediate (const Quat<T> &q0, const Quat<T> &q1,
const Quat<T> &q2, const Quat<T> &q3,
Quat<T> &qa, Quat<T> &qb);
template <class T>
class Quat
{
public:
T r; // real part
Vec3<T> v; // imaginary vector
//-----------------------------------------------------
// Constructors - default constructor is identity quat
//-----------------------------------------------------
Quat() : r(1), v(0,0,0) {}
template <class S>
Quat( const Quat<S>& q) : r(q.r), v(q.v) {}
Quat( T s, T i, T j, T k ) : r(s), v(i,j,k) {}
Quat( T s, Vec3<T> d ) : r(s), v(d) {}
static Quat<T> identity() { return Quat<T>(); }
//------------------------------------------------
// Basic Algebra - Operators and Methods
// The operator return values are *NOT* normalized
//
// operator^ is 4D dot product
// operator/ uses the inverse() quaternion
// operator~ is conjugate -- if (S+V) is quat then
// the conjugate (S+V)* == (S-V)
//
// some operators (*,/,*=,/=) treat the quat as
// a 4D vector when one of the operands is scalar
//------------------------------------------------
const Quat<T>& operator= (const Quat<T>&);
const Quat<T>& operator*= (const Quat<T>&);
const Quat<T>& operator*= (T);
const Quat<T>& operator/= (const Quat<T>&);
const Quat<T>& operator/= (T);
const Quat<T>& operator+= (const Quat<T>&);
const Quat<T>& operator-= (const Quat<T>&);
T& operator[] (int index); // as 4D vector
T operator[] (int index) const;
template <class S> bool operator == (const Quat<S> &q) const;
template <class S> bool operator != (const Quat<S> &q) const;
Quat<T>& invert(); // this -> 1 / this
Quat<T> inverse() const;
Quat<T>& normalize(); // returns this
Quat<T> normalized() const;
T length() const; // in R4
//-----------------------
// Rotation conversion
//-----------------------
Quat<T>& setAxisAngle(const Vec3<T>& axis, T radians);
Quat<T>& setRotation(const Vec3<T>& fromDirection,
const Vec3<T>& toDirection);
T angle() const;
Vec3<T> axis() const;
Matrix33<T> toMatrix33() const;
Matrix44<T> toMatrix44() const;
Quat<T> log() const;
Quat<T> exp() const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Quat<float> Quatf;
typedef Quat<double> Quatd;
//---------------
// Implementation
//---------------
template<class T>
inline const Quat<T>& Quat<T>::operator= (const Quat<T>& q)
{
r = q.r;
v = q.v;
return *this;
}
template<class T>
inline const Quat<T>& Quat<T>::operator*= (const Quat<T>& q)
{
T rtmp = r * q.r - (v ^ q.v);
v = r * q.v + v * q.r + v % q.v;
r = rtmp;
return *this;
}
template<class T>
inline const Quat<T>& Quat<T>::operator*= (T t)
{
r *= t;
v *= t;
return *this;
}
template<class T>
inline const Quat<T>& Quat<T>::operator/= (const Quat<T>& q)
{
*this = *this * q.inverse();
return *this;
}
template<class T>
inline const Quat<T>& Quat<T>::operator/= (T t)
{
r /= t;
v /= t;
return *this;
}
template<class T>
inline const Quat<T>& Quat<T>::operator+= (const Quat<T>& q)
{
r += q.r;
v += q.v;
return *this;
}
template<class T>
inline const Quat<T>& Quat<T>::operator-= (const Quat<T>& q)
{
r -= q.r;
v -= q.v;
return *this;
}
template<class T>
inline T& Quat<T>::operator[] (int index)
{
return index ? v[index-1] : r;
}
template<class T>
inline T Quat<T>::operator[] (int index) const
{
return index ? v[index-1] : r;
}
template <class T>
template <class S>
inline bool
Quat<T>::operator == (const Quat<S> &q) const
{
return r == q.r && v == q.v;
}
template <class T>
template <class S>
inline bool
Quat<T>::operator != (const Quat<S> &q) const
{
return r != q.r || v != q.v;
}
template<class T>
inline T operator^ (const Quat<T>& q1,const Quat<T>& q2)
{
return q1.r * q2.r + (q1.v ^ q2.v);
}
template <class T>
inline T Quat<T>::length() const
{
return Math<T>::sqrt( r * r + (v ^ v) );
}
template <class T>
inline Quat<T>& Quat<T>::normalize()
{
if ( T l = length() ) { r /= l; v /= l; }
else { r = 1; v = Vec3<T>(0); }
return *this;
}
template <class T>
inline Quat<T> Quat<T>::normalized() const
{
if ( T l = length() ) return Quat( r / l, v / l );
return Quat();
}
template<class T>
inline Quat<T> Quat<T>::inverse() const
{
// 1 Q*
// - = ---- where Q* is conjugate (operator~)
// Q Q* Q and (Q* Q) == Q ^ Q (4D dot)
T qdot = *this ^ *this;
return Quat( r / qdot, -v / qdot );
}
template<class T>
inline Quat<T>& Quat<T>::invert()
{
T qdot = (*this) ^ (*this);
r /= qdot;
v = -v / qdot;
return *this;
}
template<class T>
Quat<T>
slerp(const Quat<T> &q1,const Quat<T> &q2, T t)
{
//
// Spherical linear interpolation.
//
// NOTE: Assumes q1 and q2 are normalized and that 0 <= t <= 1.
//
// This method does *not* interpolate along the shortest arc
// between q1 and q2. If you desire interpolation along the
// shortest arc, then consider flipping the second quaternion
// explicitly before calling slerp. The implementation of squad()
// depends on a slerp() that interpolates as is, without the
// automatic flipping.
//
T cosomega = q1 ^ q2;
if (cosomega >= (T) 1.0)
{
//
// Special case: q1 and q2 are the same, so just return one of them.
// This also catches the case where cosomega is very slightly > 1.0
//
return q1;
}
T sinomega = Math<T>::sqrt (1 - cosomega * cosomega);
Quat<T> result;
if (sinomega * limits<T>::max() > 1)
{
T omega = Math<T>::acos (cosomega);
T s1 = Math<T>::sin ((1.0 - t) * omega) / sinomega;
T s2 = Math<T>::sin (t * omega) / sinomega;
result = s1 * q1 + s2 * q2;
}
else if (cosomega > 0)
{
//
// omega == 0
//
T s1 = 1.0 - t;
T s2 = t;
result = s1 * q1 + s2 * q2;
}
else
{
//
// omega == -pi
//
result.v.x = - q1.v.y;
result.v.y = q1.v.x;
result.v.z = - q1.r;
result.r = q1.v.z;
T s1 = Math<T>::sin ((0.5 - t) * M_PI);
T s2 = Math<T>::sin (t * M_PI);
result = s1 * q1 + s2 * result;
}
return result;
}
template<class T>
Quat<T> spline(const Quat<T> &q0, const Quat<T> &q1,
const Quat<T> &q2, const Quat<T> &q3,
T t)
{
// Spherical Cubic Spline Interpolation -
// from Advanced Animation and Rendering
// Techniques by Watt and Watt, Page 366:
// A spherical curve is constructed using three
// spherical linear interpolations of a quadrangle
// of unit quaternions: q1, qa, qb, q2.
// Given a set of quaternion keys: q0, q1, q2, q3,
// this routine does the interpolation between
// q1 and q2 by constructing two intermediate
// quaternions: qa and qb. The qa and qb are
// computed by the intermediate function to
// guarantee the continuity of tangents across
// adjacent cubic segments. The qa represents in-tangent
// for q1 and the qb represents the out-tangent for q2.
//
// The q1 q2 is the cubic segment being interpolated.
// The q0 is from the previous adjacent segment and q3 is
// from the next adjacent segment. The q0 and q3 are used
// in computing qa and qb.
//
Quat<T> qa = intermediate (q0, q1, q2);
Quat<T> qb = intermediate (q1, q2, q3);
Quat<T> result = squad(q1, qa, qb, q2, t);
return result;
}
template<class T>
Quat<T> squad(const Quat<T> &q1, const Quat<T> &qa,
const Quat<T> &qb, const Quat<T> &q2,
T t)
{
// Spherical Quadrangle Interpolation -
// from Advanced Animation and Rendering
// Techniques by Watt and Watt, Page 366:
// It constructs a spherical cubic interpolation as
// a series of three spherical linear interpolations
// of a quadrangle of unit quaternions.
//
Quat<T> r1 = slerp(q1, q2, t);
Quat<T> r2 = slerp(qa, qb, t);
Quat<T> result = slerp(r1, r2, 2*t*(1-t));
return result;
}
template<class T>
Quat<T> intermediate(const Quat<T> &q0, const Quat<T> &q1, const Quat<T> &q2)
{
// From advanced Animation and Rendering
// Techniques by Watt and Watt, Page 366:
// computing the inner quadrangle
// points (qa and qb) to guarantee tangent
// continuity.
//
Quat<T> q1inv = q1.inverse();
Quat<T> c1 = q1inv*q2;
Quat<T> c2 = q1inv*q0;
Quat<T> c3 = (T) (-0.25) * (c2.log() + c1.log());
Quat<T> qa = q1 * c3.exp();
qa.normalize();
return qa;
}
template <class T>
inline Quat<T> Quat<T>::log() const
{
//
// For unit quaternion, from Advanced Animation and
// Rendering Techniques by Watt and Watt, Page 366:
//
T theta = Math<T>::acos (std::min (r, (T) 1.0));
if (theta == 0)
return Quat<T> (0, v);
T sintheta = Math<T>::sin (theta);
T k;
if (abs (sintheta) < 1 && abs (theta) >= limits<T>::max() * abs (sintheta))
k = 0;
else
k = theta / sintheta;
return Quat<T> ((T) 0, v.x * k, v.y * k, v.z * k);
}
template <class T>
inline Quat<T> Quat<T>::exp() const
{
//
// For pure quaternion (zero scalar part):
// from Advanced Animation and Rendering
// Techniques by Watt and Watt, Page 366:
//
T theta = v.length();
T sintheta = Math<T>::sin (theta);
T k;
if (abs (theta) < 1 && abs (sintheta) >= limits<T>::max() * abs (theta))
k = 0;
else
k = sintheta / theta;
T costheta = Math<T>::cos (theta);
return Quat<T> (costheta, v.x * k, v.y * k, v.z * k);
}
template <class T>
inline T Quat<T>::angle() const
{
return 2.0*Math<T>::acos(r);
}
template <class T>
inline Vec3<T> Quat<T>::axis() const
{
return v.normalized();
}
template <class T>
inline Quat<T>& Quat<T>::setAxisAngle(const Vec3<T>& axis, T radians)
{
r = Math<T>::cos(radians/2);
v = axis.normalized() * Math<T>::sin(radians/2);
return *this;
}
template <class T>
Quat<T>&
Quat<T>::setRotation(const Vec3<T>& from, const Vec3<T>& to)
{
//
// Ported from SbRotation
//
T cost = from.dot(to) / Math<T>::sqrt(from.dot(from) * to.dot(to));
// check for degeneracies
if (cost > 0.99999)
{
//
// Vectors are parallel.
//
r = 1.0;
v = Vec3<T>(0);
}
else if (cost < -0.99999)
{
//
// Vectors are opposite. Find an axis to rotate around,
// which should be perpendicular to the original axis.
//
Vec3<T> frm = from.normalized();
v = frm.cross(Vec3<T>(1, 0, 0));
if (v.length() < 0.00001)
v = frm.cross(Vec3<T>(0, 1, 0));
r = 0;
v.normalize();
}
else
{
//
// Use half-angle formulae:
// cos^2 t = ( 1 + cos (2t) ) / 2
// w part is cosine of half the rotation angle
//
r = Math<T>::sqrt(0.5 * (1.0 + cost));
//
// sin^2 t = ( 1 - cos (2t) ) / 2
// Do the normalization of the axis vector at the same time so
// we only call sqrt once.
//
v = from.cross(to);
v *= Math<T>::sqrt((0.5 * (1.0 - cost))/(v.dot(v)));
}
return *this;
}
template<class T>
Matrix33<T> Quat<T>::toMatrix33() const
{
return Matrix33<T>(1. - 2.0 * (v.y * v.y + v.z * v.z),
2.0 * (v.x * v.y + v.z * r),
2.0 * (v.z * v.x - v.y * r),
2.0 * (v.x * v.y - v.z * r),
1. - 2.0 * (v.z * v.z + v.x * v.x),
2.0 * (v.y * v.z + v.x * r),
2.0 * (v.z * v.x + v.y * r),
2.0 * (v.y * v.z - v.x * r),
1. - 2.0 * (v.y * v.y + v.x * v.x));
}
template<class T>
Matrix44<T> Quat<T>::toMatrix44() const
{
return Matrix44<T>(1. - 2.0 * (v.y * v.y + v.z * v.z),
2.0 * (v.x * v.y + v.z * r),
2.0 * (v.z * v.x - v.y * r),
0.,
2.0 * (v.x * v.y - v.z * r),
1. - 2.0 * (v.z * v.z + v.x * v.x),
2.0 * (v.y * v.z + v.x * r),
0.,
2.0 * (v.z * v.x + v.y * r),
2.0 * (v.y * v.z - v.x * r),
1. - 2.0 * (v.y * v.y + v.x * v.x),
0.,
0.,
0.,
0.,
1.0 );
}
template<class T>
inline Matrix33<T> operator* (const Matrix33<T> &M, const Quat<T> &q)
{
return M * q.toMatrix33();
}
template<class T>
inline Matrix33<T> operator* (const Quat<T> &q, const Matrix33<T> &M)
{
return q.toMatrix33() * M;
}
template<class T>
std::ostream& operator<< (std::ostream &o, const Quat<T> &q)
{
return o << "(" << q.r
<< " " << q.v.x
<< " " << q.v.y
<< " " << q.v.z
<< ")";
}
template<class T>
inline Quat<T> operator* (const Quat<T>& q1, const Quat<T>& q2)
{
// (S1+V1) (S2+V2) = S1 S2 - V1.V2 + S1 V2 + V1 S2 + V1 x V2
return Quat<T>( q1.r * q2.r - (q1.v ^ q2.v),
q1.r * q2.v + q1.v * q2.r + q1.v % q2.v );
}
template<class T>
inline Quat<T> operator/ (const Quat<T>& q1, const Quat<T>& q2)
{
return q1 * q2.inverse();
}
template<class T>
inline Quat<T> operator/ (const Quat<T>& q,T t)
{
return Quat<T>(q.r/t,q.v/t);
}
template<class T>
inline Quat<T> operator* (const Quat<T>& q,T t)
{
return Quat<T>(q.r*t,q.v*t);
}
template<class T>
inline Quat<T> operator* (T t, const Quat<T>& q)
{
return Quat<T>(q.r*t,q.v*t);
}
template<class T>
inline Quat<T> operator+ (const Quat<T>& q1, const Quat<T>& q2)
{
return Quat<T>( q1.r + q2.r, q1.v + q2.v );
}
template<class T>
inline Quat<T> operator- (const Quat<T>& q1, const Quat<T>& q2)
{
return Quat<T>( q1.r - q2.r, q1.v - q2.v );
}
template<class T>
inline Quat<T> operator~ (const Quat<T>& q)
{
return Quat<T>( q.r, -q.v ); // conjugate: (S+V)* = S-V
}
template<class T>
inline Quat<T> operator- (const Quat<T>& q)
{
return Quat<T>( -q.r, -q.v );
}
#if (defined _WIN32 || defined _WIN64) && defined _MSC_VER
#pragma warning(default:4244)
#endif
} // namespace Imath
#endif

461
3rdparty/include/OpenEXR/ImathRandom.h vendored Normal file
View File

@ -0,0 +1,461 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHRANDOM_H
#define INCLUDED_IMATHRANDOM_H
//-----------------------------------------------------------------------------
//
// Generators for uniformly distributed pseudo-random numbers and
// functions that use those generators to generate numbers with
// different distributions:
//
// class Rand32
// class Rand48
// solidSphereRand()
// hollowSphereRand()
// gaussRand()
// gaussSphereRand()
//
//-----------------------------------------------------------------------------
//
// Here is the copyright for the *rand48() functions implemented for
// Windows.
//
//
// Copyright (c) 1993 Martin Birgmeier
// All rights reserved.
//
// You may redistribute unmodified or modified versions of this source
// code provided that the above copyright notice and this and the
// following conditions are retained.
//
// This software is provided ``as is'', and comes with no warranties
// of any kind. I shall in no event be liable for anything that happens
// to anyone/anything when using this software.
//
#include <stdlib.h>
#include <math.h>
namespace Imath {
//-----------------------------------------------
// Fast random-number generator that generates
// a uniformly distributed sequence with a period
// length of 2^32.
//-----------------------------------------------
class Rand32
{
public:
//------------
// Constructor
//------------
Rand32 (unsigned long int seed = 0);
//--------------------------------
// Re-initialize with a given seed
//--------------------------------
void init (unsigned long int seed);
//----------------------------------------------------------
// Get the next value in the sequence (range: [false, true])
//----------------------------------------------------------
bool nextb ();
//---------------------------------------------------------------
// Get the next value in the sequence (range: [0 ... 0xffffffff])
//---------------------------------------------------------------
unsigned long int nexti ();
//------------------------------------------------------
// Get the next value in the sequence (range: [0 ... 1[)
//------------------------------------------------------
float nextf ();
//-------------------------------------------------------------------
// Get the next value in the sequence (range [rangeMin ... rangeMax[)
//-------------------------------------------------------------------
float nextf (float rangeMin, float rangeMax);
private:
void next ();
unsigned long int _state;
};
//--------------------------------------------------------
// Random-number generator based on the C Standard Library
// functions drand48(), lrand48() & company; generates a
// uniformly distributed sequence.
//--------------------------------------------------------
class Rand48
{
public:
//------------
// Constructor
//------------
Rand48 (unsigned long int seed = 0);
//--------------------------------
// Re-initialize with a given seed
//--------------------------------
void init (unsigned long int seed);
//----------------------------------------------------------
// Get the next value in the sequence (range: [false, true])
//----------------------------------------------------------
bool nextb ();
//---------------------------------------------------------------
// Get the next value in the sequence (range: [0 ... 0x7fffffff])
//---------------------------------------------------------------
long int nexti ();
//------------------------------------------------------
// Get the next value in the sequence (range: [0 ... 1[)
//------------------------------------------------------
double nextf ();
//-------------------------------------------------------------------
// Get the next value in the sequence (range [rangeMin ... rangeMax[)
//-------------------------------------------------------------------
double nextf (double rangeMin, double rangeMax);
private:
unsigned short int _state[3];
#if defined ( _WIN32 ) || defined ( _WIN64 ) || defined ( __MWERKS__ )
void shiftState();
#endif
};
//------------------------------------------------------------
// Return random points uniformly distributed in a sphere with
// radius 1 around the origin (distance from origin <= 1).
//------------------------------------------------------------
template <class Vec, class Rand>
Vec
solidSphereRand (Rand &rand);
//-------------------------------------------------------------
// Return random points uniformly distributed on the surface of
// a sphere with radius 1 around the origin.
//-------------------------------------------------------------
template <class Vec, class Rand>
Vec
hollowSphereRand (Rand &rand);
//-----------------------------------------------
// Return random numbers with a normal (Gaussian)
// distribution with zero mean and unit variance.
//-----------------------------------------------
template <class Rand>
float
gaussRand (Rand &rand);
//----------------------------------------------------
// Return random points whose distance from the origin
// has a normal (Gaussian) distribution with zero mean
// and unit variance.
//----------------------------------------------------
template <class Vec, class Rand>
Vec
gaussSphereRand (Rand &rand);
//---------------
// Implementation
//---------------
inline void
Rand32::init (unsigned long int seed)
{
_state = (seed * 0xa5a573a5L) ^ 0x5a5a5a5aL;
}
inline
Rand32::Rand32 (unsigned long int seed)
{
init (seed);
}
inline void
Rand32::next ()
{
_state = 1664525L * _state + 1013904223L;
}
inline bool
Rand32::nextb ()
{
next ();
// Return the 31st (most significant) bit, by and-ing with 2 ^ 31.
return !!(_state & 2147483648UL);
}
inline unsigned long int
Rand32::nexti ()
{
next ();
return _state & 0xffffffff;
}
inline float
Rand32::nextf ()
{
next ();
return ((int) (_state & 0xffffff)) * ((float) (1.0F / 0x1000000));
}
inline float
Rand32::nextf (float rangeMin, float rangeMax)
{
return rangeMin + nextf() * (rangeMax - rangeMin);
}
inline void
Rand48::init (unsigned long int seed)
{
seed = (seed * 0xa5a573a5L) ^ 0x5a5a5a5aL;
_state[0] = (unsigned short int) (seed);
_state[1] = (unsigned short int) (seed >> 16);
_state[2] = (unsigned short int) (seed);
}
inline
Rand48::Rand48 (unsigned long int seed)
{
init (seed);
}
#if defined ( _WIN32 ) || defined ( _WIN64 ) || defined ( __MWERKS__ )
inline void
Rand48::shiftState()
{
unsigned long accu;
unsigned short temp[2];
accu = 0xe66dUL * ( unsigned long )_state[0] + 0x000bUL;
temp[0] = ( unsigned short )accu; /* lower 16 bits */
accu >>= sizeof( unsigned short ) * 8;
accu += 0xe66dUL * ( unsigned long )_state[1] +
0xdeecUL * ( unsigned long )_state[0];
temp[1] = ( unsigned short )accu; /* middle 16 bits */
accu >>= sizeof( unsigned short ) * 8;
accu += 0xe66dUL * _state[2] +
0xdeecUL * _state[1] +
0x0005UL * _state[0];
_state[0] = temp[0];
_state[1] = temp[1];
_state[2] = ( unsigned short )accu;
}
#endif
inline bool
Rand48::nextb ()
{
#if defined ( _WIN32 ) || defined ( _WIN64 ) || defined ( __MWERKS__ )
shiftState();
return ( ( long( _state[2] ) << 15 ) + ( long( _state[1] ) >> 1 ) ) & 0x1;
#else
return nrand48 (_state) & 1;
#endif
}
inline long int
Rand48::nexti ()
{
#if defined ( _WIN32 ) || defined ( _WIN64 ) || defined ( __MWERKS__ )
shiftState();
return ( long( _state[2] ) << 15 ) + ( long( _state[1] ) >> 1 );
#else
return nrand48 (_state);
#endif
}
inline double
Rand48::nextf ()
{
#if defined ( _WIN32 ) || defined ( _WIN64 ) || defined ( __MWERKS__ )
shiftState();
return ldexp( double( _state[0] ), -48 ) +
ldexp( double( _state[1] ), -32 ) +
ldexp( double( _state[2] ), -16 );
#else
return erand48 (_state);
#endif
}
inline double
Rand48::nextf (double rangeMin, double rangeMax)
{
return rangeMin + nextf() * (rangeMax - rangeMin);
}
template <class Vec, class Rand>
Vec
solidSphereRand (Rand &rand)
{
Vec v;
do
{
for (unsigned int i = 0; i < Vec::dimensions(); i++)
v[i] = (typename Vec::BaseType) rand.nextf (-1, 1);
}
while (v.length2() > 1);
return v;
}
template <class Vec, class Rand>
Vec
hollowSphereRand (Rand &rand)
{
Vec v;
typename Vec::BaseType length;
do
{
for (unsigned int i = 0; i < Vec::dimensions(); i++)
v[i] = (typename Vec::BaseType) rand.nextf (-1, 1);
length = v.length();
}
while (length > 1 || length == 0);
return v / length;
}
template <class Rand>
float
gaussRand (Rand &rand)
{
float x; // Note: to avoid numerical problems with very small
float y; // numbers, we make these variables singe-precision
float length2; // floats, but later we call the double-precision log()
// and sqrt() functions instead of logf() and sqrtf().
do
{
x = float (rand.nextf (-1, 1));
y = float (rand.nextf (-1, 1));
length2 = x * x + y * y;
}
while (length2 >= 1 || length2 == 0);
return x * sqrt (-2 * log (length2) / length2);
}
template <class Vec, class Rand>
Vec
gaussSphereRand (Rand &rand)
{
return hollowSphereRand <Vec> (rand) * gaussRand (rand);
}
double drand48();
long int lrand48();
} // namespace Imath
#endif

217
3rdparty/include/OpenEXR/ImathRoots.h vendored Normal file
View File

@ -0,0 +1,217 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHROOTS_H
#define INCLUDED_IMATHROOTS_H
//---------------------------------------------------------------------
//
// Functions to solve linear, quadratic or cubic equations
//
//---------------------------------------------------------------------
#include <complex>
namespace Imath {
//--------------------------------------------------------------------------
// Find the real solutions of a linear, quadratic or cubic equation:
//
// function equation solved
//
// solveLinear (a, b, x) a * x + b == 0
// solveQuadratic (a, b, c, x) a * x*x + b * x + c == 0
// solveNormalizedCubic (r, s, t, x) x*x*x + r * x*x + s * x + t == 0
// solveCubic (a, b, c, d, x) a * x*x*x + b * x*x + c * x + d == 0
//
// Return value:
//
// 3 three real solutions, stored in x[0], x[1] and x[2]
// 2 two real solutions, stored in x[0] and x[1]
// 1 one real solution, stored in x[1]
// 0 no real solutions
// -1 all real numbers are solutions
//
// Notes:
//
// * It is possible that an equation has real solutions, but that the
// solutions (or some intermediate result) are not representable.
// In this case, either some of the solutions returned are invalid
// (nan or infinity), or, if floating-point exceptions have been
// enabled with Iex::mathExcOn(), an Iex::MathExc exception is
// thrown.
//
// * Cubic equations are solved using Cardano's Formula; even though
// only real solutions are produced, some intermediate results are
// complex (std::complex<T>).
//
//--------------------------------------------------------------------------
template <class T> int solveLinear (T a, T b, T &x);
template <class T> int solveQuadratic (T a, T b, T c, T x[2]);
template <class T> int solveNormalizedCubic (T r, T s, T t, T x[3]);
template <class T> int solveCubic (T a, T b, T c, T d, T x[3]);
//---------------
// Implementation
//---------------
template <class T>
int
solveLinear (T a, T b, T &x)
{
if (a != 0)
{
x = -b / a;
return 1;
}
else if (b != 0)
{
return 0;
}
else
{
return -1;
}
}
template <class T>
int
solveQuadratic (T a, T b, T c, T x[2])
{
if (a == 0)
{
return solveLinear (b, c, x[0]);
}
else
{
T D = b * b - 4 * a * c;
if (D > 0)
{
T s = sqrt (D);
x[0] = (-b + s) / (2 * a);
x[1] = (-b - s) / (2 * a);
return 2;
}
if (D == 0)
{
x[0] = -b / (2 * a);
return 1;
}
else
{
return 0;
}
}
}
template <class T>
int
solveNormalizedCubic (T r, T s, T t, T x[3])
{
T p = (3 * s - r * r) / 3;
T q = 2 * r * r * r / 27 - r * s / 3 + t;
T p3 = p / 3;
T q2 = q / 2;
T D = p3 * p3 * p3 + q2 * q2;
if (D == 0 && p3 == 0)
{
x[0] = -r / 3;
x[1] = -r / 3;
x[2] = -r / 3;
return 1;
}
std::complex<T> u = std::pow (-q / 2 + std::sqrt (std::complex<T> (D)),
T (1) / T (3));
std::complex<T> v = -p / (T (3) * u);
const T sqrt3 = T (1.73205080756887729352744634150587); // enough digits
// for long double
std::complex<T> y0 (u + v);
std::complex<T> y1 (-(u + v) / T (2) +
(u - v) / T (2) * std::complex<T> (0, sqrt3));
std::complex<T> y2 (-(u + v) / T (2) -
(u - v) / T (2) * std::complex<T> (0, sqrt3));
if (D > 0)
{
x[0] = y0.real() - r / 3;
return 1;
}
else if (D == 0)
{
x[0] = y0.real() - r / 3;
x[1] = y1.real() - r / 3;
return 2;
}
else
{
x[0] = y0.real() - r / 3;
x[1] = y1.real() - r / 3;
x[2] = y2.real() - r / 3;
return 3;
}
}
template <class T>
int
solveCubic (T a, T b, T c, T d, T x[3])
{
if (a == 0)
{
return solveQuadratic (b, c, d, x);
}
else
{
return solveNormalizedCubic (b / a, c / a, d / a, x);
}
}
} // namespace Imath
#endif

659
3rdparty/include/OpenEXR/ImathShear.h vendored Normal file
View File

@ -0,0 +1,659 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHSHEAR_H
#define INCLUDED_IMATHSHEAR_H
//----------------------------------------------------
//
// Shear6 class template.
//
//----------------------------------------------------
#include "ImathExc.h"
#include "ImathLimits.h"
#include "ImathMath.h"
#include "ImathVec.h"
#include <iostream>
namespace Imath {
template <class T> class Shear6
{
public:
//-------------------
// Access to elements
//-------------------
T xy, xz, yz, yx, zx, zy;
T & operator [] (int i);
const T & operator [] (int i) const;
//-------------
// Constructors
//-------------
Shear6 (); // (0 0 0 0 0 0)
Shear6 (T XY, T XZ, T YZ); // (XY XZ YZ 0 0 0)
Shear6 (const Vec3<T> &v); // (v.x v.y v.z 0 0 0)
template <class S> // (v.x v.y v.z 0 0 0)
Shear6 (const Vec3<S> &v);
Shear6 (T XY, T XZ, T YZ, // (XY XZ YZ YX ZX ZY)
T YX, T ZX, T ZY);
//---------------------------------
// Copy constructors and assignment
//---------------------------------
Shear6 (const Shear6 &h);
template <class S> Shear6 (const Shear6<S> &h);
const Shear6 & operator = (const Shear6 &h);
template <class S>
const Shear6 & operator = (const Vec3<S> &v);
//----------------------
// Compatibility with Sb
//----------------------
template <class S>
void setValue (S XY, S XZ, S YZ, S YX, S ZX, S ZY);
template <class S>
void setValue (const Shear6<S> &h);
template <class S>
void getValue (S &XY, S &XZ, S &YZ,
S &YX, S &ZX, S &ZY) const;
template <class S>
void getValue (Shear6<S> &h) const;
T * getValue();
const T * getValue() const;
//---------
// Equality
//---------
template <class S>
bool operator == (const Shear6<S> &h) const;
template <class S>
bool operator != (const Shear6<S> &h) const;
//-----------------------------------------------------------------------
// Compare two shears and test if they are "approximately equal":
//
// equalWithAbsError (h, e)
//
// Returns true if the coefficients of this and h are the same with
// an absolute error of no more than e, i.e., for all i
//
// abs (this[i] - h[i]) <= e
//
// equalWithRelError (h, e)
//
// Returns true if the coefficients of this and h are the same with
// a relative error of no more than e, i.e., for all i
//
// abs (this[i] - h[i]) <= e * abs (this[i])
//-----------------------------------------------------------------------
bool equalWithAbsError (const Shear6<T> &h, T e) const;
bool equalWithRelError (const Shear6<T> &h, T e) const;
//------------------------
// Component-wise addition
//------------------------
const Shear6 & operator += (const Shear6 &h);
Shear6 operator + (const Shear6 &h) const;
//---------------------------
// Component-wise subtraction
//---------------------------
const Shear6 & operator -= (const Shear6 &h);
Shear6 operator - (const Shear6 &h) const;
//------------------------------------
// Component-wise multiplication by -1
//------------------------------------
Shear6 operator - () const;
const Shear6 & negate ();
//------------------------------
// Component-wise multiplication
//------------------------------
const Shear6 & operator *= (const Shear6 &h);
const Shear6 & operator *= (T a);
Shear6 operator * (const Shear6 &h) const;
Shear6 operator * (T a) const;
//------------------------
// Component-wise division
//------------------------
const Shear6 & operator /= (const Shear6 &h);
const Shear6 & operator /= (T a);
Shear6 operator / (const Shear6 &h) const;
Shear6 operator / (T a) const;
//----------------------------------------------------------
// Number of dimensions, i.e. number of elements in a Shear6
//----------------------------------------------------------
static unsigned int dimensions() {return 6;}
//-------------------------------------------------
// Limitations of type T (see also class limits<T>)
//-------------------------------------------------
static T baseTypeMin() {return limits<T>::min();}
static T baseTypeMax() {return limits<T>::max();}
static T baseTypeSmallest() {return limits<T>::smallest();}
static T baseTypeEpsilon() {return limits<T>::epsilon();}
//--------------------------------------------------------------
// Base type -- in templates, which accept a parameter, V, which
// could be either a Vec2<T> or a Shear6<T>, you can refer to T as
// V::BaseType
//--------------------------------------------------------------
typedef T BaseType;
};
//--------------
// Stream output
//--------------
template <class T>
std::ostream & operator << (std::ostream &s, const Shear6<T> &h);
//----------------------------------------------------
// Reverse multiplication: scalar * Shear6<T>
//----------------------------------------------------
template <class S, class T> Shear6<T> operator * (S a, const Shear6<T> &h);
//-------------------------
// Typedefs for convenience
//-------------------------
typedef Vec3 <float> Shear3f;
typedef Vec3 <double> Shear3d;
typedef Shear6 <float> Shear6f;
typedef Shear6 <double> Shear6d;
//-----------------------
// Implementation of Shear6
//-----------------------
template <class T>
inline T &
Shear6<T>::operator [] (int i)
{
return (&xy)[i];
}
template <class T>
inline const T &
Shear6<T>::operator [] (int i) const
{
return (&xy)[i];
}
template <class T>
inline
Shear6<T>::Shear6 ()
{
xy = xz = yz = yx = zx = zy = 0;
}
template <class T>
inline
Shear6<T>::Shear6 (T XY, T XZ, T YZ)
{
xy = XY;
xz = XZ;
yz = YZ;
yx = 0;
zx = 0;
zy = 0;
}
template <class T>
inline
Shear6<T>::Shear6 (const Vec3<T> &v)
{
xy = v.x;
xz = v.y;
yz = v.z;
yx = 0;
zx = 0;
zy = 0;
}
template <class T>
template <class S>
inline
Shear6<T>::Shear6 (const Vec3<S> &v)
{
xy = T (v.x);
xz = T (v.y);
yz = T (v.z);
yx = 0;
zx = 0;
zy = 0;
}
template <class T>
inline
Shear6<T>::Shear6 (T XY, T XZ, T YZ, T YX, T ZX, T ZY)
{
xy = XY;
xz = XZ;
yz = YZ;
yx = YX;
zx = ZX;
zy = ZY;
}
template <class T>
inline
Shear6<T>::Shear6 (const Shear6 &h)
{
xy = h.xy;
xz = h.xz;
yz = h.yz;
yx = h.yx;
zx = h.zx;
zy = h.zy;
}
template <class T>
template <class S>
inline
Shear6<T>::Shear6 (const Shear6<S> &h)
{
xy = T (h.xy);
xz = T (h.xz);
yz = T (h.yz);
yx = T (h.yx);
zx = T (h.zx);
zy = T (h.zy);
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator = (const Shear6 &h)
{
xy = h.xy;
xz = h.xz;
yz = h.yz;
yx = h.yx;
zx = h.zx;
zy = h.zy;
return *this;
}
template <class T>
template <class S>
inline const Shear6<T> &
Shear6<T>::operator = (const Vec3<S> &v)
{
xy = T (v.x);
xz = T (v.y);
yz = T (v.z);
yx = 0;
zx = 0;
zy = 0;
return *this;
}
template <class T>
template <class S>
inline void
Shear6<T>::setValue (S XY, S XZ, S YZ, S YX, S ZX, S ZY)
{
xy = T (XY);
xz = T (XZ);
yz = T (YZ);
yx = T (YX);
zx = T (ZX);
zy = T (ZY);
}
template <class T>
template <class S>
inline void
Shear6<T>::setValue (const Shear6<S> &h)
{
xy = T (h.xy);
xz = T (h.xz);
yz = T (h.yz);
yx = T (h.yx);
zx = T (h.zx);
zy = T (h.zy);
}
template <class T>
template <class S>
inline void
Shear6<T>::getValue (S &XY, S &XZ, S &YZ, S &YX, S &ZX, S &ZY) const
{
XY = S (xy);
XZ = S (xz);
YZ = S (yz);
YX = S (yx);
ZX = S (zx);
ZY = S (zy);
}
template <class T>
template <class S>
inline void
Shear6<T>::getValue (Shear6<S> &h) const
{
h.xy = S (xy);
h.xz = S (xz);
h.yz = S (yz);
h.yx = S (yx);
h.zx = S (zx);
h.zy = S (zy);
}
template <class T>
inline T *
Shear6<T>::getValue()
{
return (T *) &xy;
}
template <class T>
inline const T *
Shear6<T>::getValue() const
{
return (const T *) &xy;
}
template <class T>
template <class S>
inline bool
Shear6<T>::operator == (const Shear6<S> &h) const
{
return xy == h.xy && xz == h.xz && yz == h.yz &&
yx == h.yx && zx == h.zx && zy == h.zy;
}
template <class T>
template <class S>
inline bool
Shear6<T>::operator != (const Shear6<S> &h) const
{
return xy != h.xy || xz != h.xz || yz != h.yz ||
yx != h.yx || zx != h.zx || zy != h.zy;
}
template <class T>
bool
Shear6<T>::equalWithAbsError (const Shear6<T> &h, T e) const
{
for (int i = 0; i < 6; i++)
if (!Imath::equalWithAbsError ((*this)[i], h[i], e))
return false;
return true;
}
template <class T>
bool
Shear6<T>::equalWithRelError (const Shear6<T> &h, T e) const
{
for (int i = 0; i < 6; i++)
if (!Imath::equalWithRelError ((*this)[i], h[i], e))
return false;
return true;
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator += (const Shear6 &h)
{
xy += h.xy;
xz += h.xz;
yz += h.yz;
yx += h.yx;
zx += h.zx;
zy += h.zy;
return *this;
}
template <class T>
inline Shear6<T>
Shear6<T>::operator + (const Shear6 &h) const
{
return Shear6 (xy + h.xy, xz + h.xz, yz + h.yz,
yx + h.yx, zx + h.zx, zy + h.zy);
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator -= (const Shear6 &h)
{
xy -= h.xy;
xz -= h.xz;
yz -= h.yz;
yx -= h.yx;
zx -= h.zx;
zy -= h.zy;
return *this;
}
template <class T>
inline Shear6<T>
Shear6<T>::operator - (const Shear6 &h) const
{
return Shear6 (xy - h.xy, xz - h.xz, yz - h.yz,
yx - h.yx, zx - h.zx, zy - h.zy);
}
template <class T>
inline Shear6<T>
Shear6<T>::operator - () const
{
return Shear6 (-xy, -xz, -yz, -yx, -zx, -zy);
}
template <class T>
inline const Shear6<T> &
Shear6<T>::negate ()
{
xy = -xy;
xz = -xz;
yz = -yz;
yx = -yx;
zx = -zx;
zy = -zy;
return *this;
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator *= (const Shear6 &h)
{
xy *= h.xy;
xz *= h.xz;
yz *= h.yz;
yx *= h.yx;
zx *= h.zx;
zy *= h.zy;
return *this;
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator *= (T a)
{
xy *= a;
xz *= a;
yz *= a;
yx *= a;
zx *= a;
zy *= a;
return *this;
}
template <class T>
inline Shear6<T>
Shear6<T>::operator * (const Shear6 &h) const
{
return Shear6 (xy * h.xy, xz * h.xz, yz * h.yz,
yx * h.yx, zx * h.zx, zy * h.zy);
}
template <class T>
inline Shear6<T>
Shear6<T>::operator * (T a) const
{
return Shear6 (xy * a, xz * a, yz * a,
yx * a, zx * a, zy * a);
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator /= (const Shear6 &h)
{
xy /= h.xy;
xz /= h.xz;
yz /= h.yz;
yx /= h.yx;
zx /= h.zx;
zy /= h.zy;
return *this;
}
template <class T>
inline const Shear6<T> &
Shear6<T>::operator /= (T a)
{
xy /= a;
xz /= a;
yz /= a;
yx /= a;
zx /= a;
zy /= a;
return *this;
}
template <class T>
inline Shear6<T>
Shear6<T>::operator / (const Shear6 &h) const
{
return Shear6 (xy / h.xy, xz / h.xz, yz / h.yz,
yx / h.yx, zx / h.zx, zy / h.zy);
}
template <class T>
inline Shear6<T>
Shear6<T>::operator / (T a) const
{
return Shear6 (xy / a, xz / a, yz / a,
yx / a, zx / a, zy / a);
}
//-----------------------------
// Stream output implementation
//-----------------------------
template <class T>
std::ostream &
operator << (std::ostream &s, const Shear6<T> &h)
{
return s << '('
<< h.xy << ' ' << h.xz << ' ' << h.yz
<< h.yx << ' ' << h.zx << ' ' << h.zy
<< ')';
}
//-----------------------------------------
// Implementation of reverse multiplication
//-----------------------------------------
template <class S, class T>
inline Shear6<T>
operator * (S a, const Shear6<T> &h)
{
return Shear6<T> (a * h.xy, a * h.xz, a * h.yz,
a * h.yx, a * h.zx, a * h.zy);
}
} // namespace Imath
#endif

177
3rdparty/include/OpenEXR/ImathSphere.h vendored Normal file
View File

@ -0,0 +1,177 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHSPHERE_H
#define INCLUDED_IMATHSPHERE_H
//-------------------------------------
//
// A 3D sphere class template
//
//-------------------------------------
#include "ImathVec.h"
#include "ImathBox.h"
#include "ImathLine.h"
namespace Imath {
template <class T>
class Sphere3
{
public:
Vec3<T> center;
T radius;
//---------------
// Constructors
//---------------
Sphere3() : center(0,0,0), radius(0) {}
Sphere3(const Vec3<T> &c, T r) : center(c), radius(r) {}
//-------------------------------------------------------------------
// Utilities:
//
// s.circumscribe(b) sets center and radius of sphere s
// so that the s tightly encloses box b.
//
// s.intersectT (l, t) If sphere s and line l intersect, then
// intersectT() computes the smallest t,
// t >= 0, so that l(t) is a point on the
// sphere. intersectT() then returns true.
//
// If s and l do not intersect, intersectT()
// returns false.
//
// s.intersect (l, i) If sphere s and line l intersect, then
// intersect() calls s.intersectT(l,t) and
// computes i = l(t).
//
// If s and l do not intersect, intersect()
// returns false.
//
//-------------------------------------------------------------------
void circumscribe(const Box<Vec3<T> > &box);
bool intersect(const Line3<T> &l, Vec3<T> &intersection) const;
bool intersectT(const Line3<T> &l, T &t) const;
};
//--------------------
// Convenient typedefs
//--------------------
typedef Sphere3<float> Sphere3f;
typedef Sphere3<double> Sphere3d;
//---------------
// Implementation
//---------------
template <class T>
void Sphere3<T>::circumscribe(const Box<Vec3<T> > &box)
{
center = T(0.5) * (box.min + box.max);
radius = (box.max - center).length();
}
template <class T>
bool Sphere3<T>::intersectT(const Line3<T> &line, T &t) const
{
bool doesIntersect = true;
Vec3<T> v = line.pos - center;
T B = 2.0 * (line.dir ^ v);
T C = (v ^ v) - (radius * radius);
// compute discriminant
// if negative, there is no intersection
T discr = B*B - 4.0*C;
if (discr < 0.0)
{
// line and Sphere3 do not intersect
doesIntersect = false;
}
else
{
// t0: (-B - sqrt(B^2 - 4AC)) / 2A (A = 1)
T sqroot = Math<T>::sqrt(discr);
t = (-B - sqroot) * 0.5;
if (t < 0.0)
{
// no intersection, try t1: (-B + sqrt(B^2 - 4AC)) / 2A (A = 1)
t = (-B + sqroot) * 0.5;
}
if (t < 0.0)
doesIntersect = false;
}
return doesIntersect;
}
template <class T>
bool Sphere3<T>::intersect(const Line3<T> &line, Vec3<T> &intersection) const
{
T t;
if (intersectT (line, t))
{
intersection = line(t);
return true;
}
else
{
return false;
}
}
} //namespace Imath
#endif

1426
3rdparty/include/OpenEXR/ImathVec.h vendored Normal file

File diff suppressed because it is too large Load Diff

146
3rdparty/include/OpenEXR/ImathVecAlgo.h vendored Normal file
View File

@ -0,0 +1,146 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMATHVECALGO_H
#define INCLUDED_IMATHVECALGO_H
//-------------------------------------------------------------------------
//
// This file contains algorithms applied to or in conjunction
// with points (Imath::Vec2 and Imath::Vec3).
// The assumption made is that these functions are called much
// less often than the basic point functions or these functions
// require more support classes.
//
//-------------------------------------------------------------------------
#include "ImathVec.h"
#include "ImathLimits.h"
namespace Imath {
//--------------------------------------------------------------
// Find the projection of vector t onto vector s (Vec2 and Vec3)
//--------------------------------------------------------------
template <class Vec> Vec project (const Vec &s, const Vec &t);
//----------------------------------------------
// Find a vector which is perpendicular to s and
// in the same plane as s and t (Vec2 and Vec3)
//----------------------------------------------
template <class Vec> Vec orthogonal (const Vec &s, const Vec &t);
//-----------------------------------------------
// Find the direction of a ray s after reflection
// off a plane with normal t (Vec2 and Vec3)
//-----------------------------------------------
template <class Vec> Vec reflect (const Vec &s, const Vec &t);
//----------------------------------------------------------------------
// Find the vertex of triangle (v0, v1, v2), which is closest to point p
// (Vec2 and Vec3).
//----------------------------------------------------------------------
template <class Vec> Vec closestVertex (const Vec &v0,
const Vec &v1,
const Vec &v2,
const Vec &p);
//---------------
// Implementation
//---------------
template <class Vec>
Vec
project (const Vec &s, const Vec &t)
{
Vec sNormalized = s.normalized();
return sNormalized * (sNormalized ^ t);
}
template <class Vec>
Vec
orthogonal (const Vec &s, const Vec &t)
{
return t - project (s, t);
}
template <class Vec>
Vec
reflect (const Vec &s, const Vec &t)
{
return s - typename Vec::BaseType(2) * (s - project(t, s));
}
template <class Vec>
Vec
closestVertex(const Vec &v0,
const Vec &v1,
const Vec &v2,
const Vec &p)
{
Vec nearest = v0;
typename Vec::BaseType neardot = (v0 - p).length2();
typename Vec::BaseType tmp = (v1 - p).length2();
if (tmp < neardot)
{
neardot = tmp;
nearest = v1;
}
tmp = (v2 - p).length2();
if (tmp < neardot)
{
neardot = tmp;
nearest = v2;
}
return nearest;
}
} // namespace Imath
#endif

261
3rdparty/include/OpenEXR/ImfArray.h vendored Normal file
View File

@ -0,0 +1,261 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_ARRAY_H
#define INCLUDED_IMF_ARRAY_H
//-------------------------------------------------------------------------
//
// class Array
// class Array2D
//
// "Arrays of T" whose sizes are not known at compile time.
// When an array goes out of scope, its elements are automatically
// deleted.
//
// Usage example:
//
// struct C
// {
// C () {std::cout << "C::C (" << this << ")\n";};
// virtual ~C () {std::cout << "C::~C (" << this << ")\n";};
// };
//
// int
// main ()
// {
// Array <C> a(3);
//
// C &b = a[1];
// const C &c = a[1];
// C *d = a + 2;
// const C *e = a;
//
// return 0;
// }
//
//-------------------------------------------------------------------------
namespace Imf {
template <class T>
class Array
{
public:
//-----------------------------
// Constructors and destructors
//-----------------------------
Array () {_data = 0;}
Array (long size) {_data = new T[size];}
~Array () {delete [] _data;}
//-----------------------------
// Access to the array elements
//-----------------------------
operator T * () {return _data;}
operator const T * () const {return _data;}
//------------------------------------------------------
// Resize and clear the array (the contents of the array
// are not preserved across the resize operation).
//
// resizeEraseUnsafe() is more memory efficient than
// resizeErase() because it deletes the old memory block
// before allocating a new one, but if allocating the
// new block throws an exception, resizeEraseUnsafe()
// leaves the array in an unusable state.
//
//------------------------------------------------------
void resizeErase (long size);
void resizeEraseUnsafe (long size);
private:
Array (const Array &); // Copying and assignment
Array & operator = (const Array &); // are not implemented
T * _data;
};
template <class T>
class Array2D
{
public:
//-----------------------------
// Constructors and destructors
//-----------------------------
Array2D (); // empty array, 0 by 0 elements
Array2D (long sizeX, long sizeY); // sizeX by sizeY elements
~Array2D ();
//-----------------------------
// Access to the array elements
//-----------------------------
T * operator [] (long x);
const T * operator [] (long x) const;
//------------------------------------------------------
// Resize and clear the array (the contents of the array
// are not preserved across the resize operation).
//
// resizeEraseUnsafe() is more memory efficient than
// resizeErase() because it deletes the old memory block
// before allocating a new one, but if allocating the
// new block throws an exception, resizeEraseUnsafe()
// leaves the array in an unusable state.
//
//------------------------------------------------------
void resizeErase (long sizeX, long sizeY);
void resizeEraseUnsafe (long sizeX, long sizeY);
private:
Array2D (const Array2D &); // Copying and assignment
Array2D & operator = (const Array2D &); // are not implemented
long _sizeY;
T * _data;
};
//---------------
// Implementation
//---------------
template <class T>
inline void
Array<T>::resizeErase (long size)
{
T *tmp = new T[size];
delete [] _data;
_data = tmp;
}
template <class T>
inline void
Array<T>::resizeEraseUnsafe (long size)
{
delete [] _data;
_data = 0;
_data = new T[size];
}
template <class T>
inline
Array2D<T>::Array2D ():
_sizeY (0), _data (0)
{
// emtpy
}
template <class T>
inline
Array2D<T>::Array2D (long sizeX, long sizeY):
_sizeY (sizeY), _data (new T[sizeX * sizeY])
{
// emtpy
}
template <class T>
inline
Array2D<T>::~Array2D ()
{
delete [] _data;
}
template <class T>
inline T *
Array2D<T>::operator [] (long x)
{
return _data + x * _sizeY;
}
template <class T>
inline const T *
Array2D<T>::operator [] (long x) const
{
return _data + x * _sizeY;
}
template <class T>
inline void
Array2D<T>::resizeErase (long sizeX, long sizeY)
{
T *tmp = new T[sizeX * sizeY];
delete [] _data;
_sizeY = sizeY;
_data = tmp;
}
template <class T>
inline void
Array2D<T>::resizeEraseUnsafe (long sizeX, long sizeY)
{
delete [] _data;
_data = 0;
_sizeY = 0;
_data = new T[sizeX * sizeY];
_sizeY = sizeY;
}
} // namespace Imf
#endif

422
3rdparty/include/OpenEXR/ImfAttribute.h vendored Normal file
View File

@ -0,0 +1,422 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_ATTRIBUTE_H
#define INCLUDED_IMF_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class Attribute
//
//-----------------------------------------------------------------------------
#include "IexBaseExc.h"
#include <ImfIO.h>
#include <ImfXdr.h>
namespace Imf {
class Attribute
{
public:
//---------------------------
// Constructor and destructor
//---------------------------
Attribute ();
virtual ~Attribute ();
//-------------------------------
// Get this attribute's type name
//-------------------------------
virtual const char * typeName () const = 0;
//------------------------------
// Make a copy of this attribute
//------------------------------
virtual Attribute * copy () const = 0;
//----------------------------------------
// Type-specific attribute I/O and copying
//----------------------------------------
virtual void writeValueTo (OStream &os,
int version) const = 0;
virtual void readValueFrom (IStream &is,
int size,
int version) = 0;
virtual void copyValueFrom (const Attribute &other) = 0;
//------------------
// Attribute factory
//------------------
static Attribute * newAttribute (const char typeName[]);
//-----------------------------------------------------------
// Test if a given attribute type has already been registered
//-----------------------------------------------------------
static bool knownType (const char typeName[]);
protected:
//--------------------------------------------------
// Register an attribute type so that newAttribute()
// knows how to make objects of this type.
//--------------------------------------------------
static void registerAttributeType (const char typeName[],
Attribute *(*newAttribute)());
//------------------------------------------------------
// Un-register an attribute type so that newAttribute()
// no longer knows how to make objects of this type (for
// debugging only).
//------------------------------------------------------
static void unRegisterAttributeType (const char typeName[]);
};
//-------------------------------------------------
// Class template for attributes of a specific type
//-------------------------------------------------
template <class T>
class TypedAttribute: public Attribute
{
public:
//----------------------------
// Constructors and destructor
//------------_---------------
TypedAttribute ();
TypedAttribute (const T &value);
TypedAttribute (const TypedAttribute<T> &other);
virtual ~TypedAttribute ();
//--------------------------------
// Access to the attribute's value
//--------------------------------
T & value ();
const T & value () const;
//--------------------------------
// Get this attribute's type name.
//--------------------------------
virtual const char * typeName () const;
//---------------------------------------------------------
// Static version of typeName()
// This function must be specialized for each value type T.
//---------------------------------------------------------
static const char * staticTypeName ();
//---------------------
// Make a new attribute
//---------------------
static Attribute * makeNewAttribute ();
//------------------------------
// Make a copy of this attribute
//------------------------------
virtual Attribute * copy () const;
//-----------------------------------------------------------------
// Type-specific attribute I/O and copying.
// Depending on type T, these functions may have to be specialized.
//-----------------------------------------------------------------
virtual void writeValueTo (OStream &os,
int version) const;
virtual void readValueFrom (IStream &is,
int size,
int version);
virtual void copyValueFrom (const Attribute &other);
//------------------------------------------------------------
// Dynamic casts that throw exceptions instead of returning 0.
//------------------------------------------------------------
static TypedAttribute * cast (Attribute *attribute);
static const TypedAttribute * cast (const Attribute *attribute);
static TypedAttribute & cast (Attribute &attribute);
static const TypedAttribute & cast (const Attribute &attribute);
//---------------------------------------------------------------
// Register this attribute type so that Attribute::newAttribute()
// knows how to make objects of this type.
//
// Note that this function is not thread-safe because it modifies
// a global variable in the IlmIlm library. A thread in a multi-
// threaded program may call registerAttributeType() only when no
// other thread is accessing any functions or classes in the
// IlmImf library.
//
//---------------------------------------------------------------
static void registerAttributeType ();
//-----------------------------------------------------
// Un-register this attribute type (for debugging only)
//-----------------------------------------------------
static void unRegisterAttributeType ();
private:
T _value;
};
//------------------------------------
// Implementation of TypedAttribute<T>
//------------------------------------
template <class T>
TypedAttribute<T>::TypedAttribute (): _value (T())
{
// empty
}
template <class T>
TypedAttribute<T>::TypedAttribute (const T &value): _value (value)
{
// empty
}
template <class T>
TypedAttribute<T>::TypedAttribute (const TypedAttribute<T> &other):
_value ()
{
copyValueFrom (other);
}
template <class T>
TypedAttribute<T>::~TypedAttribute ()
{
// empty
}
template <class T>
inline T &
TypedAttribute<T>::value ()
{
return _value;
}
template <class T>
inline const T &
TypedAttribute<T>::value () const
{
return _value;
}
template <class T>
const char *
TypedAttribute<T>::typeName () const
{
return staticTypeName();
}
template <class T>
Attribute *
TypedAttribute<T>::makeNewAttribute ()
{
return new TypedAttribute<T>();
}
template <class T>
Attribute *
TypedAttribute<T>::copy () const
{
Attribute * attribute = new TypedAttribute<T>();
attribute->copyValueFrom (*this);
return attribute;
}
template <class T>
void
TypedAttribute<T>::writeValueTo (OStream &os, int version) const
{
Xdr::write <StreamIO> (os, _value);
}
template <class T>
void
TypedAttribute<T>::readValueFrom (IStream &is, int size, int version)
{
Xdr::read <StreamIO> (is, _value);
}
template <class T>
void
TypedAttribute<T>::copyValueFrom (const Attribute &other)
{
_value = cast(other)._value;
}
template <class T>
TypedAttribute<T> *
TypedAttribute<T>::cast (Attribute *attribute)
{
TypedAttribute<T> *t =
dynamic_cast <TypedAttribute<T> *> (attribute);
if (t == 0)
throw Iex::TypeExc ("Unexpected attribute type.");
return t;
}
template <class T>
const TypedAttribute<T> *
TypedAttribute<T>::cast (const Attribute *attribute)
{
const TypedAttribute<T> *t =
dynamic_cast <const TypedAttribute<T> *> (attribute);
if (t == 0)
throw Iex::TypeExc ("Unexpected attribute type.");
return t;
}
template <class T>
inline TypedAttribute<T> &
TypedAttribute<T>::cast (Attribute &attribute)
{
return *cast (&attribute);
}
template <class T>
inline const TypedAttribute<T> &
TypedAttribute<T>::cast (const Attribute &attribute)
{
return *cast (&attribute);
}
template <class T>
inline void
TypedAttribute<T>::registerAttributeType ()
{
Attribute::registerAttributeType (staticTypeName(), makeNewAttribute);
}
template <class T>
inline void
TypedAttribute<T>::unRegisterAttributeType ()
{
Attribute::unRegisterAttributeType (staticTypeName());
}
} // namespace Imf
#if defined(OPENEXR_DLL) && defined(_MSC_VER)
// Tell MS VC++ to disable "non dll-interface class used as base
// for dll-interface class" and "no suitable definition provided
// for explicit template"
#pragma warning (disable : 4275 4661)
#if defined (ILMIMF_EXPORTS)
#define IMF_EXPIMP_TEMPLATE
#else
#define IMF_EXPIMP_TEMPLATE extern
#endif
IMF_EXPIMP_TEMPLATE template class Imf::TypedAttribute<float>;
IMF_EXPIMP_TEMPLATE template class Imf::TypedAttribute<double>;
#pragma warning(default : 4251)
#undef EXTERN_TEMPLATE
#endif
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfAttribute.cpp>
#endif
#endif

View File

@ -0,0 +1,73 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_BOX_ATTRIBUTE_H
#define INCLUDED_IMF_BOX_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class Box2iAttribute
// class Box2fAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include "ImathBox.h"
namespace Imf {
typedef TypedAttribute<Imath::Box2i> Box2iAttribute;
template <> const char *Box2iAttribute::staticTypeName ();
template <> void Box2iAttribute::writeValueTo (OStream &, int) const;
template <> void Box2iAttribute::readValueFrom (IStream &, int, int);
typedef TypedAttribute<Imath::Box2f> Box2fAttribute;
template <> const char *Box2fAttribute::staticTypeName ();
template <> void Box2fAttribute::writeValueTo (OStream &, int) const;
template <> void Box2fAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfBoxAttribute.cpp>
#endif
#endif

465
3rdparty/include/OpenEXR/ImfCRgbaFile.h vendored Normal file
View File

@ -0,0 +1,465 @@
/*
Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
Digital Ltd. LLC
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 Industrial Light & Magic 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.
*/
#ifndef INCLUDED_IMF_C_RGBA_FILE_H
#define INCLUDED_IMF_C_RGBA_FILE_H
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
** Interpreting unsigned shorts as 16-bit floating point numbers
*/
typedef unsigned short ImfHalf;
void ImfFloatToHalf (float f,
ImfHalf *h);
void ImfFloatToHalfArray (int n,
const float f[/*n*/],
ImfHalf h[/*n*/]);
float ImfHalfToFloat (ImfHalf h);
void ImfHalfToFloatArray (int n,
const ImfHalf h[/*n*/],
float f[/*n*/]);
/*
** RGBA pixel; memory layout must be the same as struct Imf::Rgba.
*/
struct ImfRgba
{
ImfHalf r;
ImfHalf g;
ImfHalf b;
ImfHalf a;
};
typedef struct ImfRgba ImfRgba;
/*
** Magic number; this must be the same as Imf::MAGIC
*/
#define IMF_MAGIC 20000630
/*
** Version number; this must be the same as Imf::EXR_VERSION
*/
#define IMF_VERSION_NUMBER 2
/*
** Line order; values must the the same as in Imf::LineOrder.
*/
#define IMF_INCREASING_Y 0
#define IMF_DECREASING_Y 1
#define IMF_RAMDOM_Y 2
/*
** Compression types; values must be the same as in Imf::Compression.
*/
#define IMF_NO_COMPRESSION 0
#define IMF_RLE_COMPRESSION 1
#define IMF_ZIPS_COMPRESSION 2
#define IMF_ZIP_COMPRESSION 3
#define IMF_PIZ_COMPRESSION 4
#define IMF_PXR24_COMPRESSION 5
/*
** Channels; values must be the same as in Imf::RgbaChannels.
*/
#define IMF_WRITE_R 0x01
#define IMF_WRITE_G 0x02
#define IMF_WRITE_B 0x04
#define IMF_WRITE_A 0x08
#define IMF_WRITE_Y 0x10
#define IMF_WRITE_C 0x20
#define IMF_WRITE_RGB 0x07
#define IMF_WRITE_RGBA 0x0f
#define IMF_WRITE_YC 0x30
#define IMF_WRITE_YA 0x18
#define IMF_WRITE_YCA 0x38
/*
** Level modes; values must be the same as in Imf::LevelMode
*/
#define IMF_ONE_LEVEL 0
#define IMF_MIPMAP_LEVELS 1
#define IMF_RIPMAP_LEVELS 2
/*
** Level rounding modes; values must be the same as in Imf::LevelRoundingMode
*/
#define IMF_ROUND_DOWN 0
#define IMF_ROUND_UP 1
/*
** RGBA file header
*/
struct ImfHeader;
typedef struct ImfHeader ImfHeader;
ImfHeader * ImfNewHeader (void);
void ImfDeleteHeader (ImfHeader *hdr);
ImfHeader * ImfCopyHeader (const ImfHeader *hdr);
void ImfHeaderSetDisplayWindow (ImfHeader *hdr,
int xMin, int yMin,
int xMax, int yMax);
void ImfHeaderDisplayWindow (const ImfHeader *hdr,
int *xMin, int *yMin,
int *xMax, int *yMax);
void ImfHeaderSetDataWindow (ImfHeader *hdr,
int xMin, int yMin,
int xMax, int yMax);
void ImfHeaderDataWindow (const ImfHeader *hdr,
int *xMin, int *yMin,
int *xMax, int *yMax);
void ImfHeaderSetPixelAspectRatio (ImfHeader *hdr,
float pixelAspectRatio);
float ImfHeaderPixelAspectRatio (const ImfHeader *hdr);
void ImfHeaderSetScreenWindowCenter (ImfHeader *hdr,
float x, float y);
void ImfHeaderScreenWindowCenter (const ImfHeader *hdr,
float *x, float *y);
void ImfHeaderSetScreenWindowWidth (ImfHeader *hdr,
float width);
float ImfHeaderScreenWindowWidth (const ImfHeader *hdr);
void ImfHeaderSetLineOrder (ImfHeader *hdr,
int lineOrder);
int ImfHeaderLineOrder (const ImfHeader *hdr);
void ImfHeaderSetCompression (ImfHeader *hdr,
int compression);
int ImfHeaderCompression (const ImfHeader *hdr);
int ImfHeaderSetIntAttribute (ImfHeader *hdr,
const char name[],
int value);
int ImfHeaderIntAttribute (const ImfHeader *hdr,
const char name[],
int *value);
int ImfHeaderSetFloatAttribute (ImfHeader *hdr,
const char name[],
float value);
int ImfHeaderSetDoubleAttribute (ImfHeader *hdr,
const char name[],
double value);
int ImfHeaderFloatAttribute (const ImfHeader *hdr,
const char name[],
float *value);
int ImfHeaderDoubleAttribute (const ImfHeader *hdr,
const char name[],
double *value);
int ImfHeaderSetStringAttribute (ImfHeader *hdr,
const char name[],
const char value[]);
int ImfHeaderStringAttribute (const ImfHeader *hdr,
const char name[],
const char **value);
int ImfHeaderSetBox2iAttribute (ImfHeader *hdr,
const char name[],
int xMin, int yMin,
int xMax, int yMax);
int ImfHeaderBox2iAttribute (const ImfHeader *hdr,
const char name[],
int *xMin, int *yMin,
int *xMax, int *yMax);
int ImfHeaderSetBox2fAttribute (ImfHeader *hdr,
const char name[],
float xMin, float yMin,
float xMax, float yMax);
int ImfHeaderBox2fAttribute (const ImfHeader *hdr,
const char name[],
float *xMin, float *yMin,
float *xMax, float *yMax);
int ImfHeaderSetV2iAttribute (ImfHeader *hdr,
const char name[],
int x, int y);
int ImfHeaderV2iAttribute (const ImfHeader *hdr,
const char name[],
int *x, int *y);
int ImfHeaderSetV2fAttribute (ImfHeader *hdr,
const char name[],
float x, float y);
int ImfHeaderV2fAttribute (const ImfHeader *hdr,
const char name[],
float *x, float *y);
int ImfHeaderSetV3iAttribute (ImfHeader *hdr,
const char name[],
int x, int y, int z);
int ImfHeaderV3iAttribute (const ImfHeader *hdr,
const char name[],
int *x, int *y, int *z);
int ImfHeaderSetV3fAttribute (ImfHeader *hdr,
const char name[],
float x, float y, float z);
int ImfHeaderV3fAttribute (const ImfHeader *hdr,
const char name[],
float *x, float *y, float *z);
int ImfHeaderSetM33fAttribute (ImfHeader *hdr,
const char name[],
const float m[3][3]);
int ImfHeaderM33fAttribute (const ImfHeader *hdr,
const char name[],
float m[3][3]);
int ImfHeaderSetM44fAttribute (ImfHeader *hdr,
const char name[],
const float m[4][4]);
int ImfHeaderM44fAttribute (const ImfHeader *hdr,
const char name[],
float m[4][4]);
/*
** RGBA output file
*/
struct ImfOutputFile;
typedef struct ImfOutputFile ImfOutputFile;
ImfOutputFile * ImfOpenOutputFile (const char name[],
const ImfHeader *hdr,
int channels);
int ImfCloseOutputFile (ImfOutputFile *out);
int ImfOutputSetFrameBuffer (ImfOutputFile *out,
const ImfRgba *base,
size_t xStride,
size_t yStride);
int ImfOutputWritePixels (ImfOutputFile *out,
int numScanLines);
int ImfOutputCurrentScanLine (const ImfOutputFile *out);
const ImfHeader * ImfOutputHeader (const ImfOutputFile *out);
int ImfOutputChannels (const ImfOutputFile *out);
/*
** Tiled RGBA output file
*/
struct ImfTiledOutputFile;
typedef struct ImfTiledOutputFile ImfTiledOutputFile;
ImfTiledOutputFile * ImfOpenTiledOutputFile (const char name[],
const ImfHeader *hdr,
int channels,
int xSize, int ySize,
int mode, int rmode);
int ImfCloseTiledOutputFile (ImfTiledOutputFile *out);
int ImfTiledOutputSetFrameBuffer (ImfTiledOutputFile *out,
const ImfRgba *base,
size_t xStride,
size_t yStride);
int ImfTiledOutputWriteTile (ImfTiledOutputFile *out,
int dx, int dy,
int lx, int ly);
int ImfTiledOutputWriteTiles (ImfTiledOutputFile *out,
int dxMin, int dxMax,
int dyMin, int dyMax,
int lx, int ly);
const ImfHeader * ImfTiledOutputHeader (const ImfTiledOutputFile *out);
int ImfTiledOutputChannels (const ImfTiledOutputFile *out);
int ImfTiledOutputTileXSize (const ImfTiledOutputFile *out);
int ImfTiledOutputTileYSize (const ImfTiledOutputFile *out);
int ImfTiledOutputLevelMode (const ImfTiledOutputFile *out);
int ImfTiledOutputLevelRoundingMode
(const ImfTiledOutputFile *out);
/*
** RGBA input file
*/
struct ImfInputFile;
typedef struct ImfInputFile ImfInputFile;
ImfInputFile * ImfOpenInputFile (const char name[]);
int ImfCloseInputFile (ImfInputFile *in);
int ImfInputSetFrameBuffer (ImfInputFile *in,
ImfRgba *base,
size_t xStride,
size_t yStride);
int ImfInputReadPixels (ImfInputFile *in,
int scanLine1,
int scanLine2);
const ImfHeader * ImfInputHeader (const ImfInputFile *in);
int ImfInputChannels (const ImfInputFile *in);
const char * ImfInputFileName (const ImfInputFile *in);
/*
** Tiled RGBA input file
*/
struct ImfTiledInputFile;
typedef struct ImfTiledInputFile ImfTiledInputFile;
ImfTiledInputFile * ImfOpenTiledInputFile (const char name[]);
int ImfCloseTiledInputFile (ImfTiledInputFile *in);
int ImfTiledInputSetFrameBuffer (ImfTiledInputFile *in,
ImfRgba *base,
size_t xStride,
size_t yStride);
int ImfTiledInputReadTile (ImfTiledInputFile *in,
int dx, int dy,
int lx, int ly);
int ImfTiledInputReadTiles (ImfTiledInputFile *in,
int dxMin, int dxMax,
int dyMin, int dyMax,
int lx, int ly);
const ImfHeader * ImfTiledInputHeader (const ImfTiledInputFile *in);
int ImfTiledInputChannels (const ImfTiledInputFile *in);
const char * ImfTiledInputFileName (const ImfTiledInputFile *in);
int ImfTiledInputTileXSize (const ImfTiledInputFile *in);
int ImfTiledInputTileYSize (const ImfTiledInputFile *in);
int ImfTiledInputLevelMode (const ImfTiledInputFile *in);
int ImfTiledInputLevelRoundingMode
(const ImfTiledInputFile *in);
/*
** Lookup tables
*/
struct ImfLut;
typedef struct ImfLut ImfLut;
ImfLut * ImfNewRound12logLut (int channels);
ImfLut * ImfNewRoundNBitLut (unsigned int n, int channels);
void ImfDeleteLut (ImfLut *lut);
void ImfApplyLut (ImfLut *lut,
ImfRgba *data,
int nData,
int stride);
/*
** Most recent error message
*/
const char * ImfErrorMessage (void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif

View File

@ -0,0 +1,392 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_CHANNEL_LIST_H
#define INCLUDED_IMF_CHANNEL_LIST_H
//-----------------------------------------------------------------------------
//
// class Channel
// class ChannelList
//
//-----------------------------------------------------------------------------
#include <ImfName.h>
#include <ImfPixelType.h>
#include <map>
#include <set>
#include <string>
namespace Imf {
struct Channel
{
//------------------------------
// Data type; see ImfPixelType.h
//------------------------------
PixelType type;
//--------------------------------------------
// Subsampling: pixel (x, y) is present in the
// channel only if
//
// x % xSampling == 0 && y % ySampling == 0
//
//--------------------------------------------
int xSampling;
int ySampling;
//------------
// Constructor
//------------
Channel (PixelType type = HALF,
int xSampling = 1,
int ySampling = 1);
//------------
// Operator ==
//------------
bool operator == (const Channel &other) const;
};
class ChannelList
{
public:
//--------------
// Add a channel
//--------------
void insert (const char name[],
const Channel &channel);
//------------------------------------------------------------------
// Access to existing channels:
//
// [n] Returns a reference to the channel with name n.
// If no channel with name n exists, an Iex::ArgExc
// is thrown.
//
// findChannel(n) Returns a pointer to the channel with name n,
// or 0 if no channel with name n exists.
//
//------------------------------------------------------------------
Channel & operator [] (const char name[]);
const Channel & operator [] (const char name[]) const;
Channel * findChannel (const char name[]);
const Channel * findChannel (const char name[]) const;
//-------------------------------------------
// Iterator-style access to existing channels
//-------------------------------------------
typedef std::map <Name, Channel> ChannelMap;
class Iterator;
class ConstIterator;
Iterator begin ();
ConstIterator begin () const;
Iterator end ();
ConstIterator end () const;
Iterator find (const char name[]);
ConstIterator find (const char name[]) const;
//-----------------------------------------------------------------
// Support for image layers:
//
// In an image file with many channels it is sometimes useful to
// group the channels into "layers", that is, into sets of channels
// that logically belong together. Grouping channels into layers
// is done using a naming convention: channel C in layer L is
// called "L.C".
//
// For example, a computer graphic image may contain separate
// R, G and B channels for light that originated at each of
// several different virtual light sources. The channels in
// this image might be called "light1.R", "light1.G", "light1.B",
// "light2.R", "light2.G", "light2.B", etc.
//
// Note that this naming convention allows layers to be nested;
// for example, "light1.specular.R" identifies the "R" channel
// in the "specular" sub-layer of layer "light1".
//
// Channel names that don't contain a "." or that contain a
// "." only at the beginning or at the end are not considered
// to be part of any layer.
//
// layers(lns) sorts the channels in this ChannelList
// into layers and stores the names of
// all layers, sorted alphabetically,
// into string set lns.
//
// channelsInLayer(ln,f,l) stores a pair of iterators in f and l
// such that the loop
//
// for (ConstIterator i = f; i != l; ++i)
// ...
//
// iterates over all channels in layer ln.
// channelsInLayer (ln, l, p) calls
// channelsWithPrefix (ln + ".", l, p).
//
//-----------------------------------------------------------------
void layers (std::set <std::string> &layerNames) const;
void channelsInLayer (const std::string &layerName,
Iterator &first,
Iterator &last);
void channelsInLayer (const std::string &layerName,
ConstIterator &first,
ConstIterator &last) const;
//-------------------------------------------------------------------
// Find all channels whose name begins with a given prefix:
//
// channelsWithPrefix(p,f,l) stores a pair of iterators in f and l
// such that the following loop iterates over all channels whose name
// begins with string p:
//
// for (ConstIterator i = f; i != l; ++i)
// ...
//
//-------------------------------------------------------------------
void channelsWithPrefix (const char prefix[],
Iterator &first,
Iterator &last);
void channelsWithPrefix (const char prefix[],
ConstIterator &first,
ConstIterator &last) const;
//------------
// Operator ==
//------------
bool operator == (const ChannelList &other) const;
private:
ChannelMap _map;
};
//----------
// Iterators
//----------
class ChannelList::Iterator
{
public:
Iterator ();
Iterator (const ChannelList::ChannelMap::iterator &i);
Iterator & operator ++ ();
Iterator operator ++ (int);
const char * name () const;
Channel & channel () const;
private:
friend class ChannelList::ConstIterator;
ChannelList::ChannelMap::iterator _i;
};
class ChannelList::ConstIterator
{
public:
ConstIterator ();
ConstIterator (const ChannelList::ChannelMap::const_iterator &i);
ConstIterator (const ChannelList::Iterator &other);
ConstIterator & operator ++ ();
ConstIterator operator ++ (int);
const char * name () const;
const Channel & channel () const;
private:
friend bool operator == (const ConstIterator &, const ConstIterator &);
friend bool operator != (const ConstIterator &, const ConstIterator &);
ChannelList::ChannelMap::const_iterator _i;
};
//-----------------
// Inline Functions
//-----------------
inline
ChannelList::Iterator::Iterator (): _i()
{
// empty
}
inline
ChannelList::Iterator::Iterator (const ChannelList::ChannelMap::iterator &i):
_i (i)
{
// empty
}
inline ChannelList::Iterator &
ChannelList::Iterator::operator ++ ()
{
++_i;
return *this;
}
inline ChannelList::Iterator
ChannelList::Iterator::operator ++ (int)
{
Iterator tmp = *this;
++_i;
return tmp;
}
inline const char *
ChannelList::Iterator::name () const
{
return *_i->first;
}
inline Channel &
ChannelList::Iterator::channel () const
{
return _i->second;
}
inline
ChannelList::ConstIterator::ConstIterator (): _i()
{
// empty
}
inline
ChannelList::ConstIterator::ConstIterator
(const ChannelList::ChannelMap::const_iterator &i): _i (i)
{
// empty
}
inline
ChannelList::ConstIterator::ConstIterator (const ChannelList::Iterator &other):
_i (other._i)
{
// empty
}
inline ChannelList::ConstIterator &
ChannelList::ConstIterator::operator ++ ()
{
++_i;
return *this;
}
inline ChannelList::ConstIterator
ChannelList::ConstIterator::operator ++ (int)
{
ConstIterator tmp = *this;
++_i;
return tmp;
}
inline const char *
ChannelList::ConstIterator::name () const
{
return *_i->first;
}
inline const Channel &
ChannelList::ConstIterator::channel () const
{
return _i->second;
}
inline bool
operator == (const ChannelList::ConstIterator &x,
const ChannelList::ConstIterator &y)
{
return x._i == y._i;
}
inline bool
operator != (const ChannelList::ConstIterator &x,
const ChannelList::ConstIterator &y)
{
return !(x == y);
}
} // namespace Imf
#endif

View File

@ -0,0 +1,67 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_CHANNEL_LIST_ATTRIBUTE_H
#define INCLUDED_IMF_CHANNEL_LIST_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class ChannelListAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include <ImfChannelList.h>
namespace Imf {
typedef TypedAttribute<ChannelList> ChannelListAttribute;
template <> const char *ChannelListAttribute::staticTypeName ();
template <> void ChannelListAttribute::writeValueTo (OStream &, int) const;
template <> void ChannelListAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfChannelListAttribute.cpp>
#endif
#endif

View File

@ -0,0 +1,127 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2003, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_CHROMATICITIES_H
#define INCLUDED_IMF_CHROMATICITIES_H
//-----------------------------------------------------------------------------
//
// CIE (x,y) chromaticities, and conversions between
// RGB tiples and CIE XYZ tristimulus values.
//
//-----------------------------------------------------------------------------
#include "ImathVec.h"
#include "ImathMatrix.h"
namespace Imf {
struct Chromaticities
{
Imath::V2f red;
Imath::V2f green;
Imath::V2f blue;
Imath::V2f white;
Chromaticities (const Imath::V2f &red = Imath::V2f (0.6400f, 0.3300f),
const Imath::V2f &green = Imath::V2f (0.3000f, 0.6000f),
const Imath::V2f &blue = Imath::V2f (0.1500f, 0.0600f),
const Imath::V2f &white = Imath::V2f (0.3127f, 0.3290f));
};
//
// Conversions between RGB and CIE XYZ
//
// RGB to XYZ:
//
// Given a set of chromaticities, c, and the luminance, Y, of the RGB
// triple (1,1,1), or "white", RGBtoXYZ(c,Y) computes a matrix, M, so
// that multiplying an RGB value, v, with M produces an equivalent
// XYZ value, w. (w == v * M)
//
// If we define that
//
// (Xr, Yr, Zr) == (1, 0, 0) * M
// (Xg, Yg, Zg) == (0, 1, 0) * M
// (Xb, Yb, Zb) == (0, 0, 1) * M
// (Xw, Yw, Zw) == (1, 1, 1) * M,
//
// then the following statements are true:
//
// Xr / (Xr + Yr + Zr) == c.red.x
// Yr / (Xr + Yr + Zr) == c.red.y
//
// Xg / (Xg + Yg + Zg) == c.red.x
// Yg / (Xg + Yg + Zg) == c.red.y
//
// Xb / (Xb + Yb + Zb) == c.red.x
// Yb / (Xb + Yb + Zb) == c.red.y
//
// Xw / (Xw + Yw + Zw) == c.red.x
// Yw / (Xw + Yw + Zw) == c.red.y
//
// Yw == Y.
//
// XYZ to RGB:
//
// YYZtoRGB(c,Y) returns RGBtoXYZ(c,Y).inverse().
//
// Warning:
//
// It would seem that RGBtoXYZ() and XYZtoRGB() are all you need
// to convert RGB values with one set of primary and white point
// chromaticities into perceptually equivalent RGB values with
// different primary and white point chromaticities:
//
// M44f M = RGBtoXYZ (chromaticities1, Y1) *
// XYZtoRGB (chromaticities2, Y2);
//
// However, this simple conversion does not account for white point
// adaptation, and produces undesirable results. The proper thing
// to do is to perform a Bradford or a von Kries transform, which
// moves the white point of the original color space to the white
// point of the destination color space, dragging other colors with
// it in a sensible fashion.
//
Imath::M44f RGBtoXYZ (const Chromaticities chroma, float Y);
Imath::M44f XYZtoRGB (const Chromaticities chroma, float Y);
} // namespace Imf
#endif

View File

@ -0,0 +1,72 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2003, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_CHROMATICITIES_ATTRIBUTE_H
#define INCLUDED_IMF_CHROMATICITIES_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class ChromaticitiesAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include <ImfChromaticities.h>
namespace Imf {
typedef TypedAttribute<Chromaticities> ChromaticitiesAttribute;
template <>
const char *ChromaticitiesAttribute::staticTypeName ();
template <>
void ChromaticitiesAttribute::writeValueTo (OStream &, int) const;
template <>
void ChromaticitiesAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfChromaticitiesAttribute.cpp>
#endif
#endif

View File

@ -0,0 +1,64 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_COMPRESSION_H
#define INCLUDED_IMF_COMPRESSION_H
//-----------------------------------------------------------------------------
//
// enum Compression
//
//-----------------------------------------------------------------------------
namespace Imf {
enum Compression
{
NO_COMPRESSION = 0, // no compression
RLE_COMPRESSION = 1, // run length encoding
ZIPS_COMPRESSION = 2, // zlib compression, one scan line at a time
ZIP_COMPRESSION = 3, // zlib compression, in blocks of 16 scan lines
PIZ_COMPRESSION = 4, // piz-based wavelet compression
PXR24_COMPRESSION = 5, // lossy 24-bit float compression
NUM_COMPRESSION_METHODS // number of different compression methods
};
} // namespace Imf
#endif

View File

@ -0,0 +1,66 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_COMPRESSION_ATTRIBUTE_H
#define INCLUDED_IMF_COMPRESSION_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class CompressionAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include <ImfCompression.h>
namespace Imf {
typedef TypedAttribute<Compression> CompressionAttribute;
template <> const char *CompressionAttribute::staticTypeName ();
template <> void CompressionAttribute::writeValueTo (OStream &, int) const;
template <> void CompressionAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfCompressionAttribute.cpp>
#endif
#endif

104
3rdparty/include/OpenEXR/ImfConvert.h vendored Normal file
View File

@ -0,0 +1,104 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_CONVERT_H
#define INCLUDED_IMF_CONVERT_H
//-----------------------------------------------------------------------------
//
// Routines for converting between pixel data types,
// with well-defined behavior for exceptional cases,
// without depending on how hardware and operating
// system handle integer overflows and floating-point
// exceptions.
//
//-----------------------------------------------------------------------------
#include "half.h"
namespace Imf {
//---------------------------------------------------------
// Conversion from half or float to unsigned int:
//
// input result
// ---------------------------------------------------
//
// finite, >= 0 input, cast to unsigned int
// (rounds towards zero)
//
// finite, < 0 0
//
// NaN 0
//
// +infinity UINT_MAX
//
// -infinity 0
//
//---------------------------------------------------------
unsigned int halfToUint (half h);
unsigned int floatToUint (float f);
//---------------------------------------------------------
// Conversion from unsigned int or float to half:
//
// input result
// ---------------------------------------------------
//
// finite, closest possible half
// magnitude <= HALF_MAX
//
// finite, > HALF_MAX +infinity
//
// finite, < -HALF_MAX -infinity
//
// NaN NaN
//
// +infinity +infinity
//
// -infinity -infinity
//
//---------------------------------------------------------
half uintToHalf (unsigned int ui);
half floatToHalf (float f);
} // namespace Imf
#endif

View File

@ -0,0 +1,63 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_DOUBLE_ATTRIBUTE_H
#define INCLUDED_IMF_DOUBLE_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class DoubleAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
namespace Imf {
typedef TypedAttribute<double> DoubleAttribute;
template <> const char *DoubleAttribute::staticTypeName ();
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfDoubleAttribute.cpp>
#endif
#endif

322
3rdparty/include/OpenEXR/ImfEnvmap.h vendored Normal file
View File

@ -0,0 +1,322 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_ENVMAP_H
#define INCLUDED_IMF_ENVMAP_H
//-----------------------------------------------------------------------------
//
// Environment maps
//
// Environment maps define a mapping from 3D directions to 2D
// pixel space locations. Environment maps are typically used
// in 3D rendering, for effects such as quickly approximating
// how shiny surfaces reflect their environment.
//
// Environment maps can be stored in scanline-based or in tiled
// OpenEXR files. The fact that an image is an environment map
// is indicated by the presence of an EnvmapAttribute whose name
// is "envmap". (Convenience functions to access this attribute
// are defined in header file ImfStandardAttributes.h.)
// The attribute's value defines the mapping from 3D directions
// to 2D pixel space locations.
//
// This header file defines the set of possible EnvmapAttribute
// values.
//
// For each possible EnvmapAttribute value, this header file also
// defines a set of convienience functions to convert between 3D
// directions and 2D pixel locations.
//
// Most of the convenience functions defined below require a
// dataWindow parameter. For scanline-based images, and for
// tiled images with level mode ONE_LEVEL, the dataWindow
// parameter should be set to the image's data window, as
// defined in the image header. For tiled images with level
// mode MIPMAP_LEVELS or RIPMAP_LEVELS, the data window of the
// image level that is being accessed should be used instead.
// (See the dataWindowForLevel() methods in ImfTiledInputFile.h
// and ImfTiledOutputFile.h.)
//
//-----------------------------------------------------------------------------
#include "ImathBox.h"
namespace Imf {
//--------------------------------
// Supported environment map types
//--------------------------------
enum Envmap
{
ENVMAP_LATLONG = 0, // Latitude-longitude environment map
ENVMAP_CUBE = 1, // Cube map
NUM_ENVMAPTYPES // Number of different environment map types
};
//-------------------------------------------------------------------------
// Latitude-Longitude Map:
//
// The environment is projected onto the image using polar coordinates
// (latitude and longitude). A pixel's x coordinate corresponds to
// its longitude, and the y coordinate corresponds to its latitude.
// Pixel (dataWindow.min.x, dataWindow.min.y) has latitude +pi/2 and
// longitude +pi; pixel (dataWindow.max.x, dataWindow.max.y) has
// latitude -pi/2 and longitude -pi.
//
// In 3D space, latitudes -pi/2 and +pi/2 correspond to the negative and
// positive y direction. Latitude 0, longitude 0 points into positive
// z direction; and latitude 0, longitude pi/2 points into positive x
// direction.
//
// The size of the data window should be 2*N by N pixels (width by height),
// where N can be any integer greater than 0.
//-------------------------------------------------------------------------
namespace LatLongMap
{
//----------------------------------------------------
// Convert a 3D direction to a 2D vector whose x and y
// components represent the corresponding latitude
// and longitude.
//----------------------------------------------------
Imath::V2f latLong (const Imath::V3f &direction);
//--------------------------------------------------------
// Convert the position of a pixel to a 2D vector whose
// x and y components represent the corresponding latitude
// and longitude.
//--------------------------------------------------------
Imath::V2f latLong (const Imath::Box2i &dataWindow,
const Imath::V2f &pixelPosition);
//-------------------------------------------------------------
// Convert a 2D vector, whose x and y components represent
// longitude and latitude, into a corresponding pixel position.
//-------------------------------------------------------------
Imath::V2f pixelPosition (const Imath::Box2i &dataWindow,
const Imath::V2f &latLong);
//-----------------------------------------------------
// Convert a 3D direction vector into a corresponding
// pixel position. pixelPosition(dw,dir) is equivalent
// to pixelPosition(dw,latLong(dw,dir)).
//-----------------------------------------------------
Imath::V2f pixelPosition (const Imath::Box2i &dataWindow,
const Imath::V3f &direction);
//--------------------------------------------------------
// Convert the position of a pixel in a latitude-longitude
// map into a corresponding 3D direction.
//--------------------------------------------------------
Imath::V3f direction (const Imath::Box2i &dataWindow,
const Imath::V2f &pixelPosition);
}
//--------------------------------------------------------------
// Cube Map:
//
// The environment is projected onto the six faces of an
// axis-aligned cube. The cube's faces are then arranged
// in a 2D image as shown below.
//
// 2-----------3
// / /|
// / / | Y
// / / | |
// 6-----------7 | |
// | | | |
// | | | |
// | 0 | 1 *------- X
// | | / /
// | | / /
// | |/ /
// 4-----------5 Z
//
// dataWindow.min
// /
// /
// +-----------+
// |3 Y 7|
// | | |
// | | |
// | ---+---Z | +X face
// | | |
// | | |
// |1 5|
// +-----------+
// |6 Y 2|
// | | |
// | | |
// | Z---+--- | -X face
// | | |
// | | |
// |4 0|
// +-----------+
// |6 Z 7|
// | | |
// | | |
// | ---+---X | +Y face
// | | |
// | | |
// |2 3|
// +-----------+
// |0 1|
// | | |
// | | |
// | ---+---X | -Y face
// | | |
// | | |
// |4 Z 5|
// +-----------+
// |7 Y 6|
// | | |
// | | |
// | X---+--- | +Z face
// | | |
// | | |
// |5 4|
// +-----------+
// |2 Y 3|
// | | |
// | | |
// | ---+---X | -Z face
// | | |
// | | |
// |0 1|
// +-----------+
// /
// /
// dataWindow.max
//
// The size of the data window should be N by 6*N pixels
// (width by height), where N can be any integer greater
// than 0.
//
//--------------------------------------------------------------
//------------------------------------
// Names for the six faces of the cube
//------------------------------------
enum CubeMapFace
{
CUBEFACE_POS_X, // +X face
CUBEFACE_NEG_X, // -X face
CUBEFACE_POS_Y, // +Y face
CUBEFACE_NEG_Y, // -Y face
CUBEFACE_POS_Z, // +Z face
CUBEFACE_NEG_Z, // -Z face
};
namespace CubeMap
{
//---------------------------------------------
// Width and height of a cube's face, in pixels
//---------------------------------------------
int sizeOfFace (const Imath::Box2i &dataWindow);
//------------------------------------------
// Compute the region in the environment map
// that is covered by the specified face.
//------------------------------------------
Imath::Box2i dataWindowForFace (CubeMapFace face,
const Imath::Box2i &dataWindow);
//----------------------------------------------------
// Convert the coordinates of a pixel within a face
// [in the range from (0,0) to (s-1,s-1), where
// s == sizeOfFace(dataWindow)] to pixel coordinates
// in the environment map.
//----------------------------------------------------
Imath::V2f pixelPosition (CubeMapFace face,
const Imath::Box2i &dataWindow,
Imath::V2f positionInFace);
//--------------------------------------------------------------
// Convert a 3D direction into a cube face, and a pixel position
// within that face.
//
// If you have a 3D direction, dir, the following code fragment
// finds the position, pos, of the corresponding pixel in an
// environment map with data window dw:
//
// CubeMapFace f;
// V2f pif, pos;
//
// faceAndPixelPosition (dir, dw, f, pif);
// pos = pixelPosition (f, dw, pif);
//
//--------------------------------------------------------------
void faceAndPixelPosition (const Imath::V3f &direction,
const Imath::Box2i &dataWindow,
CubeMapFace &face,
Imath::V2f &positionInFace);
// --------------------------------------------------------
// Given a cube face and a pixel position within that face,
// compute the corresponding 3D direction.
// --------------------------------------------------------
Imath::V3f direction (CubeMapFace face,
const Imath::Box2i &dataWindow,
const Imath::V2f &positionInFace);
}
} // namespace Imf
#endif

View File

@ -0,0 +1,65 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_ENVMAP_ATTRIBUTE_H
#define INCLUDED_IMF_ENVMAP_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class EnvmapAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include <ImfEnvmap.h>
namespace Imf {
typedef TypedAttribute<Envmap> EnvmapAttribute;
template <> const char *EnvmapAttribute::staticTypeName ();
template <> void EnvmapAttribute::writeValueTo (OStream &, int) const;
template <> void EnvmapAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfEnvmapAttribute.cpp>
#endif
#endif

View File

@ -0,0 +1,63 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_FLOAT_ATTRIBUTE_H
#define INCLUDED_IMF_FLOAT_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class FloatAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
namespace Imf {
typedef TypedAttribute<float> FloatAttribute;
template <> const char *FloatAttribute::staticTypeName ();
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfFloatAttribute.cpp>
#endif
#endif

View File

@ -0,0 +1,368 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_FRAME_BUFFER_H
#define INCLUDED_IMF_FRAME_BUFFER_H
//-----------------------------------------------------------------------------
//
// class Slice
// class FrameBuffer
//
//-----------------------------------------------------------------------------
#include <ImfName.h>
#include <ImfPixelType.h>
#include <map>
namespace Imf {
//-------------------------------------------------------
// Description of a single slice of the frame buffer:
//
// Note -- terminology: as part of a file, a component of
// an image (e.g. red, green, blue, depth etc.) is called
// a "channel". As part of a frame buffer, an image
// component is called a "slice".
//-------------------------------------------------------
struct Slice
{
//------------------------------
// Data type; see ImfPixelType.h
//------------------------------
PixelType type;
//---------------------------------------------------------------------
// Memory layout: The address of pixel (x, y) is
//
// base + (xp / xSampling) * xStride + (yp / ySampling) * yStride
//
// where xp and yp are computed as follows:
//
// * If we are reading or writing a scanline-based file:
//
// xp = x
// yp = y
//
// * If we are reading a tile whose upper left coorner is at (xt, yt):
//
// if xTileCoords is true then xp = x - xt, else xp = x
// if yTileCoords is true then yp = y - yt, else yp = y
//
//---------------------------------------------------------------------
char * base;
size_t xStride;
size_t yStride;
//--------------------------------------------
// Subsampling: pixel (x, y) is present in the
// slice only if
//
// x % xSampling == 0 && y % ySampling == 0
//
//--------------------------------------------
int xSampling;
int ySampling;
//----------------------------------------------------------
// Default value, used to fill the slice when a file without
// a channel that corresponds to this slice is read.
//----------------------------------------------------------
double fillValue;
//-------------------------------------------------------
// For tiled files, the xTileCoords and yTileCoords flags
// determine whether pixel addressing is performed using
// absolute coordinates or coordinates relative to a
// tile's upper left corner. (See the comment on base,
// xStride and yStride, above.)
//
// For scanline-based files these flags have no effect;
// pixel addressing is always done using absolute
// coordinates.
//-------------------------------------------------------
bool xTileCoords;
bool yTileCoords;
//------------
// Constructor
//------------
Slice (PixelType type = HALF,
char * base = 0,
size_t xStride = 0,
size_t yStride = 0,
int xSampling = 1,
int ySampling = 1,
double fillValue = 0.0,
bool xTileCoords = false,
bool yTileCoords = false);
};
class FrameBuffer
{
public:
//------------
// Add a slice
//------------
void insert (const char name[],
const Slice &slice);
//----------------------------------------------------------------
// Access to existing slices:
//
// [n] Returns a reference to the slice with name n.
// If no slice with name n exists, an Iex::ArgExc
// is thrown.
//
// findSlice(n) Returns a pointer to the slice with name n,
// or 0 if no slice with name n exists.
//
//----------------------------------------------------------------
Slice & operator [] (const char name[]);
const Slice & operator [] (const char name[]) const;
Slice * findSlice (const char name[]);
const Slice * findSlice (const char name[]) const;
//-----------------------------------------
// Iterator-style access to existing slices
//-----------------------------------------
typedef std::map <Name, Slice> SliceMap;
class Iterator;
class ConstIterator;
Iterator begin ();
ConstIterator begin () const;
Iterator end ();
ConstIterator end () const;
Iterator find (const char name[]);
ConstIterator find (const char name[]) const;
private:
SliceMap _map;
};
//----------
// Iterators
//----------
class FrameBuffer::Iterator
{
public:
Iterator ();
Iterator (const FrameBuffer::SliceMap::iterator &i);
Iterator & operator ++ ();
Iterator operator ++ (int);
const char * name () const;
Slice & slice () const;
private:
friend class FrameBuffer::ConstIterator;
FrameBuffer::SliceMap::iterator _i;
};
class FrameBuffer::ConstIterator
{
public:
ConstIterator ();
ConstIterator (const FrameBuffer::SliceMap::const_iterator &i);
ConstIterator (const FrameBuffer::Iterator &other);
ConstIterator & operator ++ ();
ConstIterator operator ++ (int);
const char * name () const;
const Slice & slice () const;
private:
friend bool operator == (const ConstIterator &, const ConstIterator &);
friend bool operator != (const ConstIterator &, const ConstIterator &);
FrameBuffer::SliceMap::const_iterator _i;
};
//-----------------
// Inline Functions
//-----------------
inline
FrameBuffer::Iterator::Iterator (): _i()
{
// empty
}
inline
FrameBuffer::Iterator::Iterator (const FrameBuffer::SliceMap::iterator &i):
_i (i)
{
// empty
}
inline FrameBuffer::Iterator &
FrameBuffer::Iterator::operator ++ ()
{
++_i;
return *this;
}
inline FrameBuffer::Iterator
FrameBuffer::Iterator::operator ++ (int)
{
Iterator tmp = *this;
++_i;
return tmp;
}
inline const char *
FrameBuffer::Iterator::name () const
{
return *_i->first;
}
inline Slice &
FrameBuffer::Iterator::slice () const
{
return _i->second;
}
inline
FrameBuffer::ConstIterator::ConstIterator (): _i()
{
// empty
}
inline
FrameBuffer::ConstIterator::ConstIterator
(const FrameBuffer::SliceMap::const_iterator &i): _i (i)
{
// empty
}
inline
FrameBuffer::ConstIterator::ConstIterator (const FrameBuffer::Iterator &other):
_i (other._i)
{
// empty
}
inline FrameBuffer::ConstIterator &
FrameBuffer::ConstIterator::operator ++ ()
{
++_i;
return *this;
}
inline FrameBuffer::ConstIterator
FrameBuffer::ConstIterator::operator ++ (int)
{
ConstIterator tmp = *this;
++_i;
return tmp;
}
inline const char *
FrameBuffer::ConstIterator::name () const
{
return *_i->first;
}
inline const Slice &
FrameBuffer::ConstIterator::slice () const
{
return _i->second;
}
inline bool
operator == (const FrameBuffer::ConstIterator &x,
const FrameBuffer::ConstIterator &y)
{
return x._i == y._i;
}
inline bool
operator != (const FrameBuffer::ConstIterator &x,
const FrameBuffer::ConstIterator &y)
{
return !(x == y);
}
} // namespace Imf
#endif

557
3rdparty/include/OpenEXR/ImfHeader.h vendored Normal file
View File

@ -0,0 +1,557 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_HEADER_H
#define INCLUDED_IMF_HEADER_H
//-----------------------------------------------------------------------------
//
// class Header
//
//-----------------------------------------------------------------------------
#include <ImfLineOrder.h>
#include <ImfCompression.h>
#include <ImfName.h>
#include <ImfTileDescription.h>
#include <ImfInt64.h>
#include "ImathVec.h"
#include "ImathBox.h"
#include "IexBaseExc.h"
#include <map>
#include <iosfwd>
namespace Imf {
class Attribute;
class ChannelList;
class IStream;
class OStream;
class PreviewImage;
class Header
{
public:
//----------------------------------------------------------------
// Default constructor -- the display window and the data window
// are both set to Box2i (V2i (0, 0), V2i (width-1, height-1).
//----------------------------------------------------------------
Header (int width = 64,
int height = 64,
float pixelAspectRatio = 1,
const Imath::V2f &screenWindowCenter = Imath::V2f (0, 0),
float screenWindowWidth = 1,
LineOrder lineOrder = INCREASING_Y,
Compression = ZIP_COMPRESSION);
//--------------------------------------------------------------------
// Constructor -- the data window is specified explicitly; the display
// window is set to Box2i (V2i (0, 0), V2i (width-1, height-1).
//--------------------------------------------------------------------
Header (int width,
int height,
const Imath::Box2i &dataWindow,
float pixelAspectRatio = 1,
const Imath::V2f &screenWindowCenter = Imath::V2f (0, 0),
float screenWindowWidth = 1,
LineOrder lineOrder = INCREASING_Y,
Compression = ZIP_COMPRESSION);
//----------------------------------------------------------
// Constructor -- the display window and the data window are
// both specified explicitly.
//----------------------------------------------------------
Header (const Imath::Box2i &displayWindow,
const Imath::Box2i &dataWindow,
float pixelAspectRatio = 1,
const Imath::V2f &screenWindowCenter = Imath::V2f (0, 0),
float screenWindowWidth = 1,
LineOrder lineOrder = INCREASING_Y,
Compression = ZIP_COMPRESSION);
//-----------------
// Copy constructor
//-----------------
Header (const Header &other);
//-----------
// Destructor
//-----------
~Header ();
//-----------
// Assignment
//-----------
Header & operator = (const Header &other);
//---------------------------------------------------------------
// Add an attribute:
//
// insert(n,attr) If no attribute with name n exists, a new
// attribute with name n, and the same type as
// attr, is added, and the value of attr is
// copied into the new attribute.
//
// If an attribute with name n exists, and its
// type is the same as attr, the value of attr
// is copied into this attribute.
//
// If an attribute with name n exists, and its
// type is different from attr, an Iex::TypeExc
// is thrown.
//
//---------------------------------------------------------------
void insert (const char name[],
const Attribute &attribute);
//------------------------------------------------------------------
// Access to existing attributes:
//
// [n] Returns a reference to the attribute
// with name n. If no attribute with
// name n exists, an Iex::ArgExc is thrown.
//
// typedAttribute<T>(n) Returns a reference to the attribute
// with name n and type T. If no attribute
// with name n exists, an Iex::ArgExc is
// thrown. If an attribute with name n
// exists, but its type is not T, an
// Iex::TypeExc is thrown.
//
// findTypedAttribute<T>(n) Returns a pointer to the attribute with
// name n and type T, or 0 if no attribute
// with name n and type T exists.
//
//------------------------------------------------------------------
Attribute & operator [] (const char name[]);
const Attribute & operator [] (const char name[]) const;
template <class T> T& typedAttribute (const char name[]);
template <class T> const T& typedAttribute (const char name[]) const;
template <class T> T* findTypedAttribute (const char name[]);
template <class T> const T* findTypedAttribute (const char name[]) const;
//---------------------------------------------
// Iterator-style access to existing attributes
//---------------------------------------------
typedef std::map <Name, Attribute *> AttributeMap;
class Iterator;
class ConstIterator;
Iterator begin ();
ConstIterator begin () const;
Iterator end ();
ConstIterator end () const;
Iterator find (const char name[]);
ConstIterator find (const char name[]) const;
//--------------------------------
// Access to predefined attributes
//--------------------------------
Imath::Box2i & displayWindow ();
const Imath::Box2i & displayWindow () const;
Imath::Box2i & dataWindow ();
const Imath::Box2i & dataWindow () const;
float & pixelAspectRatio ();
const float & pixelAspectRatio () const;
Imath::V2f & screenWindowCenter ();
const Imath::V2f & screenWindowCenter () const;
float & screenWindowWidth ();
const float & screenWindowWidth () const;
ChannelList & channels ();
const ChannelList & channels () const;
LineOrder & lineOrder ();
const LineOrder & lineOrder () const;
Compression & compression ();
const Compression & compression () const;
//----------------------------------------------------------------------
// Tile Description:
//
// The tile description is a TileDescriptionAttribute whose name
// is "tiles". The "tiles" attribute must be present in any tiled
// image file. When present, it describes various properties of the
// tiles that make up the file.
//
// Convenience functions:
//
// setTileDescription(td)
// calls insert ("tiles", TileDescriptionAttribute (td))
//
// tileDescription()
// returns typedAttribute<TileDescriptionAttribute>("tiles").value()
//
// hasTileDescription()
// return findTypedAttribute<TileDescriptionAttribute>("tiles") != 0
//
//----------------------------------------------------------------------
void setTileDescription (const TileDescription & td);
TileDescription & tileDescription ();
const TileDescription & tileDescription () const;
bool hasTileDescription() const;
//----------------------------------------------------------------------
// Preview image:
//
// The preview image is a PreviewImageAttribute whose name is "preview".
// This attribute is special -- while an image file is being written,
// the pixels of the preview image can be changed repeatedly by calling
// OutputFile::updatePreviewImage().
//
// Convenience functions:
//
// setPreviewImage(p)
// calls insert ("preview", PreviewImageAttribute (p))
//
// previewImage()
// returns typedAttribute<PreviewImageAttribute>("preview").value()
//
// hasPreviewImage()
// return findTypedAttribute<PreviewImageAttribute>("preview") != 0
//
//----------------------------------------------------------------------
void setPreviewImage (const PreviewImage &p);
PreviewImage & previewImage ();
const PreviewImage & previewImage () const;
bool hasPreviewImage () const;
//-------------------------------------------------------------
// Sanity check -- examines the header, and throws an exception
// if it finds something wrong (empty display window, negative
// pixel aspect ratio, unknown compression sceme etc.)
//
// set isTiled to true if you are checking a tiled/multi-res
// header
//-------------------------------------------------------------
void sanityCheck (bool isTiled = false) const;
//------------------------------------------------------------------
// Input and output:
//
// If the header contains a preview image attribute, then writeTo()
// returns the position of that attribute in the output stream; this
// information is used by OutputFile::updatePreviewImage().
// If the header contains no preview image attribute, then writeTo()
// returns 0.
//------------------------------------------------------------------
Int64 writeTo (OStream &os,
bool isTiled = false) const;
void readFrom (IStream &is, int &version);
private:
AttributeMap _map;
};
//----------
// Iterators
//----------
class Header::Iterator
{
public:
Iterator ();
Iterator (const Header::AttributeMap::iterator &i);
Iterator & operator ++ ();
Iterator operator ++ (int);
const char * name () const;
Attribute & attribute () const;
private:
friend class Header::ConstIterator;
Header::AttributeMap::iterator _i;
};
class Header::ConstIterator
{
public:
ConstIterator ();
ConstIterator (const Header::AttributeMap::const_iterator &i);
ConstIterator (const Header::Iterator &other);
ConstIterator & operator ++ ();
ConstIterator operator ++ (int);
const char * name () const;
const Attribute & attribute () const;
private:
friend bool operator == (const ConstIterator &, const ConstIterator &);
friend bool operator != (const ConstIterator &, const ConstIterator &);
Header::AttributeMap::const_iterator _i;
};
//------------------------------------------------------------------------
// Library initialization:
//
// In a multithreaded program, staticInitialize() must be called once
// during startup, before the program accesses any other functions or
// classes in the IlmImf library. Calling staticInitialize() in this
// way avoids races during initialization of the library's global
// variables.
//
// Single-threaded programs are not required to call staticInitialize();
// initialization of the library's global variables happens automatically.
//
//------------------------------------------------------------------------
void staticInitialize ();
//-----------------
// Inline Functions
//-----------------
inline
Header::Iterator::Iterator (): _i()
{
// empty
}
inline
Header::Iterator::Iterator (const Header::AttributeMap::iterator &i): _i (i)
{
// empty
}
inline Header::Iterator &
Header::Iterator::operator ++ ()
{
++_i;
return *this;
}
inline Header::Iterator
Header::Iterator::operator ++ (int)
{
Iterator tmp = *this;
++_i;
return tmp;
}
inline const char *
Header::Iterator::name () const
{
return *_i->first;
}
inline Attribute &
Header::Iterator::attribute () const
{
return *_i->second;
}
inline
Header::ConstIterator::ConstIterator (): _i()
{
// empty
}
inline
Header::ConstIterator::ConstIterator
(const Header::AttributeMap::const_iterator &i): _i (i)
{
// empty
}
inline
Header::ConstIterator::ConstIterator (const Header::Iterator &other):
_i (other._i)
{
// empty
}
inline Header::ConstIterator &
Header::ConstIterator::operator ++ ()
{
++_i;
return *this;
}
inline Header::ConstIterator
Header::ConstIterator::operator ++ (int)
{
ConstIterator tmp = *this;
++_i;
return tmp;
}
inline const char *
Header::ConstIterator::name () const
{
return *_i->first;
}
inline const Attribute &
Header::ConstIterator::attribute () const
{
return *_i->second;
}
inline bool
operator == (const Header::ConstIterator &x, const Header::ConstIterator &y)
{
return x._i == y._i;
}
inline bool
operator != (const Header::ConstIterator &x, const Header::ConstIterator &y)
{
return !(x == y);
}
//---------------------
// Template definitions
//---------------------
template <class T>
T &
Header::typedAttribute (const char name[])
{
Attribute *attr = &(*this)[name];
T *tattr = dynamic_cast <T*> (attr);
if (tattr == 0)
throw Iex::TypeExc ("Unexpected attribute type.");
return *tattr;
}
template <class T>
const T &
Header::typedAttribute (const char name[]) const
{
const Attribute *attr = &(*this)[name];
const T *tattr = dynamic_cast <const T*> (attr);
if (tattr == 0)
throw Iex::TypeExc ("Unexpected attribute type.");
return *tattr;
}
template <class T>
T *
Header::findTypedAttribute (const char name[])
{
AttributeMap::iterator i = _map.find (name);
return (i == _map.end())? 0: dynamic_cast <T*> (i->second);
}
template <class T>
const T *
Header::findTypedAttribute (const char name[]) const
{
AttributeMap::const_iterator i = _map.find (name);
return (i == _map.end())? 0: dynamic_cast <const T*> (i->second);
}
} // namespace Imf
#endif

79
3rdparty/include/OpenEXR/ImfHuf.h vendored Normal file
View File

@ -0,0 +1,79 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_HUF_H
#define INCLUDED_IMF_HUF_H
//-----------------------------------------------------------------------------
//
// 16-bit Huffman compression and decompression:
//
// hufCompress (r, nr, c)
//
// Compresses the contents of array r (of length nr),
// stores the compressed data in array c, and returns
// the size of the compressed data (in bytes).
//
// To avoid buffer overflows, the size of array c should
// be at least 2 * nr + 65536.
//
// hufUncompress (c, nc, r, nr)
//
// Uncompresses the data in array c (with length nc),
// and stores the results in array r (with length nr).
//
//-----------------------------------------------------------------------------
namespace Imf {
int
hufCompress (const unsigned short raw[/*nRaw*/],
int nRaw,
char compressed[/*2 * nRaw + 65536*/]);
void
hufUncompress (const char compressed[/*nCompressed*/],
int nCompressed,
unsigned short raw[/*nRaw*/],
int nRaw);
} // namespace Imf
#endif

252
3rdparty/include/OpenEXR/ImfIO.h vendored Normal file
View File

@ -0,0 +1,252 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_IO_H
#define INCLUDED_IMF_IO_H
//-----------------------------------------------------------------------------
//
// Low-level file input and output for OpenEXR.
//
//-----------------------------------------------------------------------------
#include <ImfInt64.h>
#include <string>
namespace Imf {
//-----------------------------------------------------------
// class IStream -- an abstract base class for input streams.
//-----------------------------------------------------------
class IStream
{
public:
//-----------
// Destructor
//-----------
virtual ~IStream ();
//-------------------------------------------------
// Does this input stream support memory-mapped IO?
//
// Memory-mapped streams can avoid an extra copy;
// memory-mapped read operations return a pointer
// to an internal buffer instead of copying data
// into a buffer supplied by the caller.
//-------------------------------------------------
virtual bool isMemoryMapped () const;
//------------------------------------------------------
// Read from the stream:
//
// read(c,n) reads n bytes from the stream, and stores
// them in array c. If the stream contains less than n
// bytes, or if an I/O error occurs, read(c,n) throws
// an exception. If read(c,n) reads the last byte from
// the file it returns false, otherwise it returns true.
//------------------------------------------------------
virtual bool read (char c[/*n*/], int n) = 0;
//---------------------------------------------------
// Read from a memory-mapped stream:
//
// readMemoryMapped(n) reads n bytes from the stream
// and returns a pointer to the first byte. The
// returned pointer remains valid until the stream
// is closed. If there are less than n byte left to
// read in the stream or if the stream is not memory-
// mapped, readMemoryMapped(n) throws an exception.
//---------------------------------------------------
virtual char * readMemoryMapped (int n);
//--------------------------------------------------------
// Get the current reading position, in bytes from the
// beginning of the file. If the next call to read() will
// read the first byte in the file, tellg() returns 0.
//--------------------------------------------------------
virtual Int64 tellg () = 0;
//-------------------------------------------
// Set the current reading position.
// After calling seekg(i), tellg() returns i.
//-------------------------------------------
virtual void seekg (Int64 pos) = 0;
//------------------------------------------------------
// Clear error conditions after an operation has failed.
//------------------------------------------------------
virtual void clear ();
//------------------------------------------------------
// Get the name of the file associated with this stream.
//------------------------------------------------------
const char * fileName () const;
protected:
IStream (const char fileName[]);
private:
IStream (const IStream &); // not implemented
IStream & operator = (const IStream &); // not implemented
std::string _fileName;
};
//-----------------------------------------------------------
// class OStream -- an abstract base class for output streams
//-----------------------------------------------------------
class OStream
{
public:
//-----------
// Destructor
//-----------
virtual ~OStream ();
//----------------------------------------------------------
// Write to the stream:
//
// write(c,n) takes n bytes from array c, and stores them
// in the stream. If an I/O error occurs, write(c,n) throws
// an exception.
//----------------------------------------------------------
virtual void write (const char c[/*n*/], int n) = 0;
//---------------------------------------------------------
// Get the current writing position, in bytes from the
// beginning of the file. If the next call to write() will
// start writing at the beginning of the file, tellp()
// returns 0.
//---------------------------------------------------------
virtual Int64 tellp () = 0;
//-------------------------------------------
// Set the current writing position.
// After calling seekp(i), tellp() returns i.
//-------------------------------------------
virtual void seekp (Int64 pos) = 0;
//------------------------------------------------------
// Get the name of the file associated with this stream.
//------------------------------------------------------
const char * fileName () const;
protected:
OStream (const char fileName[]);
private:
OStream (const OStream &); // not implemented
OStream & operator = (const OStream &); // not implemented
std::string _fileName;
};
//-----------------------
// Helper classes for Xdr
//-----------------------
struct StreamIO
{
static void
writeChars (OStream &os, const char c[/*n*/], int n)
{
os.write (c, n);
}
static bool
readChars (IStream &is, char c[/*n*/], int n)
{
return is.read (c, n);
}
};
struct CharPtrIO
{
static void
writeChars (char *&op, const char c[/*n*/], int n)
{
while (n--)
*op++ = *c++;
}
static bool
readChars (const char *&ip, char c[/*n*/], int n)
{
while (n--)
*c++ = *ip++;
return true;
}
};
} // namespace Imf
#endif

209
3rdparty/include/OpenEXR/ImfInputFile.h vendored Normal file
View File

@ -0,0 +1,209 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_INPUT_FILE_H
#define INCLUDED_IMF_INPUT_FILE_H
//-----------------------------------------------------------------------------
//
// class InputFile -- a scanline-based interface that can be used
// to read both scanline-based and tiled OpenEXR image files.
//
//-----------------------------------------------------------------------------
#include <ImfHeader.h>
#include <ImfFrameBuffer.h>
#include <ImfTiledOutputFile.h>
#include <string>
#include <fstream>
#include <ImfThreading.h>
namespace Imf {
class TiledInputFile;
class ScanLineInputFile;
class InputFile
{
public:
//-----------------------------------------------------------
// A constructor that opens the file with the specified name.
// Destroying the InputFile object will close the file.
//
// numThreads determines the number of threads that will be
// used to read the file (see ImfThreading.h).
//-----------------------------------------------------------
InputFile (const char fileName[], int numThreads = globalThreadCount());
//-------------------------------------------------------------
// A constructor that attaches the new InputFile object to a
// file that has already been opened. Destroying the InputFile
// object will not close the file.
//
// numThreads determines the number of threads that will be
// used to read the file (see ImfThreading.h).
//-------------------------------------------------------------
InputFile (IStream &is, int numThreads = globalThreadCount());
//-----------
// Destructor
//-----------
virtual ~InputFile ();
//------------------------
// Access to the file name
//------------------------
const char * fileName () const;
//--------------------------
// Access to the file header
//--------------------------
const Header & header () const;
//----------------------------------
// Access to the file format version
//----------------------------------
int version () const;
//-----------------------------------------------------------
// Set the current frame buffer -- copies the FrameBuffer
// object into the InputFile object.
//
// The current frame buffer is the destination for the pixel
// data read from the file. The current frame buffer must be
// set at least once before readPixels() is called.
// The current frame buffer can be changed after each call
// to readPixels().
//-----------------------------------------------------------
void setFrameBuffer (const FrameBuffer &frameBuffer);
//-----------------------------------
// Access to the current frame buffer
//-----------------------------------
const FrameBuffer & frameBuffer () const;
//---------------------------------------------------------------
// Check if the file is complete:
//
// isComplete() returns true if all pixels in the data window are
// present in the input file, or false if any pixels are missing.
// (Another program may still be busy writing the file, or file
// writing may have been aborted prematurely.)
//---------------------------------------------------------------
bool isComplete () const;
//---------------------------------------------------------------
// Read pixel data:
//
// readPixels(s1,s2) reads all scan lines with y coordinates
// in the interval [min (s1, s2), max (s1, s2)] from the file,
// and stores them in the current frame buffer.
//
// Both s1 and s2 must be within the interval
// [header().dataWindow().min.y, header().dataWindow().max.y]
//
// The scan lines can be read from the file in random order, and
// individual scan lines may be skipped or read multiple times.
// For maximum efficiency, the scan lines should be read in the
// order in which they were written to the file.
//
// readPixels(s) calls readPixels(s,s).
//
//---------------------------------------------------------------
void readPixels (int scanLine1, int scanLine2);
void readPixels (int scanLine);
//----------------------------------------------
// Read a block of raw pixel data from the file,
// without uncompressing it (this function is
// used to implement OutputFile::copyPixels()).
//----------------------------------------------
void rawPixelData (int firstScanLine,
const char *&pixelData,
int &pixelDataSize);
//--------------------------------------------------
// Read a tile of raw pixel data from the file,
// without uncompressing it (this function is
// used to implement TiledOutputFile::copyPixels()).
//--------------------------------------------------
void rawTileData (int &dx, int &dy,
int &lx, int &ly,
const char *&pixelData,
int &pixelDataSize);
struct Data;
private:
InputFile (const InputFile &); // not implemented
InputFile & operator = (const InputFile &); // not implemented
void initialize ();
TiledInputFile * tFile ();
friend void TiledOutputFile::copyPixels (InputFile &);
Data * _data;
};
} // namespace Imf
#endif

61
3rdparty/include/OpenEXR/ImfInt64.h vendored Normal file
View File

@ -0,0 +1,61 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_INT64_H
#define INCLUDED_IMF_INT64_H
//----------------------------------------------------------------------------
//
// Int64 -- unsigned 64-bit integers
//
//----------------------------------------------------------------------------
#include <limits.h>
namespace Imf {
#if (defined _WIN32 || defined _WIN64) && _MSC_VER >= 1300
typedef unsigned __int64 Int64;
#elif ULONG_MAX == 18446744073709551615LU
typedef long unsigned int Int64;
#else
typedef long long unsigned int Int64;
#endif
} // namespace Imf
#endif

View File

@ -0,0 +1,63 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_INT_ATTRIBUTE_H
#define INCLUDED_IMF_INT_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class IntAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
namespace Imf {
typedef TypedAttribute<int> IntAttribute;
template <> const char *IntAttribute::staticTypeName ();
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfIntAttribute.cpp>
#endif
#endif

161
3rdparty/include/OpenEXR/ImfKeyCode.h vendored Normal file
View File

@ -0,0 +1,161 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_KEY_CODE_H
#define INCLUDED_IMF_KEY_CODE_H
//-----------------------------------------------------------------------------
//
// class KeyCode
//
// A KeyCode object uniquely identifies a motion picture film frame.
// The following fields specifiy film manufacturer, film type, film
// roll and the frame's position within the roll:
//
// filmMfcCode film manufacturer code
// range: 0 - 99
//
// filmType film type code
// range: 0 - 99
//
// prefix prefix to identify film roll
// range: 0 - 999999
//
// count count, increments once every perfsPerCount
// perforations (see below)
// range: 0 - 9999
//
// perfOffset offset of frame, in perforations from
// zero-frame reference mark
// range: 0 - 119
//
// perfsPerFrame number of perforations per frame
// range: 1 - 15
//
// typical values:
//
// 1 for 16mm film
// 3, 4, or 8 for 35mm film
// 5, 8 or 15 for 65mm film
//
// perfsPerCount number of perforations per count
// range: 20 - 120
//
// typical values:
//
// 20 for 16mm film
// 64 for 35mm film
// 80 or 120 for 65mm film
//
// For more information about the interpretation of those fields see
// the following standards and recommended practice publications:
//
// SMPTE 254 Motion-Picture Film (35-mm) - Manufacturer-Printed
// Latent Image Identification Information
//
// SMPTE 268M File Format for Digital Moving-Picture Exchange (DPX)
// (section 6.1)
//
// SMPTE 270 Motion-Picture Film (65-mm) - Manufacturer- Printed
// Latent Image Identification Information
//
// SMPTE 271 Motion-Picture Film (16-mm) - Manufacturer- Printed
// Latent Image Identification Information
//
//-----------------------------------------------------------------------------
namespace Imf {
class KeyCode
{
public:
//-------------------------------------
// Constructors and assignment operator
//-------------------------------------
KeyCode (int filmMfcCode = 0,
int filmType = 0,
int prefix = 0,
int count = 0,
int perfOffset = 0,
int perfsPerFrame = 4,
int perfsPerCount = 64);
KeyCode (const KeyCode &other);
KeyCode & operator = (const KeyCode &other);
//----------------------------
// Access to individual fields
//----------------------------
int filmMfcCode () const;
void setFilmMfcCode (int filmMfcCode);
int filmType () const;
void setFilmType (int filmType);
int prefix () const;
void setPrefix (int prefix);
int count () const;
void setCount (int count);
int perfOffset () const;
void setPerfOffset (int perfOffset);
int perfsPerFrame () const;
void setPerfsPerFrame (int perfsPerFrame);
int perfsPerCount () const;
void setPerfsPerCount (int perfsPerCount);
private:
int _filmMfcCode;
int _filmType;
int _prefix;
int _count;
int _perfOffset;
int _perfsPerFrame;
int _perfsPerCount;
};
} // namespace Imf
#endif

View File

@ -0,0 +1,72 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_KEY_CODE_ATTRIBUTE_H
#define INCLUDED_IMF_KEY_CODE_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class KeyCodeAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include <ImfKeyCode.h>
namespace Imf {
typedef TypedAttribute<KeyCode> KeyCodeAttribute;
template <>
const char *KeyCodeAttribute::staticTypeName ();
template <>
void KeyCodeAttribute::writeValueTo (OStream &, int) const;
template <>
void KeyCodeAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfKeyCodeAttribute.cpp>
#endif
#endif

64
3rdparty/include/OpenEXR/ImfLineOrder.h vendored Normal file
View File

@ -0,0 +1,64 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_LINE_ORDER_H
#define INCLUDED_IMF_LINE_ORDER_H
//-----------------------------------------------------------------------------
//
// enum LineOrder
//
//-----------------------------------------------------------------------------
namespace Imf {
enum LineOrder
{
INCREASING_Y = 0, // first scan line has lowest y coordinate
DECREASING_Y = 1, // first scan line has highest y coordinate
RANDOM_Y = 2, // only for tiled files; tiles are written
// in random order
NUM_LINEORDERS // number of different line orders
};
} // namespace Imf
#endif

View File

@ -0,0 +1,66 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_LINE_ORDER_ATTRIBUTE_H
#define INCLUDED_IMF_LINE_ORDER_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class LineOrderAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include <ImfLineOrder.h>
namespace Imf {
typedef TypedAttribute<LineOrder> LineOrderAttribute;
template <> const char *LineOrderAttribute::staticTypeName ();
template <> void LineOrderAttribute::writeValueTo (OStream &, int) const;
template <> void LineOrderAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfLineOrderAttribute.cpp>
#endif
#endif

185
3rdparty/include/OpenEXR/ImfLut.h vendored Normal file
View File

@ -0,0 +1,185 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_LUT_H
#define INCLUDED_IMF_LUT_H
//-----------------------------------------------------------------------------
//
// Lookup tables for efficient application
// of half --> half functions to pixel data,
// and some commonly applied functions.
//
//-----------------------------------------------------------------------------
#include <ImfRgbaFile.h>
#include <ImfFrameBuffer.h>
#include "ImathBox.h"
#include "halfFunction.h"
namespace Imf {
//
// Lookup table for individual half channels.
//
class HalfLut
{
public:
//------------
// Constructor
//------------
template <class Function>
HalfLut (Function f);
//----------------------------------------------------------------------
// Apply the table to data[0], data[stride] ... data[(nData-1) * stride]
//----------------------------------------------------------------------
void apply (half *data,
int nData,
int stride = 1) const;
//---------------------------------------------------------------
// Apply the table to a frame buffer slice (see ImfFrameBuffer.h)
//---------------------------------------------------------------
void apply (const Slice &data,
const Imath::Box2i &dataWindow) const;
private:
halfFunction <half> _lut;
};
//
// Lookup table for combined RGBA data.
//
class RgbaLut
{
public:
//------------
// Constructor
//------------
template <class Function>
RgbaLut (Function f, RgbaChannels chn = WRITE_RGB);
//----------------------------------------------------------------------
// Apply the table to data[0], data[stride] ... data[(nData-1) * stride]
//----------------------------------------------------------------------
void apply (Rgba *data,
int nData,
int stride = 1) const;
//-----------------------------------------------------------------------
// Apply the table to a frame buffer (see RgbaOutpuFile.setFrameBuffer())
//-----------------------------------------------------------------------
void apply (Rgba *base,
int xStride,
int yStride,
const Imath::Box2i &dataWindow) const;
private:
halfFunction <half> _lut;
RgbaChannels _chn;
};
//
// 12bit log rounding reduces data to 20 stops with 200 steps per stop.
// That makes 4000 numbers. An extra 96 just come along for the ride.
// Zero explicitly remains zero. The first non-zero half will map to 1
// in the 0-4095 12log space. A nice power of two number is placed at
// the center [2000] and that number is near 0.18.
//
half round12log (half x);
//
// Round to n-bit precision (n should be between 0 and 10).
// After rounding, the significand's 10-n least significant
// bits will be zero.
//
struct roundNBit
{
roundNBit (int n): n(n) {}
half operator () (half x) {return x.round(n);}
int n;
};
//
// Template definitions
//
template <class Function>
HalfLut::HalfLut (Function f):
_lut(f, -HALF_MAX, HALF_MAX, half (0),
half::posInf(), half::negInf(), half::qNan())
{
// empty
}
template <class Function>
RgbaLut::RgbaLut (Function f, RgbaChannels chn):
_lut(f, -HALF_MAX, HALF_MAX, half (0),
half::posInf(), half::negInf(), half::qNan()),
_chn(chn)
{
// empty
}
} // namespace Imf
#endif

View File

@ -0,0 +1,73 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_MATRIX_ATTRIBUTE_H
#define INCLUDED_IMF_MATRIX_ATTRIBUTE_H
//-----------------------------------------------------------------------------
//
// class M33fAttribute
// class M44fAttribute
//
//-----------------------------------------------------------------------------
#include <ImfAttribute.h>
#include "ImathMatrix.h"
namespace Imf {
typedef TypedAttribute<Imath::M33f> M33fAttribute;
template <> const char *M33fAttribute::staticTypeName ();
template <> void M33fAttribute::writeValueTo (OStream &, int) const;
template <> void M33fAttribute::readValueFrom (IStream &, int, int);
typedef TypedAttribute<Imath::M44f> M44fAttribute;
template <> const char *M44fAttribute::staticTypeName ();
template <> void M44fAttribute::writeValueTo (OStream &, int) const;
template <> void M44fAttribute::readValueFrom (IStream &, int, int);
} // namespace Imf
// Metrowerks compiler wants the .cpp file inlined, too
#ifdef __MWERKS__
#include <ImfMatrixAttribute.cpp>
#endif
#endif

146
3rdparty/include/OpenEXR/ImfName.h vendored Normal file
View File

@ -0,0 +1,146 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_NAME_H
#define INCLUDED_IMF_NAME_H
//-----------------------------------------------------------------------------
//
// class ImfName -- a zero-terminated string
// with a fixed, small maximum length
//
//-----------------------------------------------------------------------------
#include <string.h>
namespace Imf {
class Name
{
public:
//-------------
// Constructors
//-------------
Name ();
Name (const char text[]);
//--------------------
// Assignment operator
//--------------------
Name & operator = (const char text[]);
//---------------------
// Access to the string
//---------------------
const char * text () const {return _text;}
const char * operator * () const {return _text;}
//---------------
// Maximum length
//---------------
static const int SIZE = 32;
static const int MAX_LENGTH = SIZE - 1;
private:
char _text[SIZE];
};
bool operator == (const Name &x, const Name &y);
bool operator != (const Name &x, const Name &y);
bool operator < (const Name &x, const Name &y);
//-----------------
// Inline functions
//-----------------
inline Name &
Name::operator = (const char text[])
{
strncpy (_text, text, MAX_LENGTH);
return *this;
}
inline
Name::Name ()
{
_text[0] = 0;
}
inline
Name::Name (const char text[])
{
*this = text;
_text [MAX_LENGTH] = 0;
}
inline bool
operator == (const Name &x, const Name &y)
{
return strcmp (*x, *y) == 0;
}
inline bool
operator != (const Name &x, const Name &y)
{
return !(x == y);
}
inline bool
operator < (const Name &x, const Name &y)
{
return strcmp (*x, *y) < 0;
}
} // namespace IMF
#endif

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