OSDN Git Service

fix brushlib Python exception handling
[mypaint-anime/master.git] / lib / python_brush.hpp
1 /* brushlib - The MyPaint Brush Library
2  * Copyright (C) 2011 Martin Renold <martinxyz@gmx.ch>
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 class PythonBrush : public Brush {
18
19 public:
20   // get state as numpy array
21   PyObject * python_get_state ()
22   {
23     npy_intp dims = {STATE_COUNT};
24     PyObject * data = PyArray_SimpleNew(1, &dims, NPY_FLOAT32);
25     npy_float32 * data_p = (npy_float32*)PyArray_DATA(data);
26     for (int i=0; i<STATE_COUNT; i++) {
27       data_p[i] = get_state(i);
28     }
29     return data;
30   }
31
32   // set state from numpy array
33   void python_set_state (PyObject * data)
34   {
35     assert(PyArray_NDIM(data) == 1);
36     assert(PyArray_DIM(data, 0) == STATE_COUNT);
37     assert(PyArray_ISCARRAY(data));
38     npy_float32 * data_p = (npy_float32*)PyArray_DATA(data);
39     for (int i=0; i<STATE_COUNT; i++) {
40       set_state(i, data_p[i]);
41     }
42   }
43
44   // same as stroke_to() but with exception handling, should an
45   // exception happen in the surface code (eg. out-of-memory)
46   PyObject* python_stroke_to (Surface * surface, float x, float y, float pressure, float xtilt, float ytilt, double dtime)
47   {
48     bool res = stroke_to (surface, x, y, pressure, xtilt, ytilt, dtime);
49     if (PyErr_Occurred()) {
50       return NULL;
51     } else if (res) {
52       Py_RETURN_TRUE;
53     } else {
54       Py_RETURN_FALSE;
55     }
56   }
57
58 };