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