所以我想在我的基于像素的渲染系统中实现照明,用谷歌搜索并发现要显示更亮或更暗的 R/G/B 值我必须将每个红色绿色和蓝色值乘以一个数字 1 显示更亮。所以我是这样实现的,但它确实拖累了我的性能,因为我必须对每个像素都这样做:void PixelRenderer::applyLight(Uint32& color){ Uint32 alpha = color >> 24; alpha << 24; alpha >> 24; Uint32 red = color >> 16; red = red << 24; red = red >> 24; Uint32 green = color >> 8; green = green << 24; green = green >> 24; Uint32 blue = color; blue = blue << 24; blue = blue >> 24; red = red * 0.5; green = green * 0.5; blue = blue * 0.5; color = alpha << 24 | red << 16 | green << 8 | blue;}关于如何提高速度的任何想法或示例? 最佳答案 要保留前面的 alpha 值,请使用:(color>>1)&0x7F7F7F | (color&0xFF000000)(对 Wimmel 在评论中提供的内容进行了调整)。我认为这里的“学习曲线”是您使用 shift 和 shift back 来掩盖位。您应该使用带有掩码值的 &。对于更通用的解决方案(其中 0.0<=factor<=1.0 ):void PixelRenderer::applyLight(Uint32& color, double factor){ Uint32 alpha=color&0xFF000000; Uint32 red= (color&0x00FF0000)*factor; Uint32 green= (color&0x0000FF00)*factor; Uint32 blue=(color&0x000000FF)*factor; color=alpha|(red&0x00FF0000)|(green&0x0000FF00)|(blue&0x000000FF);}请注意,在执行乘法之前不需要将组件向下移动到低位。最终您可能会发现瓶颈在于浮点转换和算术。为了减少这种情况,您应该考虑: 将其减少到一个比例因子,例如在 0-256 范围内。 将 factor*component 预计算为 256 个元素的数组,然后“挑选”出组件。 我建议的范围为 257,因为您可以按如下方式实现该系数:对于更通用的解决方案(其中 0<=factor<=256 ):void PixelRenderer::applyLight(Uint32& color, Uint32 factor){ Uint32 alpha=color&0xFF000000; Uint32 red= ((color&0x00FF0000)*factor)>>8; Uint32 green= ((color&0x0000FF00)*factor)>>8; Uint32 blue=((color&0x000000FF)*factor)>>8; color=alpha|(red&0x00FF0000)|(green&0x0000FF00)|(blue&0x000000FF);}这是一个可运行的程序,用于说明第一个示例:#include <stdio.h>#include <inttypes.h>typedef uint32_t Uint32;Uint32 make(Uint32 alpha,Uint32 red,Uint32 green,Uint32 blue){ return (alpha<<24)|(red<<16)|(green<<8)|blue;}void output(Uint32 color){ printf("alpha=%"PRIu32" red=%"PRIu32" green=%"PRIu32" blue=%"PRIu32"\n",(color>>24),(color&0xFF0000)>>16,(color&0xFF00)>>8,color&0xFF);}Uint32 applyLight(Uint32 color, double factor){ Uint32 alpha=color&0xFF000000; Uint32 red= (color&0x00FF0000)*factor; Uint32 green= (color&0x0000FF00)*factor; Uint32 blue=(color&0x000000FF)*factor; return alpha|(red&0x00FF0000)|(green&0x0000FF00)|(blue&0x000000FF);}int main(void) { Uint32 color1=make(156,100,50,20); Uint32 result1=applyLight(color1,0.9); output(result1); Uint32 color2=make(255,255,255,255); Uint32 result2=applyLight(color2,0.1); output(result2); Uint32 color3=make(78,220,200,100); Uint32 result3=applyLight(color3,0.05); output(result3); return 0;}预期输出为:alpha=156 red=90 green=45 blue=18alpha=255 red=25 green=25 blue=25alpha=78 red=11 green=10 blue=5关于c++ - 如何最有效地修改 R/G/B 值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28394611/
10-11 22:37