How to use the payton.scene.geometry.mesh.Mesh function in Payton

To help you get started, we’ve selected a few Payton examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sinanislekdemir / payton / payton / scene / collision.py View on Github external
def _test(self, obj1: Mesh, obj2: Mesh) -> bool:
        bs_test = self._bounding_sphere_collision(obj1, obj2)
        if not bs_test:
            return False
        if isinstance(obj1, Sphere) and isinstance(obj2, Sphere):
            # If both objects are Spheres, this check is enough
            return True
        # No faces are colliding but an object wraps other one
        if self._sphere_in_sphere_collision(obj1, obj2):
            return True

        if isinstance(obj1, Mesh) and isinstance(obj2, Mesh):
            if self.level == self.SPHERICAL:
                return True
            return self._aabb_collision_test(obj1, obj2)
        return False
github sinanislekdemir / payton / payton / scene / geometry / md2.py View on Github external
total_length = struct_length * count
    data = b.read(total_length)
    if len(data) < total_length:
        raise ValueError("MD2: Failed to read '%d' bytes" % (total_length))
    return [struct.unpack(format_str, chunk) for chunk in chunks(data, struct_length)]


def fix_skin_name(name: bytes) -> str:
    name_str = name.decode("utf-8").replace("\x00", "")
    name_parts = os.path.splitext(name_str)
    if name_parts[1].startswith(".pcx"):
        return f"{name_parts[0]}.pcx"
    return name_str


class MD2(Mesh):
    """
    MD2 File Format Loader
    I know that this is a pretty old file format. We can consider it as ancient
    On the other hand, our target on creating Payton is not to make a game
    engine.

    Also note that there might be some bugs, I give no guarantee here.
    As this is a generic class, I haven't defined any animations before hand.
    So to make things properly looping in your code, you need to set the
    animation frame ranges yourself. For instance, as you will see at the
    defined example, infantry has a perfect walking loop between frames 2-13

    Unlike original frame names, frames in this class starts from 0 and goes
    incremented by one.

    NOTE: There are some hard-coded pre-assumptions like the scale of the
github sinanislekdemir / payton / payton / scene / geometry / cylinder.py View on Github external
import math
from typing import Any

from payton.scene.geometry.mesh import Mesh


class Cylinder(Mesh):
    def __init__(
        self,
        bottom_radius: float = 0.5,
        top_radius: float = 0.5,
        meridians: int = 12,
        height: float = 1.0,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self._bottom_radius: float = bottom_radius
        self._top_radius: float = top_radius
        self._meridians: int = meridians
        self._height: float = height
        self.build_cylinder()

    def build_cylinder(self) -> bool:
github sinanislekdemir / payton / payton / scene / geometry / wavefront.py View on Github external
def export(mesh: Mesh, filename: str, name: str = "object"):
    if not isinstance(mesh, Mesh):
        logging.exception("Object is not an instance of Mesh")
        return None
    mat_filename = filename.replace(".obj", "") + ".mtl"

    output = [
        "# Payton Wavefront OBJ Exporter",
        f"mtllib {mat_filename}",
        f"o {name}",
    ]
    for v in mesh._vertices:
        output.append("v {}".format(" ".join([str(x) for x in v])))

    for t in mesh._texcoords:
        output.append("vt {}".format(" ".join([str(x) for x in t])))

    for n in mesh._normals:
github sinanislekdemir / payton / payton / scene / gui / base.py View on Github external
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, cast

import numpy as np  # type: ignore
from OpenGL.GL import GL_DEPTH_TEST, glDisable, glEnable
from PIL import Image, ImageDraw, ImageFont  # type: ignore

from payton.math.matrix import ortho
from payton.scene.geometry.base import Object
from payton.scene.geometry.mesh import Mesh
from payton.scene.shader import Shader

S2 = TypeVar("S2", bound="Shape2D")


class Shape2D(Mesh):
    def __init__(
        self,
        position: Tuple[int, int, int],
        size: Tuple[int, int],
        on_click: Optional[Callable] = None,
        opacity: float = 0.5,
        **kwargs: Any,
    ):
        super().__init__(**kwargs)
        self.material.opacity = opacity
        self.__position: Tuple[int, int, int] = position
        self.position = list([float(x) for x in self.__position])
        self.size: Tuple[int, int] = size
        self.on_click: Optional[Callable] = on_click
        self._font: ImageFont = None
        self.parent: Any = None
github sinanislekdemir / payton / payton / scene / geometry / md2.py View on Github external
def build_frame(self, frame_information: MD2Frame, name: str):
        mesh = Mesh()
        for i, tri in enumerate(self.triangle_layout.vertex_indices):
            v3 = frame_information.vertices[tri[1]].tolist()
            v2 = frame_information.vertices[tri[0]].tolist()
            v1 = frame_information.vertices[tri[2]].tolist()
            v1[0], v1[1] = v1[1], v1[0]
            v2[0], v2[1] = v2[1], v2[0]
            v3[0], v3[1] = v3[1], v3[0]

            t3 = cast(np.ndarray, self._texcoords[self.triangle_layout.tc_indices[i][1]]).tolist()
            t2 = cast(np.ndarray, self._texcoords[self.triangle_layout.tc_indices[i][0]]).tolist()
            t1 = cast(np.ndarray, self._texcoords[self.triangle_layout.tc_indices[i][2]]).tolist()

            mesh.add_triangle(
                vertices=[v1, v2, v3], texcoords=[t1, t2, t3],
            )
github sinanislekdemir / payton / payton / scene / geometry / plane.py View on Github external
super().__init__(**kwargs)
        width *= 0.5
        height *= 0.5
        self._vertices = [
            [-width, -height, 0],
            [width, -height, 0],
            [width, height, 0],
            [-width, height, 0],
        ]
        self._normals = [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]]
        self._texcoords = [[-1, -1], [1, -1], [1, 1], [-1, 1]]
        self._indices = [[0, 1, 2], [2, 3, 0]]
        self.material._indices = self._indices


class MatrixPlane(Mesh):
    def __init__(self, width: float = 1.0, height: float = 1.0, x: int = 2, y: int = 2, **kwargs: Any,) -> None:
        super().__init__(**kwargs)
        self.width = width
        self.height = height
        self.x = x
        self.y = y
        if self.x < 2:
            self.x = 2
        if self.y < 2:
            self.y = 2
        self.grid: List[List[float]] = []
        # List of List for X, Y and List[float] for color.
        self.color_grid: List[List[List[float]]] = []
        self.populate_grid()

    def update_grid(self) -> None:
github sinanislekdemir / payton / payton / scene / geometry / md2.py View on Github external
This is suitable to fill the blank frames of an animated object
    This function makes the assumption that same indices will be forming
    the same triangle.

    This function returns at least 3 meshes;
    [mesh_1, interpolated mesh, mesh_2]
    """
    if len(mesh_1._vertices) != len(mesh_2._vertices):
        raise MeshException("Mesh 1 and Mesh 2 vertex counts do not match")
    if len(mesh_1.children) > 0:
        raise MeshException("Mesh 1 has children")
    if len(mesh_2.children) > 0:
        raise MeshException("Mesh 2 has children")

    # Generate meshes
    results: List[Mesh] = [mesh_1]

    # Calculate vertex distances;
    distances = []
    for v_i, vertex in enumerate(mesh_1._vertices):
        dist = [0.0, 0.0, 0.0]
        dist[0] = (mesh_2._vertices[v_i][0] - vertex[0]) / (steps + 1)
        dist[1] = (mesh_2._vertices[v_i][1] - vertex[1]) / (steps + 1)
        dist[2] = (mesh_2._vertices[v_i][2] - vertex[2]) / (steps + 1)
        distances.append(dist)

    for i in range(1, steps + 1):
        mesh = Mesh()
        mesh.materials = deepcopy(results[i - 1].materials)
        mesh._texcoords = deepcopy(results[i - 1]._texcoords)
        mesh._indices = deepcopy(results[i - 1]._indices)
        mesh.destroy()  # Destroy references to previous objects opengl