|
| 1 | +""" |
| 2 | + Shader Registry - drewcification 111420 |
| 3 | + Static class to register and get shaders |
| 4 | +
|
| 5 | + Shaders are registered at the games initialization |
| 6 | + from ott.ShaderRegistry import ShaderRegistry |
| 7 | + ShaderRegistry.register('render:black_and_white', |
| 8 | + frag = 'phase_3/shaders/tt_sha_render_bandw.frag', |
| 9 | + vert = 'phase_3/shaders/tt_sha_render_bandw.vert') |
| 10 | +
|
| 11 | + They can be retrieved at any point during runtime |
| 12 | + from ott.ShaderRegistry import ShaderRegistry |
| 13 | + render.setShader(ShaderRegistry.get('render:black_and_white')) |
| 14 | +""" |
| 15 | + |
| 16 | +from panda3d.core import Shader |
| 17 | + |
| 18 | + |
| 19 | +class ShaderRegistry: |
| 20 | + # Static shader dictionary |
| 21 | + shaders = {} |
| 22 | + |
| 23 | + @staticmethod |
| 24 | + def register(identifier: str, frag: str, vert: str): |
| 25 | + """ |
| 26 | + Register shader |
| 27 | +
|
| 28 | + All shaders must be in GLSL with separate .frag and .vert files! |
| 29 | +
|
| 30 | + Shader identifiers should be formatted by where they are used |
| 31 | +
|
| 32 | + e.g.: |
| 33 | + Full scene render effects are prefixed with 'render:' |
| 34 | + CheesyEffects are prefixed with 'ce:' |
| 35 | + Make-A-Toon shaders are prefixed with 'mat:' |
| 36 | + etc. |
| 37 | +
|
| 38 | + :param identifier: Identifier string |
| 39 | + :param frag: Fragment shader file path |
| 40 | + :param vert: Vertex shader file path |
| 41 | + """ |
| 42 | + shader = Shader.load(Shader.SL_GLSL, fragment = frag, vertex = vert) |
| 43 | + ShaderRegistry.shaders[identifier] = shader |
| 44 | + print(f'Registered shader {identifier}') |
| 45 | + |
| 46 | + @staticmethod |
| 47 | + def get(identifier: str) -> Shader: |
| 48 | + """ |
| 49 | + Returns loaded shader |
| 50 | +
|
| 51 | + :param identifier: |
| 52 | + :return: Shader |
| 53 | + """ |
| 54 | + |
| 55 | + # Raise an exception if we load a shader we haven't registered yet |
| 56 | + if identifier not in ShaderRegistry.shaders: |
| 57 | + raise NotInRegistryError(identifier) |
| 58 | + |
| 59 | + return ShaderRegistry.shaders.get(identifier) |
| 60 | + |
| 61 | + |
| 62 | +class NotInRegistryError(Exception): |
| 63 | + def __init__(self, identifier: str): |
| 64 | + self.identifier = identifier |
| 65 | + |
| 66 | + def __str__(self): |
| 67 | + return f'identifier {self.identifier} not in registry' |
0 commit comments