代码(注释持续更新中):
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "cpu_bitmap.h"
#include "book.h"
#include <stdio.h>
#define DIM 1000
#define R1 214 //底色,根据自己喜好输入颜色RGB值
#define G1 163
#define B1 220
#define R2 247 //Julia集颜色,根据自己喜好输入颜色RGB值
#define G2 219
#define B2 112
struct cuComplex//复数结构体
{
float r;
float i;
__device__ cuComplex(float a, float b) : r(a), i(b) {}
__device__ float magnitude2(void) {
return r * r + i * i;
}
__device__ cuComplex operator*(const cuComplex& a) {
return cuComplex(r * a.r - i * a.i, i * a.r + r * a.i);
}
__device__ cuComplex operator+(const cuComplex& a) {
return cuComplex(r + a.r, i + a.i);
}
};
__device__ int julia(int x, int y) {
const float scale = 1.5;
float jx = scale * (float)(DIM / 2 - x) / (DIM / 2);
float jy = scale * (float)(DIM / 2 - y) / (DIM / 2);
cuComplex c(-0.8, 0.156);
cuComplex a(jx, jy);
for (int i = 0; i < 200; ++i) {
a = a * a + c;
//该点发散,不在Julia集中
if (a.magnitude2() > 1000) return 0;
}
return 1;//该点在Julia集中
}
__global__ void Kernel(unsigned char* ptr)
{
int x = blockIdx.x;
int y = blockIdx.y;
int offset = x + y * gridDim.x;
int juliaValue = julia(x, y);
//RGB1是底色,RGB2是Julia集中的点的颜色
ptr[offset * 4 + 0] = R1 + (R2-R1)*juliaValue;//R
ptr[offset * 4 + 1] = G1 + (G2-G1)*juliaValue;//G
ptr[offset * 4 + 2] = B1 + (B2-B1)*juliaValue;//B
//位图中每个像素的RGB保存在一个二维数组
//为了凑整,使用4个字节存储一个RGB
//第四个字节不使用,无效,可管理可不管理
//ptr[offset * 4 + 3] = 255;
}
int main()
{
CPUBitmap bitmap(DIM, DIM);
unsigned char* dev_bitmap;
HANDLE_ERROR(cudaMalloc((void**)&dev_bitmap, bitmap.image_size()));
dim3 grid(DIM, DIM);
Kernel << <grid, 1 >> > (dev_bitmap);
HANDLE_ERROR(cudaMemcpy(bitmap.get_ptr(), dev_bitmap,
bitmap.image_size(),
cudaMemcpyDeviceToHost));
bitmap.display_and_exit();
return 0;
}
本代码中配色方案运行效果如图