Blender V5.3
gpu_py_vertex_buffer.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
11
12#include <Python.h>
13
14#include "GPU_vertex_buffer.hh"
15
17#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
18
19#include "gpu_py.hh"
20#include "gpu_py_vertex_buffer.hh" /* own include */
22
23namespace blender {
24
25/* -------------------------------------------------------------------- */
28
29#define PYGPU_AS_NATIVE_SWITCH(attr) \
30 switch (attr->type.comp_type()) { \
31 case GPU_COMP_I8: { \
32 PY_AS_NATIVE(int8_t, PyC_Long_AsI8); \
33 break; \
34 } \
35 case GPU_COMP_U8: { \
36 PY_AS_NATIVE(uint8_t, PyC_Long_AsU8); \
37 break; \
38 } \
39 case GPU_COMP_I16: { \
40 PY_AS_NATIVE(int16_t, PyC_Long_AsI16); \
41 break; \
42 } \
43 case GPU_COMP_U16: { \
44 PY_AS_NATIVE(uint16_t, PyC_Long_AsU16); \
45 break; \
46 } \
47 case GPU_COMP_I32: { \
48 PY_AS_NATIVE(int32_t, PyC_Long_AsI32); \
49 break; \
50 } \
51 case GPU_COMP_U32: { \
52 PY_AS_NATIVE(uint32_t, PyC_Long_AsU32); \
53 break; \
54 } \
55 case GPU_COMP_F32: { \
56 PY_AS_NATIVE(float, PyFloat_AsDouble); \
57 break; \
58 } \
59 default: \
60 BLI_assert_unreachable(); \
61 break; \
62 } \
63 ((void)0)
64
65/* No error checking, callers must run PyErr_Occurred */
66static void pygpu_fill_format_elem(void *data_dst_void, PyObject *py_src, const GPUVertAttr *attr)
67{
68#define PY_AS_NATIVE(ty_dst, py_as_native) \
69 { \
70 ty_dst *data_dst = static_cast<ty_dst *>(data_dst_void); \
71 *data_dst = py_as_native(py_src); \
72 } \
73 ((void)0)
74
76
77#undef PY_AS_NATIVE
78}
79
80/* No error checking, callers must run PyErr_Occurred */
81static void pygpu_fill_format_sequence(void *data_dst_void,
82 PyObject *py_seq_fast,
83 const GPUVertAttr *attr)
84{
85 const uint len = attr->type.comp_len();
86 PyObject **value_fast_items = PySequence_Fast_ITEMS(py_seq_fast);
87
91#define PY_AS_NATIVE(ty_dst, py_as_native) \
92 ty_dst *data_dst = static_cast<ty_dst *>(data_dst_void); \
93 for (uint i = 0; i < len; i++) { \
94 data_dst[i] = py_as_native(value_fast_items[i]); \
95 } \
96 ((void)0)
97
99
100#undef PY_AS_NATIVE
101}
102
103#undef PYGPU_AS_NATIVE_SWITCH
104#undef WARN_TYPE_LIMIT_PUSH
105#undef WARN_TYPE_LIMIT_POP
106
108 uint data_id,
109 PyObject *seq,
110 const char *error_prefix)
111{
112 const char *exc_str_size_mismatch = "Expected a %s of size %d, got %u";
113
114 bool ok = true;
115 const GPUVertAttr *attr = &GPU_vertbuf_get_format(vbo)->attrs[data_id];
116 uint vert_len = GPU_vertbuf_get_vertex_len(vbo);
117
118 if (PyObject_CheckBuffer(seq)) {
119 Py_buffer pybuffer;
120
121 if (PyObject_GetBuffer(seq, &pybuffer, PyBUF_STRIDES | PyBUF_ND) == -1) {
122 /* PyObject_GetBuffer raise a PyExc_BufferError */
123 return false;
124 }
125
126 const uint comp_len = pybuffer.ndim == 1 ? 1 : uint(pybuffer.shape[1]);
127
128 if (pybuffer.shape[0] != vert_len) {
129 PyErr_Format(
130 PyExc_ValueError, exc_str_size_mismatch, "sequence", vert_len, pybuffer.shape[0]);
131 ok = false;
132 }
133 else if (comp_len != attr->type.comp_len()) {
134 PyErr_Format(
135 PyExc_ValueError, exc_str_size_mismatch, "component", attr->type.comp_len(), comp_len);
136 ok = false;
137 }
138 else {
139 GPU_vertbuf_attr_fill_stride(vbo, data_id, pybuffer.strides[0], pybuffer.buf);
140 }
141
142 PyBuffer_Release(&pybuffer);
143 }
144 else {
145 GPUVertBufRaw data_step;
146 GPU_vertbuf_attr_get_raw_data(vbo, data_id, &data_step);
147
148 PyObject *seq_fast = PySequence_Fast(seq, "Vertex buffer fill");
149 if (seq_fast == nullptr) {
150 return false;
151 }
152
153 const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
154
155 if (seq_len != vert_len) {
156 PyErr_Format(PyExc_ValueError, exc_str_size_mismatch, "sequence", vert_len, seq_len);
157 }
158
159 PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
160
161 if (attr->type.comp_len() == 1) {
162 for (uint i = 0; i < seq_len; i++) {
163 uchar *data = static_cast<uchar *>(GPU_vertbuf_raw_step(&data_step));
164 PyObject *item = seq_items[i];
165 pygpu_fill_format_elem(data, item, attr);
166 }
167 }
168 else {
169 for (uint i = 0; i < seq_len; i++) {
170 uchar *data = static_cast<uchar *>(GPU_vertbuf_raw_step(&data_step));
171 PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
172
173 if (seq_fast_item == nullptr) {
174 ok = false;
175 goto finally;
176 }
177 if (PySequence_Fast_GET_SIZE(seq_fast_item) != attr->type.comp_len()) {
178 PyErr_Format(PyExc_ValueError,
179 exc_str_size_mismatch,
180 "sequence",
181 attr->type.comp_len(),
182 PySequence_Fast_GET_SIZE(seq_fast_item));
183 ok = false;
184 Py_DECREF(seq_fast_item);
185 goto finally;
186 }
187
188 /* May trigger error, check below */
189 pygpu_fill_format_sequence(data, seq_fast_item, attr);
190 Py_DECREF(seq_fast_item);
191 }
192 }
193
194 if (PyErr_Occurred()) {
195 ok = false;
196 }
197
198 finally:
199
200 Py_DECREF(seq_fast);
201 }
202 return ok;
203}
204
206 int id,
207 PyObject *py_seq_data,
208 const char *error_prefix)
209{
210 if (id < 0 || id >= GPU_vertbuf_get_format(buf)->attr_len) {
211 PyErr_Format(PyExc_ValueError, "Format id %d out of range", id);
212 return 0;
213 }
214
215 if (buf->data<char>().data() == nullptr) {
216 PyErr_SetString(PyExc_ValueError, "Can't fill, static buffer already in use");
217 return 0;
218 }
219
220 if (!pygpu_vertbuf_fill_impl(buf, uint(id), py_seq_data, error_prefix)) {
221 return 0;
222 }
223
224 return 1;
225}
226
228
229/* -------------------------------------------------------------------- */
232
233static PyObject *pygpu_vertbuf__tp_new(PyTypeObject * /*type*/, PyObject *args, PyObject *kwds)
234{
236
237 struct {
238 PyObject *py_fmt;
239 uint len;
240 } params;
241
242 static const char *_keywords[] = {"format", "len", nullptr};
243 static _PyArg_Parser _parser = {
244 "O!" /* `format` */
245 "I" /* `len` */
246 ":GPUVertBuf.__new__",
247 _keywords,
248 nullptr,
249 };
250 if (!_PyArg_ParseTupleAndKeywordsFast(
251 args, kwds, &_parser, &BPyGPUVertFormat_Type, &params.py_fmt, &params.len))
252 {
253 return nullptr;
254 }
255
256 const GPUVertFormat &fmt = (reinterpret_cast<BPyGPUVertFormat *>(params.py_fmt))->fmt;
257 gpu::VertBuf *vbo = GPU_vertbuf_create_with_format(fmt);
258
259 GPU_vertbuf_data_alloc(*vbo, params.len);
260
262}
263
265 /* Wrap. */
266 pygpu_vertbuf_attr_fill_doc,
267 ".. method:: attr_fill(id, data)\n"
268 "\n"
269 " Insert data into the buffer for a single attribute.\n"
270 "\n"
271 " :param id: Either the name or the id of the attribute.\n"
272 " :type id: int | str\n"
273 " :param data: Buffer or sequence of data that should be stored in the buffer\n"
274 " :type data: collections.abc.Buffer | "
275 "Sequence[float] | Sequence[int] | Sequence[Sequence[float]] | Sequence[Sequence[int]]\n");
276static PyObject *pygpu_vertbuf_attr_fill(BPyGPUVertBuf *self, PyObject *args, PyObject *kwds)
277{
278 PyObject *data;
279 PyObject *identifier;
280
281 static const char *_keywords[] = {"id", "data", nullptr};
282 static _PyArg_Parser _parser = {
283 "O" /* `id` */
284 "O" /* `data` */
285 ":attr_fill",
286 _keywords,
287 nullptr,
288 };
289 if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, &identifier, &data)) {
290 return nullptr;
291 }
292
293 int id;
294
295 if (PyLong_Check(identifier)) {
296 id = PyLong_AsLong(identifier);
297 }
298 else if (PyUnicode_Check(identifier)) {
299 const GPUVertFormat *format = GPU_vertbuf_get_format(self->buf);
300 const char *name = PyUnicode_AsUTF8(identifier);
301 id = GPU_vertformat_attr_id_get(format, name);
302 if (id == -1) {
303 PyErr_Format(PyExc_ValueError, "Unknown attribute '%s'", name);
304 return nullptr;
305 }
306 }
307 else {
308 PyErr_SetString(PyExc_TypeError, "expected int or str type as identifier");
309 return nullptr;
310 }
311
312 if (!pygpu_vertbuf_fill(self->buf, id, data, "GPUVertBuf.attr_fill")) {
313 return nullptr;
314 }
315
316 Py_RETURN_NONE;
317}
318
319#ifdef __GNUC__
320# ifdef __clang__
321# pragma clang diagnostic push
322# pragma clang diagnostic ignored "-Wcast-function-type"
323# else
324# pragma GCC diagnostic push
325# pragma GCC diagnostic ignored "-Wcast-function-type"
326# endif
327#endif
328
329static PyMethodDef pygpu_vertbuf__tp_methods[] = {
330 {"attr_fill",
331 reinterpret_cast<PyCFunction>(pygpu_vertbuf_attr_fill),
332 METH_VARARGS | METH_KEYWORDS,
333 pygpu_vertbuf_attr_fill_doc},
334 {nullptr, nullptr, 0, nullptr},
335};
336
337#ifdef __GNUC__
338# ifdef __clang__
339# pragma clang diagnostic pop
340# else
341# pragma GCC diagnostic pop
342# endif
343#endif
344
346{
348 Py_TYPE(self)->tp_free(self);
349}
350
352 /* Wrap. */
353 pygpu_vertbuf__tp_doc,
354 ".. class:: GPUVertBuf\n"
355 "\n"
356 " Contains a VBO.\n"
357 "\n"
358 " .. method:: __init__(format, len)\n"
359 "\n"
360 " :param format: Vertex format.\n"
361 " :type format: :class:`gpu.types.GPUVertFormat`\n"
362 " :param len: Amount of vertices that will fit into this buffer.\n"
363 " :type len: int\n");
364PyTypeObject BPyGPUVertBuf_Type = {
365 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
366 /*tp_name*/ "GPUVertBuf",
367 /*tp_basicsize*/ sizeof(BPyGPUVertBuf),
368 /*tp_itemsize*/ 0,
369 /*tp_dealloc*/ reinterpret_cast<destructor>(pygpu_vertbuf__tp_dealloc),
370 /*tp_vectorcall_offset*/ 0,
371 /*tp_getattr*/ nullptr,
372 /*tp_setattr*/ nullptr,
373 /*tp_as_async*/ nullptr,
374 /*tp_repr*/ nullptr,
375 /*tp_as_number*/ nullptr,
376 /*tp_as_sequence*/ nullptr,
377 /*tp_as_mapping*/ nullptr,
378 /*tp_hash*/ nullptr,
379 /*tp_call*/ nullptr,
380 /*tp_str*/ nullptr,
381 /*tp_getattro*/ nullptr,
382 /*tp_setattro*/ nullptr,
383 /*tp_as_buffer*/ nullptr,
384 /*tp_flags*/ Py_TPFLAGS_DEFAULT,
385 /*tp_doc*/ pygpu_vertbuf__tp_doc,
386 /*tp_traverse*/ nullptr,
387 /*tp_clear*/ nullptr,
388 /*tp_richcompare*/ nullptr,
389 /*tp_weaklistoffset*/ 0,
390 /*tp_iter*/ nullptr,
391 /*tp_iternext*/ nullptr,
392 /*tp_methods*/ pygpu_vertbuf__tp_methods,
393 /*tp_members*/ nullptr,
394 /*tp_getset*/ nullptr,
395 /*tp_base*/ nullptr,
396 /*tp_dict*/ nullptr,
397 /*tp_descr_get*/ nullptr,
398 /*tp_descr_set*/ nullptr,
399 /*tp_dictoffset*/ 0,
400 /*tp_init*/ nullptr,
401 /*tp_alloc*/ nullptr,
402 /*tp_new*/ pygpu_vertbuf__tp_new,
403 /*tp_free*/ nullptr,
404 /*tp_is_gc*/ nullptr,
405 /*tp_bases*/ nullptr,
406 /*tp_mro*/ nullptr,
407 /*tp_cache*/ nullptr,
408 /*tp_subclasses*/ nullptr,
409 /*tp_weaklist*/ nullptr,
410 /*tp_del*/ nullptr,
411 /*tp_version_tag*/ 0,
412 /*tp_finalize*/ nullptr,
413 /*tp_vectorcall*/ nullptr,
414};
415
417
418/* -------------------------------------------------------------------- */
421
423{
424 BPyGPUVertBuf *self;
425
426 self = PyObject_New(BPyGPUVertBuf, &BPyGPUVertBuf_Type);
427 self->buf = buf;
428
429 return reinterpret_cast<PyObject *>(self);
430}
431
433
434} // namespace blender
MutableSpan< T > data()
#define BPYGPU_IS_INIT_OR_ERROR_OBJ
Definition gpu_py.hh:45
#define PYGPU_AS_NATIVE_SWITCH(attr)
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
BMesh Iterators.
PyTypeObject BPyGPUVertFormat_Type
static PyObject * pygpu_vertbuf_attr_fill(BPyGPUVertBuf *self, PyObject *args, PyObject *kwds)
unsigned int uint
Definition BKE_text.h:55
static void pygpu_fill_format_sequence(void *data_dst_void, PyObject *py_seq_fast, const GPUVertAttr *attr)
PyTypeObject BPyGPUVertBuf_Type
int GPU_vertformat_attr_id_get(const GPUVertFormat *, StringRef name)
PyObject * BPyGPUVertBuf_CreatePyObject(gpu::VertBuf *buf)
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
static PyMethodDef pygpu_vertbuf__tp_methods[]
const GPUVertFormat * GPU_vertbuf_get_format(const gpu::VertBuf *verts)
static void pygpu_fill_format_elem(void *data_dst_void, PyObject *py_src, const GPUVertAttr *attr)
GPU_INLINE void * GPU_vertbuf_raw_step(GPUVertBufRaw *a)
void GPU_vertbuf_attr_fill_stride(gpu::VertBuf *, uint a_idx, uint stride, const void *data)
static PyObject * pygpu_vertbuf__tp_new(PyTypeObject *, PyObject *args, PyObject *kwds)
unsigned char uchar
Definition BKE_text.h:58
BMesh const char void * data
static bool pygpu_vertbuf_fill_impl(gpu::VertBuf *vbo, uint data_id, PyObject *seq, const char *error_prefix)
void GPU_vertbuf_attr_get_raw_data(gpu::VertBuf *, uint a_idx, GPUVertBufRaw *access)
static int pygpu_vertbuf_fill(gpu::VertBuf *buf, int id, PyObject *py_seq_data, const char *error_prefix)
void GPU_vertbuf_data_alloc(gpu::VertBuf &verts, uint v_len)
uint GPU_vertbuf_get_vertex_len(const gpu::VertBuf *verts)
void GPU_vertbuf_discard(gpu::VertBuf *)
static void pygpu_vertbuf__tp_dealloc(BPyGPUVertBuf *self)
header-only compatibility defines.
PyObject_HEAD gpu::VertBuf * buf
struct blender::GPUVertAttr::Type type
GPUVertAttr attrs[GPU_VERT_ATTR_MAX_LEN]