Skip to content

Commit

Permalink
Various type fixes and tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
einarf committed Oct 14, 2023
1 parent 991d231 commit 2a89ba0
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 44 deletions.
7 changes: 3 additions & 4 deletions moderngl_window/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import weakref

from pathlib import Path
from typing import List, Type
from typing import List, Type, Optional

import moderngl
from moderngl_window.context.base import WindowConfig, BaseWindow
Expand Down Expand Up @@ -60,9 +60,8 @@ def setup_basic_logging(level: int):

class ContextRefs:
"""Namespace for window/context references"""

WINDOW = None
CONTEXT = None
WINDOW: Optional[BaseWindow] = None
CONTEXT: Optional[moderngl.Context] = None


def activate_context(window: BaseWindow = None, ctx: moderngl.Context = None):
Expand Down
6 changes: 3 additions & 3 deletions moderngl_window/context/base/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging
import sys
import weakref
from typing import Any, Tuple, Type, List, Optional
from typing import Any, Tuple, Type, List, Optional, Dict

import moderngl
from moderngl_window.context.base import KeyModifiers, BaseKeys
Expand Down Expand Up @@ -1374,7 +1374,7 @@ def load_program(
tess_control_shader=None,
tess_evaluation_shader=None,
defines: dict = None,
varyings: List[str] = None,
varyings: Optional[List[str]] = None,
) -> moderngl.Program:
"""Loads a shader program.
Expand Down Expand Up @@ -1412,7 +1412,7 @@ def load_program(
)

def load_compute_shader(
self, path, defines: dict = None, **kwargs
self, path, defines: Optional[Dict] = None, **kwargs
) -> moderngl.ComputeShader:
"""Loads a compute shader.
Expand Down
2 changes: 1 addition & 1 deletion moderngl_window/loaders/scene/gltf2.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def load_glb(self):
version = struct.unpack("<I", fd.read(4))[0]
if version != 2:
raise ValueError(
"{} has unsupported version {}".format(self.path, version)
f"{self.path} has unsupported version {version}"
)

# Total file size including headers
Expand Down
2 changes: 1 addition & 1 deletion moderngl_window/loaders/texture/cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from moderngl_window.loaders.texture.pillow import PillowLoader, image_data
from moderngl_window.exceptions import ImproperlyConfigured

FaceInfo = namedtuple("FaceData", ["width", "height", "data", "components"])
FaceInfo = namedtuple("FaceInfo", ["width", "height", "data", "components"])


class Loader(PillowLoader):
Expand Down
22 changes: 11 additions & 11 deletions moderngl_window/meta/program.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List
from typing import List, Optional
from moderngl_window.meta.base import ResourceDescription


Expand Down Expand Up @@ -29,17 +29,17 @@ class ProgramDescription(ResourceDescription):

def __init__(
self,
path: str = None,
kind: str = None,
path: Optional[str] = None,
kind: Optional[str] = None,
reloadable=False,
vertex_shader: str = None,
geometry_shader: str = None,
fragment_shader: str = None,
tess_control_shader: str = None,
tess_evaluation_shader: str = None,
compute_shader: str = None,
defines: dict = None,
varyings: List = None,
vertex_shader: Optional[str] = None,
geometry_shader: Optional[str] = None,
fragment_shader: Optional[str] = None,
tess_control_shader: Optional[str] = None,
tess_evaluation_shader: Optional[str] = None,
compute_shader: Optional[str] = None,
defines: Optional[dict] = None,
varyings: Optional[List] = None,
**kwargs
):
"""Create a program description
Expand Down
45 changes: 22 additions & 23 deletions moderngl_window/opengl/program.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
Helper classes for loading shader
"""
from typing import List, Tuple, Union
from typing import List, Tuple, Union, Optional
import re

import moderngl
Expand All @@ -21,12 +21,12 @@ class ProgramShaders:

def __init__(self, meta: ProgramDescription):
self.meta = meta
self.vertex_source = None
self.geometry_source = None
self.fragment_source = None
self.tess_control_source = None
self.tess_evaluation_source = None
self.compute_shader_source = None
self.vertex_source: Optional[ShaderSource] = None
self.geometry_source: Optional[ShaderSource] = None
self.fragment_source: Optional[ShaderSource] = None
self.tess_control_source: Optional[ShaderSource] = None
self.tess_evaluation_source: Optional[ShaderSource] = None
self.compute_shader_source: Optional[ShaderSource] = None

@property
def ctx(self) -> moderngl.Context:
Expand Down Expand Up @@ -209,8 +209,8 @@ class ShaderSource:
"""
Helper class representing a single shader type.
It ensures the source has the right format, injects ``#define`` preprocessors,
resolves ``#include`` preprocessors etc.
It ensures the source has the right format, injects ``#define`` pre-processors,
resolves ``#include`` pre-processors etc.
A ``ShaderSource`` can be the base/root shader or a source referenced in an ``#include``.
"""
Expand Down Expand Up @@ -250,16 +250,14 @@ def __init__(
if self._root and not self._lines[0].startswith("#version"):
self.print()
raise ShaderError(
"Missing #version in {}. A version must be defined in the first line".format(
self._name
),
f"Missing #version in {self._name}. A version must be defined in the first line"
)

self.apply_defines(defines)

# Inject source with shade type
if self._root:
self._lines.insert(1, "#define {} 1".format(self._type))
self._lines.insert(1, f"#define {self._type} 1")
self._lines.insert(2, "#line 2")

@property
Expand Down Expand Up @@ -299,12 +297,13 @@ def defines(self) -> dict:

def handle_includes(self, load_source_func, depth=0, source_id=0):
"""Inject includes into the shader source.
This happens recursively up to a max level in case the users has circular includes.
We also build up a list of all the included sources in the root shader.
This happens recursively up to a max level in case the users has
circular includes. We also build up a list of all the included
sources in the root shader.
Args:
load_source_func (func): A function for finding and loading a source
depth (int): The current include depth (incease by 1 for every call)
depth (int): The current include depth (increase by 1 for every call)
"""
if depth > 100:
raise ShaderError(
Expand Down Expand Up @@ -351,7 +350,7 @@ def apply_defines(self, defines: dict):
if not value:
continue

self.lines[nr] = "#define {} {}".format(name, str(value))
self.lines[nr] = f"#define {name} {value}"
except IndexError:
pass

Expand All @@ -374,19 +373,19 @@ def find_out_attribs(self) -> List[str]:

def print(self):
"""Print the shader lines (for debugging)"""
print("---[ START {} ]---".format(self.name))
print(f"---[ START {self.name} ]---")

for i, line in enumerate(self.lines):
print("{}: {}".format(str(i).zfill(3), line))
print(f"{str(i).zfill(3)}: {line}")

print("---[ END {} ]---".format(self.name))
print("---[ END {self.name} ]---")

def __repr__(self):
return "<ShaderSource: {} id={}>".format(self.name, self.id)
return f"<ShaderSource: {self.name} id={self.id}>"


class ShaderError(Exception):
pass
"""Generic shader related error"""


class ReloadableProgram:
Expand Down Expand Up @@ -481,4 +480,4 @@ def geometry_vertices(self) -> int:
return self.program.geometry_vertices

def __repr__(self):
return "<ReloadableProgram: {} id={}>".format(self.name, self.glo)
return f"<ReloadableProgram: {self.name} id={self.glo}>"
2 changes: 1 addition & 1 deletion moderngl_window/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def _append_unique_path(path: Union[Path, str], dest: list):


@contextmanager
def temporary_dirs(dirs: Union[Path, str] = []):
def temporary_dirs(dirs: Union[Path, str]):
"""Temporarily changes all resource directories
Example::
Expand Down
47 changes: 47 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,50 @@ exclude = [
"docs/",
"temp/",
]

[tool.mypy]
disable_error_code = "annotation-unchecked"

[[tool.mypy.overrides]]
module = "pyglet.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "PIL.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "rocket.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "imgui.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "sdl2.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "pyopengltk.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "PySide2.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "pygame.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "glfw.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "PyQt5.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "pyrr.*"
ignore_missing_imports = true

0 comments on commit 2a89ba0

Please sign in to comment.