1
0

shader.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2020 The Ebiten Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package atlas
  15. import (
  16. "runtime"
  17. "github.com/hajimehoshi/ebiten/v2/internal/restorable"
  18. "github.com/hajimehoshi/ebiten/v2/internal/shaderir"
  19. )
  20. type Shader struct {
  21. ir *shaderir.Program
  22. shader *restorable.Shader
  23. name string
  24. }
  25. func NewShader(ir *shaderir.Program, name string) *Shader {
  26. // A shader is initialized lazily, and the lock is not needed.
  27. return &Shader{
  28. ir: ir,
  29. name: name,
  30. }
  31. }
  32. func (s *Shader) finalize() {
  33. // A function from finalizer must not be blocked, but disposing operation can be blocked.
  34. // Defer this operation until it becomes safe. (#913)
  35. appendDeferred(func() {
  36. s.deallocate()
  37. })
  38. }
  39. func (s *Shader) ensureShader() *restorable.Shader {
  40. if s.shader != nil {
  41. return s.shader
  42. }
  43. s.shader = restorable.NewShader(s.ir, s.name)
  44. runtime.SetFinalizer(s, (*Shader).finalize)
  45. return s.shader
  46. }
  47. // Deallocate deallocates the internal state.
  48. func (s *Shader) Deallocate() {
  49. backendsM.Lock()
  50. defer backendsM.Unlock()
  51. if !inFrame {
  52. appendDeferred(func() {
  53. s.deallocate()
  54. })
  55. return
  56. }
  57. s.deallocate()
  58. }
  59. func (s *Shader) deallocate() {
  60. runtime.SetFinalizer(s, nil)
  61. if s.shader == nil {
  62. return
  63. }
  64. s.shader.Dispose()
  65. s.shader = nil
  66. }
  67. var (
  68. NearestFilterShader = &Shader{shader: restorable.NearestFilterShader}
  69. LinearFilterShader = &Shader{shader: restorable.LinearFilterShader}
  70. )