Merge branch 'blender2.7'
[blender.git] / source / blender / python / gpu / gpu_py_vertex_buffer.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/python/gpu/gpu_py_vertex_buffer.c
22  *  \ingroup bpygpu
23  *
24  * - Use ``bpygpu_`` for local API.
25  * - Use ``BPyGPU`` for public API.
26  */
27
28 #include <Python.h>
29
30 #include "GPU_vertex_buffer.h"
31
32 #include "BLI_math.h"
33
34 #include "MEM_guardedalloc.h"
35
36 #include "../generic/py_capi_utils.h"
37 #include "../generic/python_utildefines.h"
38
39 #include "gpu_py_vertex_format.h"
40 #include "gpu_py_vertex_buffer.h" /* own include */
41
42 /* -------------------------------------------------------------------- */
43 /** \name Utility Functions
44  * \{ */
45
46 #define PY_AS_NATIVE_SWITCH(attr) \
47         switch (attr->comp_type) { \
48                 case GPU_COMP_I8:  { PY_AS_NATIVE(int8_t,   PyC_Long_AsI8); break; } \
49                 case GPU_COMP_U8:  { PY_AS_NATIVE(uint8_t,  PyC_Long_AsU8); break; } \
50                 case GPU_COMP_I16: { PY_AS_NATIVE(int16_t,  PyC_Long_AsI16); break; } \
51                 case GPU_COMP_U16: { PY_AS_NATIVE(uint16_t, PyC_Long_AsU16); break; } \
52                 case GPU_COMP_I32: { PY_AS_NATIVE(int32_t,  PyC_Long_AsI32); break; } \
53                 case GPU_COMP_U32: { PY_AS_NATIVE(uint32_t, PyC_Long_AsU32); break; } \
54                 case GPU_COMP_F32: { PY_AS_NATIVE(float, PyFloat_AsDouble); break; } \
55                 default: \
56                         BLI_assert(0); \
57         } ((void)0)
58
59 /* No error checking, callers must run PyErr_Occurred */
60 static void fill_format_elem(void *data_dst_void, PyObject *py_src, const GPUVertAttr *attr)
61 {
62 #define PY_AS_NATIVE(ty_dst, py_as_native) \
63 { \
64         ty_dst *data_dst = data_dst_void; \
65         *data_dst = py_as_native(py_src); \
66 } ((void)0)
67
68         PY_AS_NATIVE_SWITCH(attr);
69
70 #undef PY_AS_NATIVE
71 }
72
73 /* No error checking, callers must run PyErr_Occurred */
74 static void fill_format_sequence(void *data_dst_void, PyObject *py_seq_fast, const GPUVertAttr *attr)
75 {
76         const uint len = attr->comp_len;
77         PyObject **value_fast_items = PySequence_Fast_ITEMS(py_seq_fast);
78
79 /**
80  * Args are constants, so range checks will be optimized out if they're nop's.
81  */
82 #define PY_AS_NATIVE(ty_dst, py_as_native) \
83         ty_dst *data_dst = data_dst_void; \
84         for (uint i = 0; i < len; i++) { \
85                 data_dst[i] = py_as_native(value_fast_items[i]); \
86         } ((void)0)
87
88         PY_AS_NATIVE_SWITCH(attr);
89
90 #undef PY_AS_NATIVE
91 }
92
93 #undef PY_AS_NATIVE_SWITCH
94 #undef WARN_TYPE_LIMIT_PUSH
95 #undef WARN_TYPE_LIMIT_POP
96
97 static bool bpygpu_vertbuf_fill_impl(
98         GPUVertBuf *vbo,
99         uint data_id, PyObject *seq, const char *error_prefix)
100 {
101         const char *exc_str_size_mismatch = "Expected a %s of size %d, got %u";
102
103         bool ok = true;
104         const GPUVertAttr *attr = &vbo->format.attribs[data_id];
105
106         if (PyObject_CheckBuffer(seq)) {
107                 Py_buffer pybuffer;
108
109                 if (PyObject_GetBuffer(seq, &pybuffer, PyBUF_STRIDES | PyBUF_ND) == -1) {
110                         /* PyObject_GetBuffer raise a PyExc_BufferError */
111                         return false;
112                 }
113
114                 uint comp_len = pybuffer.ndim == 1 ? 1 : (uint)pybuffer.shape[1];
115
116                 if (pybuffer.shape[0] != vbo->vertex_len) {
117                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
118                                      "sequence", vbo->vertex_len, pybuffer.shape[0]);
119                         ok = false;
120                 }
121                 else if (comp_len != attr->comp_len) {
122                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
123                                     "component", attr->comp_len, comp_len);
124                         ok = false;
125                 }
126                 else {
127                         GPU_vertbuf_attr_fill_stride(vbo, data_id, pybuffer.strides[0], pybuffer.buf);
128                 }
129
130                 PyBuffer_Release(&pybuffer);
131         }
132         else {
133                 GPUVertBufRaw data_step;
134                 GPU_vertbuf_attr_get_raw_data(vbo, data_id, &data_step);
135
136                 PyObject *seq_fast = PySequence_Fast(seq, "Vertex buffer fill");
137                 if (seq_fast == NULL) {
138                         return false;
139                 }
140
141                 const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
142
143                 if (seq_len != vbo->vertex_len) {
144                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
145                                      "sequence", vbo->vertex_len, seq_len);
146                 }
147
148                 PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
149
150                 if (attr->comp_len == 1) {
151                         for (uint i = 0; i < seq_len; i++) {
152                                 uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
153                                 PyObject *item = seq_items[i];
154                                 fill_format_elem(data, item, attr);
155                         }
156                 }
157                 else {
158                         for (uint i = 0; i < seq_len; i++) {
159                                 uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
160                                 PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
161
162                                 if (seq_fast_item == NULL) {
163                                         ok = false;
164                                         goto finally;
165                                 }
166                                 if (PySequence_Fast_GET_SIZE(seq_fast_item) != attr->comp_len) {
167                                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
168                                                      "sequence", attr->comp_len, PySequence_Fast_GET_SIZE(seq_fast_item));
169                                         ok = false;
170                                         Py_DECREF(seq_fast_item);
171                                         goto finally;
172                                 }
173
174                                 /* May trigger error, check below */
175                                 fill_format_sequence(data, seq_fast_item, attr);
176                                 Py_DECREF(seq_fast_item);
177                         }
178                 }
179
180                 if (PyErr_Occurred()) {
181                         ok = false;
182                 }
183
184 finally:
185
186                 Py_DECREF(seq_fast);
187         }
188         return ok;
189 }
190
191 static int bpygpu_attr_fill(GPUVertBuf *buf, int id, PyObject *py_seq_data, const char *error_prefix)
192 {
193         if (id < 0 || id >= buf->format.attr_len) {
194                 PyErr_Format(PyExc_ValueError,
195                              "Format id %d out of range",
196                              id);
197                 return 0;
198         }
199
200         if (buf->data == NULL) {
201                 PyErr_SetString(PyExc_ValueError,
202                                 "Can't fill, static buffer already in use");
203                 return 0;
204         }
205
206         if (!bpygpu_vertbuf_fill_impl(buf, (uint)id, py_seq_data, error_prefix)) {
207                 return 0;
208         }
209
210         return 1;
211 }
212
213
214 /** \} */
215
216
217 /* -------------------------------------------------------------------- */
218 /** \name VertBuf Type
219  * \{ */
220
221 static PyObject *bpygpu_VertBuf_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
222 {
223         struct {
224                 PyObject *py_fmt;
225                 uint len;
226         } params;
227
228         static const char *_keywords[] = {"format", "len", NULL};
229         static _PyArg_Parser _parser = {"O!I:GPUVertBuf.__new__", _keywords, 0};
230         if (!_PyArg_ParseTupleAndKeywordsFast(
231                 args, kwds, &_parser,
232                 &BPyGPUVertFormat_Type, &params.py_fmt,
233                 &params.len))
234         {
235                 return NULL;
236         }
237
238         const GPUVertFormat *fmt = &((BPyGPUVertFormat *)params.py_fmt)->fmt;
239         GPUVertBuf *vbo = GPU_vertbuf_create_with_format(fmt);
240
241         GPU_vertbuf_data_alloc(vbo, params.len);
242
243         return BPyGPUVertBuf_CreatePyObject(vbo);
244 }
245
246 PyDoc_STRVAR(bpygpu_VertBuf_attr_fill_doc,
247 ".. method:: attr_fill(id, data)\n"
248 "\n"
249 "   Insert data into the buffer for a single attribute.\n"
250 "\n"
251 "   :param id: Either the name or the id of the attribute.\n"
252 "   :type id: int or str\n"
253 "   :param data: Sequence of data that should be stored in the buffer\n"
254 "   :type data: sequence of values or tuples\n"
255 );
256 static PyObject *bpygpu_VertBuf_attr_fill(BPyGPUVertBuf *self, PyObject *args, PyObject *kwds)
257 {
258         PyObject *data;
259         PyObject *identifier;
260
261         static const char *_keywords[] = {"id", "data", NULL};
262         static _PyArg_Parser _parser = {"OO:attr_fill", _keywords, 0};
263         if (!_PyArg_ParseTupleAndKeywordsFast(
264                 args, kwds, &_parser,
265                 &identifier, &data))
266         {
267                 return NULL;
268         }
269
270         int id;
271
272         if (PyLong_Check(identifier)) {
273                 id = PyLong_AsLong(identifier);
274         }
275         else if (PyUnicode_Check(identifier)) {
276                 const char *name = PyUnicode_AsUTF8(identifier);
277                 id = GPU_vertformat_attr_id_get(&self->buf->format, name);
278                 if (id == -1) {
279                         PyErr_SetString(PyExc_ValueError,
280                                         "Unknown attribute name");
281                         return NULL;
282                 }
283         }
284         else {
285                 PyErr_SetString(PyExc_TypeError,
286                                 "expected int or str type as identifier");
287                 return NULL;
288         }
289
290
291         if (!bpygpu_attr_fill(self->buf, id, data, "GPUVertBuf.attr_fill")) {
292                 return NULL;
293         }
294
295         Py_RETURN_NONE;
296 }
297
298
299 static struct PyMethodDef bpygpu_VertBuf_methods[] = {
300         {"attr_fill", (PyCFunction) bpygpu_VertBuf_attr_fill,
301          METH_VARARGS | METH_KEYWORDS, bpygpu_VertBuf_attr_fill_doc},
302         {NULL, NULL, 0, NULL}
303 };
304
305 static void bpygpu_VertBuf_dealloc(BPyGPUVertBuf *self)
306 {
307         GPU_vertbuf_discard(self->buf);
308         Py_TYPE(self)->tp_free(self);
309 }
310
311 PyDoc_STRVAR(py_gpu_vertex_buffer_doc,
312 ".. class:: GPUVertBuf(len, format)\n"
313 "\n"
314 "   Contains a VBO.\n"
315 "\n"
316 "   :param len: Amount of vertices that will fit into this buffer.\n"
317 "   :type type: `int`\n"
318 "   :param format: Vertex format.\n"
319 "   :type buf: :class:`gpu.types.GPUVertFormat`\n"
320 );
321 PyTypeObject BPyGPUVertBuf_Type = {
322         PyVarObject_HEAD_INIT(NULL, 0)
323         .tp_name = "GPUVertBuf",
324         .tp_basicsize = sizeof(BPyGPUVertBuf),
325         .tp_dealloc = (destructor)bpygpu_VertBuf_dealloc,
326         .tp_flags = Py_TPFLAGS_DEFAULT,
327         .tp_doc = py_gpu_vertex_buffer_doc,
328         .tp_methods = bpygpu_VertBuf_methods,
329         .tp_new = bpygpu_VertBuf_new,
330 };
331
332 /** \} */
333
334
335 /* -------------------------------------------------------------------- */
336 /** \name Public API
337  * \{ */
338
339 PyObject *BPyGPUVertBuf_CreatePyObject(GPUVertBuf *buf)
340 {
341         BPyGPUVertBuf *self;
342
343         self = PyObject_New(BPyGPUVertBuf, &BPyGPUVertBuf_Type);
344         self->buf = buf;
345
346         return (PyObject *)self;
347 }
348
349 /** \} */