internal/graphicscommand: cache uniform name locations and types

This commit is contained in:
Hajime Hoshi 2022-04-03 03:28:11 +09:00
parent 9be454ef25
commit 990228e216

View File

@ -162,8 +162,10 @@ func __vertex(position vec2, texCoord vec2, color vec4) (vec4, vec2, vec4) {
type Shader struct { type Shader struct {
shader graphicsdriver.Shader shader graphicsdriver.Shader
uniformNames []string uniformNames []string
uniformTypes []shaderir.Type uniformTypes []shaderir.Type
uniformNameToIndex map[string]int
uniformNameToType map[string]shaderir.Type
} }
func NewShader(src []byte) *Shader { func NewShader(src []byte) *Shader {
@ -188,40 +190,36 @@ func (s *Shader) convertUniforms(uniforms map[string]interface{}) [][]float32 {
panic("graphicscommand: shader is not compiled yet") panic("graphicscommand: shader is not compiled yet")
} }
type index struct { if s.uniformNameToIndex == nil {
resultIndex int s.uniformNameToIndex = map[string]int{}
shaderUniformIndex int s.uniformNameToType = map[string]shaderir.Type{}
var idx int
for i, n := range s.uniformNames {
if strings.HasPrefix(n, "__") {
continue
}
s.uniformNameToIndex[n] = idx
s.uniformNameToType[n] = s.uniformTypes[i]
idx++
}
} }
names := map[string]index{} us := make([][]float32, len(s.uniformNameToIndex))
var idx int for name, idx := range s.uniformNameToIndex {
for i, n := range s.uniformNames {
if strings.HasPrefix(n, "__") {
continue
}
names[n] = index{
resultIndex: idx,
shaderUniformIndex: i,
}
idx++
}
us := make([][]float32, len(names))
for name, idx := range names {
if v, ok := uniforms[name]; ok { if v, ok := uniforms[name]; ok {
switch v := v.(type) { switch v := v.(type) {
case float32: case float32:
us[idx.resultIndex] = []float32{v} us[idx] = []float32{v}
case []float32: case []float32:
us[idx.resultIndex] = v us[idx] = v
default: default:
panic(fmt.Sprintf("graphicscommand: unexpected uniform value type: %s, %T", name, v)) panic(fmt.Sprintf("graphicscommand: unexpected uniform value type: %s, %T", name, v))
} }
continue continue
} }
t := s.uniformNameToType[name]
t := s.uniformTypes[idx.shaderUniformIndex] us[idx] = make([]float32, t.FloatNum())
us[idx.resultIndex] = make([]float32, t.FloatNum())
} }
// TODO: Panic if uniforms include an invalid name // TODO: Panic if uniforms include an invalid name