#ifndef magnum_math_vector_h #define magnum_math_vector_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Vladimír Vondruš Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include #include #include #include "corrade/PybindExtras.h" #include "magnum/math.h" namespace magnum { template bool isTypeCompatible(const std::string&); template<> inline bool isTypeCompatible(const std::string& format) { return format == "f" || format == "d"; } template<> inline bool isTypeCompatible(const std::string& format) { return format == "f" || format == "d"; } template<> inline bool isTypeCompatible(const std::string& format) { return format == "i" || format == "l"; } template<> inline bool isTypeCompatible(const std::string& format) { return format == "I" || format == "L"; } template void initFromBuffer(T& out, const py::buffer_info& info) { for(std::size_t i = 0; i != T::Size; ++i) out[i] = static_cast(*reinterpret_cast(static_cast(info.ptr) + i*info.strides[0])); } /* Floating-point init */ template void initFromBuffer(T& out, const py::buffer_info& info, std::true_type, std::true_type) { if(info.format == "f") initFromBuffer(out, info); else if(info.format == "d") initFromBuffer(out, info); else CORRADE_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } /* Signed integeral init */ template void initFromBuffer(T& out, const py::buffer_info& info, std::false_type, std::true_type) { if(info.format == "i") initFromBuffer(out, info); else if(info.format == "l") initFromBuffer(out, info); else CORRADE_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } /* Unsigned integeral init */ template void initFromBuffer(T& out, const py::buffer_info& info, std::false_type, std::false_type) { if(info.format == "I") initFromBuffer(out, info); else if(info.format == "L") initFromBuffer(out, info); else CORRADE_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } /* Things that have to be defined for both VectorN and Color so they construct / return a proper type */ template void everyVector(py::class_& c) { /* Implicitly convertible from a buffer (which is a numpy array as well). Without this implicit conversion from numpy arrays sometimes doesn't work. */ py::implicitly_convertible(); c /* Constructors */ .def_static("zero_init", []() { return T{Math::ZeroInit}; }, "Construct a zero vector") .def(py::init(), "Default constructor") /* Buffer protocol. If not present, implicit conversion from numpy arrays of non-default types somehow doesn't work. On the other hand only the constructor is needed (and thus also no py::buffer_protocol() specified for the class), converting vectors to numpy arrays is doable using the simple iteration iterface. */ .def(py::init([](py::buffer buffer) { py::buffer_info info = buffer.request(); if(info.ndim != 1) throw py::buffer_error{Utility::formatString("expected 1 dimension but got {}", info.ndim)}; if(info.shape[0] != T::Size) throw py::buffer_error{Utility::formatString("expected {} elements but got {}", T::Size, info.shape[0])}; if(!isTypeCompatible(info.format)) throw py::buffer_error{Utility::formatString("unexpected format {} for a {} vector", info.format, py::format_descriptor::format())}; T out{Math::NoInit}; initFromBuffer(out, info, std::is_floating_point{}, std::is_signed{}); return out; }), "Construct from a buffer") /* Operators */ .def(-py::self, "Negated vector") .def(py::self += py::self, "Add and assign a vector") .def(py::self + py::self, "Add a vector") .def(py::self -= py::self, "Subtract and assign a vector") .def(py::self - py::self, "Subtract a vector") .def(py::self *= typename T::Type{}, "Multiply with a scalar and assign") .def(py::self * typename T::Type{}, "Multiply with a scalar") .def(py::self /= typename T::Type{}, "Divide with a scalar and assign") .def(py::self / typename T::Type{}, "Divide with a scalar") .def(py::self *= py::self, "Multiply a vector component-wise and assign") .def(py::self * py::self, "Multiply a vector component-wise") .def(py::self /= py::self, "Divide a vector component-wise and assign") .def(py::self / py::self, "Divide a vector component-wise") .def(typename T::Type{} * py::self, "Multiply a scalar with a vector") .def(typename T::Type{} / py::self, "Divide a vector with a scalar and invert"); } /* Things common for vectors of all sizes and types */ template void vector(py::module& m, py::class_& c) { /* Missing APIs: from(T*) Type construction from different types VectorNi * VectorN and variants (5) */ m .def("dot", [](const T& a, const T& b) { return Math::dot(a, b); }, "Dot product of two vectors"); c /* Constructors */ .def(py::init(), "Construct a vector with one value for all components") /* Comparison */ .def(py::self == py::self, "Equality comparison") .def(py::self != py::self, "Non-equality comparison") .def(py::self < py::self, "Component-wise less than comparison") .def(py::self > py::self, "Component-wise greater than comparison") .def(py::self <= py::self, "Component-wise less than or equal comparison") .def(py::self >= py::self, "Component-wise greater than or equal comparison") /* Set / get. Need to throw IndexError in order to allow iteration: https://docs.python.org/3/reference/datamodel.html#object.__getitem__ */ .def("__setitem__", [](T& self, std::size_t i, typename T::Type value) { if(i >= T::Size) throw pybind11::index_error{}; self[i] = value; }, "Set a value at given position") .def("__getitem__", [](const T& self, std::size_t i) { if(i >= T::Size) throw pybind11::index_error{}; return self[i]; }, "Value at given position") /* Member functions common for floating-point and integer types */ .def("is_zero", &T::isZero, "Whether the vector is zero") .def("dot", static_cast(&T::dot), "Dot product of the vector") .def("flipped", &T::flipped, "Flipped vector") .def("sum", &T::sum, "Sum of values in the vector") .def("product", &T::product, "Product of values in the vector") .def("min", &T::min, "Minimal value in the vector") .def("max", &T::max, "Maximal value in the vector") .def("minmax", &T::minmax, "Minimal and maximal value in the vector") .def("__repr__", repr, "Object representation"); /* Vector length */ char lenDocstring[] = "Vector size. Returns _."; lenDocstring[sizeof(lenDocstring) - 3] = '0' + T::Size; c.def_static("__len__", []() { return int(T::Size); }, lenDocstring); } template void vector2(py::class_>& c) { py::implicitly_convertible&, Math::Vector2>(); c /* Constructors */ .def(py::init(), "Constructor") .def(py::init([](const std::tuple& value) { return Math::Vector2{std::get<0>(value), std::get<1>(value)}; }), "Construct from a tuple") /* Static constructors */ .def_static("x_axis", &Math::Vector2::xAxis, "Vector in a direction of X axis (right)", py::arg("length") = T(1)) .def_static("y_axis", &Math::Vector2::yAxis, "Vector in a direction of Y axis (up)", py::arg("length") = T(1)) .def_static("x_scale", &Math::Vector2::xScale, "Scaling vector in a direction of X axis (width)", py::arg("scale")) .def_static("y_scale", &Math::Vector2::yScale, "Scaling vector in a direction of Y axis (height)", py::arg("scale")) /* Methods */ .def("perpendicular", &Math::Vector2::perpendicular, "Perpendicular vector") /* Properties */ .def_property("x", static_cast::*)() const>(&Math::Vector2::x), [](Math::Vector2& self, T value) { self.x() = value; }, "X component") .def_property("y", static_cast::*)() const>(&Math::Vector2::y), [](Math::Vector2& self, T value) { self.y() = value; }, "Y component"); } template void vector3(py::class_>& c) { py::implicitly_convertible&, Math::Vector3>(); c /* Constructors */ .def(py::init(), "Constructor") .def(py::init([](const std::tuple& value) { return Math::Vector3{std::get<0>(value), std::get<1>(value), std::get<2>(value)}; }), "Construct from a tuple") /* Static constructors */ .def_static("x_axis", &Math::Vector3::xAxis, "Vector in a direction of X axis (right)", py::arg("length") = T(1)) .def_static("y_axis", &Math::Vector3::yAxis, "Vector in a direction of Y axis (up)", py::arg("length") = T(1)) .def_static("z_axis", &Math::Vector3::zAxis, "Vector in a direction of Z axis (backward)", py::arg("length") = T(1)) .def_static("x_scale", &Math::Vector3::xScale, "Scaling vector in a direction of X axis (width)", py::arg("scale")) .def_static("y_scale", &Math::Vector3::yScale, "Scaling vector in a direction of Y axis (height)", py::arg("scale")) .def_static("z_scale", &Math::Vector3::zScale, "Scaling vector in a direction of Z axis (depth)", py::arg("scale")) /* Properties */ .def_property("x", static_cast::*)() const>(&Math::Vector3::x), [](Math::Vector3& self, T value) { self.x() = value; }, "X component") .def_property("y", static_cast::*)() const>(&Math::Vector3::y), [](Math::Vector3& self, T value) { self.y() = value; }, "Y component") .def_property("z", static_cast::*)() const>(&Math::Vector3::z), [](Math::Vector3& self, T value) { self.z() = value; }, "Z component") .def_property("r", static_cast::*)() const>(&Math::Vector3::r), [](Math::Vector3& self, T value) { self.r() = value; }, "R component") .def_property("g", static_cast::*)() const>(&Math::Vector3::g), [](Math::Vector3& self, T value) { self.g() = value; }, "G component") .def_property("b", static_cast::*)() const>(&Math::Vector3::b), [](Math::Vector3& self, T value) { self.b() = value; }, "B component") .def_property("xy", static_cast(Math::Vector3::*)() const>(&Math::Vector3::xy), [](Math::Vector3& self, const Math::Vector2& value) { self.xy() = value; }, "XY part of the vector"); } template void vector4(py::class_>& c) { py::implicitly_convertible&, Math::Vector4>(); c /* Constructors */ .def(py::init(), "Constructor") .def(py::init([](const std::tuple& value) { return Math::Vector4{std::get<0>(value), std::get<1>(value), std::get<2>(value), std::get<3>(value)}; }), "Construct from a tuple") /* Properties */ .def_property("x", static_cast::*)() const>(&Math::Vector4::x), [](Math::Vector4& self, T value) { self.x() = value; }, "X component") .def_property("y", static_cast::*)() const>(&Math::Vector4::y), [](Math::Vector4& self, T value) { self.y() = value; }, "Y component") .def_property("z", static_cast::*)() const>(&Math::Vector4::z), [](Math::Vector4& self, T value) { self.z() = value; }, "Z component") .def_property("w", static_cast::*)() const>(&Math::Vector4::w), [](Math::Vector4& self, T value) { self.w() = value; }, "W component") .def_property("r", static_cast::*)() const>(&Math::Vector4::r), [](Math::Vector4& self, T value) { self.r() = value; }, "R component") .def_property("g", static_cast::*)() const>(&Math::Vector4::g), [](Math::Vector4& self, T value) { self.g() = value; }, "G component") .def_property("b", static_cast::*)() const>(&Math::Vector4::b), [](Math::Vector4& self, T value) { self.b() = value; }, "B component") .def_property("a", static_cast::*)() const>(&Math::Vector4::a), [](Math::Vector4& self, T value) { self.a() = value; }, "A component") .def_property("xyz", static_cast(Math::Vector4::*)() const>(&Math::Vector4::xyz), [](Math::Vector4& self, const Math::Vector3& value) { self.xyz() = value; }, "XYZ part of the vector") .def_property("rgb", static_cast(Math::Vector4::*)() const>(&Math::Vector4::rgb), [](Math::Vector4& self, const Math::Vector3& value) { self.rgb() = value; }, "RGB part of the vector") .def_property("xy", static_cast(Math::Vector4::*)() const>(&Math::Vector4::xy), [](Math::Vector4& self, const Math::Vector2& value) { self.xy() = value; }, "XY part of the vector"); } template class Type, class T, class ...Args> void convertibleImplementation(py::class_, Args...>& c, std::false_type) { c.def(py::init>(), "Construct from different underlying type"); } template class Type, class T, class ...Args> void convertibleImplementation(py::class_, Args...>&, std::true_type) {} template class Type, class T, class ...Args> void convertible(py::class_, Args...>& c) { convertibleImplementation(c, std::is_same{}); convertibleImplementation(c, std::is_same{}); convertibleImplementation(c, std::is_same{}); convertibleImplementation(c, std::is_same{}); } template void color(py::class_& c) { c .def_static("zero_init", []() { return T{Math::ZeroInit}; }, "Construct a zero color") .def(py::init(), "Default constructor"); } template void color3(py::class_, Math::Vector3>& c) { py::implicitly_convertible&, Math::Color3>(); c /* Constructors */ .def(py::init(), "Constructor") .def(py::init(), "Construct with one value for all components") .def(py::init>(), "Construct from a vector") .def(py::init([](const std::tuple& value) { return Math::Color3{std::get<0>(value), std::get<1>(value), std::get<2>(value)}; }), "Construct from a tuple") .def_static("from_hsv", [](Degd hue, typename Math::Color3::FloatingPointType saturation, typename Math::Color3::FloatingPointType value) { return Math::Color3::fromHsv({Math::Deg(hue), saturation, value}); }, "Create RGB color from HSV representation", py::arg("hue"), py::arg("saturation"), py::arg("value")) /* Accessors */ .def("to_hsv", [](Math::Color3& self) { auto hsv = self.toHsv(); return std::make_tuple(Degd(hsv.hue), hsv.saturation, hsv.value); }, "Convert to HSV representation") .def("hue", [](Math::Color3& self) { return Degd(self.hue()); }, "Hue") .def("saturation", &Math::Color3::saturation, "Saturation") .def("value", &Math::Color3::value, "Value"); } template void color4(py::class_, Math::Vector4>& c) { py::implicitly_convertible&, Math::Color4>(); py::implicitly_convertible&, Math::Color4>(); py::implicitly_convertible&, Math::Color4>(); c /* Constructors */ .def(py::init(), "Constructor", py::arg("r"), py::arg("g"), py::arg("b"), py::arg("a") = Math::Implementation::fullChannel()) .def(py::init(), "Construct with one value for all components", py::arg("rgb"), py::arg("alpha") = Math::Implementation::fullChannel()) .def(py::init, T>(), "Construct from a vector", py::arg("rgb"), py::arg("alpha") = Math::Implementation::fullChannel()) .def(py::init>(), "Construct from a vector") .def(py::init([](const std::tuple& value) { return Math::Color4{std::get<0>(value), std::get<1>(value), std::get<2>(value)}; }), "Construct from a RGB tuple") .def(py::init([](const std::tuple& value) { return Math::Color4{std::get<0>(value), std::get<1>(value), std::get<2>(value), std::get<3>(value)}; }), "Construct from a RGBA tuple") .def_static("from_hsv", [](Degd hue, typename Math::Color4::FloatingPointType saturation, typename Math::Color4::FloatingPointType value, T alpha) { return Math::Color4::fromHsv({Math::Deg(hue), saturation, value}, alpha); }, "Create RGB color from HSV representation", py::arg("hue"), py::arg("saturation"), py::arg("value"), py::arg("alpha") = Math::Implementation::fullChannel()) /* Accessors */ .def("to_hsv", [](Math::Color4& self) { auto hsv = self.toHsv(); return std::make_tuple(Degd(hsv.hue), hsv.saturation, hsv.value); }, "Convert to HSV representation") .def("hue", [](Math::Color4& self) { return Degd(self.hue()); }, "Hue") .def("saturation", &Math::Color4::saturation, "Saturation") .def("value", &Math::Color4::value, "Value") /* Properties */ .def_property("xyz", static_cast(Math::Color4::*)() const>(&Math::Color4::xyz), [](Math::Color4& self, const Math::Color3& value) { self.xyz() = value; }, "XYZ part of the vector") .def_property("rgb", static_cast(Math::Color4::*)() const>(&Math::Color4::rgb), [](Math::Color4& self, const Math::Color3& value) { self.rgb() = value; }, "RGB part of the vector"); } } #endif