我做的对吗?我基本上想执行某种void方法。

public abstract class Uniforms {
    public static void setUniformMatrix4(final UniformLocation uniformLocation, final boolean transpose, final Matrix4f matrix4f) {
        setUniformImpl(uniformLocation, u -> GL20.glUniformMatrix4(uniformLocation.getLocation(), transpose, matrix4f.asFloatBuffer()));
    }

    public static void setUniformMatrix4(final UniformLocation uniformLocation, final boolean transpose, final FloatBuffer matrix4fFloatBuffer) {
        setUniformImpl(uniformLocation, u -> GL20.glUniformMatrix4(uniformLocation.getLocation(), transpose, matrix4fFloatBuffer));
    }

    public static void setUniform(final UniformLocation uniformLocation, final float value) {
        setUniformImpl(uniformLocation, u -> GL20.glUniform1f(uniformLocation.getLocation(), value));
    }

    public static void setUniform(final UniformLocation uniformLocation, final int value) {
        setUniformImpl(uniformLocation, u -> GL20.glUniform1i(uniformLocation.getLocation(), value));
    }

    private static void setUniformImpl(final UniformLocation uniformLocation, final Consumer<UniformLocation> consumer) {
        Program oldProgram = Program.getUsing();
        for (Program program : Program.getPrograms()) {
            if (program.usesUniform(uniformLocation)) {
                program.use();
                consumer.accept(uniformLocation);
            }
        }
        if (oldProgram != null) {
            oldProgram.use();
        }
    }
}

最佳答案

如果您的程序可以编译并提供您期望的输出,那么从这个意义上讲,它是正确的。不过可以澄清一下。

四个公共重载都带有一个UniformLocation参数,然后将其传递给setUniformImpl方法。然后,此方法调用使用者并将其传递给uniformLocation ...,然后将其忽略。在lambda中对GL2.glUniform*方法的调用全部捕获uniformLocation而不是使用u参数。您可以将Consumer替换为Runnable

或者,您可以将Consumer的类型更改为Uniform.getLocation()的返回值,然后将这些调用中的每一个提取到setUniformImpl中,并将结果作为arg传递给consumer.accept。那会简化事情。你最终会得到类似的东西,

public static void setUniform(final UniformLocation uniformLocation, final int value) {
    setUniformImpl(uniformLocation, u -> GL20.glUniform1i(u, value));
}

private static void setUniformImpl(final UniformLocation uniformLocation, final Consumer<Location> consumer) {
    ...
    consumer.accept(uniformLocation.getLocation());
    ...
}

08-07 04:01