24#ifndef PXR_BASE_VT_WRAP_ARRAY_H
25#define PXR_BASE_VT_WRAP_ARRAY_H
28#include "pxr/base/vt/api.h"
31#include "pxr/base/vt/value.h"
32#include "pxr/base/vt/pyOperators.h"
39#include "pxr/base/gf/traits.h"
41#include "pxr/base/tf/pyFunction.h"
42#include "pxr/base/tf/pyLock.h"
43#include "pxr/base/tf/pyObjWrapper.h"
44#include "pxr/base/tf/pyResultConversions.h"
47#include "pxr/base/tf/meta.h"
51#include "pxr/base/tf/wrapTypeHelpers.h"
53#include <boost/preprocessor/punctuation/comma_if.hpp>
54#include <boost/preprocessor/repetition/repeat.hpp>
56#include <boost/python/class.hpp>
57#include <boost/python/copy_const_reference.hpp>
58#include <boost/python/def.hpp>
59#include <boost/python/detail/api_placeholder.hpp>
60#include <boost/python/extract.hpp>
61#include <boost/python/implicit.hpp>
62#include <boost/python/iterator.hpp>
63#include <boost/python/make_constructor.hpp>
64#include <boost/python/object.hpp>
65#include <boost/python/operators.hpp>
66#include <boost/python/return_arg.hpp>
67#include <boost/python/slice.hpp>
68#include <boost/python/type_id.hpp>
69#include <boost/python/overloads.hpp>
78PXR_NAMESPACE_OPEN_SCOPE
80namespace Vt_WrapArray {
82using namespace boost::python;
90getitem_ellipsis(
VtArray<T> const &self,
object idx)
92 object ellipsis = object(handle<>(borrowed(Py_Ellipsis)));
93 if (idx != ellipsis) {
94 PyErr_SetString(PyExc_TypeError,
"unsupported index type");
95 throw_error_already_set();
102getitem_index(
VtArray<T> const &self, int64_t idx)
104 static const bool throwError =
true;
106 return object(self[idx]);
111getitem_slice(
VtArray<T> const &self, slice idx)
114 slice::range<typename VtArray<T>::const_iterator> range =
115 idx.get_indices(self.
begin(), self.
end());
116 const size_t setSize = 1 + (range.stop - range.start) / range.step;
119 for (; range.start != range.stop; range.start += range.step, ++i) {
120 result[i] = *range.start;
122 result[i] = *range.start;
123 return object(result);
125 catch (std::invalid_argument
const &) {
130template <
typename T,
typename S>
133 slice::range<T*>& range,
size_t setSize,
bool tile =
false)
136 const size_t length = len(value);
139 if (!tile && length < setSize) {
141 (
"Not enough values to set slice. Expected %zu, got %zu.",
148 std::vector<T> extracted;
149 extract<std::vector<T> > vectorExtraction(value);
150 if (vectorExtraction.check()) {
151 std::vector<T> tmp = vectorExtraction();
155 extracted.reserve(length);
156 for (
size_t i = 0; i != length; ++i) {
157 extracted.push_back(extract<T>(value[i]));
163 if (range.step == 1 && length >= setSize) {
164 std::copy(extracted.begin(), extracted.begin() + setSize, range.start);
167 for (
size_t i = 0; i != setSize; range.start += range.step, ++i) {
168 *range.start = extracted[i % length];
175setArraySlice(
VtArray<T> &self, slice idx,
object value,
bool tile =
false)
178 slice::range<T*> range;
180 T* data = self.
data();
181 range = idx.get_indices(data, data + self.
size());
183 catch (std::invalid_argument
const &) {
189 const size_t setSize = 1 + (range.stop - range.start) / range.step;
197 const VtArray<T> val = extract< VtArray<T> >(value);
198 const size_t length = val.
size();
201 if (!tile && length < setSize) {
203 (
"Not enough values to set slice. Expected %zu, got %zu.",
209 for (
size_t i = 0; i != setSize; range.start += range.step, ++i) {
210 *range.start = val[i % length];
215 else if (extract<T>(value).check()) {
222 const T val = extract<T>(value);
223 for (
size_t i = 0; i != setSize; range.start += range.step, ++i) {
229 else if (extract<list>(value).check()) {
230 setArraySlice(self, extract<list>(value)(), range, setSize, tile);
234 else if (extract<tuple>(value).check()) {
235 setArraySlice(self, extract<tuple>(value)(), range, setSize, tile);
240 setArraySlice(self, list(value), range, setSize, tile);
247setitem_ellipsis(
VtArray<T> &self,
object idx,
object value)
249 object ellipsis = object(handle<>(borrowed(Py_Ellipsis)));
250 if (idx != ellipsis) {
251 PyErr_SetString(PyExc_TypeError,
"unsupported index type");
252 throw_error_already_set();
254 setArraySlice(self, slice(0, self.
size()), value);
259setitem_index(
VtArray<T> &self, int64_t idx,
object value)
262 setArraySlice(self, slice(idx, idx+1), value,
true);
267setitem_slice(
VtArray<T> &self, slice idx,
object value)
269 setArraySlice(self, idx, value);
274VT_API
string GetVtArrayName();
276template <
class T,
class... Ts>
277constexpr bool Vt_IsAnySameImpl(TfMetaList<Ts...>) {
278 return (std::is_same_v<T, Ts> || ...);
281template <
class T,
class TypeList>
282constexpr bool Vt_IsAnySame() {
283 return Vt_IsAnySameImpl<T>(TypeList{});
288using Vt_OptimizedStreamIntegralTypes =
289 TfMetaList<short,
unsigned short,
292 long long,
unsigned long long>;
299inline bool _IsFinite(T
const &value) {
300 return std::isfinite(value);
302inline bool _IsFinite(
GfHalf const &value) {
303 return std::isfinite(
static_cast<float>(value));
307static void streamValue(std::ostringstream &stream, T
const &value) {
310 if constexpr(Vt_IsAnySame<T, Vt_OptimizedStreamIntegralTypes>()) {
315 if (_IsFinite(value)) {
328Vt_ComputeEffectiveRankAndLastDimSize(
329 Vt_ShapeData
const *sd,
size_t *lastDimSize)
331 unsigned int rank = sd->GetRank();
335 size_t divisor = std::accumulate(
336 sd->otherDims, sd->otherDims + rank-1,
337 1, [](
size_t x,
size_t y) { return x * y; });
339 size_t remainder = divisor ? sd->totalSize % divisor : 0;
340 *lastDimSize = divisor ? sd->totalSize / divisor : 0;
355 std::ostringstream stream;
356 stream.precision(17);
358 for (
size_t i = 0; i < self.
size(); ++i) {
359 stream << (i ?
", " :
"");
360 streamValue(stream, self[i]);
362 stream << (self.
size() == 1 ?
",)" :
")");
367 self.
size(), stream.str().c_str());
376 Vt_ShapeData
const *shapeData = self._GetShapeData();
377 size_t lastDimSize = 0;
379 Vt_ComputeEffectiveRankAndLastDimSize(shapeData, &lastDimSize);
381 std::string shapeStr =
"(";
382 for (
size_t i = 0; i != rank-1; ++i) {
384 i ?
", %d" :
"%d", shapeData->otherDims[i]);
388 repr.c_str(), shapeStr.c_str());
395VtArray<T> *VtArray__init__(
object const &values)
398 unique_ptr<VtArray<T> > ret(
new VtArray<T>(len(values)));
402 static const bool tile =
true;
403 setArraySlice(*ret, slice(0, ret->size()), values, tile);
404 return ret.release();
407VtArray<T> *VtArray__init__2(
size_t size,
object const &values)
410 unique_ptr<VtArray<T> > ret(
new VtArray<T>(size));
414 static const bool tile =
true;
415 setArraySlice(*ret, slice(0, ret->size()), values, tile);
417 return ret.release();
423ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
424ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
426VTOPERATOR_WRAP(__add__,__radd__)
427VTOPERATOR_WRAP_NONCOMM(__sub__,__rsub__)
428VTOPERATOR_WRAP(__mul__,__rmul__)
429VTOPERATOR_WRAP_NONCOMM(__div__,__rdiv__)
430VTOPERATOR_WRAP_NONCOMM(__mod__,__rmod__)
432VTOPERATOR_WRAP_BOOL(Equal,==)
433VTOPERATOR_WRAP_BOOL(NotEqual,!=)
434VTOPERATOR_WRAP_BOOL(Greater,>)
435VTOPERATOR_WRAP_BOOL(Less,<)
436VTOPERATOR_WRAP_BOOL(GreaterOrEqual,>=)
437VTOPERATOR_WRAP_BOOL(LessOrEqual,<=)
442static
std::
string _VtStr(T const &self)
450 using namespace Vt_WrapArray;
453 typedef typename This::ElementType Type;
455 string name = GetVtArrayName<This>();
457 string docStr =
TfStringPrintf(
"An array of type %s.", typeStr.c_str());
459 auto selfCls = class_<This>(name.c_str(), docStr.c_str(), no_init)
460 .setattr(
"_isVtArray",
true)
463 .def(
"__init__", make_constructor(VtArray__init__<Type>),
465 "__init__(values)\n\n"
466 "values: a sequence (tuple, list, or another VtArray with "
467 "element type convertible to the new array's element type)\n\n"
469 .def(
"__init__", make_constructor(VtArray__init__2<Type>))
470 .def(init<unsigned int>())
472 .def(
"__getitem__", getitem_ellipsis<Type>)
473 .def(
"__getitem__", getitem_slice<Type>)
474 .def(
"__getitem__", getitem_index<Type>)
475 .def(
"__setitem__", setitem_ellipsis<Type>)
476 .def(
"__setitem__", setitem_slice<Type>)
477 .def(
"__setitem__", setitem_index<Type>)
479 .def(
"__len__", &This::size)
480 .def(
"__iter__", iterator<This>())
482 .def(
"__repr__", __repr__<Type>)
485 .def(
"__str__", _VtStr<T>)
489#ifdef NUMERIC_OPERATORS
490#define ADDITION_OPERATOR
491#define SUBTRACTION_OPERATOR
492#define MULTIPLICATION_OPERATOR
493#define DIVISION_OPERATOR
494#define UNARY_NEG_OPERATOR
497#ifdef ADDITION_OPERATOR
498 VTOPERATOR_WRAPDECLARE(+,__add__,__radd__)
500#ifdef SUBTRACTION_OPERATOR
501 VTOPERATOR_WRAPDECLARE(-,__sub__,__rsub__)
503#ifdef MULTIPLICATION_OPERATOR
504 VTOPERATOR_WRAPDECLARE(*,__mul__,__rmul__)
506#ifdef DIVISION_OPERATOR
507 VTOPERATOR_WRAPDECLARE(/,__div__,__rdiv__)
510 VTOPERATOR_WRAPDECLARE(%,__mod__,__rmod__)
512#ifdef DOUBLE_MULT_OPERATOR
513 .def(self *
double())
514 .def(
double() * self)
516#ifdef DOUBLE_DIV_OPERATOR
517 .def(self /
double())
519#ifdef UNARY_NEG_OPERATOR
525#define WRITE(z, n, data) BOOST_PP_COMMA_IF(n) data
526#define VtCat_DEF(z, n, unused) \
527 def("Cat",(VtArray<Type> (*)( BOOST_PP_REPEAT(n, WRITE, VtArray<Type> const &) ))VtCat<Type>);
528 BOOST_PP_REPEAT_FROM_TO(1, VT_FUNCTIONS_MAX_ARGS, VtCat_DEF, ~)
531 VTOPERATOR_WRAPDECLARE_BOOL(Equal)
532 VTOPERATOR_WRAPDECLARE_BOOL(NotEqual)
535 TfPyContainerConversions::from_python_sequence<
537 TfPyContainerConversions::
538 variable_capacity_all_items_convertible_policy>();
541 implicitly_convertible<This, TfSpan<Type> >();
542 implicitly_convertible<This, TfSpan<const Type> >();
547void VtWrapComparisonFunctions()
549 using namespace Vt_WrapArray;
552 typedef typename This::ElementType Type;
554 def(
"AnyTrue", VtAnyTrue<Type>);
555 def(
"AllTrue", VtAllTrue<Type>);
557 VTOPERATOR_WRAPDECLARE_BOOL(Greater)
558 VTOPERATOR_WRAPDECLARE_BOOL(Less)
559 VTOPERATOR_WRAPDECLARE_BOOL(GreaterOrEqual)
560 VTOPERATOR_WRAPDECLARE_BOOL(LessOrEqual)
563template <
class Array>
567 typedef typename Array::ElementType ElemType;
569 if (PySequence_Check(obj.
ptr())) {
570 Py_ssize_t len = PySequence_Length(obj.
ptr());
572 ElemType *elem = result.data();
573 for (Py_ssize_t i = 0; i != len; ++i) {
574 boost::python::handle<> h(PySequence_ITEM(obj.
ptr(), i));
576 if (PyErr_Occurred())
580 boost::python::extract<ElemType> e(h.get());
586 }
else if (PyIter_Check(obj.
ptr())) {
588 while (PyObject *item = PyIter_Next(obj.
ptr())) {
589 boost::python::handle<> h(item);
591 if (PyErr_Occurred())
595 boost::python::extract<ElemType> e(h.get());
598 result.push_back(e());
605template <
class Array,
class Iter>
607Vt_ConvertFromRange(Iter begin, Iter end)
609 typedef typename Array::ElementType ElemType;
610 Array result(distance(begin, end));
611 for (ElemType *e = result.data(); begin != end; ++begin) {
612 VtValue cast = VtValue::Cast<ElemType>(*begin);
622Vt_CastToArray(
VtValue const &v) {
628 }
else if (v.
IsHolding<std::vector<VtValue> >()) {
629 std::vector<VtValue>
const &vec = v.
UncheckedGet<std::vector<VtValue> >();
630 ret = Vt_ConvertFromRange<T>(vec.begin(), vec.end());
637void VtRegisterValueCastsFromPythonSequencesToArray()
640 VtValue::RegisterCast<TfPyObjWrapper, Array>(Vt_CastToArray<Array>);
641 VtValue::RegisterCast<std::vector<VtValue>, Array>(Vt_CastToArray<Array>);
644#define VT_WRAP_ARRAY(unused, elem) \
645 VtWrapArray< VtArray< VT_TYPE(elem) > >();
646#define VT_WRAP_COMPARISON(unused, elem) \
647 VtWrapComparisonFunctions< VtArray< VT_TYPE(elem) > >();
649PXR_NAMESPACE_CLOSE_SCOPE
Architecture-specific math function calls.
A simple iterator adapter for STL containers.
Miscellaneous Utilities for dealing with script.
#define TF_PY_REPR_PREFIX
A macro which expands to the proper repr prefix for a library.
TF_API void TfPyThrowValueError(const char *msg)
Raises a Python ValueError with the given error msg and throws a boost::python::error_already_set exc...
TF_API int64_t TfPyNormalizeIndex(int64_t index, uint64_t size, bool throwError=false)
Return a positive index in the range [0,size).
std::string TfPyRepr(T const &t)
Return repr(t).
Defines all the types "TYPED" for which Vt creates a VtTYPEDArray typedef.
Convenience class for accessing the Python Global Interpreter Lock.
Boost Python object wrapper.
TF_API PyObject * ptr() const
Underlying PyObject* access.
Represents an arbitrary dimensional rectangular container class.
Provides a container which may hold any type, and provides introspection and iteration over array typ...
bool IsEmpty() const
Returns true iff this value is empty.
VtValue & Swap(VtValue &rhs) noexcept
Swap this with rhs.
bool IsHolding() const
Return true if this value is holding an object of type T, false otherwise.
T const & UncheckedGet() const &
Returns a const reference to the held object if the held object is of type T.
size_t size() const
Return the total number of elements in this array.
pointer data()
Return a non-const pointer to this array's data.
bool empty() const
Return true if this array contains no elements, false otherwise.
iterator end()
Returns a non-const iterator to the end of the array.
iterator begin()
Return a non-const iterator to the start of the array.
std::string ArchGetDemangled()
Return demangled RTTI generated-type name.
std::string TfStringify(const T &v)
Convert an arbitrary type into a string.
TF_API std::string TfStringPrintf(const char *fmt,...)
Returns a string formed by a printf()-like specification.
This header serves to simply bring in the half float datatype and provide a hash_value function.
pxr_half::half GfHalf
A 16-bit floating point data type.
Pragmas for controlling compiler-specific behaviors.
Utilities for providing C++ <-> Python container support.
Definitions of basic string utilities in tf.
A metafunction which is equivalent to std::is_floating_point but allows for additional specialization...
A boost.python visitor that associates the Python class object created by the wrapping with the TfTyp...
A file containing basic constants and definitions.