Merge branch 'master' into blender2.8
[blender.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.bvh_layout = (BVHLayout)get_enum(cscene, "debug_bvh_layout");
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, *pygraph, *pyscene, *pyregion, *pyv3d, *pyrv3d;
207         int preview_osl;
208
209         if(!PyArg_ParseTuple(args, "OOOOOOOOi", &pyengine, &pyuserpref, &pydata, &pygraph, &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 graphptr;
229         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pygraph), &graphptr);
230         BL::Depsgraph graph(graphptr);
231
232         PointerRNA sceneptr;
233         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
234         BL::Scene scene(sceneptr);
235
236         PointerRNA regionptr;
237         RNA_pointer_create(NULL, &RNA_Region, pylong_as_voidptr_typesafe(pyregion), &regionptr);
238         BL::Region region(regionptr);
239
240         PointerRNA v3dptr;
241         RNA_pointer_create(NULL, &RNA_SpaceView3D, pylong_as_voidptr_typesafe(pyv3d), &v3dptr);
242         BL::SpaceView3D v3d(v3dptr);
243
244         PointerRNA rv3dptr;
245         RNA_pointer_create(NULL, &RNA_RegionView3D, pylong_as_voidptr_typesafe(pyrv3d), &rv3dptr);
246         BL::RegionView3D rv3d(rv3dptr);
247
248         /* create session */
249         BlenderSession *session;
250
251         if(rv3d) {
252                 /* interactive viewport session */
253                 int width = region.width();
254                 int height = region.height();
255
256                 session = new BlenderSession(engine, userpref, data, graph, scene, v3d, rv3d, width, height);
257         }
258         else {
259                 /* override some settings for preview */
260                 if(engine.is_preview()) {
261                         PointerRNA cscene = RNA_pointer_get(&sceneptr, "cycles");
262
263                         RNA_boolean_set(&cscene, "shading_system", preview_osl);
264                         RNA_boolean_set(&cscene, "use_progressive_refine", true);
265                 }
266
267                 /* offline session or preview render */
268                 session = new BlenderSession(engine, userpref, data, graph, scene);
269         }
270
271         python_thread_state_save(&session->python_thread_state);
272
273         session->create();
274
275         python_thread_state_restore(&session->python_thread_state);
276
277         return PyLong_FromVoidPtr(session);
278 }
279
280 static PyObject *free_func(PyObject * /*self*/, PyObject *value)
281 {
282         delete (BlenderSession*)PyLong_AsVoidPtr(value);
283
284         Py_RETURN_NONE;
285 }
286
287 static PyObject *render_func(PyObject * /*self*/, PyObject *value)
288 {
289         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value);
290
291         python_thread_state_save(&session->python_thread_state);
292
293         session->render();
294
295         python_thread_state_restore(&session->python_thread_state);
296
297         Py_RETURN_NONE;
298 }
299
300 /* pixel_array and result passed as pointers */
301 static PyObject *bake_func(PyObject * /*self*/, PyObject *args)
302 {
303         PyObject *pysession, *pyobject;
304         PyObject *pypixel_array, *pyresult;
305         const char *pass_type;
306         int num_pixels, depth, object_id, pass_filter;
307
308         if(!PyArg_ParseTuple(args, "OOsiiOiiO", &pysession, &pyobject, &pass_type, &pass_filter, &object_id, &pypixel_array, &num_pixels, &depth, &pyresult))
309                 return NULL;
310
311         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
312
313         PointerRNA objectptr;
314         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyobject), &objectptr);
315         BL::Object b_object(objectptr);
316
317         void *b_result = PyLong_AsVoidPtr(pyresult);
318
319         PointerRNA bakepixelptr;
320         RNA_pointer_create(NULL, &RNA_BakePixel, PyLong_AsVoidPtr(pypixel_array), &bakepixelptr);
321         BL::BakePixel b_bake_pixel(bakepixelptr);
322
323         python_thread_state_save(&session->python_thread_state);
324
325         session->bake(b_object, pass_type, pass_filter, object_id, b_bake_pixel, (size_t)num_pixels, depth, (float *)b_result);
326
327         python_thread_state_restore(&session->python_thread_state);
328
329         Py_RETURN_NONE;
330 }
331
332 static PyObject *draw_func(PyObject * /*self*/, PyObject *args)
333 {
334         PyObject *pysession, *pygraph, *pyv3d, *pyrv3d;
335
336         if(!PyArg_ParseTuple(args, "OOOO", &pysession, &pygraph, &pyv3d, &pyrv3d))
337                 return NULL;
338         
339         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
340
341         if(PyLong_AsVoidPtr(pyrv3d)) {
342                 /* 3d view drawing */
343                 int viewport[4];
344                 glGetIntegerv(GL_VIEWPORT, viewport);
345
346                 session->draw(viewport[2], viewport[3]);
347         }
348
349         Py_RETURN_NONE;
350 }
351
352 static PyObject *reset_func(PyObject * /*self*/, PyObject *args)
353 {
354         PyObject *pysession, *pydata, *pyscene;
355
356         if(!PyArg_ParseTuple(args, "OOO", &pysession, &pydata, &pyscene))
357                 return NULL;
358
359         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
360
361         PointerRNA dataptr;
362         RNA_main_pointer_create((Main*)PyLong_AsVoidPtr(pydata), &dataptr);
363         BL::BlendData b_data(dataptr);
364
365         PointerRNA sceneptr;
366         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
367         BL::Scene b_scene(sceneptr);
368
369         python_thread_state_save(&session->python_thread_state);
370
371         session->reset_session(b_data, b_scene);
372
373         python_thread_state_restore(&session->python_thread_state);
374
375         Py_RETURN_NONE;
376 }
377
378 static PyObject *sync_func(PyObject * /*self*/, PyObject *value)
379 {
380         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value);
381
382         python_thread_state_save(&session->python_thread_state);
383
384         session->synchronize();
385
386         python_thread_state_restore(&session->python_thread_state);
387
388         Py_RETURN_NONE;
389 }
390
391 static PyObject *available_devices_func(PyObject * /*self*/, PyObject * /*args*/)
392 {
393         vector<DeviceInfo>& devices = Device::available_devices();
394         PyObject *ret = PyTuple_New(devices.size());
395
396         for(size_t i = 0; i < devices.size(); i++) {
397                 DeviceInfo& device = devices[i];
398                 string type_name = Device::string_from_type(device.type);
399                 PyObject *device_tuple = PyTuple_New(3);
400                 PyTuple_SET_ITEM(device_tuple, 0, PyUnicode_FromString(device.description.c_str()));
401                 PyTuple_SET_ITEM(device_tuple, 1, PyUnicode_FromString(type_name.c_str()));
402                 PyTuple_SET_ITEM(device_tuple, 2, PyUnicode_FromString(device.id.c_str()));
403                 PyTuple_SET_ITEM(ret, i, device_tuple);
404         }
405
406         return ret;
407 }
408
409 #ifdef WITH_OSL
410
411 static PyObject *osl_update_node_func(PyObject * /*self*/, PyObject *args)
412 {
413         PyObject *pynodegroup, *pynode;
414         const char *filepath = NULL;
415
416         if(!PyArg_ParseTuple(args, "OOs", &pynodegroup, &pynode, &filepath))
417                 return NULL;
418
419         /* RNA */
420         PointerRNA nodeptr;
421         RNA_pointer_create((ID*)PyLong_AsVoidPtr(pynodegroup), &RNA_ShaderNodeScript, (void*)PyLong_AsVoidPtr(pynode), &nodeptr);
422         BL::ShaderNodeScript b_node(nodeptr);
423
424         /* update bytecode hash */
425         string bytecode = b_node.bytecode();
426
427         if(!bytecode.empty()) {
428                 MD5Hash md5;
429                 md5.append((const uint8_t*)bytecode.c_str(), bytecode.size());
430                 b_node.bytecode_hash(md5.get_hex().c_str());
431         }
432         else
433                 b_node.bytecode_hash("");
434
435         /* query from file path */
436         OSL::OSLQuery query;
437
438         if(!OSLShaderManager::osl_query(query, filepath))
439                 Py_RETURN_FALSE;
440
441         /* add new sockets from parameters */
442         set<void*> used_sockets;
443
444         for(int i = 0; i < query.nparams(); i++) {
445                 const OSL::OSLQuery::Parameter *param = query.getparam(i);
446
447                 /* skip unsupported types */
448                 if(param->varlenarray || param->isstruct || param->type.arraylen > 1)
449                         continue;
450
451                 /* determine socket type */
452                 string socket_type;
453                 BL::NodeSocket::type_enum data_type = BL::NodeSocket::type_VALUE;
454                 float4 default_float4 = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
455                 float default_float = 0.0f;
456                 int default_int = 0;
457                 string default_string = "";
458
459                 if(param->isclosure) {
460                         socket_type = "NodeSocketShader";
461                         data_type = BL::NodeSocket::type_SHADER;
462                 }
463                 else if(param->type.vecsemantics == TypeDesc::COLOR) {
464                         socket_type = "NodeSocketColor";
465                         data_type = BL::NodeSocket::type_RGBA;
466
467                         if(param->validdefault) {
468                                 default_float4[0] = param->fdefault[0];
469                                 default_float4[1] = param->fdefault[1];
470                                 default_float4[2] = param->fdefault[2];
471                         }
472                 }
473                 else if(param->type.vecsemantics == TypeDesc::POINT ||
474                         param->type.vecsemantics == TypeDesc::VECTOR ||
475                         param->type.vecsemantics == TypeDesc::NORMAL)
476                 {
477                         socket_type = "NodeSocketVector";
478                         data_type = BL::NodeSocket::type_VECTOR;
479
480                         if(param->validdefault) {
481                                 default_float4[0] = param->fdefault[0];
482                                 default_float4[1] = param->fdefault[1];
483                                 default_float4[2] = param->fdefault[2];
484                         }
485                 }
486                 else if(param->type.aggregate == TypeDesc::SCALAR) {
487                         if(param->type.basetype == TypeDesc::INT) {
488                                 socket_type = "NodeSocketInt";
489                                 data_type = BL::NodeSocket::type_INT;
490                                 if(param->validdefault)
491                                         default_int = param->idefault[0];
492                         }
493                         else if(param->type.basetype == TypeDesc::FLOAT) {
494                                 socket_type = "NodeSocketFloat";
495                                 data_type = BL::NodeSocket::type_VALUE;
496                                 if(param->validdefault)
497                                         default_float = param->fdefault[0];
498                         }
499                         else if(param->type.basetype == TypeDesc::STRING) {
500                                 socket_type = "NodeSocketString";
501                                 data_type = BL::NodeSocket::type_STRING;
502                                 if(param->validdefault)
503                                         default_string = param->sdefault[0];
504                         }
505                         else
506                                 continue;
507                 }
508                 else
509                         continue;
510
511                 /* find socket socket */
512                 BL::NodeSocket b_sock(PointerRNA_NULL);
513                 if(param->isoutput) {
514                         b_sock = b_node.outputs[param->name.string()];
515                         /* remove if type no longer matches */
516                         if(b_sock && b_sock.bl_idname() != socket_type) {
517                                 b_node.outputs.remove(b_sock);
518                                 b_sock = BL::NodeSocket(PointerRNA_NULL);
519                         }
520                 }
521                 else {
522                         b_sock = b_node.inputs[param->name.string()];
523                         /* remove if type no longer matches */
524                         if(b_sock && b_sock.bl_idname() != socket_type) {
525                                 b_node.inputs.remove(b_sock);
526                                 b_sock = BL::NodeSocket(PointerRNA_NULL);
527                         }
528                 }
529
530                 if(!b_sock) {
531                         /* create new socket */
532                         if(param->isoutput)
533                                 b_sock = b_node.outputs.create(socket_type.c_str(), param->name.c_str(), param->name.c_str());
534                         else
535                                 b_sock = b_node.inputs.create(socket_type.c_str(), param->name.c_str(), param->name.c_str());
536
537                         /* set default value */
538                         if(data_type == BL::NodeSocket::type_VALUE) {
539                                 set_float(b_sock.ptr, "default_value", default_float);
540                         }
541                         else if(data_type == BL::NodeSocket::type_INT) {
542                                 set_int(b_sock.ptr, "default_value", default_int);
543                         }
544                         else if(data_type == BL::NodeSocket::type_RGBA) {
545                                 set_float4(b_sock.ptr, "default_value", default_float4);
546                         }
547                         else if(data_type == BL::NodeSocket::type_VECTOR) {
548                                 set_float3(b_sock.ptr, "default_value", float4_to_float3(default_float4));
549                         }
550                         else if(data_type == BL::NodeSocket::type_STRING) {
551                                 set_string(b_sock.ptr, "default_value", default_string);
552                         }
553                 }
554
555                 used_sockets.insert(b_sock.ptr.data);
556         }
557
558         /* remove unused parameters */
559         bool removed;
560
561         do {
562                 BL::Node::inputs_iterator b_input;
563                 BL::Node::outputs_iterator b_output;
564
565                 removed = false;
566
567                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
568                         if(used_sockets.find(b_input->ptr.data) == used_sockets.end()) {
569                                 b_node.inputs.remove(*b_input);
570                                 removed = true;
571                                 break;
572                         }
573                 }
574
575                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
576                         if(used_sockets.find(b_output->ptr.data) == used_sockets.end()) {
577                                 b_node.outputs.remove(*b_output);
578                                 removed = true;
579                                 break;
580                         }
581                 }
582         } while(removed);
583
584         Py_RETURN_TRUE;
585 }
586
587 static PyObject *osl_compile_func(PyObject * /*self*/, PyObject *args)
588 {
589         const char *inputfile = NULL, *outputfile = NULL;
590
591         if(!PyArg_ParseTuple(args, "ss", &inputfile, &outputfile))
592                 return NULL;
593         
594         /* return */
595         if(!OSLShaderManager::osl_compile(inputfile, outputfile))
596                 Py_RETURN_FALSE;
597
598         Py_RETURN_TRUE;
599 }
600 #endif
601
602 static PyObject *system_info_func(PyObject * /*self*/, PyObject * /*value*/)
603 {
604         string system_info = Device::device_capabilities();
605         return PyUnicode_FromString(system_info.c_str());
606 }
607
608 #ifdef WITH_OPENCL
609 static PyObject *opencl_disable_func(PyObject * /*self*/, PyObject * /*value*/)
610 {
611         VLOG(2) << "Disabling OpenCL platform.";
612         DebugFlags().opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;
613         Py_RETURN_NONE;
614 }
615 #endif
616
617 static PyObject *debug_flags_update_func(PyObject * /*self*/, PyObject *args)
618 {
619         PyObject *pyscene;
620         if(!PyArg_ParseTuple(args, "O", &pyscene)) {
621                 return NULL;
622         }
623
624         PointerRNA sceneptr;
625         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
626         BL::Scene b_scene(sceneptr);
627
628         if(debug_flags_sync_from_scene(b_scene)) {
629                 VLOG(2) << "Tagging device list for update.";
630                 Device::tag_update();
631         }
632
633         VLOG(2) << "Debug flags set to:\n"
634                 << DebugFlags();
635
636         debug_flags_set = true;
637
638         Py_RETURN_NONE;
639 }
640
641 static PyObject *debug_flags_reset_func(PyObject * /*self*/, PyObject * /*args*/)
642 {
643         if(debug_flags_reset()) {
644                 VLOG(2) << "Tagging device list for update.";
645                 Device::tag_update();
646         }
647         if(debug_flags_set) {
648                 VLOG(2) << "Debug flags reset to:\n"
649                         << DebugFlags();
650                 debug_flags_set = false;
651         }
652         Py_RETURN_NONE;
653 }
654
655 static PyObject *set_resumable_chunk_func(PyObject * /*self*/, PyObject *args)
656 {
657         int num_resumable_chunks, current_resumable_chunk;
658         if(!PyArg_ParseTuple(args, "ii",
659                              &num_resumable_chunks,
660                              &current_resumable_chunk)) {
661                 Py_RETURN_NONE;
662         }
663
664         if(num_resumable_chunks <= 0) {
665                 fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n");
666                 abort();
667                 Py_RETURN_NONE;
668         }
669         if(current_resumable_chunk < 1 ||
670            current_resumable_chunk > num_resumable_chunks)
671         {
672                 fprintf(stderr, "Cycles: Bad value for current resumable chunk number.\n");
673                 abort();
674                 Py_RETURN_NONE;
675         }
676
677         VLOG(1) << "Initialized resumable render: "
678                 << "num_resumable_chunks=" << num_resumable_chunks << ", "
679                 << "current_resumable_chunk=" << current_resumable_chunk;
680         BlenderSession::num_resumable_chunks = num_resumable_chunks;
681         BlenderSession::current_resumable_chunk = current_resumable_chunk;
682
683         printf("Cycles: Will render chunk %d of %d\n",
684                current_resumable_chunk,
685                num_resumable_chunks);
686
687         Py_RETURN_NONE;
688 }
689
690 static PyObject *set_resumable_chunk_range_func(PyObject * /*self*/, PyObject *args)
691 {
692         int num_chunks, start_chunk, end_chunk;
693         if(!PyArg_ParseTuple(args, "iii",
694                              &num_chunks,
695                              &start_chunk,
696                              &end_chunk)) {
697                 Py_RETURN_NONE;
698         }
699
700         if(num_chunks <= 0) {
701                 fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n");
702                 abort();
703                 Py_RETURN_NONE;
704         }
705         if(start_chunk < 1 || start_chunk > num_chunks) {
706                 fprintf(stderr, "Cycles: Bad value for start chunk number.\n");
707                 abort();
708                 Py_RETURN_NONE;
709         }
710         if(end_chunk < 1 || end_chunk > num_chunks) {
711                 fprintf(stderr, "Cycles: Bad value for start chunk number.\n");
712                 abort();
713                 Py_RETURN_NONE;
714         }
715         if(start_chunk > end_chunk) {
716                 fprintf(stderr, "Cycles: End chunk should be higher than start one.\n");
717                 abort();
718                 Py_RETURN_NONE;
719         }
720
721         VLOG(1) << "Initialized resumable render: "
722                 << "num_resumable_chunks=" << num_chunks << ", "
723                 << "start_resumable_chunk=" << start_chunk
724                 << "end_resumable_chunk=" << end_chunk;
725         BlenderSession::num_resumable_chunks = num_chunks;
726         BlenderSession::start_resumable_chunk = start_chunk;
727         BlenderSession::end_resumable_chunk = end_chunk;
728
729         printf("Cycles: Will render chunks %d to %d of %d\n",
730                start_chunk,
731                end_chunk,
732                num_chunks);
733
734         Py_RETURN_NONE;
735 }
736
737 static PyObject *get_device_types_func(PyObject * /*self*/, PyObject * /*args*/)
738 {
739         vector<DeviceInfo>& devices = Device::available_devices();
740         bool has_cuda = false, has_opencl = false;
741         for(int i = 0; i < devices.size(); i++) {
742                 has_cuda   |= (devices[i].type == DEVICE_CUDA);
743                 has_opencl |= (devices[i].type == DEVICE_OPENCL);
744         }
745         PyObject *list = PyTuple_New(2);
746         PyTuple_SET_ITEM(list, 0, PyBool_FromLong(has_cuda));
747         PyTuple_SET_ITEM(list, 1, PyBool_FromLong(has_opencl));
748         return list;
749 }
750
751 static PyMethodDef methods[] = {
752         {"init", init_func, METH_VARARGS, ""},
753         {"exit", exit_func, METH_VARARGS, ""},
754         {"create", create_func, METH_VARARGS, ""},
755         {"free", free_func, METH_O, ""},
756         {"render", render_func, METH_O, ""},
757         {"bake", bake_func, METH_VARARGS, ""},
758         {"draw", draw_func, METH_VARARGS, ""},
759         {"sync", sync_func, METH_O, ""},
760         {"reset", reset_func, METH_VARARGS, ""},
761 #ifdef WITH_OSL
762         {"osl_update_node", osl_update_node_func, METH_VARARGS, ""},
763         {"osl_compile", osl_compile_func, METH_VARARGS, ""},
764 #endif
765         {"available_devices", available_devices_func, METH_NOARGS, ""},
766         {"system_info", system_info_func, METH_NOARGS, ""},
767 #ifdef WITH_OPENCL
768         {"opencl_disable", opencl_disable_func, METH_NOARGS, ""},
769 #endif
770
771         /* Debugging routines */
772         {"debug_flags_update", debug_flags_update_func, METH_VARARGS, ""},
773         {"debug_flags_reset", debug_flags_reset_func, METH_NOARGS, ""},
774
775         /* Resumable render */
776         {"set_resumable_chunk", set_resumable_chunk_func, METH_VARARGS, ""},
777         {"set_resumable_chunk_range", set_resumable_chunk_range_func, METH_VARARGS, ""},
778
779         /* Compute Device selection */
780         {"get_device_types", get_device_types_func, METH_VARARGS, ""},
781
782         {NULL, NULL, 0, NULL},
783 };
784
785 static struct PyModuleDef module = {
786         PyModuleDef_HEAD_INIT,
787         "_cycles",
788         "Blender cycles render integration",
789         -1,
790         methods,
791         NULL, NULL, NULL, NULL
792 };
793
794 CCL_NAMESPACE_END
795
796 void *CCL_python_module_init()
797 {
798         PyObject *mod = PyModule_Create(&ccl::module);
799
800 #ifdef WITH_OSL
801         /* TODO(sergey): This gives us library we've been linking against.
802          *               In theory with dynamic OSL library it might not be
803          *               accurate, but there's nothing in OSL API which we
804          *               might use to get version in runtime.
805          */
806         int curversion = OSL_LIBRARY_VERSION_CODE;
807         PyModule_AddObject(mod, "with_osl", Py_True);
808         Py_INCREF(Py_True);
809         PyModule_AddObject(mod, "osl_version",
810                            Py_BuildValue("(iii)",
811                                           curversion / 10000, (curversion / 100) % 100, curversion % 100));
812         PyModule_AddObject(mod, "osl_version_string",
813                            PyUnicode_FromFormat("%2d, %2d, %2d",
814                                                 curversion / 10000, (curversion / 100) % 100, curversion % 100));
815 #else
816         PyModule_AddObject(mod, "with_osl", Py_False);
817         Py_INCREF(Py_False);
818         PyModule_AddStringConstant(mod, "osl_version", "unknown");
819         PyModule_AddStringConstant(mod, "osl_version_string", "unknown");
820 #endif
821
822 #ifdef WITH_CYCLES_DEBUG
823         PyModule_AddObject(mod, "with_cycles_debug", Py_True);
824         Py_INCREF(Py_True);
825 #else
826         PyModule_AddObject(mod, "with_cycles_debug", Py_False);
827         Py_INCREF(Py_False);
828 #endif
829
830 #ifdef WITH_NETWORK
831         PyModule_AddObject(mod, "with_network", Py_True);
832         Py_INCREF(Py_True);
833 #else /* WITH_NETWORK */
834         PyModule_AddObject(mod, "with_network", Py_False);
835         Py_INCREF(Py_False);
836 #endif /* WITH_NETWORK */
837
838         return (void*)mod;
839 }