Merge branch 'blender2.7'
[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 vertex buffer for vertex positions and vertex normals.\n"
131 "   Current a batch can have at most " STRINGIFY(GPU_BATCH_VBO_MAX_LEN) " vertex buffers.\n"
132 "\n"
133 "   :param buf: The vertex buffer that will be added to the batch.\n"
134 "   :type buf: :class:`gpu.types.GPUVertBuf`\n"
135 );
136 static PyObject *bpygpu_Batch_vertbuf_add(BPyGPUBatch *self, BPyGPUVertBuf *py_buf)
137 {
138   if (!BPyGPUVertBuf_Check(py_buf)) {
139     PyErr_Format(PyExc_TypeError, "Expected a GPUVertBuf, got %s", Py_TYPE(py_buf)->tp_name);
140     return NULL;
141   }
142
143   if (self->batch->verts[0]->vertex_len != py_buf->buf->vertex_len) {
144     PyErr_Format(PyExc_TypeError,
145                  "Expected %d length, got %d",
146                  self->batch->verts[0]->vertex_len,
147                  py_buf->buf->vertex_len);
148     return NULL;
149   }
150
151   if (self->batch->verts[GPU_BATCH_VBO_MAX_LEN - 1] != NULL) {
152     PyErr_SetString(
153         PyExc_RuntimeError,
154         "Maximum number of vertex buffers exceeded: " STRINGIFY(GPU_BATCH_VBO_MAX_LEN));
155     return NULL;
156   }
157
158 #ifdef USE_GPU_PY_REFERENCES
159   /* Hold user */
160   PyList_Append(self->references, (PyObject *)py_buf);
161 #endif
162
163   GPU_batch_vertbuf_add(self->batch, py_buf->buf);
164   Py_RETURN_NONE;
165 }
166
167 PyDoc_STRVAR(
168     bpygpu_Batch_program_set_doc,
169     ".. method:: program_set(program)\n"
170     "\n"
171     "   Assign a shader to this batch that will be used for drawing when not overwritten later.\n"
172     "   Note: This method has to be called in the draw context that the batch will be drawn in.\n"
173     "   This function does not need to be called when you always set the shader when calling "
174     "`batch.draw`.\n"
175     "\n"
176     "   :param program: The program/shader the batch will use in future draw calls.\n"
177     "   :type program: :class:`gpu.types.GPUShader`\n");
178 static PyObject *bpygpu_Batch_program_set(BPyGPUBatch *self, BPyGPUShader *py_shader)
179 {
180   if (!BPyGPUShader_Check(py_shader)) {
181     PyErr_Format(PyExc_TypeError, "Expected a GPUShader, got %s", Py_TYPE(py_shader)->tp_name);
182     return NULL;
183   }
184
185   GPUShader *shader = py_shader->shader;
186   GPU_batch_program_set(
187       self->batch, GPU_shader_get_program(shader), GPU_shader_get_interface(shader));
188
189 #ifdef USE_GPU_PY_REFERENCES
190   /* Remove existing user (if any), hold new user. */
191   int i = PyList_GET_SIZE(self->references);
192   while (--i != -1) {
193     PyObject *py_shader_test = PyList_GET_ITEM(self->references, i);
194     if (BPyGPUShader_Check(py_shader_test)) {
195       PyList_SET_ITEM(self->references, i, (PyObject *)py_shader);
196       Py_INCREF(py_shader);
197       Py_DECREF(py_shader_test);
198       /* Only ever reference one shader. */
199       break;
200     }
201   }
202   if (i != -1) {
203     PyList_Append(self->references, (PyObject *)py_shader);
204   }
205 #endif
206
207   Py_RETURN_NONE;
208 }
209
210 PyDoc_STRVAR(bpygpu_Batch_draw_doc,
211              ".. method:: draw(program=None)\n"
212              "\n"
213              "   Run the drawing program with the parameters assigned to the batch.\n"
214              "\n"
215              "   :param program: Program that performs the drawing operations.\n"
216              "      If ``None`` is passed, the last program setted to this batch will run.\n"
217              "   :type program: :class:`gpu.types.GPUShader`\n");
218 static PyObject *bpygpu_Batch_draw(BPyGPUBatch *self, PyObject *args)
219 {
220   BPyGPUShader *py_program = NULL;
221
222   if (!PyArg_ParseTuple(args, "|O!:GPUBatch.draw", &BPyGPUShader_Type, &py_program)) {
223     return NULL;
224   }
225   else if (py_program == NULL) {
226     if (!bpygpu_batch_is_program_or_error(self)) {
227       return NULL;
228     }
229   }
230   else if (self->batch->program != GPU_shader_get_program(py_program->shader)) {
231     GPU_batch_program_set(self->batch,
232                           GPU_shader_get_program(py_program->shader),
233                           GPU_shader_get_interface(py_program->shader));
234   }
235
236   GPU_batch_draw(self->batch);
237   Py_RETURN_NONE;
238 }
239
240 static PyObject *bpygpu_Batch_program_use_begin(BPyGPUBatch *self)
241 {
242   if (!bpygpu_batch_is_program_or_error(self)) {
243     return NULL;
244   }
245   GPU_batch_program_use_begin(self->batch);
246   Py_RETURN_NONE;
247 }
248
249 static PyObject *bpygpu_Batch_program_use_end(BPyGPUBatch *self)
250 {
251   if (!bpygpu_batch_is_program_or_error(self)) {
252     return NULL;
253   }
254   GPU_batch_program_use_end(self->batch);
255   Py_RETURN_NONE;
256 }
257
258 static struct PyMethodDef bpygpu_Batch_methods[] = {
259     {"vertbuf_add", (PyCFunction)bpygpu_Batch_vertbuf_add, METH_O, bpygpu_Batch_vertbuf_add_doc},
260     {"program_set", (PyCFunction)bpygpu_Batch_program_set, METH_O, bpygpu_Batch_program_set_doc},
261     {"draw", (PyCFunction)bpygpu_Batch_draw, METH_VARARGS, bpygpu_Batch_draw_doc},
262     {"_program_use_begin", (PyCFunction)bpygpu_Batch_program_use_begin, METH_NOARGS, ""},
263     {"_program_use_end", (PyCFunction)bpygpu_Batch_program_use_end, METH_NOARGS, ""},
264     {NULL, NULL, 0, NULL},
265 };
266
267 #ifdef USE_GPU_PY_REFERENCES
268
269 static int bpygpu_Batch_traverse(BPyGPUBatch *self, visitproc visit, void *arg)
270 {
271   Py_VISIT(self->references);
272   return 0;
273 }
274
275 static int bpygpu_Batch_clear(BPyGPUBatch *self)
276 {
277   Py_CLEAR(self->references);
278   return 0;
279 }
280
281 #endif
282
283 static void bpygpu_Batch_dealloc(BPyGPUBatch *self)
284 {
285   GPU_batch_discard(self->batch);
286
287 #ifdef USE_GPU_PY_REFERENCES
288   if (self->references) {
289     PyObject_GC_UnTrack(self);
290     bpygpu_Batch_clear(self);
291     Py_XDECREF(self->references);
292   }
293 #endif
294
295   Py_TYPE(self)->tp_free(self);
296 }
297
298 PyDoc_STRVAR(
299     py_gpu_batch_doc,
300     ".. class:: GPUBatch(type, buf, elem=None)\n"
301     "\n"
302     "   Reusable container for drawable geometry.\n"
303     "\n"
304     "   :arg type: One of these primitive types: {\n"
305     "       `POINTS`,\n"
306     "       `LINES`,\n"
307     "       `TRIS`,\n"
308     "       `LINE_STRIP`,\n"
309     "       `LINE_LOOP`,\n"
310     "       `TRI_STRIP`,\n"
311     "       `TRI_FAN`,\n"
312     "       `LINES_ADJ`,\n"
313     "       `TRIS_ADJ`,\n"
314     "       `LINE_STRIP_ADJ` }\n"
315     "   :type type: `str`\n"
316     "   :arg buf: Vertex buffer containing all or some of the attributes required for drawing.\n"
317     "   :type buf: :class:`gpu.types.GPUVertBuf`\n"
318     "   :arg elem: An optional index buffer.\n"
319     "   :type elem: :class:`gpu.types.GPUIndexBuf`\n");
320 PyTypeObject BPyGPUBatch_Type = {
321     PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUBatch",
322     .tp_basicsize = sizeof(BPyGPUBatch),
323     .tp_dealloc = (destructor)bpygpu_Batch_dealloc,
324 #ifdef USE_GPU_PY_REFERENCES
325     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
326     .tp_doc = py_gpu_batch_doc,
327     .tp_traverse = (traverseproc)bpygpu_Batch_traverse,
328     .tp_clear = (inquiry)bpygpu_Batch_clear,
329 #else
330     .tp_flags = Py_TPFLAGS_DEFAULT,
331 #endif
332     .tp_methods = bpygpu_Batch_methods,
333     .tp_new = bpygpu_Batch_new,
334 };
335
336 /** \} */
337
338 /* -------------------------------------------------------------------- */
339 /** \name Public API
340  * \{ */
341
342 PyObject *BPyGPUBatch_CreatePyObject(GPUBatch *batch)
343 {
344   BPyGPUBatch *self;
345
346 #ifdef USE_GPU_PY_REFERENCES
347   self = (BPyGPUBatch *)_PyObject_GC_New(&BPyGPUBatch_Type);
348   self->references = NULL;
349 #else
350   self = PyObject_New(BPyGPUBatch, &BPyGPUBatch_Type);
351 #endif
352
353   self->batch = batch;
354
355   return (PyObject *)self;
356 }
357
358 /** \} */
359
360 #undef BPY_GPU_BATCH_CHECK_OBJ