2017-05-26 101 views
0

当我想执行浮动的阵列上减少我通常做到以下几点:Cuda的推力 - 最大VEC3

float res = *thrust::max_element(thrust::device, 
      thrust::device_ptr<float>(dDensities), 
      thrust::device_ptr<float>(dDensities+numParticles) 
      ); 

但是我想现在做的是非常对VEC 3同样的事情(GLM的库类型)数组:

float res = *thrust::max_element(thrust::device, 
      thrust::device_ptr<glm::vec3>(dDensities), 
      thrust::device_ptr<glm::vec3>(dDensities+numParticles) 
      ); 

正如你所看到的,这有因为“<”运营商未在规定毫无意义。但我想根据他的长度得到最大的vec3:

len = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); 

这可能吗?

回答

1

是的,它的可能性。如果您不熟悉它,您可能需要阅读thrust quickstart guide

如果您查看thrust extrema documentation,您会注意到thrust::max_element有几种不同的品种(就像大多数推力算法一样)。其中一个接受二进制比较函子。我们可以定义一个比较函数,它可以做你想做的事情。

这里有一个简单的样例:

$ cat t134.cu 
#include <thrust/extrema.h> 
#include <thrust/device_ptr.h> 
#include <glm/glm.hpp> 
#include <iostream> 

struct comp 
{ 
template <typename T> 
__host__ __device__ 
bool operator()(T &t1, T &t2){ 
    return ((t1.x*t1.x+t1.y*t1.y+t1.z*t1.z) < (t2.x*t2.x+t2.y*t2.y+t2.z*t2.z)); 
    } 
}; 

int main(){ 

    int numParticles = 3; 
    glm::vec3 d[numParticles]; 
    d[0].x = 0; d[0].y = 0; d[0].z = 0; 
    d[1].x = 2; d[1].y = 2; d[1].z = 2; 
    d[2].x = 1; d[2].y = 1; d[2].z = 1; 

    glm::vec3 *dDensities; 
    cudaMalloc(&dDensities, numParticles*sizeof(glm::vec3)); 
    cudaMemcpy(dDensities, d, numParticles*sizeof(glm::vec3), cudaMemcpyHostToDevice); 
    glm::vec3 res = *thrust::max_element(thrust::device, 
      thrust::device_ptr<glm::vec3>(dDensities), 
      thrust::device_ptr<glm::vec3>(dDensities+numParticles), 
      comp() 
      ); 
    std::cout << "max element x: " << res.x << " y: " << res.y << " z: " << res.z << std::endl; 
} 
$ nvcc -arch=sm_61 -o t134 t134.cu 
$ ./t134 
max element x: 2 y: 2 z: 2 
$