zoukankan      html  css  js  c++  java
  • cuda编程学习5——波纹ripple

    /共有DIM×DIM个像素,每个像素对应一个线程
    dim3 blocks(DIM/16,DIM/16);//2维
    dim3 threads(16,16);//2维
    kernel<<<blocks,threads>>>(d->dev_bitmap,ticks);

    代码:

    /*
    ============================================================================
    Name : ripple.cu
    Author : can
    Version :
    Copyright : Your copyright notice
    Description : CUDA compute reciprocals
    ============================================================================
    */

    #include <iostream>
    #include <math.h>
    #include"cpu_anim.h"
    using namespace std;

    static void CheckCudaErrorAux (const char *, unsigned, const char *, cudaError_t);
    #define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__,__LINE__, #value, value)
    #define DIM 160

    struct DataBlock
    {
    unsigned char *dev_bitmap;
    CPUAnimBitmap *bitmap;
    };
    void cleanup(DataBlock *d)
    {
    cudaFree(d->dev_bitmap);
    }
    void generate_frame(DataBlock *d,int ticks);
    __global__ void kernel(unsigned char *ptr,int ticks)
    {
    //将threadId和blockId映射到像素位置
    int x=threadIdx.x+blockIdx.x*blockDim.x;
    int y=threadIdx.y+blockIdx.y*blockDim.y;
    int offset=x+y*blockDim.x*gridDim.x;
    float fx=x-DIM/2;
    float fy=y-DIM/2;
    float d=sqrtf(fx*fx+fy*fy);
    unsigned char grey=(unsigned char)(128.0f+127.0f*cos(d/10.0f-ticks/7.0f)/(d/10.0f+1.0f));
    ptr[offset*4+0]=grey;
    ptr[offset*4+1]=grey;
    ptr[offset*4+2]=grey;
    ptr[offset*4+3]=255;
    }
    int main()
    {
    DataBlock data;
    CPUAnimBitmap bitmap(DIM,DIM,&data);
    data.bitmap = &bitmap;
    CUDA_CHECK_RETURN(cudaMalloc((void **)&data.dev_bitmap,bitmap.image_size()));
    bitmap.anim_and_exit((void (*)(void*,int))generate_frame,(void (*)(void*))cleanup);
    }
    void generate_frame(DataBlock *d,int ticks)
    {
    //共有DIM×DIM个像素,每个像素对应一个线程
    dim3 blocks(DIM/16,DIM/16);//2维
    dim3 threads(16,16);//2维
    kernel<<<blocks,threads>>>(d->dev_bitmap,ticks);
    CUDA_CHECK_RETURN(cudaMemcpy(d->bitmap->get_ptr(),d->dev_bitmap,d->bitmap->image_size(),cudaMemcpyDeviceToHost));
    }
    static void CheckCudaErrorAux (const char *file, unsigned line, const char *statement, cudaError_t err)
    {
    if (err == cudaSuccess)
    return;
    std::cerr << statement<<" returned " << cudaGetErrorString(err) << "("<<err<< ") at "<<file<<":"<<line << std::endl;
    exit (1);
    }

  • 相关阅读:
    python模块--time模块
    python模块--如何相互调用自己写的模块
    Animating Views Using Scenes and Transitions
    fragment 切换
    android textview 设置text 字体
    android intent 5.1
    android EditView ime
    animation of android (4)
    animation of android (3)
    animation of android (2)
  • 原文地址:https://www.cnblogs.com/shrimp-can/p/5046486.html
Copyright © 2011-2022 走看看