Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# pylama:ignore=C901
import json
import logging
from typing import Any, Dict, Optional
from payton.math.vector import invert_vector, plane_normal, vector_angle
from payton.scene.geometry.base import Object
from payton.scene.material import DEFAULT, Material
from payton.scene.types import VList
class Mesh(Object):
"""Mesh Object
Mesh is almost like the Object except with some extra methods to make
things easier. If you want to have custom geometries/shapes, it is
better to extend `payton.scene.geometry.mesh.Mesh` instead of
`payton.scene.geometry.base.Object`. Because Mesh will give you better
and easier constructing capabilities such as adding triangles on the fly
or sub-division or cutting and so forth. It is a way of designing objects
by code.
Example use case:
.. include:: ../../../examples/basics/09_mesh.py
"""
def __init__(
self, width: int = 800, height: int = 600, on_select: Optional[Callable] = None, **kwargs: Any,
) -> None:
# All objects list
self.objects: Dict[str, Object] = {}
# All Huds (Heads Up Display)
self.huds: Dict[str, Hud] = {"_help": Hud(width=width, height=height)}
self.huds["_help"].add_child("help", help_win())
self.huds["_help"].hide()
self.__fps_counter = 0
self.fps = 0
self.__timer = -1.0
self.observers: List[Observer] = []
self.observers.append(Observer(active=True))
self.hudcam = Observer(active=True, position=[0, 0, 1.0], up=[0, 1.0, 0], perspective=False,)
self.active_observer = self.observers[0]
self._needs_update = False
return True
def to_dict(self) -> Dict[str, Any]:
return {
"vertices": self._vertices,
"normals": self._normals,
"texcoords": self._texcoords,
"matrix": self.matrix,
"materials": {mat: self.materials[mat].to_dict() for mat in self.materials},
"children": {n: self.children[n].to_dict() for n in self.children},
}
class Line(Object):
def __init__(self, vertices: Optional[VList] = None, color: Optional[List[float]] = None, **kwargs: Any,) -> None:
super().__init__(**kwargs)
self._vertices: VList = [] if vertices is None else vertices
self.material.color = [1.0, 1.0, 1.0] if color is None else color
self.material.display = WIREFRAME
self.material.lights = False
self.build_lines()
def toggle_wireframe(self) -> None:
"""Toggle Wireframe overwrite to disable mode change"""
def add_material(self, name: str, material: Material) -> None:
"""@TODO Implement this later! Not urgent"""
logging.error("Can't add materials to Line object")
def add_child(self, name: str, obj: "Object") -> bool:
if name in self.children:
logging.error(f"Name {name} exists in object children")
return False
if not isinstance(obj, Object):
logging.error("Object type is not valid")
return False
self.children[name] = obj
return True
import logging
from typing import Any, Optional
from payton.scene.geometry.base import Object
from payton.scene.material import DEFAULT, POINTS
from payton.scene.types import VList
class PointCloud(Object):
def __init__(self, vertices: Optional[VList] = None, colors: Optional[VList] = None, **kwargs: Any,) -> None:
super().__init__(**kwargs)
self._vertices: VList = [] if vertices is None else vertices
# Expose vertices by reference for modification
self.vertices: VList = self._vertices
self._vertex_colors: VList = [] if colors is None else colors
self._vertex_history: VList = []
self.material.display = POINTS
def toggle_wireframe(self) -> None:
pass
def track(self) -> bool:
return False
def add(self, vertices: VList, colors: Optional[VList] = None, material: str = DEFAULT,) -> None:
def add_object(self, name: str, obj: Object) -> bool:
if not isinstance(obj, Object):
logging.error("Given object is not an instance of `scene.Object`")
return False
if name in self.objects:
logging.error(f"Given object name [{name}] already exists")
return False
if isinstance(obj, Shape2D):
logging.error("2D Shapes can't be added directly to the scene")
return False
if isinstance(obj, Hud):
"""Huds must be rendered in a different loop after rendering
all objects"""
if self._render_lock:
while self._render_lock:
return d.textsize(self.label, font=self.font)
def draw_text(self) -> None:
img = Image.new("RGBA", self.size, color=tuple(self.bgcolor))
d = ImageDraw.Draw(img)
if self.font is not None:
d.text((1, 1), self.label, fill=tuple(self.color), font=self.font)
else:
d.text((1, 1), self.label, fill=tuple(self.color))
self.material._image = img
self.material.refresh()
class Hud(Object):
def __init__(
self, width: int = 800, height: int = 600, font: str = "", font_size: int = 15, **kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.width: int = width
self.height: int = height
self._fontname: str = font
self.children: Dict[str, Shape2D] = {} # type: ignore
self._font_size: int = font_size
if self._fontname != "":
self.set_font(self._fontname, self._font_size)
self._font: ImageFont = None
self._projection_matrix: Optional[np.ndarray] = None
try:
self.set_font(os.path.join(os.path.dirname(os.path.abspath(__file__)), "monofonto.ttf"))
except OSError:
def __init__(self, name="", visible=True, track_motion=False, **kwargs: Dict[str, Any],) -> None:
self.children: Dict[str, Object] = {}
# store diffeerent materials
self.materials: Dict[str, Material] = {DEFAULT: Material()}
self._vao: int = NO_VERTEX_ARRAY
self._vbos: List[int] = []
self._no_missing_vao = False
self.name = name
self._visible = visible
self.matrix: VList = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
up: Optional[List[float]] = None,
target_object: Optional[Type[Object]] = None,
fov: float = 45.0,
aspect_ratio: float = 1.33333,
near: float = 0.1,
far: float = 100.0,
zoom: float = 10.0,
active: bool = False,
perspective: bool = True,
**kwargs: Any,
) -> None:
self.position: List[float] = [10.0, 10.0, 5.0] if position is None else position
self.target: List[float] = [0.0, 0.0, 0.0] if target is None else target
self.up: List[float] = [0.0, 0.0, 1.0] if up is None else up
self.target_object: Optional[Type[Object]] = target_object
self.fov: float = fov
self.aspect_ratio: float = aspect_ratio
self._near: float = near
self._far: float = far
# zoom factor for Orthographic projection
self._zoom: float = zoom
self.active: bool = active
self.perspective: bool = perspective
self._use_cache = False
# Store matrices for future reference.
self._projection: Optional[np.ndarray] = None
self._view: Optional[np.ndarray] = None
self._prev_intersection: Optional[np.ndarray] = None