Cycles: Remove unneeded include statements
[blender-staging.git] / intern / cycles / blender / blender_python.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <Python.h>
18
19 #include "blender/CCL_api.h"
20
21 #include "blender/blender_sync.h"
22 #include "blender/blender_session.h"
23
24 #include "util/util_debug.h"
25 #include "util/util_foreach.h"
26 #include "util/util_logging.h"
27 #include "util/util_md5.h"
28 #include "util/util_opengl.h"
29 #include "util/util_path.h"
30 #include "util/util_string.h"
31 #include "util/util_types.h"
32
33 #ifdef WITH_OSL
34 #include "render/osl.h"
35
36 #include <OSL/oslquery.h>
37 #include <OSL/oslconfig.h>
38 #endif
39
40 CCL_NAMESPACE_BEGIN
41
42 namespace {
43
44 /* Flag describing whether debug flags were synchronized from scene. */
45 bool debug_flags_set = false;
46
47 void *pylong_as_voidptr_typesafe(PyObject *object)
48 {
49         if(object == Py_None)
50                 return NULL;
51         return PyLong_AsVoidPtr(object);
52 }
53
54 /* Synchronize debug flags from a given Blender scene.
55  * Return truth when device list needs invalidation.
56  */
57 bool debug_flags_sync_from_scene(BL::Scene b_scene)
58 {
59         DebugFlagsRef flags = DebugFlags();
60         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
61         /* Backup some settings for comparison. */
62         DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type;
63         DebugFlags::OpenCL::KernelType opencl_kernel_type = flags.opencl.kernel_type;
64         /* Synchronize shared flags. */
65         flags.viewport_static_bvh = get_enum(cscene, "debug_bvh_type");
66         /* Synchronize CPU flags. */
67         flags.cpu.avx2 = get_boolean(cscene, "debug_use_cpu_avx2");
68         flags.cpu.avx = get_boolean(cscene, "debug_use_cpu_avx");
69         flags.cpu.sse41 = get_boolean(cscene, "debug_use_cpu_sse41");
70         flags.cpu.sse3 = get_boolean(cscene, "debug_use_cpu_sse3");
71         flags.cpu.sse2 = get_boolean(cscene, "debug_use_cpu_sse2");
72         flags.cpu.qbvh = get_boolean(cscene, "debug_use_qbvh");
73         flags.cpu.split_kernel = get_boolean(cscene, "debug_use_cpu_split_kernel");
74         /* Synchronize CUDA flags. */
75         flags.cuda.adaptive_compile = get_boolean(cscene, "debug_use_cuda_adaptive_compile");
76         flags.cuda.split_kernel = get_boolean(cscene, "debug_use_cuda_split_kernel");
77         /* Synchronize OpenCL kernel type. */
78         switch(get_enum(cscene, "debug_opencl_kernel_type")) {
79                 case 0:
80                         flags.opencl.kernel_type = DebugFlags::OpenCL::KERNEL_DEFAULT;
81                         break;
82                 case 1:
83                         flags.opencl.kernel_type = DebugFlags::OpenCL::KERNEL_MEGA;
84                         break;
85                 case 2:
86                         flags.opencl.kernel_type = DebugFlags::OpenCL::KERNEL_SPLIT;
87                         break;
88         }
89         /* Synchronize OpenCL device type. */
90         switch(get_enum(cscene, "debug_opencl_device_type")) {
91                 case 0:
92                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;
93                         break;
94                 case 1:
95                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ALL;
96                         break;
97                 case 2:
98                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_DEFAULT;
99                         break;
100                 case 3:
101                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_CPU;
102                         break;
103                 case 4:
104                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_GPU;
105                         break;
106                 case 5:
107                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;
108                         break;
109         }
110         /* Synchronize other OpenCL flags. */
111         flags.opencl.debug = get_boolean(cscene, "debug_use_opencl_debug");
112         flags.opencl.mem_limit = ((size_t)get_int(cscene, "debug_opencl_mem_limit"))*1024*1024;
113         flags.opencl.single_program = get_boolean(cscene, "debug_opencl_kernel_single_program");
114         return flags.opencl.device_type != opencl_device_type ||
115                flags.opencl.kernel_type != opencl_kernel_type;
116 }
117
118 /* Reset debug flags to default values.
119  * Return truth when device list needs invalidation.
120  */
121 bool debug_flags_reset()
122 {
123         DebugFlagsRef flags = DebugFlags();
124         /* Backup some settings for comparison. */
125         DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type;
126         DebugFlags::OpenCL::KernelType opencl_kernel_type = flags.opencl.kernel_type;
127         flags.reset();
128         return flags.opencl.device_type != opencl_device_type ||
129                flags.opencl.kernel_type != opencl_kernel_type;
130 }
131
132 }  /* namespace */
133
134 void python_thread_state_save(void **python_thread_state)
135 {
136         *python_thread_state = (void*)PyEval_SaveThread();
137 }
138
139 void python_thread_state_restore(void **python_thread_state)
140 {
141         PyEval_RestoreThread((PyThreadState*)*python_thread_state);
142         *python_thread_state = NULL;
143 }
144
145 static const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
146 {
147         const char *result = _PyUnicode_AsString(py_str);
148         if(result) {
149                 /* 99% of the time this is enough but we better support non unicode
150                  * chars since blender doesnt limit this.
151                  */
152                 return result;
153         }
154         else {
155                 PyErr_Clear();
156                 if(PyBytes_Check(py_str)) {
157                         return PyBytes_AS_STRING(py_str);
158                 }
159                 else if((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
160                         return PyBytes_AS_STRING(*coerce);
161                 }
162                 else {
163                         /* Clear the error, so Cycles can be at leadt used without
164                          * GPU and OSL support,
165                          */
166                         PyErr_Clear();
167                         return "";
168                 }
169         }
170 }
171
172 static PyObject *init_func(PyObject * /*self*/, PyObject *args)
173 {
174         PyObject *path, *user_path;
175         int headless;
176
177         if(!PyArg_ParseTuple(args, "OOi", &path, &user_path, &headless)) {
178                 return NULL;
179         }
180
181         PyObject *path_coerce = NULL, *user_path_coerce = NULL;
182         path_init(PyC_UnicodeAsByte(path, &path_coerce),
183                   PyC_UnicodeAsByte(user_path, &user_path_coerce));
184         Py_XDECREF(path_coerce);
185         Py_XDECREF(user_path_coerce);
186
187         BlenderSession::headless = headless;
188
189         VLOG(2) << "Debug flags initialized to:\n"
190                 << DebugFlags();
191
192         Py_RETURN_NONE;
193 }
194
195
196 static PyObject *exit_func(PyObject * /*self*/, PyObject * /*args*/)
197 {
198         ShaderManager::free_memory();
199         TaskScheduler::free_memory();
200         Device::free_memory();
201         Py_RETURN_NONE;
202 }
203
204 static PyObject *create_func(PyObject * /*self*/, PyObject *args)
205 {
206         PyObject *pyengine, *pyuserpref, *pydata, *pyscene, *pyregion, *pyv3d, *pyrv3d;
207         int preview_osl;
208
209         if(!PyArg_ParseTuple(args, "OOOOOOOi", &pyengine, &pyuserpref, &pydata, &pyscene,
210                              &pyregion, &pyv3d, &pyrv3d, &preview_osl))
211         {
212                 return NULL;
213         }
214
215         /* RNA */
216         PointerRNA engineptr;
217         RNA_pointer_create(NULL, &RNA_RenderEngine, (void*)PyLong_AsVoidPtr(pyengine), &engineptr);
218         BL::RenderEngine engine(engineptr);
219
220         PointerRNA userprefptr;
221         RNA_pointer_create(NULL, &RNA_UserPreferences, (void*)PyLong_AsVoidPtr(pyuserpref), &userprefptr);
222         BL::UserPreferences userpref(userprefptr);
223
224         PointerRNA dataptr;
225         RNA_main_pointer_create((Main*)PyLong_AsVoidPtr(pydata), &dataptr);
226         BL::BlendData data(dataptr);
227
228         PointerRNA sceneptr;
229         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
230         BL::Scene scene(sceneptr);
231
232         PointerRNA regionptr;
233         RNA_pointer_create(NULL, &RNA_Region, pylong_as_voidptr_typesafe(pyregion), &regionptr);
234         BL::Region region(regionptr);
235
236         PointerRNA v3dptr;
237         RNA_pointer_create(NULL, &RNA_SpaceView3D, pylong_as_voidptr_typesafe(pyv3d), &v3dptr);
238         BL::SpaceView3D v3d(v3dptr);
239
240         PointerRNA rv3dptr;
241         RNA_pointer_create(NULL, &RNA_RegionView3D, pylong_as_voidptr_typesafe(pyrv3d), &rv3dptr);
242         BL::RegionView3D rv3d(rv3dptr);
243
244         /* create session */
245         BlenderSession *session;
246
247         if(rv3d) {
248                 /* interactive viewport session */
249                 int width = region.width();
250                 int height = region.height();
251
252                 session = new BlenderSession(engine, userpref, data, scene, v3d, rv3d, width, height);
253         }
254         else {
255                 /* override some settings for preview */
256                 if(engine.is_preview()) {
257                         PointerRNA cscene = RNA_pointer_get(&sceneptr, "cycles");
258
259                         RNA_boolean_set(&cscene, "shading_system", preview_osl);
260                         RNA_boolean_set(&cscene, "use_progressive_refine", true);
261                 }
262
263                 /* offline session or preview render */
264                 session = new BlenderSession(engine, userpref, data, scene);
265         }
266
267         python_thread_state_save(&session->python_thread_state);
268
269         session->create();
270
271         python_thread_state_restore(&session->python_thread_state);
272
273         return PyLong_FromVoidPtr(session);
274 }
275
276 static PyObject *free_func(PyObject * /*self*/, PyObject *value)
277 {
278         delete (BlenderSession*)PyLong_AsVoidPtr(value);
279
280         Py_RETURN_NONE;
281 }
282
283 static PyObject *render_func(PyObject * /*self*/, PyObject *value)
284 {
285         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value);
286
287         python_thread_state_save(&session->python_thread_state);
288
289         session->render();
290
291         python_thread_state_restore(&session->python_thread_state);
292
293         Py_RETURN_NONE;
294 }
295
296 /* pixel_array and result passed as pointers */
297 static PyObject *bake_func(PyObject * /*self*/, PyObject *args)
298 {
299         PyObject *pysession, *pyobject;
300         PyObject *pypixel_array, *pyresult;
301         const char *pass_type;
302         int num_pixels, depth, object_id, pass_filter;
303
304         if(!PyArg_ParseTuple(args, "OOsiiOiiO", &pysession, &pyobject, &pass_type, &pass_filter, &object_id, &pypixel_array, &num_pixels, &depth, &pyresult))
305                 return NULL;
306
307         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
308
309         PointerRNA objectptr;
310         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyobject), &objectptr);
311         BL::Object b_object(objectptr);
312
313         void *b_result = PyLong_AsVoidPtr(pyresult);
314
315         PointerRNA bakepixelptr;
316         RNA_pointer_create(NULL, &RNA_BakePixel, PyLong_AsVoidPtr(pypixel_array), &bakepixelptr);
317         BL::BakePixel b_bake_pixel(bakepixelptr);
318
319         python_thread_state_save(&session->python_thread_state);
320
321         session->bake(b_object, pass_type, pass_filter, object_id, b_bake_pixel, (size_t)num_pixels, depth, (float *)b_result);
322
323         python_thread_state_restore(&session->python_thread_state);
324
325         Py_RETURN_NONE;
326 }
327
328 static PyObject *draw_func(PyObject * /*self*/, PyObject *args)
329 {
330         PyObject *pysession, *pyv3d, *pyrv3d;
331
332         if(!PyArg_ParseTuple(args, "OOO", &pysession, &pyv3d, &pyrv3d))
333                 return NULL;
334         
335         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
336
337         if(PyLong_AsVoidPtr(pyrv3d)) {
338                 /* 3d view drawing */
339                 int viewport[4];
340                 glGetIntegerv(GL_VIEWPORT, viewport);
341
342                 session->draw(viewport[2], viewport[3]);
343         }
344
345         Py_RETURN_NONE;
346 }
347
348 static PyObject *reset_func(PyObject * /*self*/, PyObject *args)
349 {
350         PyObject *pysession, *pydata, *pyscene;
351
352         if(!PyArg_ParseTuple(args, "OOO", &pysession, &pydata, &pyscene))
353                 return NULL;
354
355         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
356
357         PointerRNA dataptr;
358         RNA_main_pointer_create((Main*)PyLong_AsVoidPtr(pydata), &dataptr);
359         BL::BlendData b_data(dataptr);
360
361         PointerRNA sceneptr;
362         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
363         BL::Scene b_scene(sceneptr);
364
365         python_thread_state_save(&session->python_thread_state);
366
367         session->reset_session(b_data, b_scene);
368
369         python_thread_state_restore(&session->python_thread_state);
370
371         Py_RETURN_NONE;
372 }
373
374 static PyObject *sync_func(PyObject * /*self*/, PyObject *value)
375 {
376         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value);
377
378         python_thread_state_save(&session->python_thread_state);
379
380         session->synchronize();
381
382         python_thread_state_restore(&session->python_thread_state);
383
384         Py_RETURN_NONE;
385 }
386
387 static PyObject *available_devices_func(PyObject * /*self*/, PyObject * /*args*/)
388 {
389         vector<DeviceInfo>& devices = Device::available_devices();
390         PyObject *ret = PyTuple_New(devices.size());
391
392         for(size_t i = 0; i < devices.size(); i++) {
393                 DeviceInfo& device = devices[i];
394                 string type_name = Device::string_from_type(device.type);
395                 PyObject *device_tuple = PyTuple_New(3);
396                 PyTuple_SET_ITEM(device_tuple, 0, PyUnicode_FromString(device.description.c_str()));
397                 PyTuple_SET_ITEM(device_tuple, 1, PyUnicode_FromString(type_name.c_str()));
398                 PyTuple_SET_ITEM(device_tuple, 2, PyUnicode_FromString(device.id.c_str()));
399                 PyTuple_SET_ITEM(ret, i, device_tuple);
400         }
401
402         return ret;
403 }
404
405 #ifdef WITH_OSL
406
407 static PyObject *osl_update_node_func(PyObject * /*self*/, PyObject *args)
408 {
409         PyObject *pynodegroup, *pynode;
410         const char *filepath = NULL;
411
412         if(!PyArg_ParseTuple(args, "OOs", &pynodegroup, &pynode, &filepath))
413                 return NULL;
414
415         /* RNA */
416         PointerRNA nodeptr;
417         RNA_pointer_create((ID*)PyLong_AsVoidPtr(pynodegroup), &RNA_ShaderNodeScript, (void*)PyLong_AsVoidPtr(pynode), &nodeptr);
418         BL::ShaderNodeScript b_node(nodeptr);
419
420         /* update bytecode hash */
421         string bytecode = b_node.bytecode();
422
423         if(!bytecode.empty()) {
424                 MD5Hash md5;
425                 md5.append((const uint8_t*)bytecode.c_str(), bytecode.size());
426                 b_node.bytecode_hash(md5.get_hex().c_str());
427         }
428         else
429                 b_node.bytecode_hash("");
430
431         /* query from file path */
432         OSL::OSLQuery query;
433
434         if(!OSLShaderManager::osl_query(query, filepath))
435                 Py_RETURN_FALSE;
436
437         /* add new sockets from parameters */
438         set<void*> used_sockets;
439
440         for(int i = 0; i < query.nparams(); i++) {
441                 const OSL::OSLQuery::Parameter *param = query.getparam(i);
442
443                 /* skip unsupported types */
444                 if(param->varlenarray || param->isstruct || param->type.arraylen > 1)
445                         continue;
446
447                 /* determine socket type */
448                 string socket_type;
449                 BL::NodeSocket::type_enum data_type = BL::NodeSocket::type_VALUE;
450                 float4 default_float4 = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
451                 float default_float = 0.0f;
452                 int default_int = 0;
453                 string default_string = "";
454
455                 if(param->isclosure) {
456                         socket_type = "NodeSocketShader";
457                         data_type = BL::NodeSocket::type_SHADER;
458                 }
459                 else if(param->type.vecsemantics == TypeDesc::COLOR) {
460                         socket_type = "NodeSocketColor";
461                         data_type = BL::NodeSocket::type_RGBA;
462
463                         if(param->validdefault) {
464                                 default_float4[0] = param->fdefault[0];
465                                 default_float4[1] = param->fdefault[1];
466                                 default_float4[2] = param->fdefault[2];
467                         }
468                 }
469                 else if(param->type.vecsemantics == TypeDesc::POINT ||
470                         param->type.vecsemantics == TypeDesc::VECTOR ||
471                         param->type.vecsemantics == TypeDesc::NORMAL)
472                 {
473                         socket_type = "NodeSocketVector";
474                         data_type = BL::NodeSocket::type_VECTOR;
475
476                         if(param->validdefault) {
477                                 default_float4[0] = param->fdefault[0];
478                                 default_float4[1] = param->fdefault[1];
479                                 default_float4[2] = param->fdefault[2];
480                         }
481                 }
482                 else if(param->type.aggregate == TypeDesc::SCALAR) {
483                         if(param->type.basetype == TypeDesc::INT) {
484                                 socket_type = "NodeSocketInt";
485                                 data_type = BL::NodeSocket::type_INT;
486                                 if(param->validdefault)
487                                         default_int = param->idefault[0];
488                         }
489                         else if(param->type.basetype == TypeDesc::FLOAT) {
490                                 socket_type = "NodeSocketFloat";
491                                 data_type = BL::NodeSocket::type_VALUE;
492                                 if(param->validdefault)
493                                         default_float = param->fdefault[0];
494                         }
495                         else if(param->type.basetype == TypeDesc::STRING) {
496                                 socket_type = "NodeSocketString";
497                                 data_type = BL::NodeSocket::type_STRING;
498                                 if(param->validdefault)
499                                         default_string = param->sdefault[0];
500                         }
501                         else
502                                 continue;
503                 }
504                 else
505                         continue;
506
507                 /* find socket socket */
508                 BL::NodeSocket b_sock(PointerRNA_NULL);
509                 if(param->isoutput) {
510                         b_sock = b_node.outputs[param->name.string()];
511                         /* remove if type no longer matches */
512                         if(b_sock && b_sock.bl_idname() != socket_type) {
513                                 b_node.outputs.remove(b_sock);
514                                 b_sock = BL::NodeSocket(PointerRNA_NULL);
515                         }
516                 }
517                 else {
518                         b_sock = b_node.inputs[param->name.string()];
519                         /* remove if type no longer matches */
520                         if(b_sock && b_sock.bl_idname() != socket_type) {
521                                 b_node.inputs.remove(b_sock);
522                                 b_sock = BL::NodeSocket(PointerRNA_NULL);
523                         }
524                 }
525
526                 if(!b_sock) {
527                         /* create new socket */
528                         if(param->isoutput)
529                                 b_sock = b_node.outputs.create(socket_type.c_str(), param->name.c_str(), param->name.c_str());
530                         else
531                                 b_sock = b_node.inputs.create(socket_type.c_str(), param->name.c_str(), param->name.c_str());
532
533                         /* set default value */
534                         if(data_type == BL::NodeSocket::type_VALUE) {
535                                 set_float(b_sock.ptr, "default_value", default_float);
536                         }
537                         else if(data_type == BL::NodeSocket::type_INT) {
538                                 set_int(b_sock.ptr, "default_value", default_int);
539                         }
540                         else if(data_type == BL::NodeSocket::type_RGBA) {
541                                 set_float4(b_sock.ptr, "default_value", default_float4);
542                         }
543                         else if(data_type == BL::NodeSocket::type_VECTOR) {
544                                 set_float3(b_sock.ptr, "default_value", float4_to_float3(default_float4));
545                         }
546                         else if(data_type == BL::NodeSocket::type_STRING) {
547                                 set_string(b_sock.ptr, "default_value", default_string);
548                         }
549                 }
550
551                 used_sockets.insert(b_sock.ptr.data);
552         }
553
554         /* remove unused parameters */
555         bool removed;
556
557         do {
558                 BL::Node::inputs_iterator b_input;
559                 BL::Node::outputs_iterator b_output;
560
561                 removed = false;
562
563                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
564                         if(used_sockets.find(b_input->ptr.data) == used_sockets.end()) {
565                                 b_node.inputs.remove(*b_input);
566                                 removed = true;
567                                 break;
568                         }
569                 }
570
571                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
572                         if(used_sockets.find(b_output->ptr.data) == used_sockets.end()) {
573                                 b_node.outputs.remove(*b_output);
574                                 removed = true;
575                                 break;
576                         }
577                 }
578         } while(removed);
579
580         Py_RETURN_TRUE;
581 }
582
583 static PyObject *osl_compile_func(PyObject * /*self*/, PyObject *args)
584 {
585         const char *inputfile = NULL, *outputfile = NULL;
586
587         if(!PyArg_ParseTuple(args, "ss", &inputfile, &outputfile))
588                 return NULL;
589         
590         /* return */
591         if(!OSLShaderManager::osl_compile(inputfile, outputfile))
592                 Py_RETURN_FALSE;
593
594         Py_RETURN_TRUE;
595 }
596 #endif
597
598 static PyObject *system_info_func(PyObject * /*self*/, PyObject * /*value*/)
599 {
600         string system_info = Device::device_capabilities();
601         return PyUnicode_FromString(system_info.c_str());
602 }
603
604 #ifdef WITH_OPENCL
605 static PyObject *opencl_disable_func(PyObject * /*self*/, PyObject * /*value*/)
606 {
607         VLOG(2) << "Disabling OpenCL platform.";
608         DebugFlags().opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;
609         Py_RETURN_NONE;
610 }
611 #endif
612
613 static PyObject *debug_flags_update_func(PyObject * /*self*/, PyObject *args)
614 {
615         PyObject *pyscene;
616         if(!PyArg_ParseTuple(args, "O", &pyscene)) {
617                 return NULL;
618         }
619
620         PointerRNA sceneptr;
621         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
622         BL::Scene b_scene(sceneptr);
623
624         if(debug_flags_sync_from_scene(b_scene)) {
625                 VLOG(2) << "Tagging device list for update.";
626                 Device::tag_update();
627         }
628
629         VLOG(2) << "Debug flags set to:\n"
630                 << DebugFlags();
631
632         debug_flags_set = true;
633
634         Py_RETURN_NONE;
635 }
636
637 static PyObject *debug_flags_reset_func(PyObject * /*self*/, PyObject * /*args*/)
638 {
639         if(debug_flags_reset()) {
640                 VLOG(2) << "Tagging device list for update.";
641                 Device::tag_update();
642         }
643         if(debug_flags_set) {
644                 VLOG(2) << "Debug flags reset to:\n"
645                         << DebugFlags();
646                 debug_flags_set = false;
647         }
648         Py_RETURN_NONE;
649 }
650
651 static PyObject *set_resumable_chunk_func(PyObject * /*self*/, PyObject *args)
652 {
653         int num_resumable_chunks, current_resumable_chunk;
654         if(!PyArg_ParseTuple(args, "ii",
655                              &num_resumable_chunks,
656                              &current_resumable_chunk)) {
657                 Py_RETURN_NONE;
658         }
659
660         if(num_resumable_chunks <= 0) {
661                 fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n");
662                 abort();
663                 Py_RETURN_NONE;
664         }
665         if(current_resumable_chunk < 1 ||
666            current_resumable_chunk > num_resumable_chunks)
667         {
668                 fprintf(stderr, "Cycles: Bad value for current resumable chunk number.\n");
669                 abort();
670                 Py_RETURN_NONE;
671         }
672
673         VLOG(1) << "Initialized resumable render: "
674                 << "num_resumable_chunks=" << num_resumable_chunks << ", "
675                 << "current_resumable_chunk=" << current_resumable_chunk;
676         BlenderSession::num_resumable_chunks = num_resumable_chunks;
677         BlenderSession::current_resumable_chunk = current_resumable_chunk;
678
679         printf("Cycles: Will render chunk %d of %d\n",
680                current_resumable_chunk,
681                num_resumable_chunks);
682
683         Py_RETURN_NONE;
684 }
685
686 static PyObject *set_resumable_chunk_range_func(PyObject * /*self*/, PyObject *args)
687 {
688         int num_chunks, start_chunk, end_chunk;
689         if(!PyArg_ParseTuple(args, "iii",
690                              &num_chunks,
691                              &start_chunk,
692                              &end_chunk)) {
693                 Py_RETURN_NONE;
694         }
695
696         if(num_chunks <= 0) {
697                 fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n");
698                 abort();
699                 Py_RETURN_NONE;
700         }
701         if(start_chunk < 1 || start_chunk > num_chunks) {
702                 fprintf(stderr, "Cycles: Bad value for start chunk number.\n");
703                 abort();
704                 Py_RETURN_NONE;
705         }
706         if(end_chunk < 1 || end_chunk > num_chunks) {
707                 fprintf(stderr, "Cycles: Bad value for start chunk number.\n");
708                 abort();
709                 Py_RETURN_NONE;
710         }
711         if(start_chunk > end_chunk) {
712                 fprintf(stderr, "Cycles: End chunk should be higher than start one.\n");
713                 abort();
714                 Py_RETURN_NONE;
715         }
716
717         VLOG(1) << "Initialized resumable render: "
718                 << "num_resumable_chunks=" << num_chunks << ", "
719                 << "start_resumable_chunk=" << start_chunk
720                 << "end_resumable_chunk=" << end_chunk;
721         BlenderSession::num_resumable_chunks = num_chunks;
722         BlenderSession::start_resumable_chunk = start_chunk;
723         BlenderSession::end_resumable_chunk = end_chunk;
724
725         printf("Cycles: Will render chunks %d to %d of %d\n",
726                start_chunk,
727                end_chunk,
728                num_chunks);
729
730         Py_RETURN_NONE;
731 }
732
733 static PyObject *get_device_types_func(PyObject * /*self*/, PyObject * /*args*/)
734 {
735         vector<DeviceInfo>& devices = Device::available_devices();
736         bool has_cuda = false, has_opencl = false;
737         for(int i = 0; i < devices.size(); i++) {
738                 has_cuda   |= (devices[i].type == DEVICE_CUDA);
739                 has_opencl |= (devices[i].type == DEVICE_OPENCL);
740         }
741         PyObject *list = PyTuple_New(2);
742         PyTuple_SET_ITEM(list, 0, PyBool_FromLong(has_cuda));
743         PyTuple_SET_ITEM(list, 1, PyBool_FromLong(has_opencl));
744         return list;
745 }
746
747 static PyMethodDef methods[] = {
748         {"init", init_func, METH_VARARGS, ""},
749         {"exit", exit_func, METH_VARARGS, ""},
750         {"create", create_func, METH_VARARGS, ""},
751         {"free", free_func, METH_O, ""},
752         {"render", render_func, METH_O, ""},
753         {"bake", bake_func, METH_VARARGS, ""},
754         {"draw", draw_func, METH_VARARGS, ""},
755         {"sync", sync_func, METH_O, ""},
756         {"reset", reset_func, METH_VARARGS, ""},
757 #ifdef WITH_OSL
758         {"osl_update_node", osl_update_node_func, METH_VARARGS, ""},
759         {"osl_compile", osl_compile_func, METH_VARARGS, ""},
760 #endif
761         {"available_devices", available_devices_func, METH_NOARGS, ""},
762         {"system_info", system_info_func, METH_NOARGS, ""},
763 #ifdef WITH_OPENCL
764         {"opencl_disable", opencl_disable_func, METH_NOARGS, ""},
765 #endif
766
767         /* Debugging routines */
768         {"debug_flags_update", debug_flags_update_func, METH_VARARGS, ""},
769         {"debug_flags_reset", debug_flags_reset_func, METH_NOARGS, ""},
770
771         /* Resumable render */
772         {"set_resumable_chunk", set_resumable_chunk_func, METH_VARARGS, ""},
773         {"set_resumable_chunk_range", set_resumable_chunk_range_func, METH_VARARGS, ""},
774
775         /* Compute Device selection */
776         {"get_device_types", get_device_types_func, METH_VARARGS, ""},
777
778         {NULL, NULL, 0, NULL},
779 };
780
781 static struct PyModuleDef module = {
782         PyModuleDef_HEAD_INIT,
783         "_cycles",
784         "Blender cycles render integration",
785         -1,
786         methods,
787         NULL, NULL, NULL, NULL
788 };
789
790 CCL_NAMESPACE_END
791
792 void *CCL_python_module_init()
793 {
794         PyObject *mod = PyModule_Create(&ccl::module);
795
796 #ifdef WITH_OSL
797         /* TODO(sergey): This gives us library we've been linking against.
798          *               In theory with dynamic OSL library it might not be
799          *               accurate, but there's nothing in OSL API which we
800          *               might use to get version in runtime.
801          */
802         int curversion = OSL_LIBRARY_VERSION_CODE;
803         PyModule_AddObject(mod, "with_osl", Py_True);
804         Py_INCREF(Py_True);
805         PyModule_AddObject(mod, "osl_version",
806                            Py_BuildValue("(iii)",
807                                           curversion / 10000, (curversion / 100) % 100, curversion % 100));
808         PyModule_AddObject(mod, "osl_version_string",
809                            PyUnicode_FromFormat("%2d, %2d, %2d",
810                                                 curversion / 10000, (curversion / 100) % 100, curversion % 100));
811 #else
812         PyModule_AddObject(mod, "with_osl", Py_False);
813         Py_INCREF(Py_False);
814         PyModule_AddStringConstant(mod, "osl_version", "unknown");
815         PyModule_AddStringConstant(mod, "osl_version_string", "unknown");
816 #endif
817
818 #ifdef WITH_CYCLES_DEBUG
819         PyModule_AddObject(mod, "with_cycles_debug", Py_True);
820         Py_INCREF(Py_True);
821 #else
822         PyModule_AddObject(mod, "with_cycles_debug", Py_False);
823         Py_INCREF(Py_False);
824 #endif
825
826 #ifdef WITH_NETWORK
827         PyModule_AddObject(mod, "with_network", Py_True);
828         Py_INCREF(Py_True);
829 #else /* WITH_NETWORK */
830         PyModule_AddObject(mod, "with_network", Py_False);
831         Py_INCREF(Py_False);
832 #endif /* WITH_NETWORK */
833
834         return (void*)mod;
835 }