a9e65413767dfee2c69546365ee5aff72eac6e8c
[blender.git] / source / blender / python / gpu / gpu_py_batch.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  * Copyright 2015, Blender Foundation.
17  */
18
19 /** \file
20  * \ingroup bpygpu
21  *
22  * This file defines the offscreen functionalities of the 'gpu' module
23  * used for off-screen OpenGL rendering.
24  *
25  * - Use ``bpygpu_`` for local API.
26  * - Use ``BPyGPU`` for public API.
27  */
28
29 #include <Python.h>
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_utildefines.h"
34
35 #include "GPU_batch.h"
36
37 #include "../mathutils/mathutils.h"
38
39 #include "../generic/py_capi_utils.h"
40
41 #include "gpu_py_api.h"
42 #include "gpu_py_shader.h"
43 #include "gpu_py_vertex_buffer.h"
44 #include "gpu_py_element.h"
45 #include "gpu_py_batch.h" /* own include */
46
47 /* -------------------------------------------------------------------- */
48 /** \name Utility Functions
49  * \{ */
50
51 static bool bpygpu_batch_is_program_or_error(BPyGPUBatch *self)
52 {
53   if (!glIsProgram(self->batch->program)) {
54     PyErr_SetString(PyExc_RuntimeError, "batch does not have any program assigned to it");
55     return false;
56   }
57   return true;
58 }
59
60 /** \} */
61
62 /* -------------------------------------------------------------------- */
63 /** \name GPUBatch Type
64  * \{ */
65
66 static PyObject *bpygpu_Batch_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
67 {
68   BPYGPU_IS_INIT_OR_ERROR_OBJ;
69
70   const char *exc_str_missing_arg = "GPUBatch.__new__() missing required argument '%s' (pos %d)";
71
72   struct {
73     GPUPrimType type_id;
74     BPyGPUVertBuf *py_vertbuf;
75     BPyGPUIndexBuf *py_indexbuf;
76   } params = {GPU_PRIM_NONE, NULL, NULL};
77
78   static const char *_keywords[] = {"type", "buf", "elem", NULL};
79   static _PyArg_Parser _parser = {"|$O&O!O!:GPUBatch.__new__", _keywords, 0};
80   if (!_PyArg_ParseTupleAndKeywordsFast(args,
81                                         kwds,
82                                         &_parser,
83                                         bpygpu_ParsePrimType,
84                                         &params.type_id,
85                                         &BPyGPUVertBuf_Type,
86                                         &params.py_vertbuf,
87                                         &BPyGPUIndexBuf_Type,
88                                         &params.py_indexbuf)) {
89     return NULL;
90   }
91
92   if (params.type_id == GPU_PRIM_NONE) {
93     PyErr_Format(PyExc_TypeError, exc_str_missing_arg, _keywords[0], 1);
94     return NULL;
95   }
96
97   if (params.py_vertbuf == NULL) {
98     PyErr_Format(PyExc_TypeError, exc_str_missing_arg, _keywords[1], 2);
99     return NULL;
100   }
101
102   GPUBatch *batch = GPU_batch_create(params.type_id,
103                                      params.py_vertbuf->buf,
104                                      params.py_indexbuf ? params.py_indexbuf->elem : NULL);
105
106   BPyGPUBatch *ret = (BPyGPUBatch *)BPyGPUBatch_CreatePyObject(batch);
107
108 #ifdef USE_GPU_PY_REFERENCES
109   ret->references = PyList_New(params.py_indexbuf ? 2 : 1);
110   PyList_SET_ITEM(ret->references, 0, (PyObject *)params.py_vertbuf);
111   Py_INCREF(params.py_vertbuf);
112
113   if (params.py_indexbuf != NULL) {
114     PyList_SET_ITEM(ret->references, 1, (PyObject *)params.py_indexbuf);
115     Py_INCREF(params.py_indexbuf);
116   }
117
118   PyObject_GC_Track(ret);
119 #endif
120
121   return (PyObject *)ret;
122 }
123
124 PyDoc_STRVAR(bpygpu_Batch_vertbuf_add_doc,
125 ".. method:: vertbuf_add(buf)\n"
126 "\n"
127 "   Add another vertex buffer to the Batch.\n"
128 "   It is not possible to add more vertices to the batch using this method.\n"
129 "   Instead it can be used to add more attributes to the existing vertices.\n"
130 "   A good use case would be when you have a separate\n"
131 "   vertex buffer for vertex positions and vertex normals.\n"
132 "   Current a batch can have at most " STRINGIFY(GPU_BATCH_VBO_MAX_LEN) " vertex buffers.\n"
133 "\n"
134 "   :param buf: The vertex buffer that will be added to the batch.\n"
135 "   :type buf: :class:`gpu.types.GPUVertBuf`\n"
136 );
137 static PyObject *bpygpu_Batch_vertbuf_add(BPyGPUBatch *self, BPyGPUVertBuf *py_buf)
138 {
139   if (!BPyGPUVertBuf_Check(py_buf)) {
140     PyErr_Format(PyExc_TypeError, "Expected a GPUVertBuf, got %s", Py_TYPE(py_buf)->tp_name);
141     return NULL;
142   }
143
144   if (self->batch->verts[0]->vertex_len != py_buf->buf->vertex_len) {
145     PyErr_Format(PyExc_TypeError,
146                  "Expected %d length, got %d",
147                  self->batch->verts[0]->vertex_len,
148                  py_buf->buf->vertex_len);
149     return NULL;
150   }
151
152   if (self->batch->verts[GPU_BATCH_VBO_MAX_LEN - 1] != NULL) {
153     PyErr_SetString(
154         PyExc_RuntimeError,
155         "Maximum number of vertex buffers exceeded: " STRINGIFY(GPU_BATCH_VBO_MAX_LEN));
156     return NULL;
157   }
158
159 #ifdef USE_GPU_PY_REFERENCES
160   /* Hold user */
161   PyList_Append(self->references, (PyObject *)py_buf);
162 #endif
163
164   GPU_batch_vertbuf_add(self->batch, py_buf->buf);
165   Py_RETURN_NONE;
166 }
167
168 PyDoc_STRVAR(
169     bpygpu_Batch_program_set_doc,
170     ".. method:: program_set(program)\n"
171     "\n"
172     "   Assign a shader to this batch that will be used for drawing when not overwritten later.\n"
173     "   Note: This method has to be called in the draw context that the batch will be drawn in.\n"
174     "   This function does not need to be called when you always set the shader when calling "
175     "`batch.draw`.\n"
176     "\n"
177     "   :param program: The program/shader the batch will use in future draw calls.\n"
178     "   :type program: :class:`gpu.types.GPUShader`\n");
179 static PyObject *bpygpu_Batch_program_set(BPyGPUBatch *self, BPyGPUShader *py_shader)
180 {
181   if (!BPyGPUShader_Check(py_shader)) {
182     PyErr_Format(PyExc_TypeError, "Expected a GPUShader, got %s", Py_TYPE(py_shader)->tp_name);
183     return NULL;
184   }
185
186   GPUShader *shader = py_shader->shader;
187   GPU_batch_program_set(
188       self->batch, GPU_shader_get_program(shader), GPU_shader_get_interface(shader));
189
190 #ifdef USE_GPU_PY_REFERENCES
191   /* Remove existing user (if any), hold new user. */
192   int i = PyList_GET_SIZE(self->references);
193   while (--i != -1) {
194     PyObject *py_shader_test = PyList_GET_ITEM(self->references, i);
195     if (BPyGPUShader_Check(py_shader_test)) {
196       PyList_SET_ITEM(self->references, i, (PyObject *)py_shader);
197       Py_INCREF(py_shader);
198       Py_DECREF(py_shader_test);
199       /* Only ever reference one shader. */
200       break;
201     }
202   }
203   if (i != -1) {
204     PyList_Append(self->references, (PyObject *)py_shader);
205   }
206 #endif
207
208   Py_RETURN_NONE;
209 }
210
211 PyDoc_STRVAR(bpygpu_Batch_draw_doc,
212              ".. method:: draw(program=None)\n"
213              "\n"
214              "   Run the drawing program with the parameters assigned to the batch.\n"
215              "\n"
216              "   :param program: Program that performs the drawing operations.\n"
217              "      If ``None`` is passed, the last program setted to this batch will run.\n"
218              "   :type program: :class:`gpu.types.GPUShader`\n");
219 static PyObject *bpygpu_Batch_draw(BPyGPUBatch *self, PyObject *args)
220 {
221   BPyGPUShader *py_program = NULL;
222
223   if (!PyArg_ParseTuple(args, "|O!:GPUBatch.draw", &BPyGPUShader_Type, &py_program)) {
224     return NULL;
225   }
226   else if (py_program == NULL) {
227     if (!bpygpu_batch_is_program_or_error(self)) {
228       return NULL;
229     }
230   }
231   else if (self->batch->program != GPU_shader_get_program(py_program->shader)) {
232     GPU_batch_program_set(self->batch,
233                           GPU_shader_get_program(py_program->shader),
234                           GPU_shader_get_interface(py_program->shader));
235   }
236
237   GPU_batch_draw(self->batch);
238   Py_RETURN_NONE;
239 }
240
241 static PyObject *bpygpu_Batch_program_use_begin(BPyGPUBatch *self)
242 {
243   if (!bpygpu_batch_is_program_or_error(self)) {
244     return NULL;
245   }
246   GPU_batch_program_use_begin(self->batch);
247   Py_RETURN_NONE;
248 }
249
250 static PyObject *bpygpu_Batch_program_use_end(BPyGPUBatch *self)
251 {
252   if (!bpygpu_batch_is_program_or_error(self)) {
253     return NULL;
254   }
255   GPU_batch_program_use_end(self->batch);
256   Py_RETURN_NONE;
257 }
258
259 static struct PyMethodDef bpygpu_Batch_methods[] = {
260     {"vertbuf_add", (PyCFunction)bpygpu_Batch_vertbuf_add, METH_O, bpygpu_Batch_vertbuf_add_doc},
261     {"program_set", (PyCFunction)bpygpu_Batch_program_set, METH_O, bpygpu_Batch_program_set_doc},
262     {"draw", (PyCFunction)bpygpu_Batch_draw, METH_VARARGS, bpygpu_Batch_draw_doc},
263     {"_program_use_begin", (PyCFunction)bpygpu_Batch_program_use_begin, METH_NOARGS, ""},
264     {"_program_use_end", (PyCFunction)bpygpu_Batch_program_use_end, METH_NOARGS, ""},
265     {NULL, NULL, 0, NULL},
266 };
267
268 #ifdef USE_GPU_PY_REFERENCES
269
270 static int bpygpu_Batch_traverse(BPyGPUBatch *self, visitproc visit, void *arg)
271 {
272   Py_VISIT(self->references);
273   return 0;
274 }
275
276 static int bpygpu_Batch_clear(BPyGPUBatch *self)
277 {
278   Py_CLEAR(self->references);
279   return 0;
280 }
281
282 #endif
283
284 static void bpygpu_Batch_dealloc(BPyGPUBatch *self)
285 {
286   GPU_batch_discard(self->batch);
287
288 #ifdef USE_GPU_PY_REFERENCES
289   if (self->references) {
290     PyObject_GC_UnTrack(self);
291     bpygpu_Batch_clear(self);
292     Py_XDECREF(self->references);
293   }
294 #endif
295
296   Py_TYPE(self)->tp_free(self);
297 }
298
299 PyDoc_STRVAR(
300     py_gpu_batch_doc,
301     ".. class:: GPUBatch(type, buf, elem=None)\n"
302     "\n"
303     "   Reusable container for drawable geometry.\n"
304     "\n"
305     "   :arg type: One of these primitive types: {\n"
306     "       `POINTS`,\n"
307     "       `LINES`,\n"
308     "       `TRIS`,\n"
309     "       `LINE_STRIP`,\n"
310     "       `LINE_LOOP`,\n"
311     "       `TRI_STRIP`,\n"
312     "       `TRI_FAN`,\n"
313     "       `LINES_ADJ`,\n"
314     "       `TRIS_ADJ`,\n"
315     "       `LINE_STRIP_ADJ` }\n"
316     "   :type type: `str`\n"
317     "   :arg buf: Vertex buffer containing all or some of the attributes required for drawing.\n"
318     "   :type buf: :class:`gpu.types.GPUVertBuf`\n"
319     "   :arg elem: An optional index buffer.\n"
320     "   :type elem: :class:`gpu.types.GPUIndexBuf`\n");
321 PyTypeObject BPyGPUBatch_Type = {
322     PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUBatch",
323     .tp_basicsize = sizeof(BPyGPUBatch),
324     .tp_dealloc = (destructor)bpygpu_Batch_dealloc,
325 #ifdef USE_GPU_PY_REFERENCES
326     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
327     .tp_doc = py_gpu_batch_doc,
328     .tp_traverse = (traverseproc)bpygpu_Batch_traverse,
329     .tp_clear = (inquiry)bpygpu_Batch_clear,
330 #else
331     .tp_flags = Py_TPFLAGS_DEFAULT,
332 #endif
333     .tp_methods = bpygpu_Batch_methods,
334     .tp_new = bpygpu_Batch_new,
335 };
336
337 /** \} */
338
339 /* -------------------------------------------------------------------- */
340 /** \name Public API
341  * \{ */
342
343 PyObject *BPyGPUBatch_CreatePyObject(GPUBatch *batch)
344 {
345   BPyGPUBatch *self;
346
347 #ifdef USE_GPU_PY_REFERENCES
348   self = (BPyGPUBatch *)_PyObject_GC_New(&BPyGPUBatch_Type);
349   self->references = NULL;
350 #else
351   self = PyObject_New(BPyGPUBatch, &BPyGPUBatch_Type);
352 #endif
353
354   self->batch = batch;
355
356   return (PyObject *)self;
357 }
358
359 /** \} */
360
361 #undef BPY_GPU_BATCH_CHECK_OBJ