PythonTypeConversions.hh 23.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/*===========================================================================*\
*                                                                            *
*                              OpenFlipper                                   *
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
*                                                                            *
\*===========================================================================*/

#include <pybind11/include/pybind11/pybind11.h>
#include <pybind11/include/pybind11/numpy.h>
44
#include <OpenFlipper/common/UpdateType.hh>
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include <QString>

namespace py = pybind11;

namespace pybind11 { namespace detail {
    template <> struct type_caster<QString> {
    public:
        /**
         * This macro establishes the name 'str' in
         * function signatures and declares a local variable
         * 'value' of type QVariant
         */
        PYBIND11_TYPE_CASTER(QString, _("str"));

        /**
60
         * Conversion part 1 (Python->C++): convert a PyObject into a QString
61 62 63 64
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
        bool load(handle src, bool ) {
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
            /* Extract PyObject from handle */
            PyObject *source = src.ptr();

            if (!PyUnicode_Check(source))
              return false;

            Py_ssize_t size;
            const char *ptr = PyUnicode_AsUTF8AndSize(source, &size);

            if (!ptr) {
                return NULL;
            }

            /* Now try to convert into a C++ int */
            value = QString::fromUtf8(ptr, size);

            /* Ensure return code was OK (to avoid out-of-range errors etc) */
            return ( !PyErr_Occurred() );
        }

        /**
87
         * Conversion part 2 (C++ -> Python): convert an QString instance into
88 89 90 91 92 93 94 95 96 97 98
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
        static handle cast(QString src, return_value_policy /* policy */, handle /* parent */) {
            return (PyUnicode_FromString( src.toUtf8().data()) );
        }
    };
}} // namespace pybind11::detail

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/** \page python_scripting_vector_type Vector data type used for python scripting
 *
 *   The matrix type Vector is mapped to python to handle Vector operations.
 *
 *   The integrated conversion can map the C++ Vector type to and from a tuple, a list or a numpy array.
 *   The preferred choice is the numpy array. Tuple and list have to contain 3 elements. A numpy array
 *   has to have a dimension of 1, with 3 elements.
 *
 *   Creating a matrix in python is the done like in the following example:
 *   \code
 *     import numpy as np
 *
 *     vector = np.array([1.0,0.0,0.0]);
 *   \endcode
 *
 *   The conversion from C++ to python will always create a numpy array on the python side.
 */
116 117 118 119 120 121 122 123 124 125 126
namespace pybind11 { namespace detail {
    template <> struct type_caster<Vector> {
    public:
        /**
         * This macro establishes the name 'str' in
         * function signatures and declares a local variable
         * 'value' of type QVariant
         */
        PYBIND11_TYPE_CASTER(Vector, _("Vector"));

        /**
127
         * Conversion part 1 (Python->C++): convert a PyObject into a Vector
128 129 130
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
131
        bool load(handle src, bool convert ) {
132 133 134 135

            /* Extract PyObject from handle */
             PyObject* source = src.ptr();

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
             if (  PyList_Check(source) ) {

               if ( PyList_Size(source) != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: List size should be 3!");
                 throw py::error_already_set();
                 return false;
               }

               /* Now try to convert into a C++ int */
               value = Vector(PyFloat_AsDouble(PyList_GetItem(source,0)),PyFloat_AsDouble(PyList_GetItem(source,1)),PyFloat_AsDouble(PyList_GetItem(source,2)));

             } else if ( PyTuple_Check(source) ) {
               if ( PyTuple_Size(source) != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Tuple size should be 3!");
                 throw py::error_already_set();
                 return false;
               }
153

154 155 156
               /* Now try to convert into a C++ int */
               value = Vector(PyFloat_AsDouble(PyTuple_GetItem(source,0)),PyFloat_AsDouble(PyTuple_GetItem(source,1)),PyFloat_AsDouble(PyTuple_GetItem(source,2)));

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
             } else if ( py::cast<py::array>(source) ) {

               py::array array = py::cast<py::array>(source);

               if (  array.size() != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array size should be 3!");
                 throw py::error_already_set();
                 return false;
               }

               if (!convert && !py::array_t<double>::check_(src)) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array, wrong dtype, conversion disabled");
                 return false;
               }

               auto buf = py::array_t<double, py::array::c_style | py::array::forcecast>::ensure(src);

               if (!buf) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array, conversion failed.");
                 return false;
               }
               if (buf.ndim() != 1 || buf.size() != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array dimension or size error. Dimension should be one, size 3!");
                 return false;
               }

               value = Vector(buf.data());
               return true;

186
             } else {
187
               PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Not a list or a tuple or a numpy array.");
188 189 190 191
               throw py::error_already_set();
               return false;
             }

192 193
             /* Ensure return code was OK (to avoid out-of-range errors etc) */
             return ( !PyErr_Occurred() );
194 195 196
        }

        /**
197
         * Conversion part 2 (C++ -> Python): convert an Vector instance into
198 199 200 201 202
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
203 204 205 206
        static handle cast(Vector src, return_value_policy /* policy */, handle parent ) {
          // Create numpy array
          py::array a(3, src.data());
          return a.release();
207 208 209 210
        }
    };
}} // namespace pybind11::detail

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
/** \page python_scripting_matrix4x4_type Matrix4x4 data type used for python scripting
 *
 *   The matrix type Matrix4x4 is mapped to python to handle matrix operations.
 *
 *   The integrated conversion can map the C++ Matrix4x4 type to and from a tuple, a list or a numpy array.
 *   The preferred choice is the numpy array. Tuple and list have to contain 16 elements. A numpy array
 *   has to have a dimension of 2, with 4x4 elements. All data is assumed to be given column major. Therefore
 *   the first for elements define the first column and so on.
 *
 *   Creating a matrix in python is the done like in the following example:
 *   \code
 *     import numpy as np
 *
 *     matr = np.array( [[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,0.0,1.0,0.0],[0.0,0.0,0.0,1.0]])
 *   \endcode
 *
 *   The conversion from C++ to python will always create a numpy array on the python side.
 */
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
namespace pybind11 { namespace detail {
    template <> struct type_caster<Matrix4x4> {
    public:
        /**
         * This macro establishes the name 'str' in
         * function signatures and declares a local variable
         * 'value' of type Matrix4x4
         */
        PYBIND11_TYPE_CASTER(Matrix4x4, _("Matrix4x4"));

        /**
         * Conversion part 1 (Python->C++): convert a PyObject into a Matrix4x4
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
        bool load(handle src, bool convert ) {

            /* Extract PyObject from handle */
             PyObject* source = src.ptr();

             if (  PyList_Check(source) ) {

               if ( PyList_Size(source) != 16) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: List size should be 16!");
                 throw py::error_already_set();
                 return false;
               }

               double convert[16] =  { PyFloat_AsDouble(PyList_GetItem(source,0)),
                                       PyFloat_AsDouble(PyList_GetItem(source,1)),
                                       PyFloat_AsDouble(PyList_GetItem(source,2)),
                                       PyFloat_AsDouble(PyList_GetItem(source,3)),
                                       PyFloat_AsDouble(PyList_GetItem(source,4)),
                                       PyFloat_AsDouble(PyList_GetItem(source,5)),
                                       PyFloat_AsDouble(PyList_GetItem(source,6)),
                                       PyFloat_AsDouble(PyList_GetItem(source,7)),
                                       PyFloat_AsDouble(PyList_GetItem(source,8)),
                                       PyFloat_AsDouble(PyList_GetItem(source,9)),
                                       PyFloat_AsDouble(PyList_GetItem(source,0)),
                                       PyFloat_AsDouble(PyList_GetItem(source,11)),
                                       PyFloat_AsDouble(PyList_GetItem(source,12)),
                                       PyFloat_AsDouble(PyList_GetItem(source,13)),
271 272
                                       PyFloat_AsDouble(PyList_GetItem(source,14)),
                                       PyFloat_AsDouble(PyList_GetItem(source,15))};
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

               /* Now convert into a C++ Matrix4x4 */
               value = Matrix4x4(convert);

             } else if ( PyTuple_Check(source) ) {
               if ( PyTuple_Size(source) != 16) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Tuple size should be 3!");
                 throw py::error_already_set();
                 return false;
               }

               double convert[16] =  { PyFloat_AsDouble(PyTuple_GetItem(source,0)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,1)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,2)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,3)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,4)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,5)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,6)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,7)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,8)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,9)),
294
                                       PyFloat_AsDouble(PyTuple_GetItem(source,10)),
295 296 297
                                       PyFloat_AsDouble(PyTuple_GetItem(source,11)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,12)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,13)),
298 299
                                       PyFloat_AsDouble(PyTuple_GetItem(source,14)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,15))};
300 301 302 303 304 305 306 307 308 309 310 311 312

               /* Now convert into a C++ Matrix4x4 */
               value = Matrix4x4(convert);

             } else if ( py::cast<py::array>(source) ) {

               py::array array = py::cast<py::array>(source);

               if (  array.size() != 16) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array size should be 16!");
                 throw py::error_already_set();
                 return false;
               }
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
               if (!convert && !py::array_t<double>::check_(src)) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array, wrong dtype, conversion disabled");
                 return false;
               }

               auto buf = py::array_t<double, py::array::c_style | py::array::forcecast>::ensure(src);

               if (!buf) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array, conversion failed.");
                 return false;
               }

               // Check Dimension   : Matrix has 2 dimensions
               // Check buffer size : 4x4 -> 16 entries
               // Check shape       : 2 dimensions, each has size 4
               if (buf.ndim() != 2 || buf.size() != 16 || buf.shape()[0] !=4  || buf.shape()[1] !=4) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array dimension or size error. Dimension should be four, size 16, and shape 4x4!");
                 return false;
               }

               value = Matrix4x4(buf.data());
               return true;

             } else {
               PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Not a list or a tuple or a numpy array.");
               throw py::error_already_set();
               return false;
             }

             /* Ensure return code was OK (to avoid out-of-range errors etc) */
             return ( !PyErr_Occurred() );
        }

        /**
         * Conversion part 2 (C++ -> Python): convert an Matrix4x4 instance into
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
        static handle cast(Matrix4x4 src, return_value_policy /* policy */, handle parent ) {
          // Create numpy array
          py::array a({4,4}, src.data());
          return a.release();
358 359 360
        }
    };
}} // namespace pybind11::detail
Jan Möbius's avatar
Jan Möbius committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469


/** \page python_scripting_IDList_type IDList data type used for python scripting
 *
 *   The list type IdList is mapped to python.
 *
 *   The integrated conversion can map the C++ IdList type to and from a tuple, a list or a numpy array.
 *   The preferred choice is the numpy array.
 *
 *   Creating a list in python is the done like in the following example:
 *   \code
 *     import numpy as np
 *
 *     list = np.array( [3,16,18])
 *   \endcode
 *
 *   The conversion from C++ to python will always create a numpy array on the python side.
 */
namespace pybind11 { namespace detail {
    template <> struct type_caster<IdList> {
    public:
        /**
         * This macro establishes the name 'IdList' in
         * function signatures and declares a local variable
         * 'value' of type IdList
         */
        PYBIND11_TYPE_CASTER(IdList, _("IdList"));

        /**
         * Conversion part 1 (Python->C++): convert a PyObject into a IdList
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
        bool load(handle src, bool convert ) {

            /* Extract PyObject from handle */
             PyObject* source = src.ptr();

             if (  PyList_Check(source) ) {

               const auto size = PyList_Size(source);

               value.resize(size);

               for ( auto i = 0 ; i < size ; ++i ) {
                 value[i] = static_cast<int>(PyLong_AsLong(PyList_GET_ITEM(source,i)));
               }

             } else if ( PyTuple_Check(source) ) {

               const auto size = PyTuple_Size(source);

               value.resize(size);

               for ( auto i = 0 ; i < size ; ++i ) {
                 value[i] = static_cast<int>(PyLong_AsLong(PyTuple_GET_ITEM(source,i)));
               }

             } else if ( py::cast<py::array>(source) ) {

               py::array array = py::cast<py::array>(source);

               if (  array.ndim() != 1) {
                 PyErr_SetString(PyExc_RuntimeError, "IdList Conversion: Numpy Array dimension should be one!");
                 throw py::error_already_set();
                 return false;
               }

               auto buf = py::array_t<int, py::array::c_style | py::array::forcecast>::ensure(src);

               if (!buf) {
                 PyErr_SetString(PyExc_RuntimeError, "IdList Conversion: Numpy Array, conversion failed.");
                 return false;
               }

               std::cerr << "Buffer size : " << buf.size() << std::endl;

               value.resize(buf.size());
               for ( auto i = 0 ; i < buf.size() ; ++i ) {
                 value[i] = *buf.data(i) ;
               }

               return true;

             } else {
               PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Not a list or a tuple or a numpy array.");
               throw py::error_already_set();
               return false;
             }

             /* Ensure return code was OK (to avoid out-of-range errors etc) */
             return ( !PyErr_Occurred() );
        }

        /**
         * Conversion part 2 (C++ -> Python): convert an IdList instance into
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
        static handle cast(IdList src, return_value_policy /* policy */, handle parent ) {
          // Create numpy array
          py::array a(1, src.data());
          return a.release();
        }
    };
}} // namespace pybind11::detail

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
/** \page python_scripting_UpdateType_type UpdateType data type used for python scripting
 *
 *   The list type UpdateType is mapped to python.
 *
 *   The integrated conversion can map the C++ UpdateType type to and from a String.
 *   The string has to be a list separated by ';' if it should be a combination of update types.
 *
 *   \code
*      core.objectUpdated(5,"Selection;Geometry")
 *   \endcode
 *
 *   Update types implemented in Core are:
 *   - All
 *   - Visibility
 *   - Geometry
 *   - Topology
 *   - Selection
 *   - VertexSelection
 *   - EdgeSelection
 *   - HalfedgeSelection
 *   - FaceSelection
 *   - KnotSelection
 *   - Color
 *   - Texture
 *   - State
 *
 *   Other plugins might have implemented additional update types, which will be automatically mapped.
 */
namespace pybind11 { namespace detail {
    template <> struct type_caster<UpdateType> {
    public:
        /**
         * This macro establishes the name 'UpdateType' in
         * function signatures and declares a local variable
         * 'value' of type UpdateType
         */
        PYBIND11_TYPE_CASTER(UpdateType, _("UpdateType"));

        /**
         * Conversion part 1 (Python->C++): convert a PyObject into a UpdateType
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
        bool load(handle src, bool ) {

            /* Extract PyObject from handle */
            PyObject *source = src.ptr();

            if (!PyUnicode_Check(source))
              return false;

            Py_ssize_t size;
            const char *ptr = PyUnicode_AsUTF8AndSize(source, &size);

            if (!ptr) {
                return NULL;
            }

            QString updateString = QString::fromUtf8(ptr, size);

            if ( updateString.contains("UPDATE_ALL") ) {
              std::cerr << "Update_ALL" << std::endl;
              value = UPDATE_ALL;

              return true;
            }


            if ( updateString.contains("All") ) {
              std::cerr << "Update_ALL" << std::endl;
              value = UPDATE_ALL;

              return true;
            }

            UpdateType type;

            QStringList updateList = updateString.split(";");

            for ( auto i = 0 ; i < updateList.size() ; ++i ) {
              type |= updateType(updateList[i]);
              std::cerr << "Update " <<  updateList[i].toStdString() << std::endl;
            }

            value = type;

            /* Ensure return code was OK (to avoid out-of-range errors etc) */
            return ( !PyErr_Occurred() );
        }

        /**
         * Conversion part 2 (C++ -> Python): convert an UpdateType instance into
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
        static handle cast(UpdateType src, return_value_policy /* policy */, handle /* parent */) {
            return (PyUnicode_FromString( updateTypeName(src).toUtf8().data()) );
        }
    };
}} // namespace pybind11::detail