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