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

@ -164,6 +164,8 @@ type Shader struct {
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{}
}
names := map[string]index{}
var idx int var idx int
for i, n := range s.uniformNames { for i, n := range s.uniformNames {
if strings.HasPrefix(n, "__") { if strings.HasPrefix(n, "__") {
continue continue
} }
names[n] = index{ s.uniformNameToIndex[n] = idx
resultIndex: idx, s.uniformNameToType[n] = s.uniformTypes[i]
shaderUniformIndex: i,
}
idx++ idx++
} }
}
us := make([][]float32, len(names)) us := make([][]float32, len(s.uniformNameToIndex))
for name, idx := range names { for name, idx := range s.uniformNameToIndex {
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