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