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