Code refactor: use device_only_memory and device_vector in more places.
[blender-staging.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           texture_info(this, "__texture_info"),
213 #define REGISTER_KERNEL(name) name ## _kernel(KERNEL_FUNCTIONS(name))
214           REGISTER_KERNEL(path_trace),
215           REGISTER_KERNEL(convert_to_half_float),
216           REGISTER_KERNEL(convert_to_byte),
217           REGISTER_KERNEL(shader),
218           REGISTER_KERNEL(filter_divide_shadow),
219           REGISTER_KERNEL(filter_get_feature),
220           REGISTER_KERNEL(filter_detect_outliers),
221           REGISTER_KERNEL(filter_combine_halves),
222           REGISTER_KERNEL(filter_nlm_calc_difference),
223           REGISTER_KERNEL(filter_nlm_blur),
224           REGISTER_KERNEL(filter_nlm_calc_weight),
225           REGISTER_KERNEL(filter_nlm_update_output),
226           REGISTER_KERNEL(filter_nlm_normalize),
227           REGISTER_KERNEL(filter_construct_transform),
228           REGISTER_KERNEL(filter_nlm_construct_gramian),
229           REGISTER_KERNEL(filter_finalize),
230           REGISTER_KERNEL(data_init)
231 #undef REGISTER_KERNEL
232         {
233                 if(info.cpu_threads == 0) {
234                         info.cpu_threads = TaskScheduler::num_threads();
235                 }
236
237 #ifdef WITH_OSL
238                 kernel_globals.osl = &osl_globals;
239 #endif
240                 use_split_kernel = DebugFlags().cpu.split_kernel;
241                 if(use_split_kernel) {
242                         VLOG(1) << "Will be using split kernel.";
243                 }
244                 need_texture_info = false;
245
246 #define REGISTER_SPLIT_KERNEL(name) split_kernels[#name] = KernelFunctions<void(*)(KernelGlobals*, KernelData*)>(KERNEL_FUNCTIONS(name))
247                 REGISTER_SPLIT_KERNEL(path_init);
248                 REGISTER_SPLIT_KERNEL(scene_intersect);
249                 REGISTER_SPLIT_KERNEL(lamp_emission);
250                 REGISTER_SPLIT_KERNEL(do_volume);
251                 REGISTER_SPLIT_KERNEL(queue_enqueue);
252                 REGISTER_SPLIT_KERNEL(indirect_background);
253                 REGISTER_SPLIT_KERNEL(shader_setup);
254                 REGISTER_SPLIT_KERNEL(shader_sort);
255                 REGISTER_SPLIT_KERNEL(shader_eval);
256                 REGISTER_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao);
257                 REGISTER_SPLIT_KERNEL(subsurface_scatter);
258                 REGISTER_SPLIT_KERNEL(direct_lighting);
259                 REGISTER_SPLIT_KERNEL(shadow_blocked_ao);
260                 REGISTER_SPLIT_KERNEL(shadow_blocked_dl);
261                 REGISTER_SPLIT_KERNEL(enqueue_inactive);
262                 REGISTER_SPLIT_KERNEL(next_iteration_setup);
263                 REGISTER_SPLIT_KERNEL(indirect_subsurface);
264                 REGISTER_SPLIT_KERNEL(buffer_update);
265 #undef REGISTER_SPLIT_KERNEL
266 #undef KERNEL_FUNCTIONS
267         }
268
269         ~CPUDevice()
270         {
271                 task_pool.stop();
272                 tex_free(texture_info);
273         }
274
275         virtual bool show_samples() const
276         {
277                 return (info.cpu_threads == 1);
278         }
279
280         void load_texture_info()
281         {
282                 if(need_texture_info) {
283                         tex_free(texture_info);
284                         tex_alloc(texture_info);
285                         need_texture_info = false;
286                 }
287         }
288
289         void mem_alloc(device_memory& mem)
290         {
291                 if(mem.name) {
292                         VLOG(1) << "Buffer allocate: " << mem.name << ", "
293                                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
294                                 << string_human_readable_size(mem.memory_size()) << ")";
295                 }
296
297                 mem.device_pointer = mem.data_pointer;
298
299                 if(!mem.device_pointer) {
300                         mem.device_pointer = (device_ptr)malloc(mem.memory_size());
301                 }
302
303                 mem.device_size = mem.memory_size();
304                 stats.mem_alloc(mem.device_size);
305         }
306
307         void mem_copy_to(device_memory& /*mem*/)
308         {
309                 /* no-op */
310         }
311
312         void mem_copy_from(device_memory& /*mem*/,
313                            int /*y*/, int /*w*/, int /*h*/,
314                            int /*elem*/)
315         {
316                 /* no-op */
317         }
318
319         void mem_zero(device_memory& mem)
320         {
321                 memset((void*)mem.device_pointer, 0, mem.memory_size());
322         }
323
324         void mem_free(device_memory& mem)
325         {
326                 if(mem.device_pointer) {
327                         if(!mem.data_pointer) {
328                                 free((void*)mem.device_pointer);
329                         }
330                         mem.device_pointer = 0;
331                         stats.mem_free(mem.device_size);
332                         mem.device_size = 0;
333                 }
334         }
335
336         virtual device_ptr mem_alloc_sub_ptr(device_memory& mem, int offset, int /*size*/)
337         {
338                 return (device_ptr) (((char*) mem.device_pointer) + mem.memory_elements_size(offset));
339         }
340
341         void const_copy_to(const char *name, void *host, size_t size)
342         {
343                 kernel_const_copy(&kernel_globals, name, host, size);
344         }
345
346         void tex_alloc(device_memory& mem)
347         {
348                 VLOG(1) << "Texture allocate: " << mem.name << ", "
349                         << string_human_readable_number(mem.memory_size()) << " bytes. ("
350                         << string_human_readable_size(mem.memory_size()) << ")";
351
352                 if(mem.interpolation == INTERPOLATION_NONE) {
353                         /* Data texture. */
354                         kernel_tex_copy(&kernel_globals,
355                                                         mem.name,
356                                                         mem.data_pointer,
357                                                         mem.data_width);
358                 }
359                 else {
360                         /* Image Texture. */
361                         int flat_slot = 0;
362                         if(string_startswith(mem.name, "__tex_image")) {
363                                 int pos =  string(mem.name).rfind("_");
364                                 flat_slot = atoi(mem.name + pos + 1);
365                         }
366                         else {
367                                 assert(0);
368                         }
369
370                         if(flat_slot >= texture_info.size()) {
371                                 /* Allocate some slots in advance, to reduce amount
372                                  * of re-allocations. */
373                                 texture_info.resize(flat_slot + 128);
374                         }
375
376                         TextureInfo& info = texture_info[flat_slot];
377                         info.data = (uint64_t)mem.data_pointer;
378                         info.cl_buffer = 0;
379                         info.interpolation = mem.interpolation;
380                         info.extension = mem.extension;
381                         info.width = mem.data_width;
382                         info.height = mem.data_height;
383                         info.depth = mem.data_depth;
384
385                         need_texture_info = true;
386                 }
387
388                 mem.device_pointer = mem.data_pointer;
389                 mem.device_size = mem.memory_size();
390                 stats.mem_alloc(mem.device_size);
391         }
392
393         void tex_free(device_memory& mem)
394         {
395                 if(mem.device_pointer) {
396                         mem.device_pointer = 0;
397                         stats.mem_free(mem.device_size);
398                         mem.device_size = 0;
399                         need_texture_info = true;
400                 }
401         }
402
403         void *osl_memory()
404         {
405 #ifdef WITH_OSL
406                 return &osl_globals;
407 #else
408                 return NULL;
409 #endif
410         }
411
412         void thread_run(DeviceTask *task)
413         {
414                 if(task->type == DeviceTask::RENDER) {
415                         thread_render(*task);
416                 }
417                 else if(task->type == DeviceTask::FILM_CONVERT)
418                         thread_film_convert(*task);
419                 else if(task->type == DeviceTask::SHADER)
420                         thread_shader(*task);
421         }
422
423         class CPUDeviceTask : public DeviceTask {
424         public:
425                 CPUDeviceTask(CPUDevice *device, DeviceTask& task)
426                 : DeviceTask(task)
427                 {
428                         run = function_bind(&CPUDevice::thread_run, device, this);
429                 }
430         };
431
432         bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task)
433         {
434                 mem_alloc(task->tiles_mem);
435
436                 TilesInfo *tiles = (TilesInfo*) task->tiles_mem.data_pointer;
437                 for(int i = 0; i < 9; i++) {
438                         tiles->buffers[i] = buffers[i];
439                 }
440
441                 return true;
442         }
443
444         bool denoising_non_local_means(device_ptr image_ptr, device_ptr guide_ptr, device_ptr variance_ptr, device_ptr out_ptr,
445                                        DenoisingTask *task)
446         {
447                 int4 rect = task->rect;
448                 int   r   = task->nlm_state.r;
449                 int   f   = task->nlm_state.f;
450                 float a   = task->nlm_state.a;
451                 float k_2 = task->nlm_state.k_2;
452
453                 int w = align_up(rect.z-rect.x, 4);
454                 int h = rect.w-rect.y;
455
456                 float *blurDifference = (float*) task->nlm_state.temporary_1_ptr;
457                 float *difference     = (float*) task->nlm_state.temporary_2_ptr;
458                 float *weightAccum    = (float*) task->nlm_state.temporary_3_ptr;
459
460                 memset(weightAccum, 0, sizeof(float)*w*h);
461                 memset((float*) out_ptr, 0, sizeof(float)*w*h);
462
463                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
464                         int dy = i / (2*r+1) - r;
465                         int dx = i % (2*r+1) - r;
466
467                         int local_rect[4] = {max(0, -dx), max(0, -dy), rect.z-rect.x - max(0, dx), rect.w-rect.y - max(0, dy)};
468                         filter_nlm_calc_difference_kernel()(dx, dy,
469                                                             (float*) guide_ptr,
470                                                             (float*) variance_ptr,
471                                                             difference,
472                                                             local_rect,
473                                                             w, 0,
474                                                             a, k_2);
475
476                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
477                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, w, f);
478                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
479
480                         filter_nlm_update_output_kernel()(dx, dy,
481                                                           blurDifference,
482                                                           (float*) image_ptr,
483                                                           (float*) out_ptr,
484                                                           weightAccum,
485                                                           local_rect,
486                                                           w, f);
487                 }
488
489                 int local_rect[4] = {0, 0, rect.z-rect.x, rect.w-rect.y};
490                 filter_nlm_normalize_kernel()((float*) out_ptr, weightAccum, local_rect, w);
491
492                 return true;
493         }
494
495         bool denoising_construct_transform(DenoisingTask *task)
496         {
497                 for(int y = 0; y < task->filter_area.w; y++) {
498                         for(int x = 0; x < task->filter_area.z; x++) {
499                                 filter_construct_transform_kernel()((float*) task->buffer.mem.device_pointer,
500                                                                     x + task->filter_area.x,
501                                                                     y + task->filter_area.y,
502                                                                     y*task->filter_area.z + x,
503                                                                     (float*) task->storage.transform.device_pointer,
504                                                                     (int*)   task->storage.rank.device_pointer,
505                                                                     &task->rect.x,
506                                                                     task->buffer.pass_stride,
507                                                                     task->radius,
508                                                                     task->pca_threshold);
509                         }
510                 }
511                 return true;
512         }
513
514         bool denoising_reconstruct(device_ptr color_ptr,
515                                    device_ptr color_variance_ptr,
516                                    device_ptr output_ptr,
517                                    DenoisingTask *task)
518         {
519                 mem_zero(task->storage.XtWX);
520                 mem_zero(task->storage.XtWY);
521
522                 float *difference     = (float*) task->reconstruction_state.temporary_1_ptr;
523                 float *blurDifference = (float*) task->reconstruction_state.temporary_2_ptr;
524
525                 int r = task->radius;
526                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
527                         int dy = i / (2*r+1) - r;
528                         int dx = i % (2*r+1) - r;
529
530                         int local_rect[4] = {max(0, -dx), max(0, -dy),
531                                              task->reconstruction_state.source_w - max(0, dx),
532                                              task->reconstruction_state.source_h - max(0, dy)};
533                         filter_nlm_calc_difference_kernel()(dx, dy,
534                                                             (float*) color_ptr,
535                                                             (float*) color_variance_ptr,
536                                                             difference,
537                                                             local_rect,
538                                                             task->buffer.w,
539                                                             task->buffer.pass_stride,
540                                                             1.0f,
541                                                             task->nlm_k_2);
542                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
543                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, task->buffer.w, 4);
544                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
545                         filter_nlm_construct_gramian_kernel()(dx, dy,
546                                                               blurDifference,
547                                                               (float*)  task->buffer.mem.device_pointer,
548                                                               (float*)  task->storage.transform.device_pointer,
549                                                               (int*)    task->storage.rank.device_pointer,
550                                                               (float*)  task->storage.XtWX.device_pointer,
551                                                               (float3*) task->storage.XtWY.device_pointer,
552                                                               local_rect,
553                                                               &task->reconstruction_state.filter_rect.x,
554                                                               task->buffer.w,
555                                                               task->buffer.h,
556                                                               4,
557                                                               task->buffer.pass_stride);
558                 }
559                 for(int y = 0; y < task->filter_area.w; y++) {
560                         for(int x = 0; x < task->filter_area.z; x++) {
561                                 filter_finalize_kernel()(x,
562                                                          y,
563                                                          y*task->filter_area.z + x,
564                                                          task->buffer.w,
565                                                          task->buffer.h,
566                                                          (float*)  output_ptr,
567                                                          (int*)    task->storage.rank.device_pointer,
568                                                          (float*)  task->storage.XtWX.device_pointer,
569                                                          (float3*) task->storage.XtWY.device_pointer,
570                                                          &task->reconstruction_state.buffer_params.x,
571                                                          task->render_buffer.samples);
572                         }
573                 }
574                 return true;
575         }
576
577         bool denoising_combine_halves(device_ptr a_ptr, device_ptr b_ptr,
578                                       device_ptr mean_ptr, device_ptr variance_ptr,
579                                       int r, int4 rect, DenoisingTask * /*task*/)
580         {
581                 for(int y = rect.y; y < rect.w; y++) {
582                         for(int x = rect.x; x < rect.z; x++) {
583                                 filter_combine_halves_kernel()(x, y,
584                                                                (float*) mean_ptr,
585                                                                (float*) variance_ptr,
586                                                                (float*) a_ptr,
587                                                                (float*) b_ptr,
588                                                                &rect.x,
589                                                                r);
590                         }
591                 }
592                 return true;
593         }
594
595         bool denoising_divide_shadow(device_ptr a_ptr, device_ptr b_ptr,
596                                      device_ptr sample_variance_ptr, device_ptr sv_variance_ptr,
597                                      device_ptr buffer_variance_ptr, DenoisingTask *task)
598         {
599                 for(int y = task->rect.y; y < task->rect.w; y++) {
600                         for(int x = task->rect.x; x < task->rect.z; x++) {
601                                 filter_divide_shadow_kernel()(task->render_buffer.samples,
602                                                               task->tiles,
603                                                               x, y,
604                                                               (float*) a_ptr,
605                                                               (float*) b_ptr,
606                                                               (float*) sample_variance_ptr,
607                                                               (float*) sv_variance_ptr,
608                                                               (float*) buffer_variance_ptr,
609                                                               &task->rect.x,
610                                                               task->render_buffer.pass_stride,
611                                                               task->render_buffer.denoising_data_offset);
612                         }
613                 }
614                 return true;
615         }
616
617         bool denoising_get_feature(int mean_offset,
618                                    int variance_offset,
619                                    device_ptr mean_ptr,
620                                    device_ptr variance_ptr,
621                                    DenoisingTask *task)
622         {
623                 for(int y = task->rect.y; y < task->rect.w; y++) {
624                         for(int x = task->rect.x; x < task->rect.z; x++) {
625                                 filter_get_feature_kernel()(task->render_buffer.samples,
626                                                             task->tiles,
627                                                             mean_offset,
628                                                             variance_offset,
629                                                             x, y,
630                                                             (float*) mean_ptr,
631                                                             (float*) variance_ptr,
632                                                             &task->rect.x,
633                                                             task->render_buffer.pass_stride,
634                                                             task->render_buffer.denoising_data_offset);
635                         }
636                 }
637                 return true;
638         }
639
640         bool denoising_detect_outliers(device_ptr image_ptr,
641                                        device_ptr variance_ptr,
642                                        device_ptr depth_ptr,
643                                        device_ptr output_ptr,
644                                        DenoisingTask *task)
645         {
646                 for(int y = task->rect.y; y < task->rect.w; y++) {
647                         for(int x = task->rect.x; x < task->rect.z; x++) {
648                                 filter_detect_outliers_kernel()(x, y,
649                                                                 (float*) image_ptr,
650                                                                 (float*) variance_ptr,
651                                                                 (float*) depth_ptr,
652                                                                 (float*) output_ptr,
653                                                                 &task->rect.x,
654                                                                 task->buffer.pass_stride);
655                         }
656                 }
657                 return true;
658         }
659
660         void path_trace(DeviceTask &task, RenderTile &tile, KernelGlobals *kg)
661         {
662                 float *render_buffer = (float*)tile.buffer;
663                 int start_sample = tile.start_sample;
664                 int end_sample = tile.start_sample + tile.num_samples;
665
666                 for(int sample = start_sample; sample < end_sample; sample++) {
667                         if(task.get_cancel() || task_pool.canceled()) {
668                                 if(task.need_finish_queue == false)
669                                         break;
670                         }
671
672                         for(int y = tile.y; y < tile.y + tile.h; y++) {
673                                 for(int x = tile.x; x < tile.x + tile.w; x++) {
674                                         path_trace_kernel()(kg, render_buffer,
675                                                             sample, x, y, tile.offset, tile.stride);
676                                 }
677                         }
678
679                         tile.sample = sample + 1;
680
681                         task.update_progress(&tile, tile.w*tile.h);
682                 }
683         }
684
685         void denoise(DeviceTask &task, RenderTile &tile)
686         {
687                 tile.sample = tile.start_sample + tile.num_samples;
688
689                 DenoisingTask denoising(this);
690
691                 denoising.functions.construct_transform = function_bind(&CPUDevice::denoising_construct_transform, this, &denoising);
692                 denoising.functions.reconstruct = function_bind(&CPUDevice::denoising_reconstruct, this, _1, _2, _3, &denoising);
693                 denoising.functions.divide_shadow = function_bind(&CPUDevice::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
694                 denoising.functions.non_local_means = function_bind(&CPUDevice::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
695                 denoising.functions.combine_halves = function_bind(&CPUDevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
696                 denoising.functions.get_feature = function_bind(&CPUDevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising);
697                 denoising.functions.detect_outliers = function_bind(&CPUDevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
698                 denoising.functions.set_tiles = function_bind(&CPUDevice::denoising_set_tiles, this, _1, &denoising);
699
700                 denoising.filter_area = make_int4(tile.x, tile.y, tile.w, tile.h);
701                 denoising.render_buffer.samples = tile.sample;
702
703                 RenderTile rtiles[9];
704                 rtiles[4] = tile;
705                 task.map_neighbor_tiles(rtiles, this);
706                 denoising.tiles_from_rendertiles(rtiles);
707
708                 denoising.init_from_devicetask(task);
709
710                 denoising.run_denoising();
711
712                 task.unmap_neighbor_tiles(rtiles, this);
713
714                 task.update_progress(&tile, tile.w*tile.h);
715         }
716
717         void thread_render(DeviceTask& task)
718         {
719                 if(task_pool.canceled()) {
720                         if(task.need_finish_queue == false)
721                                 return;
722                 }
723
724                 /* allocate buffer for kernel globals */
725                 device_only_memory<KernelGlobals> kgbuffer(this, "kernel_globals");
726                 kgbuffer.resize(1);
727                 mem_alloc(kgbuffer);
728
729                 KernelGlobals *kg = new ((void*) kgbuffer.device_pointer) KernelGlobals(thread_kernel_globals_init());
730
731                 CPUSplitKernel *split_kernel = NULL;
732                 if(use_split_kernel) {
733                         split_kernel = new CPUSplitKernel(this);
734                         requested_features.max_closure = MAX_CLOSURE;
735                         if(!split_kernel->load_kernels(requested_features)) {
736                                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
737                                 mem_free(kgbuffer);
738
739                                 delete split_kernel;
740                                 return;
741                         }
742                 }
743
744                 RenderTile tile;
745                 while(task.acquire_tile(this, tile)) {
746                         if(tile.task == RenderTile::PATH_TRACE) {
747                                 if(use_split_kernel) {
748                                         device_only_memory<uchar> void_buffer(this, "void_buffer");
749                                         split_kernel->path_trace(&task, tile, kgbuffer, void_buffer);
750                                 }
751                                 else {
752                                         path_trace(task, tile, kg);
753                                 }
754                         }
755                         else if(tile.task == RenderTile::DENOISE) {
756                                 denoise(task, tile);
757                         }
758
759                         task.release_tile(tile);
760
761                         if(task_pool.canceled()) {
762                                 if(task.need_finish_queue == false)
763                                         break;
764                         }
765                 }
766
767                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
768                 kg->~KernelGlobals();
769                 mem_free(kgbuffer);
770                 delete split_kernel;
771         }
772
773         void thread_film_convert(DeviceTask& task)
774         {
775                 float sample_scale = 1.0f/(task.sample + 1);
776
777                 if(task.rgba_half) {
778                         for(int y = task.y; y < task.y + task.h; y++)
779                                 for(int x = task.x; x < task.x + task.w; x++)
780                                         convert_to_half_float_kernel()(&kernel_globals, (uchar4*)task.rgba_half, (float*)task.buffer,
781                                                                        sample_scale, x, y, task.offset, task.stride);
782                 }
783                 else {
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_byte_kernel()(&kernel_globals, (uchar4*)task.rgba_byte, (float*)task.buffer,
787                                                                  sample_scale, x, y, task.offset, task.stride);
788
789                 }
790         }
791
792         void thread_shader(DeviceTask& task)
793         {
794                 KernelGlobals kg = kernel_globals;
795
796 #ifdef WITH_OSL
797                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
798 #endif
799                 for(int sample = 0; sample < task.num_samples; sample++) {
800                         for(int x = task.shader_x; x < task.shader_x + task.shader_w; x++)
801                                 shader_kernel()(&kg,
802                                                 (uint4*)task.shader_input,
803                                                 (float4*)task.shader_output,
804                                                 task.shader_eval_type,
805                                                 task.shader_filter,
806                                                 x,
807                                                 task.offset,
808                                                 sample);
809
810                         if(task.get_cancel() || task_pool.canceled())
811                                 break;
812
813                         task.update_progress(NULL);
814
815                 }
816
817 #ifdef WITH_OSL
818                 OSLShader::thread_free(&kg);
819 #endif
820         }
821
822         int get_split_task_count(DeviceTask& task)
823         {
824                 if(task.type == DeviceTask::SHADER)
825                         return task.get_subtask_count(info.cpu_threads, 256);
826                 else
827                         return task.get_subtask_count(info.cpu_threads);
828         }
829
830         void task_add(DeviceTask& task)
831         {
832                 /* Load texture info. */
833                 load_texture_info();
834
835                 /* split task into smaller ones */
836                 list<DeviceTask> tasks;
837
838                 if(task.type == DeviceTask::SHADER)
839                         task.split(tasks, info.cpu_threads, 256);
840                 else
841                         task.split(tasks, info.cpu_threads);
842
843                 foreach(DeviceTask& task, tasks)
844                         task_pool.push(new CPUDeviceTask(this, task));
845         }
846
847         void task_wait()
848         {
849                 task_pool.wait_work();
850         }
851
852         void task_cancel()
853         {
854                 task_pool.cancel();
855         }
856
857 protected:
858         inline KernelGlobals thread_kernel_globals_init()
859         {
860                 KernelGlobals kg = kernel_globals;
861                 kg.transparent_shadow_intersections = NULL;
862                 const int decoupled_count = sizeof(kg.decoupled_volume_steps) /
863                                             sizeof(*kg.decoupled_volume_steps);
864                 for(int i = 0; i < decoupled_count; ++i) {
865                         kg.decoupled_volume_steps[i] = NULL;
866                 }
867                 kg.decoupled_volume_steps_index = 0;
868 #ifdef WITH_OSL
869                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
870 #endif
871                 return kg;
872         }
873
874         inline void thread_kernel_globals_free(KernelGlobals *kg)
875         {
876                 if(kg == NULL) {
877                         return;
878                 }
879
880                 if(kg->transparent_shadow_intersections != NULL) {
881                         free(kg->transparent_shadow_intersections);
882                 }
883                 const int decoupled_count = sizeof(kg->decoupled_volume_steps) /
884                                             sizeof(*kg->decoupled_volume_steps);
885                 for(int i = 0; i < decoupled_count; ++i) {
886                         if(kg->decoupled_volume_steps[i] != NULL) {
887                                 free(kg->decoupled_volume_steps[i]);
888                         }
889                 }
890 #ifdef WITH_OSL
891                 OSLShader::thread_free(kg);
892 #endif
893         }
894
895         virtual bool load_kernels(DeviceRequestedFeatures& requested_features_) {
896                 requested_features = requested_features_;
897
898                 return true;
899         }
900 };
901
902 /* split kernel */
903
904 class CPUSplitKernelFunction : public SplitKernelFunction {
905 public:
906         CPUDevice* device;
907         void (*func)(KernelGlobals *kg, KernelData *data);
908
909         CPUSplitKernelFunction(CPUDevice* device) : device(device), func(NULL) {}
910         ~CPUSplitKernelFunction() {}
911
912         virtual bool enqueue(const KernelDimensions& dim, device_memory& kernel_globals, device_memory& data)
913         {
914                 if(!func) {
915                         return false;
916                 }
917
918                 KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
919                 kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
920
921                 for(int y = 0; y < dim.global_size[1]; y++) {
922                         for(int x = 0; x < dim.global_size[0]; x++) {
923                                 kg->global_id = make_int2(x, y);
924
925                                 func(kg, (KernelData*)data.device_pointer);
926                         }
927                 }
928
929                 return true;
930         }
931 };
932
933 CPUSplitKernel::CPUSplitKernel(CPUDevice *device) : DeviceSplitKernel(device), device(device)
934 {
935 }
936
937 bool CPUSplitKernel::enqueue_split_kernel_data_init(const KernelDimensions& dim,
938                                                     RenderTile& rtile,
939                                                     int num_global_elements,
940                                                     device_memory& kernel_globals,
941                                                     device_memory& data,
942                                                     device_memory& split_data,
943                                                     device_memory& ray_state,
944                                                     device_memory& queue_index,
945                                                     device_memory& use_queues_flags,
946                                                     device_memory& work_pool_wgs)
947 {
948         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
949         kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
950
951         for(int y = 0; y < dim.global_size[1]; y++) {
952                 for(int x = 0; x < dim.global_size[0]; x++) {
953                         kg->global_id = make_int2(x, y);
954
955                         device->data_init_kernel()((KernelGlobals*)kernel_globals.device_pointer,
956                                                    (KernelData*)data.device_pointer,
957                                                    (void*)split_data.device_pointer,
958                                                    num_global_elements,
959                                                    (char*)ray_state.device_pointer,
960                                                    rtile.start_sample,
961                                                    rtile.start_sample + rtile.num_samples,
962                                                    rtile.x,
963                                                    rtile.y,
964                                                    rtile.w,
965                                                    rtile.h,
966                                                    rtile.offset,
967                                                    rtile.stride,
968                                                    (int*)queue_index.device_pointer,
969                                                    dim.global_size[0] * dim.global_size[1],
970                                                    (char*)use_queues_flags.device_pointer,
971                                                    (uint*)work_pool_wgs.device_pointer,
972                                                    rtile.num_samples,
973                                                    (float*)rtile.buffer);
974                 }
975         }
976
977         return true;
978 }
979
980 SplitKernelFunction* CPUSplitKernel::get_split_kernel_function(const string& kernel_name,
981                                                                const DeviceRequestedFeatures&)
982 {
983         CPUSplitKernelFunction *kernel = new CPUSplitKernelFunction(device);
984
985         kernel->func = device->split_kernels[kernel_name]();
986         if(!kernel->func) {
987                 delete kernel;
988                 return NULL;
989         }
990
991         return kernel;
992 }
993
994 int2 CPUSplitKernel::split_kernel_local_size()
995 {
996         return make_int2(1, 1);
997 }
998
999 int2 CPUSplitKernel::split_kernel_global_size(device_memory& /*kg*/, device_memory& /*data*/, DeviceTask * /*task*/) {
1000         return make_int2(1, 1);
1001 }
1002
1003 uint64_t CPUSplitKernel::state_buffer_size(device_memory& kernel_globals, device_memory& /*data*/, size_t num_threads) {
1004         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
1005
1006         return split_data_buffer_size(kg, num_threads);
1007 }
1008
1009 Device *device_cpu_create(DeviceInfo& info, Stats &stats, bool background)
1010 {
1011         return new CPUDevice(info, stats, background);
1012 }
1013
1014 void device_cpu_info(vector<DeviceInfo>& devices)
1015 {
1016         DeviceInfo info;
1017
1018         info.type = DEVICE_CPU;
1019         info.description = system_cpu_brand_string();
1020         info.id = "CPU";
1021         info.num = 0;
1022         info.advanced_shading = true;
1023         info.has_qbvh = system_cpu_support_sse2();
1024         info.has_volume_decoupled = true;
1025         info.has_osl = true;
1026
1027         devices.insert(devices.begin(), info);
1028 }
1029
1030 string device_cpu_capabilities(void)
1031 {
1032         string capabilities = "";
1033         capabilities += system_cpu_support_sse2() ? "SSE2 " : "";
1034         capabilities += system_cpu_support_sse3() ? "SSE3 " : "";
1035         capabilities += system_cpu_support_sse41() ? "SSE41 " : "";
1036         capabilities += system_cpu_support_avx() ? "AVX " : "";
1037         capabilities += system_cpu_support_avx2() ? "AVX2" : "";
1038         if(capabilities[capabilities.size() - 1] == ' ')
1039                 capabilities.resize(capabilities.size() - 1);
1040         return capabilities;
1041 }
1042
1043 CCL_NAMESPACE_END