3773dda76311e15472f9112f3e520cef486366d5
[blender.git] / intern / cycles / device / device_cuda.cpp
1 /*
2  * Copyright 2011, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include "device.h"
24 #include "device_intern.h"
25
26 #include "util_cuda.h"
27 #include "util_debug.h"
28 #include "util_map.h"
29 #include "util_opengl.h"
30 #include "util_path.h"
31 #include "util_system.h"
32 #include "util_types.h"
33 #include "util_time.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 class CUDADevice : public Device
38 {
39 public:
40         CUdevice cuDevice;
41         CUcontext cuContext;
42         CUmodule cuModule;
43         map<device_ptr, bool> tex_interp_map;
44         int cuDevId;
45
46         struct PixelMem {
47                 GLuint cuPBO;
48                 CUgraphicsResource cuPBOresource;
49                 GLuint cuTexId;
50                 int w, h;
51         };
52
53         map<device_ptr, PixelMem> pixel_mem_map;
54
55         CUdeviceptr cuda_device_ptr(device_ptr mem)
56         {
57                 return (CUdeviceptr)mem;
58         }
59
60         const char *cuda_error_string(CUresult result)
61         {
62                 switch(result) {
63                         case CUDA_SUCCESS: return "No errors";
64                         case CUDA_ERROR_INVALID_VALUE: return "Invalid value";
65                         case CUDA_ERROR_OUT_OF_MEMORY: return "Out of memory";
66                         case CUDA_ERROR_NOT_INITIALIZED: return "Driver not initialized";
67                         case CUDA_ERROR_DEINITIALIZED: return "Driver deinitialized";
68
69                         case CUDA_ERROR_NO_DEVICE: return "No CUDA-capable device available";
70                         case CUDA_ERROR_INVALID_DEVICE: return "Invalid device";
71
72                         case CUDA_ERROR_INVALID_IMAGE: return "Invalid kernel image";
73                         case CUDA_ERROR_INVALID_CONTEXT: return "Invalid context";
74                         case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "Context already current";
75                         case CUDA_ERROR_MAP_FAILED: return "Map failed";
76                         case CUDA_ERROR_UNMAP_FAILED: return "Unmap failed";
77                         case CUDA_ERROR_ARRAY_IS_MAPPED: return "Array is mapped";
78                         case CUDA_ERROR_ALREADY_MAPPED: return "Already mapped";
79                         case CUDA_ERROR_NO_BINARY_FOR_GPU: return "No binary for GPU";
80                         case CUDA_ERROR_ALREADY_ACQUIRED: return "Already acquired";
81                         case CUDA_ERROR_NOT_MAPPED: return "Not mapped";
82                         case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "Mapped resource not available for access as an array";
83                         case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "Mapped resource not available for access as a pointer";
84                         case CUDA_ERROR_ECC_UNCORRECTABLE: return "Uncorrectable ECC error detected";
85                         case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUlimit not supported by device";
86
87                         case CUDA_ERROR_INVALID_SOURCE: return "Invalid source";
88                         case CUDA_ERROR_FILE_NOT_FOUND: return "File not found";
89                         case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "Link to a shared object failed to resolve";
90                         case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "Shared object initialization failed";
91
92                         case CUDA_ERROR_INVALID_HANDLE: return "Invalid handle";
93
94                         case CUDA_ERROR_NOT_FOUND: return "Not found";
95
96                         case CUDA_ERROR_NOT_READY: return "CUDA not ready";
97
98                         case CUDA_ERROR_LAUNCH_FAILED: return "Launch failed";
99                         case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "Launch exceeded resources";
100                         case CUDA_ERROR_LAUNCH_TIMEOUT: return "Launch exceeded timeout";
101                         case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "Launch with incompatible texturing";
102
103                         case CUDA_ERROR_UNKNOWN: return "Unknown error";
104
105                         default: return "Unknown CUDA error value";
106                 }
107         }
108
109         static int cuda_align_up(int& offset, int alignment)
110         {
111                 return (offset + alignment - 1) & ~(alignment - 1);
112         }
113
114 #ifdef NDEBUG
115 #define cuda_abort()
116 #else
117 #define cuda_abort() abort()
118 #endif
119
120 #define cuda_assert(stmt) \
121         { \
122                 CUresult result = stmt; \
123                 \
124                 if(result != CUDA_SUCCESS) { \
125                         fprintf(stderr, "CUDA error: %s in %s\n", cuda_error_string(result), #stmt); \
126                         cuda_abort(); \
127                 } \
128         }
129
130         bool cuda_error(CUresult result)
131         {
132                 if(result == CUDA_SUCCESS)
133                         return false;
134
135                 fprintf(stderr, "CUDA error: %s\n", cuda_error_string(result));
136                 return true;
137         }
138
139         void cuda_push_context()
140         {
141                 cuda_assert(cuCtxSetCurrent(cuContext))
142         }
143
144         void cuda_pop_context()
145         {
146                 cuda_assert(cuCtxSetCurrent(NULL));
147         }
148
149         CUDADevice(bool background_)
150         {
151                 background = background_;
152
153                 cuDevId = 0;
154                 cuDevice = 0;
155                 cuContext = 0;
156
157                 /* intialize */
158                 if(cuda_error(cuInit(0)))
159                         return;
160
161                 /* setup device and context */
162                 if(cuda_error(cuDeviceGet(&cuDevice, cuDevId)))
163                         return;
164
165                 CUresult result;
166
167                 if(background)
168                         result = cuCtxCreate(&cuContext, 0, cuDevice);
169                 else
170                         result = cuGLCtxCreate(&cuContext, 0, cuDevice);
171
172                 if(cuda_error(result))
173                         return;
174
175                 cuda_pop_context();
176         }
177
178         ~CUDADevice()
179         {
180                 cuda_push_context();
181                 cuda_assert(cuCtxDetach(cuContext))
182         }
183
184         string description()
185         {
186                 /* print device information */
187                 char deviceName[100];
188
189                 cuda_push_context();
190                 cuDeviceGetName(deviceName, 256, cuDevId);
191                 cuda_pop_context();
192
193                 return string("CUDA ") + deviceName;
194         }
195
196         string compile_kernel()
197         {
198                 /* compute cubin name */
199                 int major, minor;
200                 cuDeviceComputeCapability(&major, &minor, cuDevId);
201
202                 /* attempt to use kernel provided with blender */
203                 string cubin = path_get(string_printf("lib/kernel_sm_%d%d.cubin", major, minor));
204                 if(path_exists(cubin))
205                         return cubin;
206
207                 /* not found, try to use locally compiled kernel */
208                 string kernel_path = path_get("kernel");
209                 string md5 = path_files_md5_hash(kernel_path);
210
211                 cubin = string_printf("cycles_kernel_sm%d%d_%s.cubin", major, minor, md5.c_str());;
212                 cubin = path_user_get(path_join("cache", cubin));
213
214                 /* if exists already, use it */
215                 if(path_exists(cubin))
216                         return cubin;
217
218                 /* if not, find CUDA compiler */
219                 string nvcc = cuCompilerPath();
220
221                 if(nvcc == "") {
222                         fprintf(stderr, "CUDA nvcc compiler not found. Install CUDA toolkit in default location.\n");
223                         return "";
224                 }
225
226                 /* compile */
227                 string kernel = path_join(kernel_path, "kernel.cu");
228                 string include = kernel_path;
229                 const int machine = system_cpu_bits();
230                 const int maxreg = 24;
231
232                 double starttime = time_dt();
233                 printf("Compiling CUDA kernel ...\n");
234
235                 path_create_directories(cubin);
236
237                 string command = string_printf("%s -arch=sm_%d%d -m%d --cubin \"%s\" --use_fast_math "
238                         "-o \"%s\" --ptxas-options=\"-v\" --maxrregcount=%d --opencc-options -OPT:Olimit=0 -I\"%s\" -DNVCC",
239                         nvcc.c_str(), major, minor, machine, kernel.c_str(), cubin.c_str(), maxreg, include.c_str());
240
241                 if(system(command.c_str()) == -1) {
242                         fprintf(stderr, "Failed to execute compilation command.\n");
243                         return "";
244                 }
245
246                 /* verify if compilation succeeded */
247                 if(!path_exists(cubin)) {
248                         fprintf(stderr, "CUDA kernel compilation failed.\n");
249                         return "";
250                 }
251
252                 printf("Kernel compilation finished in %.2lfs.\n", time_dt() - starttime);
253
254                 return cubin;
255         }
256
257         bool load_kernels()
258         {
259                 /* check if cuda init succeeded */
260                 if(cuContext == 0)
261                         return false;
262
263                 /* get kernel */
264                 string cubin = compile_kernel();
265
266                 if(cubin == "")
267                         return false;
268
269                 /* open module */
270                 cuda_push_context();
271
272                 CUresult result = cuModuleLoad(&cuModule, cubin.c_str());
273                 if(cuda_error(result))
274                         fprintf(stderr, "Failed loading CUDA kernel %s.\n", cubin.c_str());
275
276                 cuda_pop_context();
277
278                 return (result == CUDA_SUCCESS);
279         }
280
281         void mem_alloc(device_memory& mem, MemoryType type)
282         {
283                 cuda_push_context();
284                 CUdeviceptr device_pointer;
285                 cuda_assert(cuMemAlloc(&device_pointer, mem.memory_size()))
286                 mem.device_pointer = (device_ptr)device_pointer;
287                 cuda_pop_context();
288         }
289
290         void mem_copy_to(device_memory& mem)
291         {
292                 cuda_push_context();
293                 cuda_assert(cuMemcpyHtoD(cuda_device_ptr(mem.device_pointer), (void*)mem.data_pointer, mem.memory_size()))
294                 cuda_pop_context();
295         }
296
297         void mem_copy_from(device_memory& mem, size_t offset, size_t size)
298         {
299                 /* todo: offset is ignored */
300                 cuda_push_context();
301                 cuda_assert(cuMemcpyDtoH((uchar*)mem.data_pointer + offset,
302                         (CUdeviceptr)((uchar*)mem.device_pointer + offset), size))
303                 cuda_pop_context();
304         }
305
306         void mem_zero(device_memory& mem)
307         {
308                 memset((void*)mem.data_pointer, 0, mem.memory_size());
309
310                 cuda_push_context();
311                 cuda_assert(cuMemsetD8(cuda_device_ptr(mem.device_pointer), 0, mem.memory_size()))
312                 cuda_pop_context();
313         }
314
315         void mem_free(device_memory& mem)
316         {
317                 if(mem.device_pointer) {
318                         cuda_push_context();
319                         cuda_assert(cuMemFree(cuda_device_ptr(mem.device_pointer)))
320                         cuda_pop_context();
321
322                         mem.device_pointer = 0;
323                 }
324         }
325
326         void const_copy_to(const char *name, void *host, size_t size)
327         {
328                 CUdeviceptr mem;
329                 size_t bytes;
330
331                 cuda_push_context();
332                 cuda_assert(cuModuleGetGlobal(&mem, &bytes, cuModule, name))
333                 //assert(bytes == size);
334                 cuda_assert(cuMemcpyHtoD(mem, host, size))
335                 cuda_pop_context();
336         }
337
338         void tex_alloc(const char *name, device_memory& mem, bool interpolation, bool periodic)
339         {
340                 /* determine format */
341                 CUarray_format_enum format;
342                 size_t dsize = datatype_size(mem.data_type);
343                 size_t size = mem.memory_size();
344
345                 switch(mem.data_type) {
346                         case TYPE_UCHAR: format = CU_AD_FORMAT_UNSIGNED_INT8; break;
347                         case TYPE_UINT: format = CU_AD_FORMAT_UNSIGNED_INT32; break;
348                         case TYPE_INT: format = CU_AD_FORMAT_SIGNED_INT32; break;
349                         case TYPE_FLOAT: format = CU_AD_FORMAT_FLOAT; break;
350                         default: assert(0); return;
351                 }
352
353                 CUtexref texref;
354
355                 cuda_push_context();
356                 cuda_assert(cuModuleGetTexRef(&texref, cuModule, name))
357
358                 if(interpolation) {
359                         CUarray handle;
360                         CUDA_ARRAY_DESCRIPTOR desc;
361
362                         desc.Width = mem.data_width;
363                         desc.Height = mem.data_height;
364                         desc.Format = format;
365                         desc.NumChannels = mem.data_elements;
366
367                         cuda_assert(cuArrayCreate(&handle, &desc))
368
369                         if(mem.data_height > 1) {
370                                 CUDA_MEMCPY2D param;
371                                 memset(&param, 0, sizeof(param));
372                                 param.dstMemoryType = CU_MEMORYTYPE_ARRAY;
373                                 param.dstArray = handle;
374                                 param.srcMemoryType = CU_MEMORYTYPE_HOST;
375                                 param.srcHost = (void*)mem.data_pointer;
376                                 param.srcPitch = mem.data_width*dsize*mem.data_elements;
377                                 param.WidthInBytes = param.srcPitch;
378                                 param.Height = mem.data_height;
379
380                                 cuda_assert(cuMemcpy2D(&param))
381                         }
382                         else
383                                 cuda_assert(cuMemcpyHtoA(handle, 0, (void*)mem.data_pointer, size))
384
385                         cuda_assert(cuTexRefSetArray(texref, handle, CU_TRSA_OVERRIDE_FORMAT))
386
387                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_LINEAR))
388                         cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_NORMALIZED_COORDINATES))
389
390                         mem.device_pointer = (device_ptr)handle;
391                 }
392                 else {
393                         cuda_pop_context();
394
395                         mem_alloc(mem, MEM_READ_ONLY);
396                         mem_copy_to(mem);
397
398                         cuda_push_context();
399
400                         cuda_assert(cuTexRefSetAddress(NULL, texref, cuda_device_ptr(mem.device_pointer), size))
401                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_POINT))
402                         cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_READ_AS_INTEGER))
403                 }
404
405                 if(periodic) {
406                         cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_WRAP))
407                         cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_WRAP))
408                 }
409                 else {
410                         cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_CLAMP))
411                         cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_CLAMP))
412                 }
413                 cuda_assert(cuTexRefSetFormat(texref, format, mem.data_elements))
414
415                 cuda_pop_context();
416
417                 tex_interp_map[mem.device_pointer] = interpolation;
418         }
419
420         void tex_free(device_memory& mem)
421         {
422                 if(mem.device_pointer) {
423                         if(tex_interp_map[mem.device_pointer]) {
424                                 cuda_push_context();
425                                 cuArrayDestroy((CUarray)mem.device_pointer);
426                                 cuda_pop_context();
427
428                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
429                                 mem.device_pointer = 0;
430                         }
431                         else {
432                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
433                                 mem_free(mem);
434                         }
435                 }
436         }
437
438         void path_trace(DeviceTask& task)
439         {
440                 cuda_push_context();
441
442                 CUfunction cuPathTrace;
443                 CUdeviceptr d_buffer = cuda_device_ptr(task.buffer);
444                 CUdeviceptr d_rng_state = cuda_device_ptr(task.rng_state);
445
446                 /* get kernel function */
447                 cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_path_trace"))
448                 
449                 /* pass in parameters */
450                 int offset = 0;
451                 
452                 cuda_assert(cuParamSetv(cuPathTrace, offset, &d_buffer, sizeof(d_buffer)))
453                 offset += sizeof(d_buffer);
454
455                 cuda_assert(cuParamSetv(cuPathTrace, offset, &d_rng_state, sizeof(d_rng_state)))
456                 offset += sizeof(d_rng_state);
457
458                 int sample = task.sample;
459                 offset = cuda_align_up(offset, __alignof(sample));
460
461                 cuda_assert(cuParamSeti(cuPathTrace, offset, task.sample))
462                 offset += sizeof(task.sample);
463
464                 cuda_assert(cuParamSeti(cuPathTrace, offset, task.x))
465                 offset += sizeof(task.x);
466
467                 cuda_assert(cuParamSeti(cuPathTrace, offset, task.y))
468                 offset += sizeof(task.y);
469
470                 cuda_assert(cuParamSeti(cuPathTrace, offset, task.w))
471                 offset += sizeof(task.w);
472
473                 cuda_assert(cuParamSeti(cuPathTrace, offset, task.h))
474                 offset += sizeof(task.h);
475
476                 cuda_assert(cuParamSetSize(cuPathTrace, offset))
477
478                 /* launch kernel: todo find optimal size, cache config for fermi */
479 #ifndef __APPLE__
480                 int xthreads = 16;
481                 int ythreads = 16;
482 #else
483                 int xthreads = 8;
484                 int ythreads = 8;
485 #endif
486                 int xblocks = (task.w + xthreads - 1)/xthreads;
487                 int yblocks = (task.h + ythreads - 1)/ythreads;
488
489                 cuda_assert(cuFuncSetCacheConfig(cuPathTrace, CU_FUNC_CACHE_PREFER_L1))
490                 cuda_assert(cuFuncSetBlockShape(cuPathTrace, xthreads, ythreads, 1))
491                 cuda_assert(cuLaunchGrid(cuPathTrace, xblocks, yblocks))
492
493                 cuda_pop_context();
494         }
495
496         void tonemap(DeviceTask& task)
497         {
498                 cuda_push_context();
499
500                 CUfunction cuFilmConvert;
501                 CUdeviceptr d_rgba = map_pixels(task.rgba);
502                 CUdeviceptr d_buffer = cuda_device_ptr(task.buffer);
503
504                 /* get kernel function */
505                 cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_tonemap"))
506
507                 /* pass in parameters */
508                 int offset = 0;
509
510                 cuda_assert(cuParamSetv(cuFilmConvert, offset, &d_rgba, sizeof(d_rgba)))
511                 offset += sizeof(d_rgba);
512                 
513                 cuda_assert(cuParamSetv(cuFilmConvert, offset, &d_buffer, sizeof(d_buffer)))
514                 offset += sizeof(d_buffer);
515
516                 int sample = task.sample;
517                 offset = cuda_align_up(offset, __alignof(sample));
518
519                 cuda_assert(cuParamSeti(cuFilmConvert, offset, task.sample))
520                 offset += sizeof(task.sample);
521
522                 cuda_assert(cuParamSeti(cuFilmConvert, offset, task.resolution))
523                 offset += sizeof(task.resolution);
524
525                 cuda_assert(cuParamSeti(cuFilmConvert, offset, task.x))
526                 offset += sizeof(task.x);
527
528                 cuda_assert(cuParamSeti(cuFilmConvert, offset, task.y))
529                 offset += sizeof(task.y);
530
531                 cuda_assert(cuParamSeti(cuFilmConvert, offset, task.w))
532                 offset += sizeof(task.w);
533
534                 cuda_assert(cuParamSeti(cuFilmConvert, offset, task.h))
535                 offset += sizeof(task.h);
536
537                 cuda_assert(cuParamSetSize(cuFilmConvert, offset))
538
539                 /* launch kernel: todo find optimal size, cache config for fermi */
540 #ifndef __APPLE__
541                 int xthreads = 16;
542                 int ythreads = 16;
543 #else
544                 int xthreads = 8;
545                 int ythreads = 8;
546 #endif
547                 int xblocks = (task.w + xthreads - 1)/xthreads;
548                 int yblocks = (task.h + ythreads - 1)/ythreads;
549
550                 cuda_assert(cuFuncSetCacheConfig(cuFilmConvert, CU_FUNC_CACHE_PREFER_L1))
551                 cuda_assert(cuFuncSetBlockShape(cuFilmConvert, xthreads, ythreads, 1))
552                 cuda_assert(cuLaunchGrid(cuFilmConvert, xblocks, yblocks))
553
554                 unmap_pixels(task.rgba);
555
556                 cuda_pop_context();
557         }
558
559         void displace(DeviceTask& task)
560         {
561                 cuda_push_context();
562
563                 CUfunction cuDisplace;
564                 CUdeviceptr d_input = cuda_device_ptr(task.displace_input);
565                 CUdeviceptr d_offset = cuda_device_ptr(task.displace_offset);
566
567                 /* get kernel function */
568                 cuda_assert(cuModuleGetFunction(&cuDisplace, cuModule, "kernel_cuda_displace"))
569                 
570                 /* pass in parameters */
571                 int offset = 0;
572                 
573                 cuda_assert(cuParamSetv(cuDisplace, offset, &d_input, sizeof(d_input)))
574                 offset += sizeof(d_input);
575
576                 cuda_assert(cuParamSetv(cuDisplace, offset, &d_offset, sizeof(d_offset)))
577                 offset += sizeof(d_offset);
578
579                 int displace_x = task.displace_x;
580                 offset = cuda_align_up(offset, __alignof(displace_x));
581
582                 cuda_assert(cuParamSeti(cuDisplace, offset, task.displace_x))
583                 offset += sizeof(task.displace_x);
584
585                 cuda_assert(cuParamSetSize(cuDisplace, offset))
586
587                 /* launch kernel: todo find optimal size, cache config for fermi */
588 #ifndef __APPLE__
589                 int xthreads = 16;
590 #else
591                 int xthreads = 8;
592 #endif
593                 int xblocks = (task.displace_w + xthreads - 1)/xthreads;
594
595                 cuda_assert(cuFuncSetCacheConfig(cuDisplace, CU_FUNC_CACHE_PREFER_L1))
596                 cuda_assert(cuFuncSetBlockShape(cuDisplace, xthreads, 1, 1))
597                 cuda_assert(cuLaunchGrid(cuDisplace, xblocks, 1))
598
599                 cuda_pop_context();
600         }
601
602         CUdeviceptr map_pixels(device_ptr mem)
603         {
604                 if(!background) {
605                         PixelMem pmem = pixel_mem_map[mem];
606                         CUdeviceptr buffer;
607                         
608                         size_t bytes;
609                         cuda_assert(cuGraphicsMapResources(1, &pmem.cuPBOresource, 0))
610                         cuda_assert(cuGraphicsResourceGetMappedPointer(&buffer, &bytes, pmem.cuPBOresource))
611                         
612                         return buffer;
613                 }
614
615                 return cuda_device_ptr(mem);
616         }
617
618         void unmap_pixels(device_ptr mem)
619         {
620                 if(!background) {
621                         PixelMem pmem = pixel_mem_map[mem];
622
623                         cuda_assert(cuGraphicsUnmapResources(1, &pmem.cuPBOresource, 0))
624                 }
625         }
626
627         void pixels_alloc(device_memory& mem)
628         {
629                 if(!background) {
630                         PixelMem pmem;
631
632                         pmem.w = mem.data_width;
633                         pmem.h = mem.data_height;
634
635                         cuda_push_context();
636
637                         glGenBuffers(1, &pmem.cuPBO);
638                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
639                         glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(GLfloat)*3, NULL, GL_DYNAMIC_DRAW);
640                         
641                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
642                         
643                         glGenTextures(1, &pmem.cuTexId);
644                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
645                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pmem.w, pmem.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
646                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
647                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
648                         glBindTexture(GL_TEXTURE_2D, 0);
649                         
650                         cuda_assert(cuGraphicsGLRegisterBuffer(&pmem.cuPBOresource, pmem.cuPBO, CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE))
651
652                         cuda_pop_context();
653
654                         mem.device_pointer = pmem.cuTexId;
655                         pixel_mem_map[mem.device_pointer] = pmem;
656
657                         return;
658                 }
659
660                 Device::pixels_alloc(mem);
661         }
662
663         void pixels_copy_from(device_memory& mem, int y, int w, int h)
664         {
665                 if(!background) {
666                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
667
668                         cuda_push_context();
669
670                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
671                         uchar *pixels = (uchar*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_ONLY);
672                         size_t offset = sizeof(uchar)*4*y*w;
673                         memcpy((uchar*)mem.data_pointer + offset, pixels + offset, sizeof(uchar)*4*w*h);
674                         glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
675                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
676
677                         cuda_pop_context();
678
679                         return;
680                 }
681
682                 Device::pixels_copy_from(mem, y, w, h);
683         }
684
685         void pixels_free(device_memory& mem)
686         {
687                 if(mem.device_pointer) {
688                         if(!background) {
689                                 PixelMem pmem = pixel_mem_map[mem.device_pointer];
690
691                                 cuda_push_context();
692
693                                 cuda_assert(cuGraphicsUnregisterResource(pmem.cuPBOresource))
694                                 glDeleteBuffers(1, &pmem.cuPBO);
695                                 glDeleteTextures(1, &pmem.cuTexId);
696
697                                 cuda_pop_context();
698
699                                 pixel_mem_map.erase(pixel_mem_map.find(mem.device_pointer));
700                                 mem.device_pointer = 0;
701
702                                 return;
703                         }
704
705                         Device::pixels_free(mem);
706                 }
707         }
708
709         void draw_pixels(device_memory& mem, int y, int w, int h, int width, int height, bool transparent)
710         {
711                 if(!background) {
712                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
713
714                         cuda_push_context();
715
716                         /* for multi devices, this assumes the ineffecient method that we allocate
717                            all pixels on the device even though we only render to a subset */
718                         size_t offset = sizeof(uint8_t)*4*y*w;
719
720                         glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pmem.cuPBO);
721                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
722                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, (void*)offset);
723                         glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
724                         
725                         glEnable(GL_TEXTURE_2D);
726                         
727                         if(transparent) {
728                                 glEnable(GL_BLEND);
729                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
730                         }
731
732                         glColor3f(1.0f, 1.0f, 1.0f);
733
734                         glPushMatrix();
735                         glTranslatef(0.0f, (float)y, 0.0f);
736                                 
737                         glBegin(GL_QUADS);
738                         
739                         glTexCoord2f(0.0f, 0.0f);
740                         glVertex2f(0.0f, 0.0f);
741                         glTexCoord2f((float)w/(float)pmem.w, 0.0f);
742                         glVertex2f((float)width, 0.0f);
743                         glTexCoord2f((float)w/(float)pmem.w, (float)h/(float)pmem.h);
744                         glVertex2f((float)width, (float)height);
745                         glTexCoord2f(0.0f, (float)h/(float)pmem.h);
746                         glVertex2f(0.0f, (float)height);
747
748                         glEnd();
749
750                         glPopMatrix();
751
752                         if(transparent)
753                                 glDisable(GL_BLEND);
754                         
755                         glBindTexture(GL_TEXTURE_2D, 0);
756                         glDisable(GL_TEXTURE_2D);
757
758                         cuda_pop_context();
759
760                         return;
761                 }
762
763                 Device::draw_pixels(mem, y, w, h, width, height, transparent);
764         }
765
766         void task_add(DeviceTask& task)
767         {
768                 if(task.type == DeviceTask::TONEMAP)
769                         tonemap(task);
770                 else if(task.type == DeviceTask::PATH_TRACE)
771                         path_trace(task);
772                 else if(task.type == DeviceTask::DISPLACE)
773                         displace(task);
774         }
775
776         void task_wait()
777         {
778                 cuda_push_context();
779
780                 cuda_assert(cuCtxSynchronize())
781
782                 cuda_pop_context();
783         }
784
785         void task_cancel()
786         {
787         }
788 };
789
790 Device *device_cuda_create(bool background)
791 {
792         return new CUDADevice(background);
793 }
794
795 CCL_NAMESPACE_END
796