首页 > 解决方案 > glsl - 我可以将常量传递给函数而不将常量复制到参数中吗?

问题描述

我有一个 glsl 函数,它可以接受几个 const 数组之一,并使用该数组中的信息进行一些操作。例如:

const uint A[] = { /* 10 values here */ };
const uint B[] = { /* 10 different values here */ };
const uint C[] = { /* 10 different values here */ };

float doSomethingWithArray(const uint arr[10], float x){
  // do some operations which use the constant array and a non-constant value. Eg:
  uint a = arr[floor(x)];
  uint b = arr[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}

如果我要调用这个函数,将其中一个常量数组作为参数传递doSomethingWithArray(A, 5.0),我担心数组会被复制到参数中,从而减慢程序的速度。

https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#Parameters

调用函数时,传递给函数的值被复制到参数中

这让我认为拥有 3 个单独的函数会更快,每个函数都使用不同的常量数组。这样,就不必复制数组。例如:

float doSomethingWithA(float x){
  uint a = A[floor(x)];
  uint b = A[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}
float doSomethingWithB(float x){
  uint a = B[floor(x)];
  uint b = B[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}
float doSomethingWithC(float x){
  uint a = C[floor(x)];
  uint b = C[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}

但是,这会导致大量重复代码,尤其是在有更多常量数组的情况下。有没有办法在不复制数组且不重复代码的情况下执行此操作?

我正在使用 glslc 编译为 .spv。

标签: glslvulkan

解决方案


不使用 Vulcan 作为我的 gfx 卡不支持它,但在 GLSL 中,我可以随意使用宏作为函数,而不是像这样:

#define doSomethingWithArray(arr,x) ((arr[arr[floor(x)]] * 2 + 3 + arr[floor(x)]) * x)

宏将为您硬编码 3 个实例......这里有一个例子(片段着色器):

#version 420 core
out layout(location=0) vec4 col;
#define test(arr,x) ((arr[arr[int(floor(x))]] * 2 + 3 + arr[int(floor(x))]) * x)
const uint A[]={0,1,2,3,4,5,6,7,8,9};
const uint B[]={1,2,3,4,5,6,7,8,9,0};
const uint C[]={2,3,4,5,6,7,8,9,0,1};
void main()
    {
    float x=3.75;
    col=vec4(test(A,x),test(B,x),test(C,x),1.0);
    }

#version 420 core是第一个不会对您在我的 nVidia 上使用的东西(如 const 数组等)抛出大量警告和错误的版本


推荐阅读