Cycles: combined CPU + GPU rendering support.
[blender.git] / intern / cycles / device / device_cpu.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 <stdlib.h>
18 #include <string.h>
19
20 /* So ImathMath is included before our kernel_cpu_compat. */
21 #ifdef WITH_OSL
22 /* So no context pollution happens from indirectly included windows.h */
23 #  include "util/util_windows.h"
24 #  include <OSL/oslexec.h>
25 #endif
26
27 #include "device/device.h"
28 #include "device/device_denoising.h"
29 #include "device/device_intern.h"
30 #include "device/device_split_kernel.h"
31
32 #include "kernel/kernel.h"
33 #include "kernel/kernel_compat_cpu.h"
34 #include "kernel/kernel_types.h"
35 #include "kernel/split/kernel_split_data.h"
36 #include "kernel/kernel_globals.h"
37
38 #include "kernel/filter/filter.h"
39
40 #include "kernel/osl/osl_shader.h"
41 #include "kernel/osl/osl_globals.h"
42
43 #include "render/buffers.h"
44
45 #include "util/util_debug.h"
46 #include "util/util_foreach.h"
47 #include "util/util_function.h"
48 #include "util/util_logging.h"
49 #include "util/util_map.h"
50 #include "util/util_opengl.h"
51 #include "util/util_optimization.h"
52 #include "util/util_progress.h"
53 #include "util/util_system.h"
54 #include "util/util_thread.h"
55
56 CCL_NAMESPACE_BEGIN
57
58 class CPUDevice;
59
60 /* Has to be outside of the class to be shared across template instantiations. */
61 static const char *logged_architecture = "";
62
63 template<typename F>
64 class KernelFunctions {
65 public:
66         KernelFunctions()
67         {
68                 kernel = (F)NULL;
69         }
70
71         KernelFunctions(F kernel_default,
72                         F kernel_sse2,
73                         F kernel_sse3,
74                         F kernel_sse41,
75                         F kernel_avx,
76                         F kernel_avx2)
77         {
78                 const char *architecture_name = "default";
79                 kernel = kernel_default;
80
81                 /* Silence potential warnings about unused variables
82                  * when compiling without some architectures. */
83                 (void)kernel_sse2;
84                 (void)kernel_sse3;
85                 (void)kernel_sse41;
86                 (void)kernel_avx;
87                 (void)kernel_avx2;
88 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_AVX2
89                 if(system_cpu_support_avx2()) {
90                         architecture_name = "AVX2";
91                         kernel = kernel_avx2;
92                 }
93                 else
94 #endif
95 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_AVX
96                 if(system_cpu_support_avx()) {
97                         architecture_name = "AVX";
98                         kernel = kernel_avx;
99                 }
100                 else
101 #endif
102 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE41
103                 if(system_cpu_support_sse41()) {
104                         architecture_name = "SSE4.1";
105                         kernel = kernel_sse41;
106                 }
107                 else
108 #endif
109 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE3
110                 if(system_cpu_support_sse3()) {
111                         architecture_name = "SSE3";
112                         kernel = kernel_sse3;
113                 }
114                 else
115 #endif
116 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE2
117                 if(system_cpu_support_sse2()) {
118                         architecture_name = "SSE2";
119                         kernel = kernel_sse2;
120                 }
121 #endif
122
123                 if(strcmp(architecture_name, logged_architecture) != 0) {
124                         VLOG(1) << "Will be using " << architecture_name << " kernels.";
125                         logged_architecture = architecture_name;
126                 }
127         }
128
129         inline F operator()() const {
130                 assert(kernel);
131                 return kernel;
132         }
133 protected:
134         F kernel;
135 };
136
137 class CPUSplitKernel : public DeviceSplitKernel {
138         CPUDevice *device;
139 public:
140         explicit CPUSplitKernel(CPUDevice *device);
141
142         virtual bool enqueue_split_kernel_data_init(const KernelDimensions& dim,
143                                                     RenderTile& rtile,
144                                                     int num_global_elements,
145                                                     device_memory& kernel_globals,
146                                                     device_memory& kernel_data_,
147                                                     device_memory& split_data,
148                                                     device_memory& ray_state,
149                                                     device_memory& queue_index,
150                                                     device_memory& use_queues_flag,
151                                                     device_memory& work_pool_wgs);
152
153         virtual SplitKernelFunction* get_split_kernel_function(const string& kernel_name,
154                                                                const DeviceRequestedFeatures&);
155         virtual int2 split_kernel_local_size();
156         virtual int2 split_kernel_global_size(device_memory& kg, device_memory& data, DeviceTask *task);
157         virtual uint64_t state_buffer_size(device_memory& kg, device_memory& data, size_t num_threads);
158 };
159
160 class CPUDevice : public Device
161 {
162 public:
163         TaskPool task_pool;
164         KernelGlobals kernel_globals;
165
166         device_vector<TextureInfo> texture_info;
167         bool need_texture_info;
168
169 #ifdef WITH_OSL
170         OSLGlobals osl_globals;
171 #endif
172
173         bool use_split_kernel;
174
175         DeviceRequestedFeatures requested_features;
176
177         KernelFunctions<void(*)(KernelGlobals *, float *, int, int, int, int, int)>             path_trace_kernel;
178         KernelFunctions<void(*)(KernelGlobals *, uchar4 *, float *, float, int, int, int, int)> convert_to_half_float_kernel;
179         KernelFunctions<void(*)(KernelGlobals *, uchar4 *, float *, float, int, int, int, int)> convert_to_byte_kernel;
180         KernelFunctions<void(*)(KernelGlobals *, uint4 *, float4 *, int, int, int, int, int)>   shader_kernel;
181
182         KernelFunctions<void(*)(int, TilesInfo*, int, int, float*, float*, float*, float*, float*, int*, int, int)> filter_divide_shadow_kernel;
183         KernelFunctions<void(*)(int, TilesInfo*, int, int, int, int, float*, float*, int*, int, int)>               filter_get_feature_kernel;
184         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int)>                               filter_detect_outliers_kernel;
185         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int)>                               filter_combine_halves_kernel;
186
187         KernelFunctions<void(*)(int, int, float*, float*, float*, int*, int, int, float, float)> filter_nlm_calc_difference_kernel;
188         KernelFunctions<void(*)(float*, float*, int*, int, int)>                                 filter_nlm_blur_kernel;
189         KernelFunctions<void(*)(float*, float*, int*, int, int)>                                 filter_nlm_calc_weight_kernel;
190         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int, int)>       filter_nlm_update_output_kernel;
191         KernelFunctions<void(*)(float*, float*, int*, int)>                                      filter_nlm_normalize_kernel;
192
193         KernelFunctions<void(*)(float*, int, int, int, float*, int*, int*, int, int, float)>                              filter_construct_transform_kernel;
194         KernelFunctions<void(*)(int, int, float*, float*, float*, int*, float*, float3*, int*, int*, int, int, int, int)> filter_nlm_construct_gramian_kernel;
195         KernelFunctions<void(*)(int, int, int, int, int, float*, int*, float*, float3*, int*, int)>                       filter_finalize_kernel;
196
197         KernelFunctions<void(*)(KernelGlobals *, ccl_constant KernelData*, ccl_global void*, int, ccl_global char*,
198                                int, int, int, int, int, int, int, int, ccl_global int*, int,
199                                ccl_global char*, ccl_global unsigned int*, unsigned int, ccl_global float*)>        data_init_kernel;
200         unordered_map<string, KernelFunctions<void(*)(KernelGlobals*, KernelData*)> > split_kernels;
201
202 #define KERNEL_FUNCTIONS(name) \
203               KERNEL_NAME_EVAL(cpu, name), \
204               KERNEL_NAME_EVAL(cpu_sse2, name), \
205               KERNEL_NAME_EVAL(cpu_sse3, name), \
206               KERNEL_NAME_EVAL(cpu_sse41, name), \
207               KERNEL_NAME_EVAL(cpu_avx, name), \
208               KERNEL_NAME_EVAL(cpu_avx2, name)
209
210         CPUDevice(DeviceInfo& info_, Stats &stats_, bool background_)
211         : Device(info_, stats_, background_),
212 #define REGISTER_KERNEL(name) name ## _kernel(KERNEL_FUNCTIONS(name))
213           REGISTER_KERNEL(path_trace),
214           REGISTER_KERNEL(convert_to_half_float),
215           REGISTER_KERNEL(convert_to_byte),
216           REGISTER_KERNEL(shader),
217           REGISTER_KERNEL(filter_divide_shadow),
218           REGISTER_KERNEL(filter_get_feature),
219           REGISTER_KERNEL(filter_detect_outliers),
220           REGISTER_KERNEL(filter_combine_halves),
221           REGISTER_KERNEL(filter_nlm_calc_difference),
222           REGISTER_KERNEL(filter_nlm_blur),
223           REGISTER_KERNEL(filter_nlm_calc_weight),
224           REGISTER_KERNEL(filter_nlm_update_output),
225           REGISTER_KERNEL(filter_nlm_normalize),
226           REGISTER_KERNEL(filter_construct_transform),
227           REGISTER_KERNEL(filter_nlm_construct_gramian),
228           REGISTER_KERNEL(filter_finalize),
229           REGISTER_KERNEL(data_init)
230 #undef REGISTER_KERNEL
231         {
232                 if(info.cpu_threads == 0) {
233                         info.cpu_threads = TaskScheduler::num_threads();
234                 }
235
236 #ifdef WITH_OSL
237                 kernel_globals.osl = &osl_globals;
238 #endif
239                 use_split_kernel = DebugFlags().cpu.split_kernel;
240                 if(use_split_kernel) {
241                         VLOG(1) << "Will be using split kernel.";
242                 }
243                 need_texture_info = false;
244
245 #define REGISTER_SPLIT_KERNEL(name) split_kernels[#name] = KernelFunctions<void(*)(KernelGlobals*, KernelData*)>(KERNEL_FUNCTIONS(name))
246                 REGISTER_SPLIT_KERNEL(path_init);
247                 REGISTER_SPLIT_KERNEL(scene_intersect);
248                 REGISTER_SPLIT_KERNEL(lamp_emission);
249                 REGISTER_SPLIT_KERNEL(do_volume);
250                 REGISTER_SPLIT_KERNEL(queue_enqueue);
251                 REGISTER_SPLIT_KERNEL(indirect_background);
252                 REGISTER_SPLIT_KERNEL(shader_setup);
253                 REGISTER_SPLIT_KERNEL(shader_sort);
254                 REGISTER_SPLIT_KERNEL(shader_eval);
255                 REGISTER_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao);
256                 REGISTER_SPLIT_KERNEL(subsurface_scatter);
257                 REGISTER_SPLIT_KERNEL(direct_lighting);
258                 REGISTER_SPLIT_KERNEL(shadow_blocked_ao);
259                 REGISTER_SPLIT_KERNEL(shadow_blocked_dl);
260                 REGISTER_SPLIT_KERNEL(enqueue_inactive);
261                 REGISTER_SPLIT_KERNEL(next_iteration_setup);
262                 REGISTER_SPLIT_KERNEL(indirect_subsurface);
263                 REGISTER_SPLIT_KERNEL(buffer_update);
264 #undef REGISTER_SPLIT_KERNEL
265 #undef KERNEL_FUNCTIONS
266         }
267
268         ~CPUDevice()
269         {
270                 task_pool.stop();
271                 tex_free(texture_info);
272         }
273
274         virtual bool show_samples() const
275         {
276                 return (info.cpu_threads == 1);
277         }
278
279         void load_texture_info()
280         {
281                 if(need_texture_info) {
282                         tex_free(texture_info);
283                         tex_alloc("__texture_info", texture_info, INTERPOLATION_NONE, EXTENSION_REPEAT);
284                         need_texture_info = false;
285                 }
286         }
287
288         void mem_alloc(const char *name, device_memory& mem, MemoryType /*type*/)
289         {
290                 if(name) {
291                         VLOG(1) << "Buffer allocate: " << name << ", "
292                                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
293                                 << string_human_readable_size(mem.memory_size()) << ")";
294                 }
295
296                 mem.device_pointer = mem.data_pointer;
297
298                 if(!mem.device_pointer) {
299                         mem.device_pointer = (device_ptr)malloc(mem.memory_size());
300                 }
301
302                 mem.device_size = mem.memory_size();
303                 stats.mem_alloc(mem.device_size);
304         }
305
306         void mem_copy_to(device_memory& /*mem*/)
307         {
308                 /* no-op */
309         }
310
311         void mem_copy_from(device_memory& /*mem*/,
312                            int /*y*/, int /*w*/, int /*h*/,
313                            int /*elem*/)
314         {
315                 /* no-op */
316         }
317
318         void mem_zero(device_memory& mem)
319         {
320                 memset((void*)mem.device_pointer, 0, mem.memory_size());
321         }
322
323         void mem_free(device_memory& mem)
324         {
325                 if(mem.device_pointer) {
326                         if(!mem.data_pointer) {
327                                 free((void*)mem.device_pointer);
328                         }
329                         mem.device_pointer = 0;
330                         stats.mem_free(mem.device_size);
331                         mem.device_size = 0;
332                 }
333         }
334
335         virtual device_ptr mem_alloc_sub_ptr(device_memory& mem, int offset, int /*size*/, MemoryType /*type*/)
336         {
337                 return (device_ptr) (((char*) mem.device_pointer) + mem.memory_elements_size(offset));
338         }
339
340         void const_copy_to(const char *name, void *host, size_t size)
341         {
342                 kernel_const_copy(&kernel_globals, name, host, size);
343         }
344
345         void tex_alloc(const char *name,
346                        device_memory& mem,
347                        InterpolationType interpolation,
348                        ExtensionType extension)
349         {
350                 VLOG(1) << "Texture allocate: " << name << ", "
351                         << string_human_readable_number(mem.memory_size()) << " bytes. ("
352                         << string_human_readable_size(mem.memory_size()) << ")";
353
354                 if(interpolation == INTERPOLATION_NONE) {
355                         /* Data texture. */
356                         kernel_tex_copy(&kernel_globals,
357                                                         name,
358                                                         mem.data_pointer,
359                                                         mem.data_width,
360                                                         mem.data_height,
361                                                         mem.data_depth,
362                                                         interpolation,
363                                                         extension);
364                 }
365                 else {
366                         /* Image Texture. */
367                         int flat_slot = 0;
368                         if(string_startswith(name, "__tex_image")) {
369                                 int pos =  string(name).rfind("_");
370                                 flat_slot = atoi(name + pos + 1);
371                         }
372                         else {
373                                 assert(0);
374                         }
375
376                         if(flat_slot >= texture_info.size()) {
377                                 /* Allocate some slots in advance, to reduce amount
378                                  * of re-allocations. */
379                                 texture_info.resize(flat_slot + 128);
380                         }
381
382                         TextureInfo& info = texture_info.get_data()[flat_slot];
383                         info.data = (uint64_t)mem.data_pointer;
384                         info.cl_buffer = 0;
385                         info.interpolation = interpolation;
386                         info.extension = extension;
387                         info.width = mem.data_width;
388                         info.height = mem.data_height;
389                         info.depth = mem.data_depth;
390
391                         need_texture_info = true;
392                 }
393
394                 mem.device_pointer = mem.data_pointer;
395                 mem.device_size = mem.memory_size();
396                 stats.mem_alloc(mem.device_size);
397         }
398
399         void tex_free(device_memory& mem)
400         {
401                 if(mem.device_pointer) {
402                         mem.device_pointer = 0;
403                         stats.mem_free(mem.device_size);
404                         mem.device_size = 0;
405                         need_texture_info = true;
406                 }
407         }
408
409         void *osl_memory()
410         {
411 #ifdef WITH_OSL
412                 return &osl_globals;
413 #else
414                 return NULL;
415 #endif
416         }
417
418         void thread_run(DeviceTask *task)
419         {
420                 if(task->type == DeviceTask::RENDER) {
421                         thread_render(*task);
422                 }
423                 else if(task->type == DeviceTask::FILM_CONVERT)
424                         thread_film_convert(*task);
425                 else if(task->type == DeviceTask::SHADER)
426                         thread_shader(*task);
427         }
428
429         class CPUDeviceTask : public DeviceTask {
430         public:
431                 CPUDeviceTask(CPUDevice *device, DeviceTask& task)
432                 : DeviceTask(task)
433                 {
434                         run = function_bind(&CPUDevice::thread_run, device, this);
435                 }
436         };
437
438         bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task)
439         {
440                 mem_alloc("Denoising Tile Info", task->tiles_mem, MEM_READ_ONLY);
441
442                 TilesInfo *tiles = (TilesInfo*) task->tiles_mem.data_pointer;
443                 for(int i = 0; i < 9; i++) {
444                         tiles->buffers[i] = buffers[i];
445                 }
446
447                 return true;
448         }
449
450         bool denoising_non_local_means(device_ptr image_ptr, device_ptr guide_ptr, device_ptr variance_ptr, device_ptr out_ptr,
451                                        DenoisingTask *task)
452         {
453                 int4 rect = task->rect;
454                 int   r   = task->nlm_state.r;
455                 int   f   = task->nlm_state.f;
456                 float a   = task->nlm_state.a;
457                 float k_2 = task->nlm_state.k_2;
458
459                 int w = align_up(rect.z-rect.x, 4);
460                 int h = rect.w-rect.y;
461
462                 float *blurDifference = (float*) task->nlm_state.temporary_1_ptr;
463                 float *difference     = (float*) task->nlm_state.temporary_2_ptr;
464                 float *weightAccum    = (float*) task->nlm_state.temporary_3_ptr;
465
466                 memset(weightAccum, 0, sizeof(float)*w*h);
467                 memset((float*) out_ptr, 0, sizeof(float)*w*h);
468
469                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
470                         int dy = i / (2*r+1) - r;
471                         int dx = i % (2*r+1) - r;
472
473                         int local_rect[4] = {max(0, -dx), max(0, -dy), rect.z-rect.x - max(0, dx), rect.w-rect.y - max(0, dy)};
474                         filter_nlm_calc_difference_kernel()(dx, dy,
475                                                             (float*) guide_ptr,
476                                                             (float*) variance_ptr,
477                                                             difference,
478                                                             local_rect,
479                                                             w, 0,
480                                                             a, k_2);
481
482                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
483                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, w, f);
484                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
485
486                         filter_nlm_update_output_kernel()(dx, dy,
487                                                           blurDifference,
488                                                           (float*) image_ptr,
489                                                           (float*) out_ptr,
490                                                           weightAccum,
491                                                           local_rect,
492                                                           w, f);
493                 }
494
495                 int local_rect[4] = {0, 0, rect.z-rect.x, rect.w-rect.y};
496                 filter_nlm_normalize_kernel()((float*) out_ptr, weightAccum, local_rect, w);
497
498                 return true;
499         }
500
501         bool denoising_construct_transform(DenoisingTask *task)
502         {
503                 for(int y = 0; y < task->filter_area.w; y++) {
504                         for(int x = 0; x < task->filter_area.z; x++) {
505                                 filter_construct_transform_kernel()((float*) task->buffer.mem.device_pointer,
506                                                                     x + task->filter_area.x,
507                                                                     y + task->filter_area.y,
508                                                                     y*task->filter_area.z + x,
509                                                                     (float*) task->storage.transform.device_pointer,
510                                                                     (int*)   task->storage.rank.device_pointer,
511                                                                     &task->rect.x,
512                                                                     task->buffer.pass_stride,
513                                                                     task->radius,
514                                                                     task->pca_threshold);
515                         }
516                 }
517                 return true;
518         }
519
520         bool denoising_reconstruct(device_ptr color_ptr,
521                                    device_ptr color_variance_ptr,
522                                    device_ptr output_ptr,
523                                    DenoisingTask *task)
524         {
525                 mem_zero(task->storage.XtWX);
526                 mem_zero(task->storage.XtWY);
527
528                 float *difference     = (float*) task->reconstruction_state.temporary_1_ptr;
529                 float *blurDifference = (float*) task->reconstruction_state.temporary_2_ptr;
530
531                 int r = task->radius;
532                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
533                         int dy = i / (2*r+1) - r;
534                         int dx = i % (2*r+1) - r;
535
536                         int local_rect[4] = {max(0, -dx), max(0, -dy),
537                                              task->reconstruction_state.source_w - max(0, dx),
538                                              task->reconstruction_state.source_h - max(0, dy)};
539                         filter_nlm_calc_difference_kernel()(dx, dy,
540                                                             (float*) color_ptr,
541                                                             (float*) color_variance_ptr,
542                                                             difference,
543                                                             local_rect,
544                                                             task->buffer.w,
545                                                             task->buffer.pass_stride,
546                                                             1.0f,
547                                                             task->nlm_k_2);
548                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
549                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, task->buffer.w, 4);
550                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
551                         filter_nlm_construct_gramian_kernel()(dx, dy,
552                                                               blurDifference,
553                                                               (float*)  task->buffer.mem.device_pointer,
554                                                               (float*)  task->storage.transform.device_pointer,
555                                                               (int*)    task->storage.rank.device_pointer,
556                                                               (float*)  task->storage.XtWX.device_pointer,
557                                                               (float3*) task->storage.XtWY.device_pointer,
558                                                               local_rect,
559                                                               &task->reconstruction_state.filter_rect.x,
560                                                               task->buffer.w,
561                                                               task->buffer.h,
562                                                               4,
563                                                               task->buffer.pass_stride);
564                 }
565                 for(int y = 0; y < task->filter_area.w; y++) {
566                         for(int x = 0; x < task->filter_area.z; x++) {
567                                 filter_finalize_kernel()(x,
568                                                          y,
569                                                          y*task->filter_area.z + x,
570                                                          task->buffer.w,
571                                                          task->buffer.h,
572                                                          (float*)  output_ptr,
573                                                          (int*)    task->storage.rank.device_pointer,
574                                                          (float*)  task->storage.XtWX.device_pointer,
575                                                          (float3*) task->storage.XtWY.device_pointer,
576                                                          &task->reconstruction_state.buffer_params.x,
577                                                          task->render_buffer.samples);
578                         }
579                 }
580                 return true;
581         }
582
583         bool denoising_combine_halves(device_ptr a_ptr, device_ptr b_ptr,
584                                       device_ptr mean_ptr, device_ptr variance_ptr,
585                                       int r, int4 rect, DenoisingTask * /*task*/)
586         {
587                 for(int y = rect.y; y < rect.w; y++) {
588                         for(int x = rect.x; x < rect.z; x++) {
589                                 filter_combine_halves_kernel()(x, y,
590                                                                (float*) mean_ptr,
591                                                                (float*) variance_ptr,
592                                                                (float*) a_ptr,
593                                                                (float*) b_ptr,
594                                                                &rect.x,
595                                                                r);
596                         }
597                 }
598                 return true;
599         }
600
601         bool denoising_divide_shadow(device_ptr a_ptr, device_ptr b_ptr,
602                                      device_ptr sample_variance_ptr, device_ptr sv_variance_ptr,
603                                      device_ptr buffer_variance_ptr, DenoisingTask *task)
604         {
605                 for(int y = task->rect.y; y < task->rect.w; y++) {
606                         for(int x = task->rect.x; x < task->rect.z; x++) {
607                                 filter_divide_shadow_kernel()(task->render_buffer.samples,
608                                                               task->tiles,
609                                                               x, y,
610                                                               (float*) a_ptr,
611                                                               (float*) b_ptr,
612                                                               (float*) sample_variance_ptr,
613                                                               (float*) sv_variance_ptr,
614                                                               (float*) buffer_variance_ptr,
615                                                               &task->rect.x,
616                                                               task->render_buffer.pass_stride,
617                                                               task->render_buffer.denoising_data_offset);
618                         }
619                 }
620                 return true;
621         }
622
623         bool denoising_get_feature(int mean_offset,
624                                    int variance_offset,
625                                    device_ptr mean_ptr,
626                                    device_ptr variance_ptr,
627                                    DenoisingTask *task)
628         {
629                 for(int y = task->rect.y; y < task->rect.w; y++) {
630                         for(int x = task->rect.x; x < task->rect.z; x++) {
631                                 filter_get_feature_kernel()(task->render_buffer.samples,
632                                                             task->tiles,
633                                                             mean_offset,
634                                                             variance_offset,
635                                                             x, y,
636                                                             (float*) mean_ptr,
637                                                             (float*) variance_ptr,
638                                                             &task->rect.x,
639                                                             task->render_buffer.pass_stride,
640                                                             task->render_buffer.denoising_data_offset);
641                         }
642                 }
643                 return true;
644         }
645
646         bool denoising_detect_outliers(device_ptr image_ptr,
647                                        device_ptr variance_ptr,
648                                        device_ptr depth_ptr,
649                                        device_ptr output_ptr,
650                                        DenoisingTask *task)
651         {
652                 for(int y = task->rect.y; y < task->rect.w; y++) {
653                         for(int x = task->rect.x; x < task->rect.z; x++) {
654                                 filter_detect_outliers_kernel()(x, y,
655                                                                 (float*) image_ptr,
656                                                                 (float*) variance_ptr,
657                                                                 (float*) depth_ptr,
658                                                                 (float*) output_ptr,
659                                                                 &task->rect.x,
660                                                                 task->buffer.pass_stride);
661                         }
662                 }
663                 return true;
664         }
665
666         void path_trace(DeviceTask &task, RenderTile &tile, KernelGlobals *kg)
667         {
668                 float *render_buffer = (float*)tile.buffer;
669                 int start_sample = tile.start_sample;
670                 int end_sample = tile.start_sample + tile.num_samples;
671
672                 for(int sample = start_sample; sample < end_sample; sample++) {
673                         if(task.get_cancel() || task_pool.canceled()) {
674                                 if(task.need_finish_queue == false)
675                                         break;
676                         }
677
678                         for(int y = tile.y; y < tile.y + tile.h; y++) {
679                                 for(int x = tile.x; x < tile.x + tile.w; x++) {
680                                         path_trace_kernel()(kg, render_buffer,
681                                                             sample, x, y, tile.offset, tile.stride);
682                                 }
683                         }
684
685                         tile.sample = sample + 1;
686
687                         task.update_progress(&tile, tile.w*tile.h);
688                 }
689         }
690
691         void denoise(DeviceTask &task, RenderTile &tile)
692         {
693                 tile.sample = tile.start_sample + tile.num_samples;
694
695                 DenoisingTask denoising(this);
696
697                 denoising.functions.construct_transform = function_bind(&CPUDevice::denoising_construct_transform, this, &denoising);
698                 denoising.functions.reconstruct = function_bind(&CPUDevice::denoising_reconstruct, this, _1, _2, _3, &denoising);
699                 denoising.functions.divide_shadow = function_bind(&CPUDevice::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
700                 denoising.functions.non_local_means = function_bind(&CPUDevice::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
701                 denoising.functions.combine_halves = function_bind(&CPUDevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
702                 denoising.functions.get_feature = function_bind(&CPUDevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising);
703                 denoising.functions.detect_outliers = function_bind(&CPUDevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
704                 denoising.functions.set_tiles = function_bind(&CPUDevice::denoising_set_tiles, this, _1, &denoising);
705
706                 denoising.filter_area = make_int4(tile.x, tile.y, tile.w, tile.h);
707                 denoising.render_buffer.samples = tile.sample;
708
709                 RenderTile rtiles[9];
710                 rtiles[4] = tile;
711                 task.map_neighbor_tiles(rtiles, this);
712                 denoising.tiles_from_rendertiles(rtiles);
713
714                 denoising.init_from_devicetask(task);
715
716                 denoising.run_denoising();
717
718                 task.unmap_neighbor_tiles(rtiles, this);
719
720                 task.update_progress(&tile, tile.w*tile.h);
721         }
722
723         void thread_render(DeviceTask& task)
724         {
725                 if(task_pool.canceled()) {
726                         if(task.need_finish_queue == false)
727                                 return;
728                 }
729
730                 /* allocate buffer for kernel globals */
731                 device_only_memory<KernelGlobals> kgbuffer;
732                 kgbuffer.resize(1);
733                 mem_alloc("kernel_globals", kgbuffer, MEM_READ_WRITE);
734
735                 KernelGlobals *kg = new ((void*) kgbuffer.device_pointer) KernelGlobals(thread_kernel_globals_init());
736
737                 CPUSplitKernel *split_kernel = NULL;
738                 if(use_split_kernel) {
739                         split_kernel = new CPUSplitKernel(this);
740                         requested_features.max_closure = MAX_CLOSURE;
741                         if(!split_kernel->load_kernels(requested_features)) {
742                                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
743                                 mem_free(kgbuffer);
744
745                                 delete split_kernel;
746                                 return;
747                         }
748                 }
749
750                 RenderTile tile;
751                 while(task.acquire_tile(this, tile)) {
752                         if(tile.task == RenderTile::PATH_TRACE) {
753                                 if(use_split_kernel) {
754                                         device_memory data;
755                                         split_kernel->path_trace(&task, tile, kgbuffer, data);
756                                 }
757                                 else {
758                                         path_trace(task, tile, kg);
759                                 }
760                         }
761                         else if(tile.task == RenderTile::DENOISE) {
762                                 denoise(task, tile);
763                         }
764
765                         task.release_tile(tile);
766
767                         if(task_pool.canceled()) {
768                                 if(task.need_finish_queue == false)
769                                         break;
770                         }
771                 }
772
773                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
774                 kg->~KernelGlobals();
775                 mem_free(kgbuffer);
776                 delete split_kernel;
777         }
778
779         void thread_film_convert(DeviceTask& task)
780         {
781                 float sample_scale = 1.0f/(task.sample + 1);
782
783                 if(task.rgba_half) {
784                         for(int y = task.y; y < task.y + task.h; y++)
785                                 for(int x = task.x; x < task.x + task.w; x++)
786                                         convert_to_half_float_kernel()(&kernel_globals, (uchar4*)task.rgba_half, (float*)task.buffer,
787                                                                        sample_scale, x, y, task.offset, task.stride);
788                 }
789                 else {
790                         for(int y = task.y; y < task.y + task.h; y++)
791                                 for(int x = task.x; x < task.x + task.w; x++)
792                                         convert_to_byte_kernel()(&kernel_globals, (uchar4*)task.rgba_byte, (float*)task.buffer,
793                                                                  sample_scale, x, y, task.offset, task.stride);
794
795                 }
796         }
797
798         void thread_shader(DeviceTask& task)
799         {
800                 KernelGlobals kg = kernel_globals;
801
802 #ifdef WITH_OSL
803                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
804 #endif
805                 for(int sample = 0; sample < task.num_samples; sample++) {
806                         for(int x = task.shader_x; x < task.shader_x + task.shader_w; x++)
807                                 shader_kernel()(&kg,
808                                                 (uint4*)task.shader_input,
809                                                 (float4*)task.shader_output,
810                                                 task.shader_eval_type,
811                                                 task.shader_filter,
812                                                 x,
813                                                 task.offset,
814                                                 sample);
815
816                         if(task.get_cancel() || task_pool.canceled())
817                                 break;
818
819                         task.update_progress(NULL);
820
821                 }
822
823 #ifdef WITH_OSL
824                 OSLShader::thread_free(&kg);
825 #endif
826         }
827
828         int get_split_task_count(DeviceTask& task)
829         {
830                 if(task.type == DeviceTask::SHADER)
831                         return task.get_subtask_count(info.cpu_threads, 256);
832                 else
833                         return task.get_subtask_count(info.cpu_threads);
834         }
835
836         void task_add(DeviceTask& task)
837         {
838                 /* Load texture info. */
839                 load_texture_info();
840
841                 /* split task into smaller ones */
842                 list<DeviceTask> tasks;
843
844                 if(task.type == DeviceTask::SHADER)
845                         task.split(tasks, info.cpu_threads, 256);
846                 else
847                         task.split(tasks, info.cpu_threads);
848
849                 foreach(DeviceTask& task, tasks)
850                         task_pool.push(new CPUDeviceTask(this, task));
851         }
852
853         void task_wait()
854         {
855                 task_pool.wait_work();
856         }
857
858         void task_cancel()
859         {
860                 task_pool.cancel();
861         }
862
863 protected:
864         inline KernelGlobals thread_kernel_globals_init()
865         {
866                 KernelGlobals kg = kernel_globals;
867                 kg.transparent_shadow_intersections = NULL;
868                 const int decoupled_count = sizeof(kg.decoupled_volume_steps) /
869                                             sizeof(*kg.decoupled_volume_steps);
870                 for(int i = 0; i < decoupled_count; ++i) {
871                         kg.decoupled_volume_steps[i] = NULL;
872                 }
873                 kg.decoupled_volume_steps_index = 0;
874 #ifdef WITH_OSL
875                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
876 #endif
877                 return kg;
878         }
879
880         inline void thread_kernel_globals_free(KernelGlobals *kg)
881         {
882                 if(kg == NULL) {
883                         return;
884                 }
885
886                 if(kg->transparent_shadow_intersections != NULL) {
887                         free(kg->transparent_shadow_intersections);
888                 }
889                 const int decoupled_count = sizeof(kg->decoupled_volume_steps) /
890                                             sizeof(*kg->decoupled_volume_steps);
891                 for(int i = 0; i < decoupled_count; ++i) {
892                         if(kg->decoupled_volume_steps[i] != NULL) {
893                                 free(kg->decoupled_volume_steps[i]);
894                         }
895                 }
896 #ifdef WITH_OSL
897                 OSLShader::thread_free(kg);
898 #endif
899         }
900
901         virtual bool load_kernels(DeviceRequestedFeatures& requested_features_) {
902                 requested_features = requested_features_;
903
904                 return true;
905         }
906 };
907
908 /* split kernel */
909
910 class CPUSplitKernelFunction : public SplitKernelFunction {
911 public:
912         CPUDevice* device;
913         void (*func)(KernelGlobals *kg, KernelData *data);
914
915         CPUSplitKernelFunction(CPUDevice* device) : device(device), func(NULL) {}
916         ~CPUSplitKernelFunction() {}
917
918         virtual bool enqueue(const KernelDimensions& dim, device_memory& kernel_globals, device_memory& data)
919         {
920                 if(!func) {
921                         return false;
922                 }
923
924                 KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
925                 kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
926
927                 for(int y = 0; y < dim.global_size[1]; y++) {
928                         for(int x = 0; x < dim.global_size[0]; x++) {
929                                 kg->global_id = make_int2(x, y);
930
931                                 func(kg, (KernelData*)data.device_pointer);
932                         }
933                 }
934
935                 return true;
936         }
937 };
938
939 CPUSplitKernel::CPUSplitKernel(CPUDevice *device) : DeviceSplitKernel(device), device(device)
940 {
941 }
942
943 bool CPUSplitKernel::enqueue_split_kernel_data_init(const KernelDimensions& dim,
944                                                     RenderTile& rtile,
945                                                     int num_global_elements,
946                                                     device_memory& kernel_globals,
947                                                     device_memory& data,
948                                                     device_memory& split_data,
949                                                     device_memory& ray_state,
950                                                     device_memory& queue_index,
951                                                     device_memory& use_queues_flags,
952                                                     device_memory& work_pool_wgs)
953 {
954         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
955         kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
956
957         for(int y = 0; y < dim.global_size[1]; y++) {
958                 for(int x = 0; x < dim.global_size[0]; x++) {
959                         kg->global_id = make_int2(x, y);
960
961                         device->data_init_kernel()((KernelGlobals*)kernel_globals.device_pointer,
962                                                    (KernelData*)data.device_pointer,
963                                                    (void*)split_data.device_pointer,
964                                                    num_global_elements,
965                                                    (char*)ray_state.device_pointer,
966                                                    rtile.start_sample,
967                                                    rtile.start_sample + rtile.num_samples,
968                                                    rtile.x,
969                                                    rtile.y,
970                                                    rtile.w,
971                                                    rtile.h,
972                                                    rtile.offset,
973                                                    rtile.stride,
974                                                    (int*)queue_index.device_pointer,
975                                                    dim.global_size[0] * dim.global_size[1],
976                                                    (char*)use_queues_flags.device_pointer,
977                                                    (uint*)work_pool_wgs.device_pointer,
978                                                    rtile.num_samples,
979                                                    (float*)rtile.buffer);
980                 }
981         }
982
983         return true;
984 }
985
986 SplitKernelFunction* CPUSplitKernel::get_split_kernel_function(const string& kernel_name,
987                                                                const DeviceRequestedFeatures&)
988 {
989         CPUSplitKernelFunction *kernel = new CPUSplitKernelFunction(device);
990
991         kernel->func = device->split_kernels[kernel_name]();
992         if(!kernel->func) {
993                 delete kernel;
994                 return NULL;
995         }
996
997         return kernel;
998 }
999
1000 int2 CPUSplitKernel::split_kernel_local_size()
1001 {
1002         return make_int2(1, 1);
1003 }
1004
1005 int2 CPUSplitKernel::split_kernel_global_size(device_memory& /*kg*/, device_memory& /*data*/, DeviceTask * /*task*/) {
1006         return make_int2(1, 1);
1007 }
1008
1009 uint64_t CPUSplitKernel::state_buffer_size(device_memory& kernel_globals, device_memory& /*data*/, size_t num_threads) {
1010         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
1011
1012         return split_data_buffer_size(kg, num_threads);
1013 }
1014
1015 Device *device_cpu_create(DeviceInfo& info, Stats &stats, bool background)
1016 {
1017         return new CPUDevice(info, stats, background);
1018 }
1019
1020 void device_cpu_info(vector<DeviceInfo>& devices)
1021 {
1022         DeviceInfo info;
1023
1024         info.type = DEVICE_CPU;
1025         info.description = system_cpu_brand_string();
1026         info.id = "CPU";
1027         info.num = 0;
1028         info.advanced_shading = true;
1029         info.has_qbvh = system_cpu_support_sse2();
1030         info.has_volume_decoupled = true;
1031
1032         devices.insert(devices.begin(), info);
1033 }
1034
1035 string device_cpu_capabilities(void)
1036 {
1037         string capabilities = "";
1038         capabilities += system_cpu_support_sse2() ? "SSE2 " : "";
1039         capabilities += system_cpu_support_sse3() ? "SSE3 " : "";
1040         capabilities += system_cpu_support_sse41() ? "SSE41 " : "";
1041         capabilities += system_cpu_support_avx() ? "AVX " : "";
1042         capabilities += system_cpu_support_avx2() ? "AVX2" : "";
1043         if(capabilities[capabilities.size() - 1] == ' ')
1044                 capabilities.resize(capabilities.size() - 1);
1045         return capabilities;
1046 }
1047
1048 CCL_NAMESPACE_END