add usd-21-11-win64_py39

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:43:55 +01:00
1 parent 41d23e71ba
commit ba5e1f7e67
15684 files changed
+3069957

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_API_H
#define PXR_BASE_VT_API_H
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define VT_API
# define VT_API_TEMPLATE_CLASS(...)
# define VT_API_TEMPLATE_STRUCT(...)
# define VT_LOCAL
#else
# if defined(VT_EXPORTS)
# define VT_API ARCH_EXPORT
# define VT_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define VT_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define VT_API ARCH_IMPORT
# define VT_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define VT_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define VT_LOCAL ARCH_HIDDEN
#endif
#endif
+962
View File
@@ -0,0 +1,962 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_ARRAY_H
#define PXR_BASE_VT_ARRAY_H
/// \file vt/array.h
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/hash.h"
#include "pxr/base/vt/operators.h"
#include "pxr/base/vt/streamOut.h"
#include "pxr/base/vt/traits.h"
#include "pxr/base/vt/types.h"
#include "pxr/base/arch/functionLite.h"
#include "pxr/base/arch/pragmas.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/mallocTag.h"
#include <boost/functional/hash.hpp>
#include <boost/iterator_adaptors.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdlib>
#include <memory>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
// Helper class for clients that create VtArrays referring to foreign-owned
// data.
class Vt_ArrayForeignDataSource
{
public:
explicit Vt_ArrayForeignDataSource(
void (*detachedFn)(Vt_ArrayForeignDataSource *self) = nullptr,
size_t initRefCount = 0)
: _refCount(initRefCount)
, _detachedFn(detachedFn) {}
private:
template <class T> friend class VtArray;
// Invoked when no more arrays share this data source.
void _ArraysDetached() { if (_detachedFn) { _detachedFn(this); } }
protected:
std::atomic<size_t> _refCount;
void (*_detachedFn)(Vt_ArrayForeignDataSource *self);
};
// Private base class helper for VtArray implementation.
class Vt_ArrayBase
{
public:
Vt_ArrayBase() : _shapeData { 0 }, _foreignSource(nullptr) {}
Vt_ArrayBase(Vt_ArrayForeignDataSource *foreignSrc)
: _shapeData { 0 }, _foreignSource(foreignSrc) {}
Vt_ArrayBase(Vt_ArrayBase const &other) = default;
Vt_ArrayBase(Vt_ArrayBase &&other) : Vt_ArrayBase(other) {
other._shapeData.clear();
other._foreignSource = nullptr;
}
Vt_ArrayBase &operator=(Vt_ArrayBase const &other) = default;
Vt_ArrayBase &operator=(Vt_ArrayBase &&other) {
if (this == &other)
return *this;
*this = other;
other._shapeData.clear();
other._foreignSource = nullptr;
return *this;
}
protected:
// Control block header for native data representation. Houses refcount and
// capacity. For arrays with native data, this structure always lives
// immediately preceding the start of the array's _data in memory. See
// _GetControlBlock() for details.
struct _ControlBlock {
_ControlBlock() : nativeRefCount(0), capacity(0) {}
_ControlBlock(size_t initCount, size_t initCap)
: nativeRefCount(initCount), capacity(initCap) {}
mutable std::atomic<size_t> nativeRefCount;
size_t capacity;
};
_ControlBlock &_GetControlBlock(void *nativeData) {
TF_DEV_AXIOM(!_foreignSource);
return *(reinterpret_cast<_ControlBlock *>(nativeData) - 1);
}
_ControlBlock const &_GetControlBlock(void *nativeData) const {
TF_DEV_AXIOM(!_foreignSource);
return *(reinterpret_cast<_ControlBlock *>(nativeData) - 1);
}
// Mutable ref count, as is standard.
std::atomic<size_t> &_GetNativeRefCount(void *nativeData) const {
return _GetControlBlock(nativeData).nativeRefCount;
}
size_t &_GetCapacity(void *nativeData) {
return _GetControlBlock(nativeData).capacity;
}
size_t const &_GetCapacity(void *nativeData) const {
return _GetControlBlock(nativeData).capacity;
}
VT_API void _DetachCopyHook(char const *funcName) const;
Vt_ShapeData _shapeData;
Vt_ArrayForeignDataSource *_foreignSource;
};
/// \class VtArray
///
/// Represents an arbitrary dimensional rectangular container class.
///
/// Originally, VtArray was built to mimic the arrays in menv2x's MDL language,
/// but since VtArray has typed elements, the multidimensionality has found
/// little use. For example, if you have only scalar elements, then to
/// represent a list of vectors you need a two dimensional array. To represent
/// a list of matrices you need a three dimensional array. However with
/// VtArray<GfVec3d> and VtArray<GfMatrix4d>, the VtArray is one dimensional and
/// the extra dimensions are encoded in the element types themselves.
///
/// For this reason, VtArray has been moving toward being more like std::vector,
/// and it now has much of std::vector's API, but there are still important
/// differences.
///
/// First, VtArray shares data between instances using a copy-on-write scheme.
/// This means that making copies of VtArray instances is cheap: it only copies
/// the pointer to the data. But on the other hand, invoking any non-const
/// member function incurs a copy of the underlying data if it is not
/// uniquely owned. For example, assume 'a' and 'b' are VtArray<int>:
///
/// \code
/// a = b; // No copy; a and b now share ownership of underlying data.
/// a[0] = 123; // A copy is incurred, to detach a's data from b.
/// // a and b no longer share data.
/// a[1] = 234; // No copy: a's data is uniquely owned by a.
/// \endcode
///
/// Note that since all non-const member functions will potentially cause a
/// copy, it's possible to accidentally incur a copy even when unintended, or
/// when no actual data mutation occurs. For example:
///
/// \code
/// int sum = 0;
/// for (VtArray<int>::iterator i = a.begin(), end = a.end(); i != end; ++i) {
/// sum += *i;
/// }
/// \endcode
///
/// Invoking a.begin() here will incur a copy if a's data is shared. This is
/// required since it's possible to mutate the data through the returned
/// iterator, even though the subsequent code doesn't do any mutation. This can
/// be avoided by explicitly const-iterating like the following:
///
/// \code
/// int sum = 0;
/// for (VtArray<int>::const_iterator i = a.cbegin(), end = a.cend(); i != end; ++i) {
/// sum += *i;
/// }
/// \endcode
///
/// This can be quite subtle. In C++, calling a member function that has const
/// and non-const overloads on a non-const object must invoke the non-const
/// version, even if the const version would suffice. So something as simple
/// this:
///
/// \code
/// float x = array[123];
/// \endcode
///
/// Invokes the non-const operator[] if \p array is non-const. That means this
/// kind of benign looking code can cause a copy-on-write detachment of the
/// entire array, and thus is not safe to invoke concurrently with any other
/// member function. If we were building this class today we would make
/// different choices about this API, but changing this now is a gargantuan
/// task, so it remains.
///
/// So, it is best practice to ensure you use const VtArray, or const VtArray &,
/// or VtArray::AsConst(), as well as the `c`-prefixed member functions like
/// cbegin()/cend(), cfront()/cback() to avoid these pitfalls when your intent
/// is not to mutate the array.
///
/// Regarding thread safety, for the same reasons spelled out above, all
/// mutating member functions must be invoked exclusively to all other member
/// functions, even if they are invoked in a way that does not mutate (as in the
/// operator[] example above). This is the same general rule that the STL
/// abides by.
///
/// Also, and again for the same reasons, all mutating member functions can
/// invalidate iterators, even if the member functions are invoked in a way that
/// does not mutate (as in the operator[] example above).
///
/// The TfEnvSetting 'VT_LOG_STACK_ON_ARRAY_DETACH_COPY' can be set to help
/// determine where unintended copy-on-write detaches come from. When set,
/// VtArray will log a stack trace for every copy-on-write detach that occurs.
///
template<typename ELEM>
class VtArray : public Vt_ArrayBase {
public:
/// Type this array holds.
typedef ELEM ElementType;
typedef ELEM value_type;
template <typename Value>
class PointerIterator
: public boost::iterator_adaptor<PointerIterator<Value>, Value *> {
public:
PointerIterator() :
PointerIterator::iterator_adaptor_(0) {}
explicit PointerIterator(Value *p) :
PointerIterator::iterator_adaptor_(p) {}
template <typename OtherValue>
PointerIterator(PointerIterator<OtherValue> const &other,
typename boost::enable_if_convertible
<OtherValue*, Value*>::type* = 0) :
PointerIterator::iterator_adaptor_(other.base()) {}
private:
friend class boost::iterator_core_access;
};
/// \defgroup STL_API STL-like API
/// @{
/// Iterator type.
typedef PointerIterator<ElementType> iterator;
/// Const iterator type.
typedef PointerIterator<const ElementType> const_iterator;
/// Reverse iterator type.
typedef boost::reverse_iterator<iterator> reverse_iterator;
/// Reverse const iterator type.
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
/// Reference type.
typedef typename PointerIterator<ElementType>::reference
reference;
/// Const reference type.
typedef typename PointerIterator<const ElementType>::reference
const_reference;
/// Pointer type.
typedef typename PointerIterator<ElementType>::pointer pointer;
/// Const pointer type.
typedef typename PointerIterator<const ElementType>::pointer const_pointer;
/// @}
/// Create an empty array.
VtArray() : _data(nullptr) {}
/// Create an array from a pair of iterators
///
/// Equivalent to:
/// \code
/// VtArray<T> v;
/// v.assign(first, last);
/// \endcode
///
/// Note we use enable_if with a dummy parameter here to avoid clashing
/// with our other constructor with the following signature:
///
/// VtArray(size_t n, value_type const &value = value_type())
template <typename LegacyInputIterator>
VtArray(LegacyInputIterator first, LegacyInputIterator last,
typename std::enable_if<
!std::is_integral<LegacyInputIterator>::value,
void>::type* = nullptr)
: VtArray() {
assign(first, last);
}
/// Create an array with foreign source.
VtArray(Vt_ArrayForeignDataSource *foreignSrc,
ElementType *data, size_t size, bool addRef = true)
: Vt_ArrayBase(foreignSrc)
, _data(data) {
if (addRef) {
foreignSrc->_refCount.fetch_add(1, std::memory_order_relaxed);
}
_shapeData.totalSize = size;
}
/// Copy \p other. The new array shares underlying data with \p other.
VtArray(VtArray const &other) : Vt_ArrayBase(other)
, _data(other._data) {
if (!_data)
return;
if (ARCH_LIKELY(!_foreignSource)) {
_GetNativeRefCount(_data).fetch_add(1, std::memory_order_relaxed);
}
else {
_foreignSource->_refCount.fetch_add(1, std::memory_order_relaxed);
}
}
/// Move from \p other. The new array takes ownership of \p other's
/// underlying data.
VtArray(VtArray &&other) : Vt_ArrayBase(std::move(other))
, _data(other._data) {
other._data = nullptr;
}
/// Initialize array from the contents of a \p initializerList.
VtArray(std::initializer_list<ELEM> initializerList)
: VtArray() {
assign(initializerList);
}
/// Create an array filled with \p n value-initialized elements.
explicit VtArray(size_t n)
: VtArray() {
assign(n, value_type());
}
/// Create an array filled with \p n copies of \p value.
explicit VtArray(size_t n, value_type const &value)
: VtArray() {
assign(n, value);
}
/// Copy assign from \p other. This array shares underlying data with
/// \p other.
VtArray &operator=(VtArray const &other) {
// This might look recursive but it's really invoking move-assign, since
// we create a temporary copy (an rvalue).
if (this != &other)
*this = VtArray(other);
return *this;
}
/// Move assign from \p other. This array takes ownership of \p other's
/// underlying data.
VtArray &operator=(VtArray &&other) {
if (this == &other)
return *this;
_DecRef();
static_cast<Vt_ArrayBase &>(*this) = std::move(other);
_data = other._data;
other._data = nullptr;
return *this;
}
/// Replace current array contents with those in \p initializerList
VtArray &operator=(std::initializer_list<ELEM> initializerList) {
this->assign(initializerList.begin(), initializerList.end());
return *this;
}
~VtArray() { _DecRef(); }
/// Return *this as a const reference. This ensures that all operations on
/// the result do not mutate and thus are safe to invoke concurrently with
/// other non-mutating operations, and will never cause a copy-on-write
/// detach.
///
/// Note that the return is a const reference to this object, so it is only
/// valid within the lifetime of this array object. Take special care
/// invoking AsConst() on VtArray temporaries/rvalues.
VtArray const &AsConst() const noexcept {
return *this;
}
/// \addtogroup STL_API
/// @{
/// Return a non-const iterator to the start of the array. The underlying
/// data is copied if it is not uniquely owned.
iterator begin() { return iterator(data()); }
/// Returns a non-const iterator to the end of the array. The underlying
/// data is copied if it is not uniquely owned.
iterator end() { return iterator(data() + size()); }
/// Return a const iterator to the start of the array.
const_iterator begin() const { return const_iterator(data()); }
/// Return a const iterator to the end of the array.
const_iterator end() const { return const_iterator(data() + size()); }
/// Return a const iterator to the start of the array.
const_iterator cbegin() const { return begin(); }
/// Return a const iterator to the end of the array.
const_iterator cend() const { return end(); }
/// Return a non-const reverse iterator to the end of the array. The
/// underlying data is copied if it is not uniquely owned.
reverse_iterator rbegin() { return reverse_iterator(end()); }
/// Return a reverse iterator to the start of the array. The underlying
/// data is copied if it is not uniquely owned.
reverse_iterator rend() { return reverse_iterator(begin()); }
/// Return a const reverse iterator to the end of the array.
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
/// Return a const reverse iterator to the start of the array.
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
/// Return a const reverse iterator to the end of the array.
const_reverse_iterator crbegin() const { return rbegin(); }
/// Return a const reverse iterator to the start of the array.
const_reverse_iterator crend() const { return rend(); }
/// Return a non-const pointer to this array's data. The underlying data is
/// copied if it is not uniquely owned.
pointer data() { _DetachIfNotUnique(); return _data; }
/// Return a const pointer to this array's data.
const_pointer data() const { return _data; }
/// Return a const pointer to the data held by this array.
const_pointer cdata() const { return _data; }
/// Initializes a new element at the end of the array. The underlying data
/// is first copied if it is not uniquely owned.
///
/// \sa push_back(ElementType const&)
/// \sa push_back(ElementType&&)
template <typename... Args>
void emplace_back(Args&&... args) {
// If this is a non-pxr array with rank > 1, disallow push_back.
if (ARCH_UNLIKELY(_shapeData.otherDims[0])) {
TF_CODING_ERROR("Array rank %u != 1", _shapeData.GetRank());
return;
}
// If we don't own the data, or if we need more space, realloc.
size_t curSize = size();
if (ARCH_UNLIKELY(
_foreignSource || !_IsUnique() || curSize == capacity())) {
value_type *newData = _AllocateCopy(
_data, _CapacityForSize(curSize + 1), curSize);
_DecRef();
_data = newData;
}
// Copy the value.
::new (static_cast<void*>(_data + curSize)) value_type(
std::forward<Args>(args)...);
// Adjust size.
++_shapeData.totalSize;
}
/// Appends an element at the end of the array. The underlying data
/// is first copied if it is not uniquely owned.
///
/// \sa emplace_back
/// \sa push_back(ElementType&&)
void push_back(ElementType const& element) {
emplace_back(element);
}
/// Appends an element at the end of the array. The underlying data
/// is first copied if it is not uniquely owned.
///
/// \sa emplace_back
/// \sa push_back(ElementType const&)
void push_back(ElementType&& element) {
emplace_back(std::move(element));
}
/// Remove the last element of an array. The underlying data is first
/// copied if it is not uniquely owned.
void pop_back() {
// If this is a presto array with rank > 1, disallow push_back.
if (ARCH_UNLIKELY(_shapeData.otherDims[0])) {
TF_CODING_ERROR("Array rank %u != 1", _shapeData.GetRank());
return;
}
_DetachIfNotUnique();
// Invoke the destructor.
(_data + size() - 1)->~value_type();
// Adjust size.
--_shapeData.totalSize;
}
/// Return the total number of elements in this array.
size_t size() const { return _shapeData.totalSize; }
/// Return the number of items this container can grow to hold without
/// triggering a (re)allocation. Note that if the underlying data is not
/// uniquely owned, a reallocation can occur upon object insertion even if
/// there is remaining capacity.
size_t capacity() const {
if (!_data) {
return 0;
}
// We do not allow mutation to foreign source data, so always report
// foreign sourced arrays as at capacity.
return ARCH_UNLIKELY(_foreignSource) ? size() : _GetCapacity(_data);
}
/// Return true if this array contains no elements, false otherwise.
bool empty() const { return size() == 0; }
/// Ensure enough memory is allocated to hold \p num elements. Note that
/// this currently does not ensure that the underlying data is uniquely
/// owned. If that is desired, invoke a method like data() first.
void reserve(size_t num) {
if (num <= capacity())
return;
value_type *newData =
_data ? _AllocateCopy(_data, num, size()) : _AllocateNew(num);
_DecRef();
_data = newData;
}
/// Return a non-const reference to the first element in this array. The
/// underlying data is copied if it is not uniquely owned. Invokes
/// undefined behavior if the array is empty.
reference front() { return *begin(); }
/// Return a const reference to the first element in this array. Invokes
/// undefined behavior if the array is empty.
const_reference front() const { return *begin(); }
/// Return a const reference to the first element in this array. Invokes
/// undefined behavior if the array is empty.
const_reference cfront() const { return *begin(); }
/// Return a reference to the last element in this array. The underlying
/// data is copied if it is not uniquely owned. Invokes undefined behavior
/// if the array is empty.
reference back() { return *rbegin(); }
/// Return a const reference to the last element in this array. Invokes
/// undefined behavior if the array is empty.
const_reference back() const { return *rbegin(); }
/// Return a const reference to the last element in this array. Invokes
/// undefined behavior if the array is empty.
const_reference cback() const { return *rbegin(); }
/// Resize this array. Preserve existing elements that remain,
/// value-initialize any newly added elements. For example, calling
/// resize(10) on an array of size 5 would change the size to 10, the first
/// 5 elements would be left unchanged and the last 5 elements would be
/// value-initialized.
void resize(size_t newSize) {
struct _Filler {
inline void operator()(pointer b, pointer e) const {
std::uninitialized_fill(b, e, value_type());
}
};
return resize(newSize, _Filler());
}
/// Resize this array. Preserve existing elements that remain, initialize
/// any newly added elements by calling \p fillElems(first, last). Note
/// that this function is passed pointers to uninitialized memory, so the
/// elements must be filled with something like placement-new.
template <class FillElemsFn>
void resize(size_t newSize, FillElemsFn &&fillElems) {
const size_t oldSize = size();
if (oldSize == newSize) {
return;
}
if (newSize == 0) {
clear();
return;
}
const bool growing = newSize > oldSize;
value_type *newData = _data;
if (!_data) {
// Allocate newSize elements and initialize.
newData = _AllocateNew(newSize);
std::forward<FillElemsFn>(fillElems)(newData, newData + newSize);
}
else if (_IsUnique()) {
if (growing) {
if (newSize > _GetCapacity(_data)) {
newData = _AllocateCopy(_data, newSize, oldSize);
}
// fill with newly added elements from oldSize to newSize.
std::forward<FillElemsFn>(fillElems)(newData + oldSize,
newData + newSize);
}
else {
// destroy removed elements
for (auto *cur = newData + newSize,
*end = newData + oldSize; cur != end; ++cur) {
cur->~value_type();
}
}
}
else {
newData =
_AllocateCopy(_data, newSize, growing ? oldSize : newSize);
if (growing) {
// fill with newly added elements from oldSize to newSize.
std::forward<FillElemsFn>(fillElems)(newData + oldSize,
newData + newSize);
}
}
// If we created new data, clean up the old and move over to the new.
if (newData != _data) {
_DecRef();
_data = newData;
}
// Adjust size.
_shapeData.totalSize = newSize;
}
/// Equivalent to resize(0).
void clear() {
if (!_data)
return;
if (_IsUnique()) {
// Clear out elements, run dtors, keep capacity.
for (value_type *p = _data, *e = _data + size(); p != e; ++p) {
p->~value_type();
}
}
else {
// Detach to empty.
_DecRef();
}
_shapeData.totalSize = 0;
}
/// Removes a single element at \p pos from the array
///
/// To match the behavior of std::vector, returns an iterator
/// pointing to the position following the removed element.
///
/// Since the returned iterator is mutable, when the array is
/// not uniquely owned, a copy will be required.
///
/// Erase invalidates all iterators (unlike std::vector
/// where iterators prior to \p pos remain valid).
///
/// \sa erase(const_iterator, const_iterator)
iterator erase(const_iterator pos) {
TF_DEV_AXIOM(pos != cend());
return erase(pos, pos+1);
}
/// Remove a range of elements [\p first, \p last) from the array.
///
/// To match the behavior of std::vector, returns an iterator
/// at the position following the removed element.
/// If no elements are removed, a non-const iterator pointing
/// to last will be returned.
///
/// Since the returned iterator is mutable, when the array is
/// not uniquely owned, a copy will be required even when
/// the contents are unchanged.
///
/// Erase invalidates all iterators (unlike std::vector
/// where iterators prior to \p first remain valid).
///
/// \sa erase(const_iterator)
iterator erase(const_iterator first, const_iterator last) {
if (first == last){
return std::next(begin(), std::distance(cbegin(), last));
}
if ((first == cbegin()) && (last == cend())){
clear();
return end();
}
// Given the previous two conditions, we know that we are removing
// at least one element and the result array will contain at least one
// element.
value_type* removeStart = std::next(_data, std::distance(cbegin(), first));
value_type* removeEnd = std::next(_data, std::distance(cbegin(), last));
value_type* endIt = std::next(_data, size());
size_t newSize = size() - std::distance(first, last);
if (_IsUnique()){
// If the array is unique, we can simply move the tail elements
// and free to the end of the array.
value_type* deleteIt = std::move(removeEnd, endIt, removeStart);
for (; deleteIt != endIt; ++deleteIt) {
deleteIt->~value_type();
}
_shapeData.totalSize = newSize;
return iterator(removeStart);
} else{
// If the array is not unique, we want to avoid copying the
// elements in the range we are erasing. We allocate a
// new buffer and copy the head and tail ranges, omitting
// [first, last)
value_type* newData = _AllocateNew(newSize);
value_type* newMiddle = std::uninitialized_copy(
_data, removeStart, newData);
value_type* newEnd = std::uninitialized_copy(
removeEnd, endIt, newMiddle);
TF_DEV_AXIOM(newEnd == std::next(newData, newSize));
TF_DEV_AXIOM(std::distance(newData, newMiddle) ==
std::distance(_data, removeStart));
_DecRef();
_data = newData;
_shapeData.totalSize = newSize;
return iterator(newMiddle);
}
}
/// Assign array contents.
/// Equivalent to:
/// \code
/// array.resize(std::distance(first, last));
/// std::copy(first, last, array.begin());
/// \endcode
template <class ForwardIter>
typename std::enable_if<!std::is_integral<ForwardIter>::value>::type
assign(ForwardIter first, ForwardIter last) {
struct _Copier {
void operator()(pointer b, pointer e) const {
std::uninitialized_copy(first, last, b);
}
ForwardIter const &first, &last;
};
clear();
resize(std::distance(first, last), _Copier { first, last });
}
/// Assign array contents.
/// Equivalent to:
/// \code
/// array.resize(n);
/// std::fill(array.begin(), array.end(), fill);
/// \endcode
void assign(size_t n, const value_type &fill) {
struct _Filler {
void operator()(pointer b, pointer e) const {
std::uninitialized_fill(b, e, fill);
}
const value_type &fill;
};
clear();
resize(n, _Filler { fill });
}
/// Assign array contents via intializer list
/// Equivalent to:
/// \code
/// array.assign(list.begin(), list.end());
/// \endcode
void assign(std::initializer_list<ELEM> initializerList) {
assign(initializerList.begin(), initializerList.end());
}
/// Swap the contents of this array with \p other.
void swap(VtArray &other) {
std::swap(_data, other._data);
std::swap(_shapeData, other._shapeData);
std::swap(_foreignSource, other._foreignSource);
}
/// @}
/// Allows usage of [i].
ElementType &operator[](size_t index) {
return data()[index];
}
/// Allows usage of [i].
ElementType const &operator[](size_t index) const {
return data()[index];
}
/// Tests if two arrays are identical, i.e. that they share
/// the same underlying copy-on-write data. See also operator==().
bool IsIdentical(VtArray const & other) const {
return
_data == other._data &&
_shapeData == other._shapeData &&
_foreignSource == other._foreignSource;
}
/// Tests two arrays for equality. See also IsIdentical().
bool operator == (VtArray const & other) const {
return IsIdentical(other) ||
(*_GetShapeData() == *other._GetShapeData() &&
std::equal(cbegin(), cend(), other.cbegin()));
}
/// Tests two arrays for inequality.
bool operator != (VtArray const &other) const {
return !(*this == other);
}
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_FORCING_TO_BOOL
ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
VTOPERATOR_CPPARRAY(+)
VTOPERATOR_CPPARRAY(-)
VTOPERATOR_CPPARRAY(*)
VTOPERATOR_CPPARRAY(/)
VTOPERATOR_CPPARRAY(%)
VTOPERATOR_CPPARRAY_UNARY(-)
ARCH_PRAGMA_POP
public:
// XXX -- Public so VtValue::_ArrayHelper<T,U>::GetShapeData() has access.
Vt_ShapeData const *_GetShapeData() const {
return &_shapeData;
}
Vt_ShapeData *_GetShapeData() {
return &_shapeData;
}
private:
class _Streamer : public VtStreamOutIterator {
public:
_Streamer(const_pointer data) : _p(data) { }
virtual ~_Streamer() { }
virtual void Next(std::ostream &out)
{
VtStreamOut(*_p++, out);
}
private:
const_pointer _p;
};
/// Outputs a comma-separated list of the values in the array.
friend std::ostream &operator <<(std::ostream &out, const VtArray &self) {
VtArray::_Streamer streamer(self.cdata());
VtStreamOutArray(&streamer, self.size(), self._GetShapeData(), out);
return out;
}
/// Swap array contents.
friend void swap(VtArray &lhs, VtArray &rhs) {
lhs.swap(rhs);
}
void _DetachIfNotUnique() {
if (_IsUnique())
return;
// Copy to local.
_DetachCopyHook(__ARCH_PRETTY_FUNCTION__);
auto *newData = _AllocateCopy(_data, size(), size());
_DecRef();
_data = newData;
}
inline bool _IsUnique() const {
return !_data ||
(ARCH_LIKELY(!_foreignSource) && _GetNativeRefCount(_data) == 1);
}
inline size_t _CapacityForSize(size_t sz) const {
// Currently just successive powers of two.
size_t cap = 1;
while (cap < sz) {
cap += cap;
}
return cap;
}
value_type *_AllocateNew(size_t capacity) {
TfAutoMallocTag2 tag("VtArray::_AllocateNew", __ARCH_PRETTY_FUNCTION__);
// Need space for the control block and capacity elements.
void *data = malloc(
sizeof(_ControlBlock) + capacity * sizeof(value_type));
// Placement-new a control block.
::new (data) _ControlBlock(/*count=*/1, capacity);
// Data starts after the block.
return reinterpret_cast<value_type *>(
static_cast<_ControlBlock *>(data) + 1);
}
value_type *_AllocateCopy(value_type *src, size_t newCapacity,
size_t numToCopy) {
// Allocate and copy elements.
value_type *newData = _AllocateNew(newCapacity);
std::uninitialized_copy(src, src + numToCopy, newData);
return newData;
}
void _DecRef() {
if (!_data)
return;
if (ARCH_LIKELY(!_foreignSource)) {
// Drop the refcount. If we take it to zero, destroy the data.
if (_GetNativeRefCount(_data).fetch_sub(
1, std::memory_order_release) == 1) {
std::atomic_thread_fence(std::memory_order_acquire);
for (value_type *p = _data, *e = _data + _shapeData.totalSize;
p != e; ++p) {
p->~value_type();
}
free(std::addressof(_GetControlBlock(_data)));
}
}
else {
// Drop the refcount in the foreign source. If we take it to zero,
// invoke the function pointer to alert the foreign source.
if (_foreignSource->_refCount.fetch_sub(
1, std::memory_order_release) == 1) {
std::atomic_thread_fence(std::memory_order_acquire);
_foreignSource->_ArraysDetached();
}
}
_foreignSource = nullptr;
_data = nullptr;
}
value_type *_data;
};
template <class ELEM>
typename std::enable_if<VtIsHashable<ELEM>(), size_t>::type
hash_value(VtArray<ELEM> const &array) {
size_t h = array.size();
for (auto const &x: array) {
boost::hash_combine(h, x);
}
return h;
}
// Specialize traits so others can figure out that VtArray is an array.
template <typename T>
struct VtIsArray< VtArray <T> > : public std::true_type {};
// free functions for operators combining scalar and array types
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_FORCING_TO_BOOL
ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
VTOPERATOR_CPPSCALAR(+)
VTOPERATOR_CPPSCALAR(-)
VTOPERATOR_CPPSCALAR(*)
VTOPERATOR_CPPSCALAR_DOUBLE(*)
VTOPERATOR_CPPSCALAR(/)
VTOPERATOR_CPPSCALAR_DOUBLE(/)
VTOPERATOR_CPPSCALAR(%)
ARCH_PRAGMA_POP
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_ARRAY_H
+60
View File
@@ -0,0 +1,60 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_ARRAY_PY_BUFFER_H
#define PXR_BASE_VT_ARRAY_PY_BUFFER_H
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/array.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include <boost/optional.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// Convert \p obj which should support the python buffer protocol (e.g. a
/// numpy array) to a VtArray if possible and return it. Return empty
/// optional if \p obj does not support the buffer protocol or does not have
/// compatible type and dimensions. If \p err is supplied, set it to an
/// explanatory message in case of conversion failure. This function may be
/// invoked for VtArray<T> where T is one of VT_ARRAY_PYBUFFER_TYPES.
template <class T>
boost::optional<VtArray<T> >
VtArrayFromPyBuffer(TfPyObjWrapper const &obj, std::string *err=nullptr);
/// The set of types for which it's valid to call VtArrayFromPyBuffer().
#define VT_ARRAY_PYBUFFER_TYPES \
VT_BUILTIN_NUMERIC_VALUE_TYPES \
VT_VEC_VALUE_TYPES \
VT_MATRIX_VALUE_TYPES \
VT_GFRANGE_VALUE_TYPES \
((GfRect2i, Rect2i)) \
((GfQuath, Quath)) \
((GfQuatf, Quatf)) \
((GfQuatd, Quatd))
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_ARRAY_PY_BUFFER_H
+622
View File
@@ -0,0 +1,622 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_DICTIONARY_H
#define PXR_BASE_VT_DICTIONARY_H
/// \file vt/dictionary.h
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/mallocTag.h"
#include <boost/functional/hash.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <initializer_list>
#include <iosfwd>
#include <map>
#include <memory>
PXR_NAMESPACE_OPEN_SCOPE
/// \defgroup group_vtdict_functions VtDictionary Functions
/// Functions for manipulating VtDictionary objects.
/// \class VtDictionary
///
/// A map with string keys and VtValue values.
///
/// VtDictionary converts to and from a python dictionary as long
/// as each element contains either
/// - another VtDictionary (converts to a nested dictionary)
/// - std::vector<VtValue> (converts to a nested list)
/// - VtValue with one of the supported Vt Types.
///
/// For a list of functions that can manipulate VtDictionary objects, see the
/// \link group_vtdict_functions VtDictionary Functions \endlink group page .
///
class VtDictionary {
typedef std::map<std::string, VtValue, std::less<>> _Map;
std::unique_ptr<_Map> _dictMap;
public:
// The iterator class, used to make both const and non-const iterators.
// Currently only forward traversal is supported. In order to support lazy
// allocation, VtDictionary's Map pointer (_dictMap) must be nullable,
// but that would break the VtDictionary iterators. So instead, VtDictionary
// uses this Iterator class, which considers an iterator to an empty
// VtDictionary to be the same as an iterator at the end of a VtDictionary
// (i.e. if Iterator's _dictMap pointer is null, that either means that the
// VtDictionary is empty, or the Iterator is at the end of a VtDictionary
// that contains values).
template<class UnderlyingMapPtr, class UnderlyingIterator>
class Iterator : public boost::iterator_adaptor<Iterator<UnderlyingMapPtr,
UnderlyingIterator>, UnderlyingIterator> {
public:
// Default constructor creates an Iterator equivalent to end() (i.e.
// UnderlyingMapPtr is null)
Iterator()
: Iterator::iterator_adaptor_(UnderlyingIterator())
, _underlyingMap(0) {}
// Copy constructor (also allows for converting non-const to const).
template <class OtherUnderlyingMapPtr, class OtherUnderlyingIterator>
Iterator(Iterator<OtherUnderlyingMapPtr,
OtherUnderlyingIterator> const &other)
: Iterator::iterator_adaptor_(other.base())
, _underlyingMap(other._underlyingMap) {}
private:
// Private constructor allowing the find, begin and insert methods
// to create and return the proper Iterator.
Iterator(UnderlyingMapPtr m, UnderlyingIterator i)
: Iterator::iterator_adaptor_(i)
, _underlyingMap(m) {
if (m && i == m->end())
_underlyingMap = 0;
}
friend class boost::iterator_core_access;
friend class VtDictionary;
UnderlyingIterator GetUnderlyingIterator(UnderlyingMapPtr map)
const {
TF_AXIOM(!_underlyingMap || _underlyingMap == map);
return (!_underlyingMap) ? map->end() : this->base();
}
// Fundamental functionality to implement the iterator.
// boost::iterator_adaptor will invoke these as necessary to implement
// the full iterator public interface.
// Increments the underlying iterator, and sets the underlying map to
// null when the iterator reaches the end of the map.
void increment() {
if (!_underlyingMap) {
TF_FATAL_ERROR("Attempted invalid increment operation on a "
"VtDictionary iterator");
return;
}
if (++this->base_reference() == _underlyingMap->end()) {
_underlyingMap = 0;
}
}
// Equality comparison. Iterators are considered equal if:
// 1) They both point to empty VtDictionaries
// 2) They both point to the end() of a VtDictionary
// - or-
// 3) They both point to the same VtDictionary and their
// boost::iterator_adaptors' base() iterators are the same
// In cases 1 and 2 above, _underlyingMap will be null
template <class OtherUnderlyingMapPtr, class OtherUnderlyingIterator>
bool equal(Iterator<OtherUnderlyingMapPtr,
OtherUnderlyingIterator> const& i) const {
if (_underlyingMap == i._underlyingMap)
if (!_underlyingMap || this->base() == i.base())
return true;
return false;
}
UnderlyingMapPtr _underlyingMap;
};
TF_MALLOC_TAG_NEW("Vt", "VtDictionary");
typedef _Map::key_type key_type;
typedef _Map::mapped_type mapped_type;
typedef _Map::value_type value_type;
typedef _Map::allocator_type allocator_type;
typedef _Map::size_type size_type;
typedef Iterator<_Map*, _Map::iterator> iterator;
typedef Iterator<_Map const*, _Map::const_iterator> const_iterator;
/// Creates an empty \p VtDictionary.
VtDictionary() {}
/// Creates an empty \p VtDictionary with at least \p size buckets.
explicit VtDictionary(int size) {}
/// Creates a \p VtDictionary with a copy of a range.
template<class _InputIterator>
VtDictionary(_InputIterator f, _InputIterator l){
TfAutoMallocTag2 tag("Vt", "VtDictionary::VtDictionary (range)");
insert(f, l);
}
/// Creates a copy of the supplied \p VtDictionary
VT_API
VtDictionary(VtDictionary const& other);
/// Creates a new VtDictionary by moving the supplied \p VtDictionary.
VT_API
VtDictionary(VtDictionary && other) = default;
/// Creates a new VtDictionary from a braced initializer list.
VT_API
VtDictionary(std::initializer_list<value_type> init);
/// Copy assignment operator
VT_API
VtDictionary& operator=(VtDictionary const& other);
/// Move assignment operator
VT_API
VtDictionary& operator=(VtDictionary && other) = default;
/// Returns a reference to the \p VtValue that is associated with a
/// particular key.
VT_API
VtValue& operator[](const std::string& key);
/// Counts the number of elements whose key is \p key.
VT_API
size_type count(const std::string& key) const;
/// Counts the number of elements whose key is \p key.
VT_API
size_type count(const char* key) const;
/// Erases the element whose key is \p key.
VT_API
size_type erase(const std::string& key);
/// Erases the element pointed to by \p it.
VT_API
void erase(iterator it);
/// Erases all elements in a range.
VT_API
void erase(iterator f, iterator l);
/// Erases all of the elements.
VT_API
void clear();
/// Finds an element whose key is \p key.
VT_API
iterator find(const std::string& key);
/// Finds an element whose key is \p key.
VT_API
iterator find(const char* key);
/// Finds an element whose key is \p key.
VT_API
const_iterator find(const std::string& key) const;
/// Finds an element whose key is \p key.
VT_API
const_iterator find(const char* key) const;
/// Returns an \p iterator pointing to the beginning of the \p VtDictionary.
VT_API
iterator begin();
/// Returns an \p iterator pointing to the beginning of the \p VtDictionary.
VT_API
const_iterator begin() const;
/// Returns an \p iterator pointing to the end of the \p VtDictionary.
VT_API
iterator end();
/// Returns an \p iterator pointing to the end of the \p VtDictionary.
VT_API
const_iterator end() const;
/// Returns the size of the VtDictionary.
VT_API
size_type size() const;
/// \c true if the \p VtDictionary's size is 0.
VT_API
bool empty() const;
/// Swaps the contents of two \p VtDictionaries.
VT_API
void swap(VtDictionary& dict);
// Global overload for swap for unqualified calls in generic code.
friend void swap(VtDictionary &lhs, VtDictionary &rhs) {
lhs.swap(rhs);
}
friend size_t hash_value(VtDictionary const &dict) {
// Hash empty dict as zero.
if (dict.empty())
return 0;
// Otherwise hash the map.
return boost::hash_value(*dict._dictMap);
}
/// Inserts a range into the \p VtDictionary.
template<class _InputIterator>
void insert(_InputIterator f, _InputIterator l) {
TfAutoMallocTag2 tag("Vt", "VtDictionary::insert (range)");
if (f != l) {
_CreateDictIfNeeded();
_dictMap->insert(f, l);
}
}
/// Inserts \p obj into the \p VtDictionary.
VT_API
std::pair<iterator, bool> insert(const value_type& obj);
/// Return a pointer to the value at \p keyPath if one exists. \p keyPath
/// is a delimited string of sub-dictionary names. Key path elements are
/// produced by calling TfStringTokenize() with \p keyPath and
/// \p delimiters. \p keyPath may identify a leaf element or an entire
/// sub-dictionary. Return null if no such element at \p keyPath exists.
VT_API
VtValue const *
GetValueAtPath(std::string const &keyPath,
char const *delimiters = ":") const;
/// Return a pointer to the value at \p keyPath if one exists. \p keyPath
/// may identify a leaf element or an entire sub-dictionary. Return null if
/// no such element at \p keyPath exists.
VT_API
VtValue const *
GetValueAtPath(std::vector<std::string> const &keyPath) const;
/// Set the value at \p keyPath to \p value. \p keyPath is a delimited
/// string of sub-dictionary names. Key path elements are produced by
/// calling TfStringTokenize() with \p keyPath and \p delimiters. Create
/// sub-dictionaries as necessary according to the path elements in
/// \p keyPath. If \p keyPath identifies a full sub-dictionary, replace the
/// entire sub-dictionary with \p value.
VT_API
void SetValueAtPath(std::string const &keyPath,
VtValue const &value, char const *delimiters = ":");
/// Set the value at \p keyPath to \p value. Create sub-dictionaries as
/// necessary according to the path elements in \p keyPath. If \p keyPath
/// identifies a full sub-dictionary, replace the entire sub-dictionary with
/// \p value.
VT_API
void SetValueAtPath(std::vector<std::string> const &keyPath,
VtValue const &value);
/// Erase the value at \a keyPath. \p keyPath is a delimited string of
/// sub-dictionary names. Key path elements are produced by calling
/// TfStringTokenize() with \p keyPath and \p delimiters. If no such
/// element exists at \p keyPath, do nothing. If \p keyPath identifies a
/// sub-dictionary, erase the entire sub-dictionary.
VT_API
void EraseValueAtPath(std::string const &keyPath,
char const *delimiters = ":");
/// Erase the value at \a keyPath. If no such element exists at \p keyPath,
/// do nothing. If \p keyPath identifies a sub-dictionary, erase the entire
/// sub-dictionary.
VT_API
void EraseValueAtPath(std::vector<std::string> const &keyPath);
private:
void
_SetValueAtPathImpl(std::vector<std::string>::const_iterator curKeyElem,
std::vector<std::string>::const_iterator keyElemEnd,
VtValue const &value);
void _EraseValueAtPathImpl(
std::vector<std::string>::const_iterator curKeyElem,
std::vector<std::string>::const_iterator keyElemEnd);
void _CreateDictIfNeeded();
};
/// Equality comparison.
VT_API bool operator==(VtDictionary const &, VtDictionary const &);
VT_API bool operator!=(VtDictionary const &, VtDictionary const &);
/// Write the contents of a VtDictionary to a stream, formatted like "{ 'key1':
/// value1, 'key2': value2 }".
VT_API std::ostream &operator<<(std::ostream &, VtDictionary const &);
//
// Return a const reference to an empty VtDictionary.
//
VT_API VtDictionary const &VtGetEmptyDictionary();
/// Returns true if \p dictionary contains \p key and the corresponding value
/// is of type \p T.
/// \ingroup group_vtdict_functions
///
template <typename T>
bool
VtDictionaryIsHolding( const VtDictionary &dictionary,
const std::string &key )
{
VtDictionary::const_iterator i = dictionary.find(key);
if ( i == dictionary.end() ) {
return false;
}
return i->second.IsHolding<T>();
}
/// \overload
template <typename T>
bool
VtDictionaryIsHolding( const VtDictionary &dictionary,
const char *key )
{
VtDictionary::const_iterator i = dictionary.find(key);
if ( i == dictionary.end() ) {
return false;
}
return i->second.IsHolding<T>();
}
/// Return a value held in a VtDictionary by reference.
///
/// If \p key is in \p dictionary and the corresponding value is of type
/// \p T, returns a reference to the value.
///
/// \remark If \p key is not in \p dictionary, or the value for \p key is of
/// the wrong type, a fatal error occurs, so clients should always call
/// VtDictionaryIsHolding first.
///
/// \ingroup group_vtdict_functions
template <typename T>
const T &
VtDictionaryGet( const VtDictionary &dictionary,
const std::string &key )
{
VtDictionary::const_iterator i = dictionary.find(key);
if (ARCH_UNLIKELY(i == dictionary.end())) {
TF_FATAL_ERROR("Attempted to get value for key '" + key +
"', which is not in the dictionary.");
}
return i->second.Get<T>();
}
/// \overload
template <typename T>
const T &
VtDictionaryGet( const VtDictionary &dictionary,
const char *key )
{
VtDictionary::const_iterator i = dictionary.find(key);
if (ARCH_UNLIKELY(i == dictionary.end())) {
TF_FATAL_ERROR("Attempted to get value for key '%s', "
"which is not in the dictionary.", key);
}
return i->second.Get<T>();
}
// This is an internal holder class that is used in the version of
// VtDictionaryGet that takes a default.
template <class T>
struct Vt_DefaultHolder {
explicit Vt_DefaultHolder(T const &t) : val(t) {}
T const &val;
};
// This internal class has a very unusual assignment operator that returns an
// instance of Vt_DefaultHolder, holding any type T. This is used to get the
// "VtDefault = X" syntax for VtDictionaryGet.
struct Vt_DefaultGenerator {
template <class T>
Vt_DefaultHolder<T> operator=(T const &t) {
return Vt_DefaultHolder<T>(t);
}
};
// This is a global stateless variable used to get the VtDefault = X syntax in
// VtDictionaryGet.
extern VT_API Vt_DefaultGenerator VtDefault;
/// Return a value held in a VtDictionary, or a default value either if the
/// supplied key is missing or if the types do not match.
///
/// For example, this code will get a bool value under key "key" if "key" has a
/// boolean value in the dictionary. If there is no such key, or the value
/// under the key is not a bool, the specified default (false) is returned.
///
/// \code
/// bool val = VtDictionaryGet<bool>(dict, "key", VtDefault = false);
/// \endcode
///
/// \ingroup group_vtdict_functions
template <class T, class U>
T VtDictionaryGet( const VtDictionary &dictionary,
const std::string &key,
Vt_DefaultHolder<U> const &def )
{
VtDictionary::const_iterator i = dictionary.find(key);
if (i == dictionary.end() || !i->second.IsHolding<T>())
return def.val;
return i->second.UncheckedGet<T>();
}
/// \overload
template <class T, class U>
T VtDictionaryGet( const VtDictionary &dictionary,
const char *key,
Vt_DefaultHolder<U> const &def )
{
VtDictionary::const_iterator i = dictionary.find(key);
if (i == dictionary.end() || !i->second.IsHolding<T>())
return def.val;
return i->second.UncheckedGet<T>();
}
/// Creates a dictionary containing \p strong composed over \p weak.
///
/// The new dictionary will contain all key-value pairs from \p strong
/// together with the key-value pairs from \p weak whose keys are not in \p
/// strong.
///
/// If \p coerceToWeakerOpinionType is \c true then coerce a strong value to
/// the weaker value's type, if there is a weaker value. This is mainly
/// intended to promote to enum types.
///
/// \ingroup group_vtdict_functions
VT_API VtDictionary
VtDictionaryOver(const VtDictionary &strong, const VtDictionary &weak,
bool coerceToWeakerOpinionType = false);
/// Updates \p strong to become \p strong composed over \p weak.
///
/// The updated contents of \p strong will be all key-value pairs from \p
/// strong together with the key-value pairs from \p weak whose keys are not in
/// \p strong.
///
/// If \p coerceToWeakerOpinionType is \c true then coerce a strong value to
/// the weaker value's type, if there is a weaker value. This is mainly
/// intended to promote to enum types.
///
/// \ingroup group_vtdict_functions
VT_API void
VtDictionaryOver(VtDictionary *strong, const VtDictionary &weak,
bool coerceToWeakerOpinionType = false);
/// Updates \p weak to become \p strong composed over \p weak.
///
/// The updated contents of \p weak will be all key-value pairs from \p strong
/// together with the key-value pairs from \p weak whose keys are not in \p
/// strong.
///
/// If \p coerceToWeakerOpinionType is \c true then coerce a strong value to
/// the weaker value's type, if there is a weaker value. This is mainly
/// intended to promote to enum types.
///
/// \ingroup group_vtdict_functions
VT_API void
VtDictionaryOver(const VtDictionary &strong, VtDictionary *weak,
bool coerceToWeakerOpinionType = false);
/// Returns a dictionary containing \p strong recursively composed over \p
/// weak.
///
/// The new dictionary will be all key-value pairs from \p strong together
/// with the key-value pairs from \p weak whose keys are not in \p strong.
///
/// If a value for a key is in turn a dictionary, and both \a strong and \a
/// weak have values for that key, then the result may not contain strong's
/// exact value for the subdict. Rather, the result will contain a subdict
/// that is the result of a recursive call to this method. Hence, the
/// subdict, too, will contain values from \a weak that are not found in \a
/// strong.
///
/// If \p coerceToWeakerOpinionType is \c true then coerce a strong value to
/// the weaker value's type, if there is a weaker value. This is mainly
/// intended to promote to enum types.
///
/// \ingroup group_vtdict_functions
VT_API VtDictionary
VtDictionaryOverRecursive(const VtDictionary &strong, const VtDictionary &weak,
bool coerceToWeakerOpinionType = false);
/// Updates \p strong to become \p strong composed recursively over \p weak.
///
/// The updated contents of \p strong will be all key-value pairs from \p
/// strong together with the key-value pairs from \p weak whose keys are not
/// in \p strong.
///
/// If a value for a key is in turn a dictionary, and both \a strong and \a
/// weak have values for that key, then \a strong's subdict may not be left
/// untouched. Rather, the dictionary will be replaced by the result of a
/// recursive call to this method in which \a strong's subdictionary will have
/// entries added if they are contained in \a weak but not in \a strong
///
/// If \p coerceToWeakerOpinionType is \c true then coerce a strong value to
/// the weaker value's type, if there is a weaker value. This is mainly
/// intended to promote to enum types.
///
/// \ingroup group_vtdict_functions
VT_API void
VtDictionaryOverRecursive(VtDictionary *strong, const VtDictionary &weak,
bool coerceToWeakerOpinionType = false);
/// Updates \p weak to become \p strong composed recursively over \p weak.
///
/// The updated contents of \p weak will be all key-value pairs from \p strong
/// together with the key-value pairs from \p weak whose keys are not in \p
/// strong.
///
/// If a value is in turn a dictionary, the dictionary in \a weak may not be
/// replaced wholesale by that of \a strong. Rather, the dictionary will be
/// replaced by the result of a recursive call to this method in which \a
/// weak's subdictionary is recursively overlayed by \a strong's
/// subdictionary.
///
/// The result is that no key/value pairs of \a will be lost in nested
/// dictionaries. Rather, only non-dictionary values will be overwritten
///
/// If \p coerceToWeakerOpinionType is \c true then coerce a strong value to
/// the weaker value's type, if there is a weaker value. This is mainly
/// intended to promote to enum types.
///
/// \ingroup group_vtdict_functions
VT_API void
VtDictionaryOverRecursive(const VtDictionary &strong, VtDictionary *weak,
bool coerceToWeakerOpinionType = false);
struct VtDictionaryHash {
inline size_t operator()(VtDictionary const &dict) const {
return hash_value(dict);
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif /* PXR_BASE_VT_DICTIONARY_H */
+348
View File
@@ -0,0 +1,348 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#if !BOOST_PP_IS_ITERATING
#ifndef PXR_BASE_VT_FUNCTIONS_H
#define PXR_BASE_VT_FUNCTIONS_H
/// \file vt/functions.h
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/array.h"
#include <boost/preprocessor/enum_params.hpp>
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repeat.hpp>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
#define VT_FUNCTIONS_MAX_ARGS 6
// Set up preprocessor iterations to allow various functions to accept multiple
// arguments.
// VtCat
#define BOOST_PP_ITERATION_PARAMS_1 (4, \
(0, VT_FUNCTIONS_MAX_ARGS, "pxr/base/vt/functions.h", 0))
#include BOOST_PP_ITERATE()
// ****************************************************************************
// Doc headers for functions that are generated through macros. These get
// decent doxygen (and epydoc) output even though we can't put them on the
// real functions because they're expanded through boost or cpp macros.
// ****************************************************************************
// documentation for bool-result array comparison functions
#ifdef doxygen
/// Returns a bool array specifying, element-by-element, if the two inputs
/// contain equal values. The shape of the return array is the same as the
/// shape of the largest input array.
///
/// If one input is a single element (either a single-element array or a scalar
/// of the same type held in the array), it is compared to all the elements
/// in the other array. Otherwise both arrays must have the same shape.
template<typename T>
VtArray<T>
VtEqual( VtArray<T> const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtEqual( T const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtEqual( VtArray<T> const &a, T const &b );
/// Returns a bool array specifying, element-by-element, if the two inputs
/// contain inequal values. The shape of the return array is the same as the
/// shape of the largest input array.
///
/// If one input is a single element (either a single-element array or a scalar
/// of the same type held in the array), it is compared to all the elements
/// in the other array. Otherwise both arrays must have the same shape.
template<typename T>
VtArray<T>
VtNotEqual( VtArray<T> const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtNotEqual( T const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtNotEqual( VtArray<T> const &a, T const &b );
/// Returns a bool array specifying, element-by-element, if the first input
/// contains values greater than those in the second input. The shape of the
/// return array is the same as the shape of the largest input array.
///
/// If one input is a single element (either a single-element array or a scalar
/// of the same type held in the array), it is compared to all the elements
/// in the other array. Otherwise both arrays must have the same shape.
template<typename T>
VtArray<T>
VtGreater( VtArray<T> const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtGreater( T const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtGreater( VtArray<T> const &a, T const &b );
/// Returns a bool array specifying, element-by-element, if the first input
/// contains values less than those in the second input. The shape of the
/// return array is the same as the shape of the largest input array.
///
/// If one input is a single element (either a single-element array or a scalar
/// of the same type held in the array), it is compared to all the elements
/// in the other array. Otherwise both arrays must have the same shape.
template<typename T>
VtArray<T>
VtLess( VtArray<T> const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtLess( T const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtLess( VtArray<T> const &a, T const &b );
/// Returns a bool array specifying, element-by-element, if the first input
/// contains values greater than or equal to those in the second input. The
/// shape of the return array is the same as the shape of the largest input
/// array.
///
/// If one input is a single element (either a single-element array or a scalar
/// of the same type held in the array), it is compared to all the elements
/// in the other array. Otherwise both arrays must have the same shape.
template<typename T>
VtArray<T>
VtGreaterOrEqual( VtArray<T> const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtGreaterOrEqual( T const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtGreaterOrEqual( VtArray<T> const &a, T const &b );
/// Returns a bool array specifying, element-by-element, if the first input
/// contains values less than or equal to those in the second input. The shape
/// of the return array is the same as the shape of the largest input array.
///
/// If one input is a single element (either a single-element array or a scalar
/// of the same type held in the array), it is compared to all the elements
/// in the other array. Otherwise both arrays must have the same shape.
template<typename T>
VtArray<T>
VtLessOrEqual( VtArray<T> const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtLessOrEqual( T const &a, VtArray<T> const &b );
template<typename T>
VtArray<T>
VtLessOrEqual( VtArray<T> const &a, T const &b );
#endif
// provide documentation for functions with variable numbers of inputs
#ifdef doxygen
/// Concatenates arrays.
///
/// The result is an array with length equal to the sum of the number
/// of elements in the source arrays.
template<typename T>
VtArray<T>
VtCat( VtArray<T> const &a0, VtArray<T> const &a1, ... VtArray<T> const &aN);
#endif
// ****************************************************************************
// Fixed-number-of-arguments functions go here (no preprocessor iteration to
// handle multiple args)
// ****************************************************************************
/// Returns true if any element of input array is not VtZero, else false.
///
/// Intended to be used to evaluate results of boolean operations on arrays, e.g.
/// \code
/// a = Vt.StringArray((3,),("foo","bar","baz"))
/// t = Vt.AnyTrue(Vt.Equal(a,"bar"))
/// \endcode
///
/// (This example, if
/// you look carefully, evaluates this function not on the strings, but on
/// the results of the comparison).
template<typename T>
bool VtAnyTrue(VtArray<T> const &a)
{
if (a.empty())
return false;
for (size_t i = 0; i != a.size(); ++i) {
if (a[i] != VtZero<T>())
return true;
}
return false;
}
/// Returns true if every element of input array is not VtZero, else false.
///
/// Intended to be used to evaluate results of boolean operations on arrays, e.g.
/// \code
/// a = Vt.StringArray((3,),("foo","bar","baz"))
/// t = Vt.AllTrue(Vt.Equal(a,"bar"))
/// \endcode
///
/// (This example, if you look carefully, evaluates this function not on the
/// strings, but on the results of the comparison).
template<typename T>
bool
VtAllTrue(VtArray<T> const &a)
{
if (a.empty())
return false;
for (size_t i = 0; i != a.size(); ++i) {
if (a[i] == VtZero<T>())
return false;
}
return true;
}
// Macro defining functions for element-by-element comparison
// operators (i.e. Equal, etc). There are three versions; each returns
// a VtBoolArray of the same shape as the largest input.
// *) two input arrays:
// If one array contains a single element, it is compared to all the elements
// in the other array. Otherwise both arrays must have the same shape.
// *) scalar and array:
// The scalar is compared to all the elements in the array.
// *) array and scalar:
// The same as scalar and array.
#define VTFUNCTION_BOOL(funcname,op) \
template<typename T> \
VtArray<bool> \
funcname(T const &scalar, VtArray<T> const &vec) { \
VtArray<bool> ret(vec.size()); \
for (size_t i = 0, n = vec.size(); i != n; ++i) { \
ret[i] = (scalar op vec[i]); \
} \
return ret; \
} \
template<typename T> \
VtArray<bool> \
funcname(VtArray<T> const &vec, T const &scalar) { \
VtArray<bool> ret(vec.size()); \
for (size_t i = 0, n = vec.size(); i != n; ++i) { \
ret[i] = (vec[i] op scalar); \
} \
return ret; \
} \
template<typename T> \
VtArray<bool> \
funcname(VtArray<T> const &a, VtArray<T> const &b) \
{ \
if (a.empty() || b.empty()) { \
return VtArray<bool>(); \
} \
\
if (a.size() == 1) { \
return funcname(a[0], b); \
} else if (b.size() == 1) { \
return funcname(a, b[0]); \
} else if (a.size() == b.size()) { \
VtArray<bool> ret(a.size()); \
for (size_t i = 0, n = a.size(); i != n; ++i) { \
ret[i] = (a[i] op b[i]); \
} \
return ret; \
} else { \
TF_CODING_ERROR("Non-conforming inputs."); \
return VtArray<bool>(); \
} \
}
VTFUNCTION_BOOL(VtEqual,==)
VTFUNCTION_BOOL(VtNotEqual,!=)
VTFUNCTION_BOOL(VtGreater,>)
VTFUNCTION_BOOL(VtLess,<)
VTFUNCTION_BOOL(VtGreaterOrEqual,>=)
VTFUNCTION_BOOL(VtLessOrEqual,<=)
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_FUNCTIONS_H
#else // BOOST_PP_IS_ITERATING
// ****************************************************************************
// Variable-number-of-arguments functions go here; preprocessor iteration
// includes this file again and again, but turns off the pieces we don't
// want to use for a particular function.
// ****************************************************************************
#define N BOOST_PP_ITERATION()
#if BOOST_PP_ITERATION_FLAGS() == 0 // VtCat
#define VtCat_SIZE(dummy, n, dummy2) newSize += s##n.size();
#define VtCat_COPY(dummy, n, dummy2) \
for (size_t i = 0; i < s##n.size(); ++i) \
ret[offset+i] = s##n[i]; \
offset += s##n.size();
// real documentation is above (for doxygen purposes)
template<typename T>
VtArray<T>
VtCat( BOOST_PP_ENUM_PARAMS(N, VtArray<T> const &s) )
{
size_t newSize = 0;
BOOST_PP_REPEAT( N, VtCat_SIZE, ignored )
if (newSize == 0)
return VtArray<T>();
// new array with flattened size
VtArray<T> ret(newSize);
// fill it with data from old arrays
#if N > 0
size_t offset = 0;
BOOST_PP_REPEAT( N, VtCat_COPY, ignored )
#endif
return ret;
}
#undef VtCat_SIZE
#undef VtCat_COPY
#endif // BOOST_PP_ITERATION_FLAGS
#undef N
#endif // BOOST_PP_IS_ITERATING
+101
View File
@@ -0,0 +1,101 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_HASH_H
#define PXR_BASE_VT_HASH_H
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/tf/hash.h"
#include <boost/functional/hash.hpp>
#include <typeinfo>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
namespace Vt_HashDetail {
// Issue a coding error when we attempt to hash a t.
VT_API void _IssueUnimplementedHashError(std::type_info const &t);
// We make unqualified calls, intending to pick up boost::hash_value if an
// overload isn't found by ADL.
using boost::hash_value;
// A constexpr function that determines hashability.
template <class T, class = decltype(hash_value(std::declval<T>()))>
constexpr bool _IsHashable(int) { return true; }
template <class T, class = decltype(TfHash()(std::declval<T>()))>
constexpr bool _IsHashable(long) { return true; }
template <class T>
constexpr bool _IsHashable(...) { return false; }
// Hash implementations -- We're using an overload resolution ordering trick
// here (int vs long vs ...) so that we pick hash_value first, if possible,
// otherwise we do TfHash() if possible, otherwise we issue a runtime error.
template <class T, class = decltype(hash_value(std::declval<T>()))>
inline size_t
_HashValueImpl(T const &val, int)
{
return hash_value(val);
}
template <class T, class = decltype(TfHash()(std::declval<T>()))>
inline size_t
_HashValueImpl(T const &val, long)
{
return TfHash()(val);
}
template <class T>
inline size_t
_HashValueImpl(T const &val, ...)
{
Vt_HashDetail::_IssueUnimplementedHashError(typeid(T));
return 0;
}
} // Vt_HashDetail
/// A constexpr function that returns true if T is hashable via VtHashValue,
/// false otherwise. This is true if we can either invoke
/// (boost::)hash_value() or TfHash()() on a T instance.
template <class T>
constexpr bool
VtIsHashable() {
return Vt_HashDetail::_IsHashable<T>(0);
}
/// Compute a hash code for \p val by invoking (boost::)hash_value(val) if
/// possible, otherwise by invoking TfHash()(val), or if neither are possible
/// issue a coding error and return 0.
template <class T>
size_t VtHashValue(T const &val)
{
return Vt_HashDetail::_HashValueImpl(val, 0);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_HASH_H
+165
View File
@@ -0,0 +1,165 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_OPERATORS_H
#define PXR_BASE_VT_OPERATORS_H
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
//
// Operators.h
//
// Define macros to make it easier to create and wrap operators that work
// with multiple types. In general, we want most operators to allow
// array OP array
// array OP scalar
// scalar OP array
// array OP tuple
// tuple OP array
// array OP list
// list OP array
//
// where the operators work element-by-element. For arrays, this means they
// need to be the same size and shape. For tuples and lists, this means
// the array shape is ignored, and the array and tuple/list need to contain the
// same number of elements. For scalars, this means the same scalar value is
// used for every array element. Naturally we require that the types held in
// the array, tuple, list, and scalar are all the same (i.e no multiplying
// a VtDoubleArray by a GfVec3d).
//
// However, we do have special cases for
// array OP double
// double OP array
// for some OPs, for cases where you may want to do element-by-element
// operations with a double when the array type is *not* double (e.g. Vec3d).
// This is done in Core/Anim, for example, for spline calculations on the
// underlying data type.
//
// We define macros because this is so repetitive, and because they need to be
// defined in different places (the array operators on the class, the array and
// scalar operators as free functions, and the tuple/list operators in the
// Python wrapping of course). Having them here allows us to put them all
// in one place for better editability.
// -------------------------------------------------------------------------
// C++ operator definitions
// -------------------------------------------------------------------------
// These will be callable from C++, and define operations between arrays
// and between arrays and scalars.
PXR_NAMESPACE_OPEN_SCOPE
// Operations on arrays
// These go into the class definition for VtArray
#define VTOPERATOR_CPPARRAY(op) \
VtArray operator op (VtArray const &other) const { \
/* accept empty vecs */ \
if ((size()!=0 && other.size()!=0) && \
(size() != other.size())) { \
TF_CODING_ERROR("Non-conforming inputs for operator %s",#op); \
return VtArray(); \
} \
/* promote empty vecs to vecs of zeros */ \
const bool thisEmpty = size() == 0, \
otherEmpty = other.size() == 0; \
VtArray ret(thisEmpty ? other.size() : size()); \
ElementType zero = VtZero<ElementType>(); \
for (size_t i = 0, n = ret.size(); i != n; ++i) { \
ret[i] = (thisEmpty ? zero : (*this)[i]) op \
(otherEmpty ? zero : other[i]); \
} \
return ret; \
}
#define VTOPERATOR_CPPARRAY_UNARY(op) \
VtArray operator op () const { \
VtArray ret(size()); \
for (size_t i = 0, sz = ret.size(); i != sz; ++i) { \
ret[i] = op (*this)[i]; \
} \
return ret; \
}
// Operations on scalars and arrays
// These are free functions defined in Array.h
#define VTOPERATOR_CPPSCALAR_TYPE(op,arraytype,scalartype,rettype) \
template<typename arraytype> \
VtArray<ElemType> \
operator op (scalartype const &scalar, \
VtArray<arraytype> const &vec) { \
VtArray<rettype> ret(vec.size()); \
for (size_t i = 0; i<vec.size(); ++i) { \
ret[i] = scalar op vec[i]; \
} \
return ret; \
} \
template<typename arraytype> \
VtArray<ElemType> \
operator op (VtArray<arraytype> const &vec, \
scalartype const &scalar) { \
VtArray<rettype> ret(vec.size()); \
for (size_t i = 0; i<vec.size(); ++i) { \
ret[i] = vec[i] op scalar; \
} \
return ret; \
}
#define VTOPERATOR_CPPSCALAR(op) \
VTOPERATOR_CPPSCALAR_TYPE(op,ElemType,ElemType,ElemType)
// define special-case operators on arrays and doubles - except if the array
// holds doubles, in which case we already defined the operator (with
// VTOPERATOR_CPPSCALAR above) so we can't do it again!
#define VTOPERATOR_CPPSCALAR_DOUBLE(op) \
template<typename ElemType> \
typename boost::disable_if<boost::is_same<ElemType, double>, \
VtArray<ElemType> >::type \
operator op (double const &scalar, \
VtArray<ElemType> const &vec) { \
VtArray<ElemType> ret(vec.size()); \
for (size_t i = 0; i<vec.size(); ++i) { \
ret[i] = scalar op vec[i]; \
} \
return ret; \
} \
template<typename ElemType> \
typename boost::disable_if<boost::is_same<ElemType, double>, \
VtArray<ElemType> >::type \
operator op (VtArray<ElemType> const &vec, \
double const &scalar) { \
VtArray<ElemType> ret(vec.size()); \
for (size_t i = 0; i<vec.size(); ++i) { \
ret[i] = vec[i] op scalar; \
} \
return ret; \
}
struct Vt_ShapeData;
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_OPERATORS_H
+155
View File
@@ -0,0 +1,155 @@
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
// See the description in vt/operators.h for a better understanding regarding
// the purpose and usage of macros defined below.
PXR_NAMESPACE_OPEN_SCOPE
// -------------------------------------------------------------------------
// Python operator definitions
// -------------------------------------------------------------------------
// These will define the operator to work with tuples and lists from Python.
// base macro called by wrapping layers below for various operators, python
// types (lists and tuples), and special methods
#define VTOPERATOR_WRAP_PYTYPE_BASE(op,method,pytype,rettype,expr) \
template <typename T> static \
VtArray<rettype> method##pytype(VtArray<T> vec, pytype obj) \
{ \
size_t length = len(obj); \
if (length != vec.size()) { \
TfPyThrowValueError("Non-conforming inputs for operator " #op); \
return VtArray<T>(); \
} \
VtArray<rettype> ret(vec.size()); \
for (size_t i = 0; i < length; ++i) { \
if (!extract<T>(obj[i]).check()) \
TfPyThrowValueError("Element is of incorrect type."); \
ret[i] = expr; \
} \
return ret; \
}
// wrap Array op pytype
#define VTOPERATOR_WRAP_PYTYPE(op,lmethod,tuple,T) \
VTOPERATOR_WRAP_PYTYPE_BASE(op,lmethod,tuple,T, \
(vec[i] op (T)extract<T>(obj[i])) )
// wrap pytype op Array (for noncommutative ops like subtraction)
#define VTOPERATOR_WRAP_PYTYPE_R(op,lmethod,tuple,T) \
VTOPERATOR_WRAP_PYTYPE_BASE(op,lmethod,tuple,T, \
((T)extract<T>(obj[i]) op vec[i]) )
// operator that needs a special method plus a reflected special method,
// each defined on tuples and lists
#define VTOPERATOR_WRAP(op,lmethod,rmethod) \
VTOPERATOR_WRAP_PYTYPE(op,lmethod,tuple,T) \
VTOPERATOR_WRAP_PYTYPE(op,lmethod,list,T) \
VTOPERATOR_WRAP_PYTYPE(op,rmethod,tuple,T) \
VTOPERATOR_WRAP_PYTYPE(op,rmethod,list,T)
// like above, but for non-commutative ops like subtraction
#define VTOPERATOR_WRAP_NONCOMM(op,lmethod,rmethod) \
VTOPERATOR_WRAP_PYTYPE(op,lmethod,tuple,T) \
VTOPERATOR_WRAP_PYTYPE(op,lmethod,list,T) \
VTOPERATOR_WRAP_PYTYPE_R(op,rmethod,tuple,T) \
VTOPERATOR_WRAP_PYTYPE_R(op,rmethod,list,T)
// to be used to actually declare the wrapping with def() on the class
#define VTOPERATOR_WRAPDECLARE_BASE(op,method,rettype) \
.def(self op self) \
.def(self op Type()) \
.def(Type() op self) \
.def(#method,method##tuple<rettype>) \
.def(#method,method##list<rettype>)
#define VTOPERATOR_WRAPDECLARE(op,lmethod,rmethod) \
VTOPERATOR_WRAPDECLARE_BASE(op,lmethod,Type) \
.def(#rmethod,rmethod##tuple<Type>) \
.def(#rmethod,rmethod##list<Type>)
// to be used for wrapping conditional functions that return bool arrays
// (i.e. Equal, etc)
#define VTOPERATOR_WRAP_PYTYPE_BOOL_BASE(func,arg1,arg2,expr) \
template <typename T> static \
VtArray<bool> Vt##func(arg1, arg2) \
{ \
size_t length = len(obj); \
if (length != vec.size()) { \
TfPyThrowValueError("Non-conforming inputs for " #func); \
return VtArray<bool>(); \
} \
VtArray<bool> ret(vec.size()); \
for (size_t i = 0; i < length; ++i) { \
if (!extract<T>(obj[i]).check()) \
TfPyThrowValueError("Element is of incorrect type."); \
ret[i] = expr; \
} \
return ret; \
}
// array OP pytype
// pytype OP array
#define VTOPERATOR_WRAP_PYTYPE_BOOL(func,pytype,op) \
VTOPERATOR_WRAP_PYTYPE_BOOL_BASE(func, \
VtArray<T> const &vec, pytype const &obj, \
(vec[i] op (T)extract<T>(obj[i])) ) \
VTOPERATOR_WRAP_PYTYPE_BOOL_BASE(func, \
pytype const &obj,VtArray<T> const &vec, \
((T)extract<T>(obj[i]) op vec[i]) )
#define VTOPERATOR_WRAP_BOOL(func,op) \
VTOPERATOR_WRAP_PYTYPE_BOOL(func,list,op) \
VTOPERATOR_WRAP_PYTYPE_BOOL(func,tuple,op)
// to be used to actually declare the wrapping with def() on the class
#define VTOPERATOR_WRAPDECLARE_BOOL(func) \
def(#func,(VtArray<bool> (*) \
(VtArray<Type> const &,VtArray<Type> const &)) \
Vt##func<Type>); \
def(#func,(VtArray<bool> (*) \
(Type const &,VtArray<Type> const &)) \
Vt##func<Type>); \
def(#func,(VtArray<bool> (*) \
(VtArray<Type> const &,Type const &)) \
Vt##func<Type>); \
def(#func,(VtArray<bool> (*) \
(VtArray<Type> const &,tuple const &)) \
Vt##func<Type>); \
def(#func,(VtArray<bool> (*) \
(tuple const &,VtArray<Type> const &)) \
Vt##func<Type>); \
def(#func,(VtArray<bool> (*) \
(VtArray<Type> const &,list const &)) \
Vt##func<Type>); \
def(#func,(VtArray<bool> (*) \
(list const &,VtArray<Type> const &)) \
Vt##func<Type>);
PXR_NAMESPACE_CLOSE_SCOPE
+104
View File
@@ -0,0 +1,104 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_STREAM_OUT_H
#define PXR_BASE_VT_STREAM_OUT_H
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/tf/enum.h"
#include <iosfwd>
#include <typeinfo>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
// Helper that's used to stream a generic string for a type that isn't
// streamable and doesn't provide VtStreamOut. Inserts a message like
// <'typeName' @ 0xXXXXXXXX>.
VT_API std::ostream &
Vt_StreamOutGeneric(std::type_info const &type,
void const *addr,
std::ostream &stream);
// Function used in the case that T has a stream insertion operator.
template <class T>
inline auto
Vt_StreamOutImpl(T const &obj, std::ostream &stream, int)
-> decltype(stream << obj)
{
return stream << obj;
}
// Function used in the case that T does not have a stream insertion operator.
template <class T>
inline std::ostream &
Vt_StreamOutImpl(T const &obj, std::ostream &stream, long)
{
return Vt_StreamOutGeneric(
typeid(T), static_cast<void const *>(&obj), stream);
}
/// VtValue and VtArray make unqualified calls to VtStreamOut when writing
/// values to streams. Clients may overload VtStreamOut for their own types
/// if desired.
template <class T>
typename std::enable_if<!std::is_enum<T>::value, std::ostream &>::type
VtStreamOut(T const &obj, std::ostream &stream)
{
// For types that have an operator<< suitable for ostream, we use the
// traditional int/long 0-argument technique to disambiguate overloads.
return Vt_StreamOutImpl(obj, stream, 0);
}
template <class EnumT>
typename std::enable_if<std::is_enum<EnumT>::value, std::ostream &>::type
VtStreamOut(EnumT const &e, std::ostream &stream)
{
return VtStreamOut(TfEnum::GetName(e), stream);
}
VT_API std::ostream &VtStreamOut(bool const &, std::ostream &);
VT_API std::ostream &VtStreamOut(char const &, std::ostream &);
VT_API std::ostream &VtStreamOut(unsigned char const &, std::ostream &);
VT_API std::ostream &VtStreamOut(signed char const &, std::ostream &);
VT_API std::ostream &VtStreamOut(float const &, std::ostream &);
VT_API std::ostream &VtStreamOut(double const &, std::ostream &);
class VtStreamOutIterator {
public:
VT_API virtual ~VtStreamOutIterator();
virtual void Next(std::ostream&) = 0;
};
struct Vt_ShapeData;
VT_API void VtStreamOutArray(VtStreamOutIterator*, size_t size,
const Vt_ShapeData*, std::ostream&);
#ifdef PXR_PYTHON_SUPPORT_ENABLED
VT_API std::ostream &VtStreamOut(class TfPyObjWrapper const &, std::ostream &);
#endif // PXR_PYTHON_SUPPORT_ENABLED
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_STREAM_OUT_H
+151
View File
@@ -0,0 +1,151 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_TRAITS_H
#define PXR_BASE_VT_TRAITS_H
/// \file vt/traits.h
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/tf/preprocessorUtils.h"
#include <boost/type_traits/has_trivial_assign.hpp>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
/// Array concept. By default, types are not arrays.
template <typename T>
struct VtIsArray : public std::false_type {};
// We attempt to use local storage if a given type will fit and if it has a
// cheap copy operation. By default we only treat types with trivial
// assignments as "cheap to copy". Typically types that would fit in local
// space but do not have a trivial assignment are not cheap to copy. E.g. std::
// containers. Clients can specialize this template for their own types that
// aren't trivially assignable but are cheap to copy to enable local storage.
template <class T>
struct VtValueTypeHasCheapCopy : boost::has_trivial_assign<T> {};
#define VT_TYPE_IS_CHEAP_TO_COPY(T) \
template <> struct VtValueTypeHasCheapCopy<TF_PP_EAT_PARENS(T)> \
: std::true_type {}
// VtValue supports two kinds of "value proxy":
//
// 1. Typed proxies, where given a proxy type P, we can determine the underlying
// proxied type at compile-time.
//
// 2. Erased proxies, where we cannot know the underlying proxied type at
// compile-time.
//
// Typed proxies are mostly useful from a performance standpoint, where you can
// produce a VtValue that holds an object that is not stored in its own storage
// area. That is, you can make a VtValue that points at an object you own
// rather than copying/swapping/moving it to the VtValue.
//
// To implement a Typed proxy, either have it derive VtTypedValueProxyBase or
// specialize the VtIsTypedValueProxy class template (possibly by way of the
// VT_TYPE_IS_TYPED_VALUE_PROXY macro). Then provide an implementation of
// VtGetProxiedObject that accepts `TypedProxy const &` and returns a const
// lvalue reference to the underlying proxied type. That reference must be
// valid so long as the YourProxyType argument reference is valid. Like:
//
// ProxiedType const &VtGetProxiedObject(TypedProxy const &);
//
// Erased proxies are mostly useful to enable producing VtValues holding
// "deferred" values; values whose types are not yet loaded in the process. For
// example, this can be used to produce VtValues holding objects whose types are
// provided in plugins that are not yet loaded. When a real object instance is
// required, VtValue will call `VtGetErasedProxiedVtValue(YourErasedProxy const
// &)` which must return a pointer to a VtValue holding the underlying proxied
// type. This can be manufactured "on-the-fly" (with affordances for
// thread-safety).
//
// To implement an Erased proxy, either have it derive VtErasedValueProxyBase or
// specialize the VtIsErasedValueProxy class template (possibly by way of the
// VT_TYPE_IS_ERASED_VALUE_PROXY macro). Then provide implementations of:
//
// bool VtErasedProxyHoldsType(ErasedProxy const &, std::type_info const &);
// TfType VtGetErasedProxiedTfType(ErasedProxy const &);
// VtValue const *VtGetErasedProxiedVtValue(ErasedProxy const &);
//
// The pointer returned by VtGetErasedProxiedVtValue must be valid as long as
// the ErasedProxy argument reference is valid.
//
// A note on Equality Comparisons. If a proxy type provides equality
// comparison, then two VtValues that hold the same proxy types will invoke that
// equality comparison when compared. Otherwise, the underlying proxied objects
// will be compared. This is beneficial when equality can be checked without
// having to actually instantiate the proxied object (for proxies that load &
// construct the proxied object lazily).
// Clients may derive VtTypedValueProxyBase, specialize VtIsTypedValueProxy,
// or use the VT_TYPE_IS_TYPED_VALUE_PROXY macro to indicate their type is a
// VtValue proxy type.
struct VtTypedValueProxyBase {};
template <class T>
struct VtIsTypedValueProxy : std::is_base_of<VtTypedValueProxyBase, T> {};
#define VT_TYPE_IS_TYPED_VALUE_PROXY(T) \
template <> struct VtIsTypedValueProxy<TF_PP_EAT_PARENS(T)> \
: std::true_type {}
// Base implementation for VtGetProxiedObject (for non-proxy types).
template <class T,
typename std::enable_if<
!VtIsTypedValueProxy<T>::value, int>::type = 0>
T const &
VtGetProxiedObject(T const &nonProxy) {
return nonProxy;
}
// Metafunction to determine the proxied type for a typed proxy.
template <class T>
struct VtGetProxiedType
{
using type = typename std::decay<
decltype(VtGetProxiedObject(std::declval<T>()))>::type;
};
// Clients may derive VtErasedValueProxyBase, specialize VtIsErasedValueProxy,
// or use the VT_TYPE_IS_ERASED_VALUE_PROXY macro to indicate their type is a
// VtValue proxy type.
struct VtErasedValueProxyBase {};
template <class T>
struct VtIsErasedValueProxy : std::is_base_of<VtErasedValueProxyBase, T> {};
#define VT_TYPE_IS_ERASED_VALUE_PROXY(T) \
template <> struct VtIsErasedValueProxy<TF_PP_EAT_PARENS(T)> \
: std::true_type {}
// Metafunction to determine whether or not a given type T is a value proxy
// (either typed or type-erased).
template <class T>
struct VtIsValueProxy :
std::integral_constant<
bool, VtIsTypedValueProxy<T>::value || VtIsErasedValueProxy<T>::value> {};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_TRAITS_H
+221
View File
@@ -0,0 +1,221 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_TYPES_H
#define PXR_BASE_VT_TYPES_H
/// \file vt/types.h
/// Defines all the types "TYPED" for which Vt creates a VtTYPEDArray typedef.
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/traits.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/gf/declare.h"
#include "pxr/base/gf/half.h"
#include "pxr/base/tf/token.h"
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <cstddef>
#include <cstring>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
// Help ensure TfToken is stored in local storage in VtValue by indicating it is
// cheap to copy (just refcount operations).
VT_TYPE_IS_CHEAP_TO_COPY(TfToken);
// Value types.
#define VT_FLOATING_POINT_BUILTIN_VALUE_TYPES \
(( double, Double )) \
(( float, Float )) \
(( GfHalf, Half ))
#define VT_INTEGRAL_BUILTIN_VALUE_TYPES \
(( bool, Bool )) \
(( char, Char )) \
(( unsigned char, UChar )) \
(( short, Short )) \
(( unsigned short, UShort )) \
(( int, Int )) \
(( unsigned int, UInt )) \
(( int64_t, Int64 )) \
(( uint64_t, UInt64 ))
#define VT_VEC_INT_VALUE_TYPES \
(( GfVec4i, Vec4i )) \
(( GfVec3i, Vec3i )) \
(( GfVec2i, Vec2i ))
#define VT_VEC_HALF_VALUE_TYPES \
(( GfVec4h, Vec4h )) \
(( GfVec3h, Vec3h )) \
(( GfVec2h, Vec2h ))
#define VT_VEC_FLOAT_VALUE_TYPES \
(( GfVec4f, Vec4f )) \
(( GfVec3f, Vec3f )) \
(( GfVec2f, Vec2f ))
#define VT_VEC_DOUBLE_VALUE_TYPES \
(( GfVec4d, Vec4d )) \
(( GfVec3d, Vec3d )) \
(( GfVec2d, Vec2d ))
#define VT_VEC_VALUE_TYPES \
VT_VEC_INT_VALUE_TYPES \
VT_VEC_HALF_VALUE_TYPES \
VT_VEC_FLOAT_VALUE_TYPES \
VT_VEC_DOUBLE_VALUE_TYPES
#define VT_MATRIX_FLOAT_VALUE_TYPES \
(( GfMatrix4f, Matrix4f )) \
(( GfMatrix3f, Matrix3f )) \
(( GfMatrix2f, Matrix2f )) \
#define VT_MATRIX_DOUBLE_VALUE_TYPES \
(( GfMatrix4d, Matrix4d )) \
(( GfMatrix3d, Matrix3d )) \
(( GfMatrix2d, Matrix2d ))
#define VT_MATRIX_VALUE_TYPES \
VT_MATRIX_FLOAT_VALUE_TYPES \
VT_MATRIX_DOUBLE_VALUE_TYPES \
#define VT_GFRANGE_VALUE_TYPES \
(( GfRange3f, Range3f )) \
(( GfRange3d, Range3d )) \
(( GfRange2f, Range2f )) \
(( GfRange2d, Range2d )) \
(( GfRange1f, Range1f )) \
(( GfRange1d, Range1d ))
#define VT_RANGE_VALUE_TYPES \
VT_GFRANGE_VALUE_TYPES \
(( GfInterval, Interval )) \
(( GfRect2i, Rect2i ))
#define VT_STRING_VALUE_TYPES \
(( std::string, String )) \
(( TfToken, Token ))
#define VT_QUATERNION_VALUE_TYPES \
(( GfQuath, Quath )) \
(( GfQuatf, Quatf )) \
(( GfQuatd, Quatd )) \
(( GfQuaternion, Quaternion ))
#define VT_NONARRAY_VALUE_TYPES \
(( GfFrustum, Frustum)) \
(( GfMultiInterval, MultiInterval))
// Helper macros for extracting bits from a type tuple.
#define VT_TYPE(elem) \
BOOST_PP_TUPLE_ELEM(2, 0, elem)
#define VT_TYPE_NAME(elem) \
BOOST_PP_TUPLE_ELEM(2, 1, elem)
// Composite groups of types.
#define VT_BUILTIN_NUMERIC_VALUE_TYPES \
VT_INTEGRAL_BUILTIN_VALUE_TYPES VT_FLOATING_POINT_BUILTIN_VALUE_TYPES
#define VT_BUILTIN_VALUE_TYPES \
VT_BUILTIN_NUMERIC_VALUE_TYPES VT_STRING_VALUE_TYPES
#define VT_SCALAR_CLASS_VALUE_TYPES \
VT_VEC_VALUE_TYPES \
VT_MATRIX_VALUE_TYPES \
VT_RANGE_VALUE_TYPES \
VT_QUATERNION_VALUE_TYPES
#define VT_SCALAR_VALUE_TYPES \
VT_SCALAR_CLASS_VALUE_TYPES VT_BUILTIN_VALUE_TYPES
// The following preprocessor code produces typedefs for VtArray holding
// various scalar value types. The produced typedefs are of the form:
//
// typedef VtArray<int> VtIntArray;
// typedef VtArray<double> VtDoubleArray;
template<typename T> class VtArray;
#define VT_ARRAY_TYPEDEF(r, unused, elem) \
typedef VtArray< VT_TYPE(elem) > \
BOOST_PP_CAT(Vt, BOOST_PP_CAT(VT_TYPE_NAME(elem), Array)) ;
BOOST_PP_SEQ_FOR_EACH(VT_ARRAY_TYPEDEF, ~, VT_SCALAR_VALUE_TYPES)
// The following preprocessor code generates the boost pp sequence for
// all array value types (VT_ARRAY_VALUE_TYPES)
#define VT_ARRAY_TYPE_TUPLE(r, unused, elem) \
(( BOOST_PP_CAT(Vt, BOOST_PP_CAT(VT_TYPE_NAME(elem), Array)) , \
BOOST_PP_CAT(VT_TYPE_NAME(elem), Array) ))
#define VT_ARRAY_VALUE_TYPES \
BOOST_PP_SEQ_FOR_EACH(VT_ARRAY_TYPE_TUPLE, ~, VT_SCALAR_VALUE_TYPES)
#define VT_CLASS_VALUE_TYPES \
VT_ARRAY_VALUE_TYPES VT_SCALAR_CLASS_VALUE_TYPES VT_NONARRAY_VALUE_TYPES
// Free functions to represent "zero" for various base types. See
// specializations in Types.cpp
template<typename T>
T VtZero();
// Shape representation used in VtArray for legacy code. This is not supported
// at the pxr level or in usd. Shape is represented by a total size, plus sized
// dimensions other than the last. The size of the last dimension is computed
// as totalSize / (product-of-other-dimensions).
struct Vt_ShapeData {
unsigned int GetRank() const {
return
otherDims[0] == 0 ? 1 :
otherDims[1] == 0 ? 2 :
otherDims[2] == 0 ? 3 : 4;
}
bool operator==(Vt_ShapeData const &other) const {
if (totalSize != other.totalSize)
return false;
unsigned int thisRank = GetRank(), otherRank = other.GetRank();
if (thisRank != otherRank)
return false;
return std::equal(otherDims, otherDims + GetRank() - 1,
other.otherDims);
}
bool operator!=(Vt_ShapeData const &other) const {
return !(*this == other);
}
void clear() {
memset(this, 0, sizeof(*this));
}
static const int NumOtherDims = 3;
size_t totalSize;
unsigned int otherDims[NumOtherDims];
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_TYPES_H
File diff suppressed because it is too large. Load diff
+166
View File
@@ -0,0 +1,166 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_VALUE_FROM_PYTHON_H
#define PXR_BASE_VT_VALUE_FROM_PYTHON_H
/// \file vt/valueFromPython.h
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/pySafePython.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class Vt_ValueFromPythonRegistry
///
class Vt_ValueFromPythonRegistry {
public:
static bool HasConversions() {
return !_GetInstance()._lvalueExtractors.empty() &&
!_GetInstance()._rvalueExtractors.empty();
}
VT_API static VtValue Invoke(PyObject *obj);
template <class T>
static void Register(bool registerRvalue) {
if (!TfPyIsInitialized()) {
TF_FATAL_ERROR("Tried to register a VtValue from python conversion "
"but python is not initialized!");
}
_GetInstance()._RegisterLValue(_Extractor::MakeLValue<T>());
if (registerRvalue)
_GetInstance()._RegisterRValue(_Extractor::MakeRValue<T>());
}
Vt_ValueFromPythonRegistry(Vt_ValueFromPythonRegistry const&) = delete;
Vt_ValueFromPythonRegistry& operator=(
Vt_ValueFromPythonRegistry const&) = delete;
Vt_ValueFromPythonRegistry(Vt_ValueFromPythonRegistry &&) = delete;
Vt_ValueFromPythonRegistry& operator=(
Vt_ValueFromPythonRegistry &&) = delete;
private:
Vt_ValueFromPythonRegistry() {}
VT_API ~Vt_ValueFromPythonRegistry();
friend class TfSingleton<Vt_ValueFromPythonRegistry>;
class _Extractor {
private:
using _ExtractFunc = VtValue (*)(PyObject *);
// _ExtractLValue will attempt to obtain an l-value T from the python
// object it's passed. This effectively disallows type conversions
// (other than things like derived-to-base type conversions).
template <class T>
static VtValue _ExtractLValue(PyObject *);
// _ExtractRValue will attempt to obtain an r-value T from the python
// object it's passed. This allows boost.python to invoke type
// conversions to produce the T.
template <class T>
static VtValue _ExtractRValue(PyObject *);
public:
template <class T>
static _Extractor MakeLValue() {
return _Extractor(&_ExtractLValue<T>);
}
template <class T>
static _Extractor MakeRValue() {
return _Extractor(&_ExtractRValue<T>);
}
VtValue Invoke(PyObject *obj) const {
return _extract(obj);
}
private:
explicit _Extractor(_ExtractFunc extract) : _extract(extract) {}
_ExtractFunc _extract;
};
VT_API static Vt_ValueFromPythonRegistry &_GetInstance() {
return TfSingleton<Vt_ValueFromPythonRegistry>::GetInstance();
}
VT_API void _RegisterLValue(_Extractor const &e);
VT_API void _RegisterRValue(_Extractor const &e);
std::vector<_Extractor> _lvalueExtractors;
std::vector<_Extractor> _rvalueExtractors;
typedef TfHashMap<PyObject *, _Extractor, TfHash> _LValueExtractorCache;
_LValueExtractorCache _lvalueExtractorCache;
};
VT_API_TEMPLATE_CLASS(TfSingleton<Vt_ValueFromPythonRegistry>);
template <class T>
VtValue Vt_ValueFromPythonRegistry::
_Extractor::_ExtractLValue(PyObject *obj) {
boost::python::extract<T &> x(obj);
if (x.check())
return VtValue(x());
return VtValue();
}
template <class T>
VtValue Vt_ValueFromPythonRegistry::
_Extractor::_ExtractRValue(PyObject *obj) {
boost::python::extract<T> x(obj);
if (x.check())
return VtValue(x());
return VtValue();
}
template <class T>
void VtValueFromPython() {
Vt_ValueFromPythonRegistry::Register<T>(/* registerRvalue = */ true);
}
template <class T>
void VtValueFromPythonLValue() {
Vt_ValueFromPythonRegistry::Register<T>(/* registerRvalue = */ false);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_VALUE_FROM_PYTHON_H
+639
View File
@@ -0,0 +1,639 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_VT_WRAP_ARRAY_H
#define PXR_BASE_VT_WRAP_ARRAY_H
#include "pxr/pxr.h"
#include "pxr/base/vt/api.h"
#include "pxr/base/vt/array.h"
#include "pxr/base/vt/types.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/vt/pyOperators.h"
#include "pxr/base/vt/functions.h"
#include "pxr/base/arch/math.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/arch/pragmas.h"
#include "pxr/base/gf/half.h"
#include "pxr/base/tf/pyContainerConversions.h"
#include "pxr/base/tf/pyFunction.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/span.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/tf.h"
#include "pxr/base/tf/wrapTypeHelpers.h"
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/python/class.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <boost/python/def.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/iterator.hpp>
#include <boost/python/make_constructor.hpp>
#include <boost/python/object.hpp>
#include <boost/python/operators.hpp>
#include <boost/python/return_arg.hpp>
#include <boost/python/slice.hpp>
#include <boost/python/type_id.hpp>
#include <boost/python/overloads.hpp>
#include <algorithm>
#include <numeric>
#include <ostream>
#include <string>
#include <memory>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
namespace Vt_WrapArray {
using namespace boost::python;
using std::unique_ptr;
using std::vector;
using std::string;
template <typename T>
object
getitem_ellipsis(VtArray<T> const &self, object idx)
{
object ellipsis = object(handle<>(borrowed(Py_Ellipsis)));
if (idx != ellipsis) {
PyErr_SetString(PyExc_TypeError, "unsupported index type");
throw_error_already_set();
}
return object(self);
}
template <typename T>
object
getitem_index(VtArray<T> const &self, int64_t idx)
{
static const bool throwError = true;
idx = TfPyNormalizeIndex(idx, self.size(), throwError);
return object(self[idx]);
}
template <typename T>
object
getitem_slice(VtArray<T> const &self, slice idx)
{
try {
slice::range<typename VtArray<T>::const_iterator> range =
idx.get_indices(self.begin(), self.end());
const size_t setSize = 1 + (range.stop - range.start) / range.step;
VtArray<T> result(setSize);
size_t i = 0;
for (; range.start != range.stop; range.start += range.step, ++i) {
result[i] = *range.start;
}
result[i] = *range.start;
return object(result);
}
catch (std::invalid_argument) {
return object();
}
}
template <typename T, typename S>
void
setArraySlice(VtArray<T> &self, S value,
slice::range<T*>& range, size_t setSize, bool tile = false)
{
// Check size.
const size_t length = len(value);
if (length == 0)
TfPyThrowValueError("No values with which to set array slice.");
if (!tile && length < setSize) {
string msg = TfStringPrintf
("Not enough values to set slice. Expected %zu, got %zu.",
setSize, length);
TfPyThrowValueError(msg);
}
// Extract the values before setting any. If we can extract the
// whole vector at once then do that since it should be faster.
std::vector<T> extracted;
extract<std::vector<T> > vectorExtraction(value);
if (vectorExtraction.check()) {
std::vector<T> tmp = vectorExtraction();
extracted.swap(tmp);
}
else {
extracted.reserve(length);
for (size_t i = 0; i != length; ++i) {
extracted.push_back(extract<T>(value[i]));
}
}
// We're fine, go through and set them. Handle common case as a fast
// path.
if (range.step == 1 && length >= setSize) {
std::copy(extracted.begin(), extracted.begin() + setSize, range.start);
}
else {
for (size_t i = 0; i != setSize; range.start += range.step, ++i) {
*range.start = extracted[i % length];
}
}
}
template <typename T>
void
setArraySlice(VtArray<T> &self, slice idx, object value, bool tile = false)
{
// Get the range.
slice::range<T*> range;
try {
T* data = self.data();
range = idx.get_indices(data, data + self.size());
}
catch (std::invalid_argument) {
// Do nothing
return;
}
// Get the number of items to be set.
const size_t setSize = 1 + (range.stop - range.start) / range.step;
// Copy from VtArray. We only want to take this path if the passed value is
// *exactly* a VtArray. That is, we don't want to take this path if it can
// merely *convert* to a VtArray, so we check that we can extract a mutable
// lvalue reference from the python object, which requires that there be a
// real VtArray there.
if (extract< VtArray<T> &>(value).check()) {
const VtArray<T> val = extract< VtArray<T> >(value);
const size_t length = val.size();
if (length == 0)
TfPyThrowValueError("No values with which to set array slice.");
if (!tile && length < setSize) {
string msg = TfStringPrintf
("Not enough values to set slice. Expected %zu, got %zu.",
setSize, length);
TfPyThrowValueError(msg);
}
// We're fine, go through and set them.
for (size_t i = 0; i != setSize; range.start += range.step, ++i) {
*range.start = val[i % length];
}
}
// Copy from scalar.
else if (extract<T>(value).check()) {
if (!tile) {
// XXX -- We're allowing implicit tiling; do we want to?
//TfPyThrowValueError("can only assign an iterable.");
}
// Use scalar to fill entire slice.
const T val = extract<T>(value);
for (size_t i = 0; i != setSize; range.start += range.step, ++i) {
*range.start = val;
}
}
// Copy from list.
else if (extract<list>(value).check()) {
setArraySlice(self, extract<list>(value)(), range, setSize, tile);
}
// Copy from tuple.
else if (extract<tuple>(value).check()) {
setArraySlice(self, extract<tuple>(value)(), range, setSize, tile);
}
// Copy from iterable.
else {
setArraySlice(self, list(value), range, setSize, tile);
}
}
template <typename T>
void
setitem_ellipsis(VtArray<T> &self, object idx, object value)
{
object ellipsis = object(handle<>(borrowed(Py_Ellipsis)));
if (idx != ellipsis) {
PyErr_SetString(PyExc_TypeError, "unsupported index type");
throw_error_already_set();
}
setArraySlice(self, slice(0, self.size()), value);
}
template <typename T>
void
setitem_index(VtArray<T> &self, int64_t idx, object value)
{
static const bool tile = true;
setArraySlice(self, slice(idx, idx + 1), value, tile);
}
template <typename T>
void
setitem_slice(VtArray<T> &self, slice idx, object value)
{
setArraySlice(self, idx, value);
}
template <class T>
VT_API string GetVtArrayName();
// To avoid overhead we stream out certain builtin types directly
// without calling TfPyRepr().
template <typename T>
static void streamValue(std::ostringstream &stream, T const &value) {
stream << TfPyRepr(value);
}
// This is the same types as in VT_INTEGRAL_BUILTIN_VALUE_TYPES with char
// and bool types removed.
#define _OPTIMIZED_STREAM_INTEGRAL_TYPES \
(short) \
(unsigned short) \
(int) \
(unsigned int) \
(long) \
(unsigned long) \
(long long) \
(unsigned long long)
#define MAKE_STREAM_FUNC(r, unused, type) \
static inline void \
streamValue(std::ostringstream &stream, type const &value) { \
stream << value; \
}
BOOST_PP_SEQ_FOR_EACH(MAKE_STREAM_FUNC, ~, _OPTIMIZED_STREAM_INTEGRAL_TYPES)
#undef MAKE_STREAM_FUNC
#undef _OPTIMIZED_STREAM_INTEGRAL_TYPES
// Explicitly convert half to float here instead of relying on implicit
// conversion to float to work around the fact that libc++ only provides
// implementations of std::isfinite for types where std::is_arithmetic
// is true.
template <typename T>
static bool _IsFinite(T const &value) {
return std::isfinite(value);
}
static bool _IsFinite(GfHalf const &value) {
return std::isfinite(static_cast<float>(value));
}
// For float types we need to be make sure to represent infs and nans correctly.
#define MAKE_STREAM_FUNC(r, unused, elem) \
static inline void \
streamValue(std::ostringstream &stream, VT_TYPE(elem) const &value) { \
if (_IsFinite(value)) { \
stream << value; \
} else { \
stream << TfPyRepr(value); \
} \
}
BOOST_PP_SEQ_FOR_EACH(
MAKE_STREAM_FUNC, ~, VT_FLOATING_POINT_BUILTIN_VALUE_TYPES)
#undef MAKE_STREAM_FUNC
static unsigned int
Vt_ComputeEffectiveRankAndLastDimSize(
Vt_ShapeData const *sd, size_t *lastDimSize)
{
unsigned int rank = sd->GetRank();
if (rank == 1)
return rank;
size_t divisor = std::accumulate(
sd->otherDims, sd->otherDims + rank-1,
1, [](size_t x, size_t y) { return x * y; });
size_t remainder = divisor ? sd->totalSize % divisor : 0;
*lastDimSize = divisor ? sd->totalSize / divisor : 0;
if (remainder)
rank = 1;
return rank;
}
template <typename T>
string __repr__(VtArray<T> const &self)
{
if (self.empty())
return TF_PY_REPR_PREFIX +
TfStringPrintf("%s()", GetVtArrayName<VtArray<T> >().c_str());
std::ostringstream stream;
stream.precision(17);
stream << "(";
for (size_t i = 0; i < self.size(); ++i) {
stream << (i ? ", " : "");
streamValue(stream, self[i]);
}
stream << (self.size() == 1 ? ",)" : ")");
const std::string repr = TF_PY_REPR_PREFIX +
TfStringPrintf("%s(%zd, %s)",
GetVtArrayName<VtArray<T> >().c_str(),
self.size(), stream.str().c_str());
// XXX: This is to deal with legacy shaped arrays and should be removed
// once all shaped arrays have been eliminated.
// There is no nice way to make an eval()able __repr__ for shaped arrays
// that preserves the shape information, so put it in <> to make it
// clearly not eval()able. That has the advantage that, if somebody passes
// the repr into eval(), it'll raise a SyntaxError that clearly points to
// the beginning of the __repr__.
Vt_ShapeData const *shapeData = self._GetShapeData();
size_t lastDimSize = 0;
unsigned int rank =
Vt_ComputeEffectiveRankAndLastDimSize(shapeData, &lastDimSize);
if (rank > 1) {
std::string shapeStr = "(";
for (size_t i = 0; i != rank-1; ++i) {
shapeStr += TfStringPrintf(
i ? ", %d" : "%d", shapeData->otherDims[i]);
}
shapeStr += TfStringPrintf(", %zu)", lastDimSize);
return TfStringPrintf("<%s with shape %s>",
repr.c_str(), shapeStr.c_str());
}
return repr;
}
template <typename T>
VtArray<T> *VtArray__init__(object const &values)
{
// Make an array.
unique_ptr<VtArray<T> > ret(new VtArray<T>(len(values)));
// Set the values. This is equivalent to saying 'ret[...] = values'
// in python, except that we allow tiling here.
static const bool tile = true;
setArraySlice(*ret, slice(0, ret->size()), values, tile);
return ret.release();
}
template <typename T>
VtArray<T> *VtArray__init__2(size_t size, object const &values)
{
// Make the array.
unique_ptr<VtArray<T> > ret(new VtArray<T>(size));
// Set the values. This is equivalent to saying 'ret[...] = values'
// in python, except that we allow tiling here.
static const bool tile = true;
setArraySlice(*ret, slice(0, ret->size()), values, tile);
return ret.release();
}
// overloading for operator special methods, to allow tuple / list & array
// combinations
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
VTOPERATOR_WRAP(+,__add__,__radd__)
VTOPERATOR_WRAP_NONCOMM(-,__sub__,__rsub__)
VTOPERATOR_WRAP(*,__mul__,__rmul__)
VTOPERATOR_WRAP_NONCOMM(/,__div__,__rdiv__)
VTOPERATOR_WRAP_NONCOMM(%,__mod__,__rmod__)
VTOPERATOR_WRAP_BOOL(Equal,==)
VTOPERATOR_WRAP_BOOL(NotEqual,!=)
VTOPERATOR_WRAP_BOOL(Greater,>)
VTOPERATOR_WRAP_BOOL(Less,<)
VTOPERATOR_WRAP_BOOL(GreaterOrEqual,>=)
VTOPERATOR_WRAP_BOOL(LessOrEqual,<=)
ARCH_PRAGMA_POP
}
template <typename T>
static std::string _VtStr(T const &self)
{
return boost::lexical_cast<std::string>(self);
}
template <typename T>
void VtWrapArray()
{
using namespace Vt_WrapArray;
typedef T This;
typedef typename This::ElementType Type;
string name = GetVtArrayName<This>();
string typeStr = ArchGetDemangled(typeid(Type));
string docStr = TfStringPrintf("An array of type %s.", typeStr.c_str());
class_<This>(name.c_str(), docStr.c_str(), no_init)
.setattr("_isVtArray", true)
.def(TfTypePythonClass())
.def(init<>())
.def("__init__", make_constructor(VtArray__init__<Type>),
(const char *)
"__init__(values)\n\n"
"values: a sequence (tuple, list, or another VtArray with "
"element type convertible to the new array's element type)\n\n"
)
.def("__init__", make_constructor(VtArray__init__2<Type>))
.def(init<unsigned int>())
.def("__getitem__", getitem_ellipsis<Type>)
.def("__getitem__", getitem_slice<Type>)
.def("__getitem__", getitem_index<Type>)
.def("__setitem__", setitem_ellipsis<Type>)
.def("__setitem__", setitem_slice<Type>)
.def("__setitem__", setitem_index<Type>)
.def("__len__", &This::size)
.def("__iter__", iterator<This>())
.def("__repr__", __repr__<Type>)
// .def(str(self))
.def("__str__", _VtStr<T>)
.def(self == self)
.def(self != self)
#ifdef NUMERIC_OPERATORS
#define ADDITION_OPERATOR
#define SUBTRACTION_OPERATOR
#define MULTIPLICATION_OPERATOR
#define DIVISION_OPERATOR
#define UNARY_NEG_OPERATOR
#endif
#ifdef ADDITION_OPERATOR
VTOPERATOR_WRAPDECLARE(+,__add__,__radd__)
#endif
#ifdef SUBTRACTION_OPERATOR
VTOPERATOR_WRAPDECLARE(-,__sub__,__rsub__)
#endif
#ifdef MULTIPLICATION_OPERATOR
VTOPERATOR_WRAPDECLARE(*,__mul__,__rmul__)
#endif
#ifdef DIVISION_OPERATOR
VTOPERATOR_WRAPDECLARE(/,__div__,__rdiv__)
#endif
#ifdef MOD_OPERATOR
VTOPERATOR_WRAPDECLARE(%,__mod__,__rmod__)
#endif
#ifdef DOUBLE_MULT_OPERATOR
.def(self * double())
.def(double() * self)
#endif
#ifdef DOUBLE_DIV_OPERATOR
.def(self / double())
#endif
#ifdef UNARY_NEG_OPERATOR
.def(- self)
#endif
;
#define WRITE(z, n, data) BOOST_PP_COMMA_IF(n) data
#define VtCat_DEF(z, n, unused) \
def("Cat",(VtArray<Type> (*)( BOOST_PP_REPEAT(n, WRITE, VtArray<Type> const &) ))VtCat<Type>);
BOOST_PP_REPEAT_FROM_TO(1, VT_FUNCTIONS_MAX_ARGS, VtCat_DEF, ~)
#undef VtCat_DEF
VTOPERATOR_WRAPDECLARE_BOOL(Equal)
VTOPERATOR_WRAPDECLARE_BOOL(NotEqual)
// Wrap conversions from python sequences.
TfPyContainerConversions::from_python_sequence<
This,
TfPyContainerConversions::
variable_capacity_all_items_convertible_policy>();
// Wrap implicit conversions from VtArray to TfSpan.
implicitly_convertible<This, TfSpan<Type> >();
implicitly_convertible<This, TfSpan<const Type> >();
}
// wrapping for functions that work for base types that support comparisons
template <typename T>
void VtWrapComparisonFunctions()
{
using namespace Vt_WrapArray;
typedef T This;
typedef typename This::ElementType Type;
def("AnyTrue", VtAnyTrue<Type>);
def("AllTrue", VtAllTrue<Type>);
VTOPERATOR_WRAPDECLARE_BOOL(Greater)
VTOPERATOR_WRAPDECLARE_BOOL(Less)
VTOPERATOR_WRAPDECLARE_BOOL(GreaterOrEqual)
VTOPERATOR_WRAPDECLARE_BOOL(LessOrEqual)
}
template <class Array>
VtValue
Vt_ConvertFromPySequence(TfPyObjWrapper const &obj)
{
typedef typename Array::ElementType ElemType;
TfPyLock lock;
if (PySequence_Check(obj.ptr())) {
Py_ssize_t len = PySequence_Length(obj.ptr());
Array result(len);
ElemType *elem = result.data();
for (Py_ssize_t i = 0; i != len; ++i) {
boost::python::handle<> h(PySequence_ITEM(obj.ptr(), i));
if (!h) {
if (PyErr_Occurred())
PyErr_Clear();
return VtValue();
}
boost::python::extract<ElemType> e(h.get());
if (!e.check())
return VtValue();
*elem++ = e();
}
return VtValue(result);
}
return VtValue();
}
template <class Array, class Iter>
VtValue
Vt_ConvertFromRange(Iter begin, Iter end)
{
typedef typename Array::ElementType ElemType;
Array result(distance(begin, end));
for (ElemType *e = result.data(); begin != end; ++begin) {
VtValue cast = VtValue::Cast<ElemType>(*begin);
if (cast.IsEmpty())
return cast;
cast.Swap(*e++);
}
return VtValue(result);
}
template <class T>
VtValue
Vt_CastToArray(VtValue const &v) {
VtValue ret;
TfPyObjWrapper obj;
// Attempt to convert from either python sequence or vector<VtValue>.
if (v.IsHolding<TfPyObjWrapper>()) {
ret = Vt_ConvertFromPySequence<T>(v.UncheckedGet<TfPyObjWrapper>());
} else if (v.IsHolding<std::vector<VtValue> >()) {
std::vector<VtValue> const &vec = v.UncheckedGet<std::vector<VtValue> >();
ret = Vt_ConvertFromRange<T>(vec.begin(), vec.end());
}
return ret;
}
/// Register casts with VtValue from python sequences to VtArray types.
template <class Elem>
void VtRegisterValueCastsFromPythonSequencesToArray()
{
typedef VtArray<Elem> Array;
VtValue::RegisterCast<TfPyObjWrapper, Array>(Vt_CastToArray<Array>);
VtValue::RegisterCast<std::vector<VtValue>, Array>(Vt_CastToArray<Array>);
}
#define VT_WRAP_ARRAY(r, unused, elem) \
VtWrapArray< VtArray< VT_TYPE(elem) > >();
#define VT_WRAP_COMPARISON(r, unused, elem) \
VtWrapComparisonFunctions< VtArray< VT_TYPE(elem) > >();
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_VT_WRAP_ARRAY_H