From 4258e15f0f11b50d5103e1b604d964fa9ca8c146 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Mon, 2 Nov 2026 13:23:00 -0800 Subject: [PATCH 1/4] Rust api. --- Cargo.toml | 11 +- .../processing_pyo3/processing_py/color.pyi | 96 ++ crates/processing_pyo3/processing_py/math.pyi | 1277 +++++++++++++++++ examples/background_image.rs | 47 +- examples/blend_modes.rs | 114 +- examples/create_graphics.rs | 40 + examples/curves.rs | 134 +- examples/input.rs | 83 +- examples/pbr.rs | 126 +- examples/primitives_2d.rs | 137 +- examples/primitives_3d.rs | 173 +-- examples/rectangle.rs | 54 +- examples/shapes.rs | 186 +-- examples/stroke_2d.rs | 77 +- examples/stroke_3d.rs | 217 +-- examples/text.rs | 121 +- examples/transforms.rs | 88 +- examples/update_pixels.rs | 116 +- src/args.rs | 89 ++ src/color.rs | 303 ++++ src/draw.rs | 358 +++++ src/graphics.rs | 1062 ++++++++++++++ src/image.rs | 109 ++ src/input.rs | 70 + src/lib.rs | 35 + src/shape.rs | 113 ++ src/sketch.rs | 128 ++ 27 files changed, 4195 insertions(+), 1169 deletions(-) create mode 100644 crates/processing_pyo3/processing_py/color.pyi create mode 100644 crates/processing_pyo3/processing_py/math.pyi create mode 100644 examples/create_graphics.rs create mode 100644 src/args.rs create mode 100644 src/color.rs create mode 100644 src/draw.rs create mode 100644 src/graphics.rs create mode 100644 src/image.rs create mode 100644 src/input.rs create mode 100644 src/shape.rs create mode 100644 src/sketch.rs diff --git a/Cargo.toml b/Cargo.toml index 5ef3f465..4990f307 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,8 +10,8 @@ workspace = true [features] default = ["wayland", "x11"] -wayland = ["processing_render/wayland"] -x11 = ["processing_render/x11"] +wayland = ["processing_render/wayland", "processing_glfw/wayland"] +x11 = ["processing_render/x11", "processing_glfw/x11"] webcam = ["dep:processing_webcam"] cuda = ["dep:processing_cuda", "processing_cuda/cuda"] @@ -90,6 +90,9 @@ processing_cuda = { workspace = true, optional = true } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +processing_glfw = { workspace = true } + [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen-futures = "0.4" js-sys = "0.3" @@ -133,6 +136,10 @@ path = "examples/background_image.rs" name = "update_pixels" path = "examples/update_pixels.rs" +[[example]] +name = "create_graphics" +path = "examples/create_graphics.rs" + [[example]] name = "transforms" path = "examples/transforms.rs" diff --git a/crates/processing_pyo3/processing_py/color.pyi b/crates/processing_pyo3/processing_py/color.pyi new file mode 100644 index 00000000..74229cd3 --- /dev/null +++ b/crates/processing_pyo3/processing_py/color.pyi @@ -0,0 +1,96 @@ +from mewnala.math import PyVecIter, Vec3, Vec4 +from typing import final + +@final +class Color: + def __eq__(self, /, other: object) -> bool: ... + def __getitem__(self, /, idx: int) -> float: ... + def __hash__(self, /) -> int: ... + def __iter__(self, /) -> PyVecIter: ... + def __len__(self, /) -> int: ... + def __new__(cls, /, *args) -> Color: ... + def __repr__(self, /) -> str: ... + def __str__(self, /) -> str: ... + @property + def a(self, /) -> float: ... + @a.setter + def a(self, /, val: float) -> None: ... + @property + def b(self, /) -> float: ... + @b.setter + def b(self, /, val: float) -> None: ... + def darker(self, /, amount: float) -> Color: ... + def distance(self, /, other: Color) -> float: ... + def distance_squared(self, /, other: Color) -> float: ... + @property + def g(self, /) -> float: ... + @g.setter + def g(self, /, val: float) -> None: ... + @staticmethod + def gray(lightness: float) -> Color: ... + @staticmethod + def hex(s: str) -> Color: ... + @staticmethod + def hsla(h: float, s: float, l: float, a: float = 1.0) -> Color: ... + @staticmethod + def hsva(h: float, s: float, v: float, a: float = 1.0) -> Color: ... + def hue(self, /) -> float: ... + @staticmethod + def hwba(h: float, w: float, b: float, a: float = 1.0) -> Color: ... + def is_fully_opaque(self, /) -> bool: ... + def is_fully_transparent(self, /) -> bool: ... + @staticmethod + def lab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... + @staticmethod + def lch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... + def lerp(self, /, other: Color, t: float) -> Color: ... + def lighter(self, /, amount: float) -> Color: ... + @staticmethod + def linear(r: float, g: float, b: float, a: float = 1.0) -> Color: ... + def luminance(self, /) -> float: ... + def mix(self, /, other: Color, t: float) -> Color: ... + @staticmethod + def oklab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... + @staticmethod + def oklch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... + @property + def r(self, /) -> float: ... + @r.setter + def r(self, /, val: float) -> None: ... + def rotate_hue(self, /, degrees: float) -> Color: ... + def saturation(self, /) -> float: ... + @staticmethod + def srgb(r: float, g: float, b: float, a: float = 1.0) -> Color: ... + def to_hex(self, /) -> str: ... + def to_hsla(self, /) -> Color: ... + def to_hsva(self, /) -> Color: ... + def to_hwba(self, /) -> Color: ... + def to_lab(self, /) -> Color: ... + def to_lch(self, /) -> Color: ... + def to_linear(self, /) -> Color: ... + def to_list(self, /) -> list[float]: ... + def to_oklab(self, /) -> Color: ... + def to_oklch(self, /) -> Color: ... + def to_srgba(self, /) -> Color: ... + def to_tuple(self, /) -> tuple: ... + def to_vec3(self, /) -> Vec3: ... + def to_vec4(self, /) -> Vec4: ... + def to_xyz(self, /) -> Color: ... + def with_alpha(self, /, a: float) -> Color: ... + def with_hue(self, /, hue: float) -> Color: ... + def with_luminance(self, /, value: float) -> Color: ... + def with_saturation(self, /, saturation: float) -> Color: ... + @staticmethod + def xyz(x: float, y: float, z: float, a: float = 1.0) -> Color: ... + +def hex(s: str) -> Color: ... +def hsla(h: float, s: float, l: float, a: float = 1.0) -> Color: ... +def hsva(h: float, s: float, v: float, a: float = 1.0) -> Color: ... +def hwba(h: float, w: float, b: float, a: float = 1.0) -> Color: ... +def lab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... +def lch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... +def linear(r: float, g: float, b: float, a: float = 1.0) -> Color: ... +def oklab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... +def oklch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... +def srgb(r: float, g: float, b: float, a: float = 1.0) -> Color: ... +def xyz(x: float, y: float, z: float, a: float = 1.0) -> Color: ... diff --git a/crates/processing_pyo3/processing_py/math.pyi b/crates/processing_pyo3/processing_py/math.pyi new file mode 100644 index 00000000..3f946342 --- /dev/null +++ b/crates/processing_pyo3/processing_py/math.pyi @@ -0,0 +1,1277 @@ +from collections.abc import Sequence +from typing import Any, Final, final + +@final +class Affine2: + def __eq__(self, other: object, /) -> bool: ... + def __hash__(self, /) -> int: ... + def __new__(cls, /, matrix: Mat2 | None = None, translation: Vec2 | None = None) -> Affine2: ... + def __repr__(self, /) -> str: ... + def __str__(self, /) -> str: ... + @staticmethod + def from_scale(scale: Vec2) -> Affine2: ... + @staticmethod + def from_scale_angle_translation(scale: Vec2, angle: float, translation: Vec2) -> Affine2: ... + def inverse(self, /) -> Affine2: ... + @property + def matrix(self, /) -> Mat2: ... + @property + def translation(self, /) -> Vec2: ... + +@final +class Mat2: + def __eq__(self, other: object, /) -> bool: ... + def __hash__(self, /) -> int: ... + def __mul__(self, rhs: object, /) -> Any: ... + def __new__(cls, /, *args) -> Mat2: ... + def __repr__(self, /) -> str: ... + def __str__(self, /) -> str: ... + def determinant(self, /) -> float: ... + @staticmethod + def from_angle(angle: float) -> Mat2: ... + @staticmethod + def from_scale(scale: Vec2) -> Mat2: ... + def inverse(self, /) -> Mat2: ... + def transpose(self, /) -> Mat2: ... + +@final +class PyVecIter: + def __iter__(self, /) -> PyVecIter: ... + def __next__(self, /) -> float | None: ... + +@final +class Quat: + def __eq__(self, other: object, /) -> bool: ... + def __hash__(self, /) -> int: ... + def __mul__(self, rhs: object, /) -> Any: ... + def __new__(cls, /, *args) -> Quat: ... + def __repr__(self, /) -> str: ... + def __str__(self, /) -> str: ... + def dot(self, /, other: Quat) -> float: ... + @staticmethod + def from_axis_angle(axis: Vec3 | tuple[float, float, float] | Sequence[float], angle: float) -> Quat: ... + @staticmethod + def from_euler(x: float, y: float, z: float) -> Quat: ... + @staticmethod + def from_rotation_x(angle: float) -> Quat: ... + @staticmethod + def from_rotation_y(angle: float) -> Quat: ... + @staticmethod + def from_rotation_z(angle: float) -> Quat: ... + @staticmethod + def identity() -> Quat: ... + def inverse(self, /) -> Quat: ... + def length(self, /) -> float: ... + def mul_vec3(self, /, v: Vec3 | tuple[float, float, float] | Sequence[float]) -> Vec3: ... + def normalize(self, /) -> Quat: ... + def slerp(self, /, other: Quat, t: float) -> Quat: ... + def to_euler(self, /) -> Vec3: ... + @property + def w(self, /) -> float: ... + @w.setter + def w(self, /, val: float) -> None: ... + @property + def x(self, /) -> float: ... + @x.setter + def x(self, /, val: float) -> None: ... + @property + def y(self, /) -> float: ... + @y.setter + def y(self, /, val: float) -> None: ... + @property + def z(self, /) -> float: ... + @z.setter + def z(self, /, val: float) -> None: ... + +@final +class Vec2: + ONE: Final[Vec2] + X: Final[Vec2] + Y: Final[Vec2] + ZERO: Final[Vec2] + def __add__(self, other: object, /) -> Vec2: ... + def __eq__(self, other: object, /) -> bool: ... + def __getattr__(self, name: str, /) -> Any: ... + def __getitem__(self, idx: int, /) -> float: ... + def __hash__(self, /) -> int: ... + def __iadd__(self, other: object, /) -> None: ... + def __imul__(self, rhs: object, /) -> None: ... + def __isub__(self, other: object, /) -> None: ... + def __iter__(self, /) -> PyVecIter: ... + def __itruediv__(self, rhs: object, /) -> None: ... + def __len__(self, /) -> int: ... + def __mul__(self, rhs: object, /) -> Vec2: ... + def __neg__(self, /) -> Vec2: ... + def __new__(cls, /, *args) -> Vec2: ... + def __radd__(self, other: object, /) -> Vec2: ... + def __repr__(self, /) -> str: ... + def __rmul__(self, lhs: object, /) -> Vec2: ... + def __rsub__(self, other: object, /) -> Vec2: ... + def __rtruediv__(self, lhs: object, /) -> Vec2: ... + def __setitem__(self, idx: int, val: float, /) -> None: ... + def __str__(self, /) -> str: ... + def __sub__(self, other: object, /) -> Vec2: ... + def __truediv__(self, rhs: object, /) -> Vec2: ... + def abs(self, /) -> Vec2: ... + def add(self, /, *args) -> None: ... + def angle(self, /) -> float: ... + @staticmethod + def angle_between(v1: Vec2, v2: Vec2) -> float: ... + def clamp(self, /, min: Vec2, max: Vec2) -> Vec2: ... + def copy(self, /) -> Vec2: ... + def dist(self, /, other: Vec2) -> float: ... + def distance(self, /, other: Vec2) -> float: ... + def div(self, /, n: float) -> None: ... + def dot(self, /, other: Vec2) -> float: ... + def equals(self, /, other: Vec2) -> bool: ... + def extend(self, /, z: float) -> Vec3: ... + @staticmethod + def from_angle(angle: float) -> Vec2: ... + def hash_code(self, /) -> int: ... + def heading(self, /) -> float: ... + def length(self, /) -> float: ... + def length_squared(self, /) -> float: ... + def lerp(self, /, other: Vec2, t: float) -> Vec2: ... + def limit(self, /, max: float) -> None: ... + def mag(self, /) -> float: ... + def mag_sq(self, /) -> float: ... + def max(self, /, other: Vec2) -> Vec2: ... + def min(self, /, other: Vec2) -> Vec2: ... + def mult(self, /, n: float) -> None: ... + def normalize(self, /) -> Vec2: ... + def perpendicular(self, /) -> Vec2: ... + @staticmethod + def random() -> Vec2: ... + def rotate(self, /, angle: float) -> Vec2: ... + def set(self, /, *args) -> None: ... + def set_heading(self, /, angle: float) -> None: ... + def set_mag(self, /, len: float) -> None: ... + def sub(self, /, *args) -> None: ... + def to_list(self, /) -> list[float]: ... + def to_tuple(self, /) -> tuple: ... + @property + def x(self, /) -> float: ... + @x.setter + def x(self, /, val: float) -> None: ... + @property + def y(self, /) -> float: ... + @y.setter + def y(self, /, val: float) -> None: ... + @property + def xx(self, /) -> Vec2: ... + @property + def yx(self, /) -> Vec2: ... + @property + def xy(self, /) -> Vec2: ... + @property + def yy(self, /) -> Vec2: ... + @property + def xxx(self, /) -> Vec3: ... + @property + def yxx(self, /) -> Vec3: ... + @property + def xyx(self, /) -> Vec3: ... + @property + def yyx(self, /) -> Vec3: ... + @property + def xxy(self, /) -> Vec3: ... + @property + def yxy(self, /) -> Vec3: ... + @property + def xyy(self, /) -> Vec3: ... + @property + def yyy(self, /) -> Vec3: ... + @property + def xxxx(self, /) -> Vec4: ... + @property + def yxxx(self, /) -> Vec4: ... + @property + def xyxx(self, /) -> Vec4: ... + @property + def yyxx(self, /) -> Vec4: ... + @property + def xxyx(self, /) -> Vec4: ... + @property + def yxyx(self, /) -> Vec4: ... + @property + def xyyx(self, /) -> Vec4: ... + @property + def yyyx(self, /) -> Vec4: ... + @property + def xxxy(self, /) -> Vec4: ... + @property + def yxxy(self, /) -> Vec4: ... + @property + def xyxy(self, /) -> Vec4: ... + @property + def yyxy(self, /) -> Vec4: ... + @property + def xxyy(self, /) -> Vec4: ... + @property + def yxyy(self, /) -> Vec4: ... + @property + def xyyy(self, /) -> Vec4: ... + @property + def yyyy(self, /) -> Vec4: ... + +@final +class Vec3: + ONE: Final[Vec3] + X: Final[Vec3] + Y: Final[Vec3] + Z: Final[Vec3] + ZERO: Final[Vec3] + def __add__(self, other: object, /) -> Vec3: ... + def __eq__(self, other: object, /) -> bool: ... + def __getattr__(self, name: str, /) -> Any: ... + def __getitem__(self, idx: int, /) -> float: ... + def __hash__(self, /) -> int: ... + def __iadd__(self, other: object, /) -> None: ... + def __imul__(self, rhs: object, /) -> None: ... + def __isub__(self, other: object, /) -> None: ... + def __iter__(self, /) -> PyVecIter: ... + def __itruediv__(self, rhs: object, /) -> None: ... + def __len__(self, /) -> int: ... + def __mul__(self, rhs: object, /) -> Vec3: ... + def __neg__(self, /) -> Vec3: ... + def __new__(cls, /, *args) -> Vec3: ... + def __radd__(self, other: object, /) -> Vec3: ... + def __repr__(self, /) -> str: ... + def __rmul__(self, lhs: object, /) -> Vec3: ... + def __rsub__(self, other: object, /) -> Vec3: ... + def __rtruediv__(self, lhs: object, /) -> Vec3: ... + def __setitem__(self, idx: int, val: float, /) -> None: ... + def __str__(self, /) -> str: ... + def __sub__(self, other: object, /) -> Vec3: ... + def __truediv__(self, rhs: object, /) -> Vec3: ... + def abs(self, /) -> Vec3: ... + def add(self, /, *args) -> None: ... + @staticmethod + def angle_between(v1: Vec3, v2: Vec3) -> float: ... + def clamp(self, /, min: Vec3, max: Vec3) -> Vec3: ... + def copy(self, /) -> Vec3: ... + def cross(self, /, other: Vec3) -> Vec3: ... + def dist(self, /, other: Vec3) -> float: ... + def distance(self, /, other: Vec3) -> float: ... + def div(self, /, n: float) -> None: ... + def dot(self, /, other: Vec3) -> float: ... + def equals(self, /, other: Vec3) -> bool: ... + def extend(self, /, w: float) -> Vec4: ... + def hash_code(self, /) -> int: ... + def length(self, /) -> float: ... + def length_squared(self, /) -> float: ... + def lerp(self, /, other: Vec3, t: float) -> Vec3: ... + def limit(self, /, max: float) -> None: ... + def mag(self, /) -> float: ... + def mag_sq(self, /) -> float: ... + def max(self, /, other: Vec3) -> Vec3: ... + def min(self, /, other: Vec3) -> Vec3: ... + def mult(self, /, n: float) -> None: ... + def normalize(self, /) -> Vec3: ... + @staticmethod + def random() -> Vec3: ... + def set(self, /, *args) -> None: ... + def set_mag(self, /, len: float) -> None: ... + def sub(self, /, *args) -> None: ... + def to_list(self, /) -> list[float]: ... + def to_tuple(self, /) -> tuple: ... + def truncate(self, /) -> Vec2: ... + @property + def x(self, /) -> float: ... + @x.setter + def x(self, /, val: float) -> None: ... + @property + def y(self, /) -> float: ... + @y.setter + def y(self, /, val: float) -> None: ... + @property + def z(self, /) -> float: ... + @z.setter + def z(self, /, val: float) -> None: ... + @property + def xx(self, /) -> Vec2: ... + @property + def yx(self, /) -> Vec2: ... + @property + def zx(self, /) -> Vec2: ... + @property + def xy(self, /) -> Vec2: ... + @property + def yy(self, /) -> Vec2: ... + @property + def zy(self, /) -> Vec2: ... + @property + def xz(self, /) -> Vec2: ... + @property + def yz(self, /) -> Vec2: ... + @property + def zz(self, /) -> Vec2: ... + @property + def xxx(self, /) -> Vec3: ... + @property + def yxx(self, /) -> Vec3: ... + @property + def zxx(self, /) -> Vec3: ... + @property + def xyx(self, /) -> Vec3: ... + @property + def yyx(self, /) -> Vec3: ... + @property + def zyx(self, /) -> Vec3: ... + @property + def xzx(self, /) -> Vec3: ... + @property + def yzx(self, /) -> Vec3: ... + @property + def zzx(self, /) -> Vec3: ... + @property + def xxy(self, /) -> Vec3: ... + @property + def yxy(self, /) -> Vec3: ... + @property + def zxy(self, /) -> Vec3: ... + @property + def xyy(self, /) -> Vec3: ... + @property + def yyy(self, /) -> Vec3: ... + @property + def zyy(self, /) -> Vec3: ... + @property + def xzy(self, /) -> Vec3: ... + @property + def yzy(self, /) -> Vec3: ... + @property + def zzy(self, /) -> Vec3: ... + @property + def xxz(self, /) -> Vec3: ... + @property + def yxz(self, /) -> Vec3: ... + @property + def zxz(self, /) -> Vec3: ... + @property + def xyz(self, /) -> Vec3: ... + @property + def yyz(self, /) -> Vec3: ... + @property + def zyz(self, /) -> Vec3: ... + @property + def xzz(self, /) -> Vec3: ... + @property + def yzz(self, /) -> Vec3: ... + @property + def zzz(self, /) -> Vec3: ... + @property + def xxxx(self, /) -> Vec4: ... + @property + def yxxx(self, /) -> Vec4: ... + @property + def zxxx(self, /) -> Vec4: ... + @property + def xyxx(self, /) -> Vec4: ... + @property + def yyxx(self, /) -> Vec4: ... + @property + def zyxx(self, /) -> Vec4: ... + @property + def xzxx(self, /) -> Vec4: ... + @property + def yzxx(self, /) -> Vec4: ... + @property + def zzxx(self, /) -> Vec4: ... + @property + def xxyx(self, /) -> Vec4: ... + @property + def yxyx(self, /) -> Vec4: ... + @property + def zxyx(self, /) -> Vec4: ... + @property + def xyyx(self, /) -> Vec4: ... + @property + def yyyx(self, /) -> Vec4: ... + @property + def zyyx(self, /) -> Vec4: ... + @property + def xzyx(self, /) -> Vec4: ... + @property + def yzyx(self, /) -> Vec4: ... + @property + def zzyx(self, /) -> Vec4: ... + @property + def xxzx(self, /) -> Vec4: ... + @property + def yxzx(self, /) -> Vec4: ... + @property + def zxzx(self, /) -> Vec4: ... + @property + def xyzx(self, /) -> Vec4: ... + @property + def yyzx(self, /) -> Vec4: ... + @property + def zyzx(self, /) -> Vec4: ... + @property + def xzzx(self, /) -> Vec4: ... + @property + def yzzx(self, /) -> Vec4: ... + @property + def zzzx(self, /) -> Vec4: ... + @property + def xxxy(self, /) -> Vec4: ... + @property + def yxxy(self, /) -> Vec4: ... + @property + def zxxy(self, /) -> Vec4: ... + @property + def xyxy(self, /) -> Vec4: ... + @property + def yyxy(self, /) -> Vec4: ... + @property + def zyxy(self, /) -> Vec4: ... + @property + def xzxy(self, /) -> Vec4: ... + @property + def yzxy(self, /) -> Vec4: ... + @property + def zzxy(self, /) -> Vec4: ... + @property + def xxyy(self, /) -> Vec4: ... + @property + def yxyy(self, /) -> Vec4: ... + @property + def zxyy(self, /) -> Vec4: ... + @property + def xyyy(self, /) -> Vec4: ... + @property + def yyyy(self, /) -> Vec4: ... + @property + def zyyy(self, /) -> Vec4: ... + @property + def xzyy(self, /) -> Vec4: ... + @property + def yzyy(self, /) -> Vec4: ... + @property + def zzyy(self, /) -> Vec4: ... + @property + def xxzy(self, /) -> Vec4: ... + @property + def yxzy(self, /) -> Vec4: ... + @property + def zxzy(self, /) -> Vec4: ... + @property + def xyzy(self, /) -> Vec4: ... + @property + def yyzy(self, /) -> Vec4: ... + @property + def zyzy(self, /) -> Vec4: ... + @property + def xzzy(self, /) -> Vec4: ... + @property + def yzzy(self, /) -> Vec4: ... + @property + def zzzy(self, /) -> Vec4: ... + @property + def xxxz(self, /) -> Vec4: ... + @property + def yxxz(self, /) -> Vec4: ... + @property + def zxxz(self, /) -> Vec4: ... + @property + def xyxz(self, /) -> Vec4: ... + @property + def yyxz(self, /) -> Vec4: ... + @property + def zyxz(self, /) -> Vec4: ... + @property + def xzxz(self, /) -> Vec4: ... + @property + def yzxz(self, /) -> Vec4: ... + @property + def zzxz(self, /) -> Vec4: ... + @property + def xxyz(self, /) -> Vec4: ... + @property + def yxyz(self, /) -> Vec4: ... + @property + def zxyz(self, /) -> Vec4: ... + @property + def xyyz(self, /) -> Vec4: ... + @property + def yyyz(self, /) -> Vec4: ... + @property + def zyyz(self, /) -> Vec4: ... + @property + def xzyz(self, /) -> Vec4: ... + @property + def yzyz(self, /) -> Vec4: ... + @property + def zzyz(self, /) -> Vec4: ... + @property + def xxzz(self, /) -> Vec4: ... + @property + def yxzz(self, /) -> Vec4: ... + @property + def zxzz(self, /) -> Vec4: ... + @property + def xyzz(self, /) -> Vec4: ... + @property + def yyzz(self, /) -> Vec4: ... + @property + def zyzz(self, /) -> Vec4: ... + @property + def xzzz(self, /) -> Vec4: ... + @property + def yzzz(self, /) -> Vec4: ... + @property + def zzzz(self, /) -> Vec4: ... + +@final +class Vec4: + ONE: Final[Vec4] + W: Final[Vec4] + X: Final[Vec4] + Y: Final[Vec4] + Z: Final[Vec4] + ZERO: Final[Vec4] + def __add__(self, other: object, /) -> Vec4: ... + def __eq__(self, other: object, /) -> bool: ... + def __getattr__(self, name: str, /) -> Any: ... + def __getitem__(self, idx: int, /) -> float: ... + def __hash__(self, /) -> int: ... + def __iadd__(self, other: object, /) -> None: ... + def __imul__(self, rhs: object, /) -> None: ... + def __isub__(self, other: object, /) -> None: ... + def __iter__(self, /) -> PyVecIter: ... + def __itruediv__(self, rhs: object, /) -> None: ... + def __len__(self, /) -> int: ... + def __mul__(self, rhs: object, /) -> Vec4: ... + def __neg__(self, /) -> Vec4: ... + def __new__(cls, /, *args) -> Vec4: ... + def __radd__(self, other: object, /) -> Vec4: ... + def __repr__(self, /) -> str: ... + def __rmul__(self, lhs: object, /) -> Vec4: ... + def __rsub__(self, other: object, /) -> Vec4: ... + def __rtruediv__(self, lhs: object, /) -> Vec4: ... + def __setitem__(self, idx: int, val: float, /) -> None: ... + def __str__(self, /) -> str: ... + def __sub__(self, other: object, /) -> Vec4: ... + def __truediv__(self, rhs: object, /) -> Vec4: ... + def abs(self, /) -> Vec4: ... + def add(self, /, *args) -> None: ... + @staticmethod + def angle_between(v1: Vec4, v2: Vec4) -> float: ... + def clamp(self, /, min: Vec4, max: Vec4) -> Vec4: ... + def copy(self, /) -> Vec4: ... + def dist(self, /, other: Vec4) -> float: ... + def distance(self, /, other: Vec4) -> float: ... + def div(self, /, n: float) -> None: ... + def dot(self, /, other: Vec4) -> float: ... + def equals(self, /, other: Vec4) -> bool: ... + def hash_code(self, /) -> int: ... + def length(self, /) -> float: ... + def length_squared(self, /) -> float: ... + def lerp(self, /, other: Vec4, t: float) -> Vec4: ... + def limit(self, /, max: float) -> None: ... + def mag(self, /) -> float: ... + def mag_sq(self, /) -> float: ... + def max(self, /, other: Vec4) -> Vec4: ... + def min(self, /, other: Vec4) -> Vec4: ... + def mult(self, /, n: float) -> None: ... + def normalize(self, /) -> Vec4: ... + def set(self, /, *args) -> None: ... + def set_mag(self, /, len: float) -> None: ... + def sub(self, /, *args) -> None: ... + def to_list(self, /) -> list[float]: ... + def to_tuple(self, /) -> tuple: ... + def truncate(self, /) -> Vec3: ... + @property + def w(self, /) -> float: ... + @w.setter + def w(self, /, val: float) -> None: ... + @property + def x(self, /) -> float: ... + @x.setter + def x(self, /, val: float) -> None: ... + @property + def y(self, /) -> float: ... + @y.setter + def y(self, /, val: float) -> None: ... + @property + def z(self, /) -> float: ... + @z.setter + def z(self, /, val: float) -> None: ... + @property + def xx(self, /) -> Vec2: ... + @property + def yx(self, /) -> Vec2: ... + @property + def zx(self, /) -> Vec2: ... + @property + def wx(self, /) -> Vec2: ... + @property + def xy(self, /) -> Vec2: ... + @property + def yy(self, /) -> Vec2: ... + @property + def zy(self, /) -> Vec2: ... + @property + def wy(self, /) -> Vec2: ... + @property + def xz(self, /) -> Vec2: ... + @property + def yz(self, /) -> Vec2: ... + @property + def zz(self, /) -> Vec2: ... + @property + def wz(self, /) -> Vec2: ... + @property + def xw(self, /) -> Vec2: ... + @property + def yw(self, /) -> Vec2: ... + @property + def zw(self, /) -> Vec2: ... + @property + def ww(self, /) -> Vec2: ... + @property + def xxx(self, /) -> Vec3: ... + @property + def yxx(self, /) -> Vec3: ... + @property + def zxx(self, /) -> Vec3: ... + @property + def wxx(self, /) -> Vec3: ... + @property + def xyx(self, /) -> Vec3: ... + @property + def yyx(self, /) -> Vec3: ... + @property + def zyx(self, /) -> Vec3: ... + @property + def wyx(self, /) -> Vec3: ... + @property + def xzx(self, /) -> Vec3: ... + @property + def yzx(self, /) -> Vec3: ... + @property + def zzx(self, /) -> Vec3: ... + @property + def wzx(self, /) -> Vec3: ... + @property + def xwx(self, /) -> Vec3: ... + @property + def ywx(self, /) -> Vec3: ... + @property + def zwx(self, /) -> Vec3: ... + @property + def wwx(self, /) -> Vec3: ... + @property + def xxy(self, /) -> Vec3: ... + @property + def yxy(self, /) -> Vec3: ... + @property + def zxy(self, /) -> Vec3: ... + @property + def wxy(self, /) -> Vec3: ... + @property + def xyy(self, /) -> Vec3: ... + @property + def yyy(self, /) -> Vec3: ... + @property + def zyy(self, /) -> Vec3: ... + @property + def wyy(self, /) -> Vec3: ... + @property + def xzy(self, /) -> Vec3: ... + @property + def yzy(self, /) -> Vec3: ... + @property + def zzy(self, /) -> Vec3: ... + @property + def wzy(self, /) -> Vec3: ... + @property + def xwy(self, /) -> Vec3: ... + @property + def ywy(self, /) -> Vec3: ... + @property + def zwy(self, /) -> Vec3: ... + @property + def wwy(self, /) -> Vec3: ... + @property + def xxz(self, /) -> Vec3: ... + @property + def yxz(self, /) -> Vec3: ... + @property + def zxz(self, /) -> Vec3: ... + @property + def wxz(self, /) -> Vec3: ... + @property + def xyz(self, /) -> Vec3: ... + @property + def yyz(self, /) -> Vec3: ... + @property + def zyz(self, /) -> Vec3: ... + @property + def wyz(self, /) -> Vec3: ... + @property + def xzz(self, /) -> Vec3: ... + @property + def yzz(self, /) -> Vec3: ... + @property + def zzz(self, /) -> Vec3: ... + @property + def wzz(self, /) -> Vec3: ... + @property + def xwz(self, /) -> Vec3: ... + @property + def ywz(self, /) -> Vec3: ... + @property + def zwz(self, /) -> Vec3: ... + @property + def wwz(self, /) -> Vec3: ... + @property + def xxw(self, /) -> Vec3: ... + @property + def yxw(self, /) -> Vec3: ... + @property + def zxw(self, /) -> Vec3: ... + @property + def wxw(self, /) -> Vec3: ... + @property + def xyw(self, /) -> Vec3: ... + @property + def yyw(self, /) -> Vec3: ... + @property + def zyw(self, /) -> Vec3: ... + @property + def wyw(self, /) -> Vec3: ... + @property + def xzw(self, /) -> Vec3: ... + @property + def yzw(self, /) -> Vec3: ... + @property + def zzw(self, /) -> Vec3: ... + @property + def wzw(self, /) -> Vec3: ... + @property + def xww(self, /) -> Vec3: ... + @property + def yww(self, /) -> Vec3: ... + @property + def zww(self, /) -> Vec3: ... + @property + def www(self, /) -> Vec3: ... + @property + def xxxx(self, /) -> Vec4: ... + @property + def yxxx(self, /) -> Vec4: ... + @property + def zxxx(self, /) -> Vec4: ... + @property + def wxxx(self, /) -> Vec4: ... + @property + def xyxx(self, /) -> Vec4: ... + @property + def yyxx(self, /) -> Vec4: ... + @property + def zyxx(self, /) -> Vec4: ... + @property + def wyxx(self, /) -> Vec4: ... + @property + def xzxx(self, /) -> Vec4: ... + @property + def yzxx(self, /) -> Vec4: ... + @property + def zzxx(self, /) -> Vec4: ... + @property + def wzxx(self, /) -> Vec4: ... + @property + def xwxx(self, /) -> Vec4: ... + @property + def ywxx(self, /) -> Vec4: ... + @property + def zwxx(self, /) -> Vec4: ... + @property + def wwxx(self, /) -> Vec4: ... + @property + def xxyx(self, /) -> Vec4: ... + @property + def yxyx(self, /) -> Vec4: ... + @property + def zxyx(self, /) -> Vec4: ... + @property + def wxyx(self, /) -> Vec4: ... + @property + def xyyx(self, /) -> Vec4: ... + @property + def yyyx(self, /) -> Vec4: ... + @property + def zyyx(self, /) -> Vec4: ... + @property + def wyyx(self, /) -> Vec4: ... + @property + def xzyx(self, /) -> Vec4: ... + @property + def yzyx(self, /) -> Vec4: ... + @property + def zzyx(self, /) -> Vec4: ... + @property + def wzyx(self, /) -> Vec4: ... + @property + def xwyx(self, /) -> Vec4: ... + @property + def ywyx(self, /) -> Vec4: ... + @property + def zwyx(self, /) -> Vec4: ... + @property + def wwyx(self, /) -> Vec4: ... + @property + def xxzx(self, /) -> Vec4: ... + @property + def yxzx(self, /) -> Vec4: ... + @property + def zxzx(self, /) -> Vec4: ... + @property + def wxzx(self, /) -> Vec4: ... + @property + def xyzx(self, /) -> Vec4: ... + @property + def yyzx(self, /) -> Vec4: ... + @property + def zyzx(self, /) -> Vec4: ... + @property + def wyzx(self, /) -> Vec4: ... + @property + def xzzx(self, /) -> Vec4: ... + @property + def yzzx(self, /) -> Vec4: ... + @property + def zzzx(self, /) -> Vec4: ... + @property + def wzzx(self, /) -> Vec4: ... + @property + def xwzx(self, /) -> Vec4: ... + @property + def ywzx(self, /) -> Vec4: ... + @property + def zwzx(self, /) -> Vec4: ... + @property + def wwzx(self, /) -> Vec4: ... + @property + def xxwx(self, /) -> Vec4: ... + @property + def yxwx(self, /) -> Vec4: ... + @property + def zxwx(self, /) -> Vec4: ... + @property + def wxwx(self, /) -> Vec4: ... + @property + def xywx(self, /) -> Vec4: ... + @property + def yywx(self, /) -> Vec4: ... + @property + def zywx(self, /) -> Vec4: ... + @property + def wywx(self, /) -> Vec4: ... + @property + def xzwx(self, /) -> Vec4: ... + @property + def yzwx(self, /) -> Vec4: ... + @property + def zzwx(self, /) -> Vec4: ... + @property + def wzwx(self, /) -> Vec4: ... + @property + def xwwx(self, /) -> Vec4: ... + @property + def ywwx(self, /) -> Vec4: ... + @property + def zwwx(self, /) -> Vec4: ... + @property + def wwwx(self, /) -> Vec4: ... + @property + def xxxy(self, /) -> Vec4: ... + @property + def yxxy(self, /) -> Vec4: ... + @property + def zxxy(self, /) -> Vec4: ... + @property + def wxxy(self, /) -> Vec4: ... + @property + def xyxy(self, /) -> Vec4: ... + @property + def yyxy(self, /) -> Vec4: ... + @property + def zyxy(self, /) -> Vec4: ... + @property + def wyxy(self, /) -> Vec4: ... + @property + def xzxy(self, /) -> Vec4: ... + @property + def yzxy(self, /) -> Vec4: ... + @property + def zzxy(self, /) -> Vec4: ... + @property + def wzxy(self, /) -> Vec4: ... + @property + def xwxy(self, /) -> Vec4: ... + @property + def ywxy(self, /) -> Vec4: ... + @property + def zwxy(self, /) -> Vec4: ... + @property + def wwxy(self, /) -> Vec4: ... + @property + def xxyy(self, /) -> Vec4: ... + @property + def yxyy(self, /) -> Vec4: ... + @property + def zxyy(self, /) -> Vec4: ... + @property + def wxyy(self, /) -> Vec4: ... + @property + def xyyy(self, /) -> Vec4: ... + @property + def yyyy(self, /) -> Vec4: ... + @property + def zyyy(self, /) -> Vec4: ... + @property + def wyyy(self, /) -> Vec4: ... + @property + def xzyy(self, /) -> Vec4: ... + @property + def yzyy(self, /) -> Vec4: ... + @property + def zzyy(self, /) -> Vec4: ... + @property + def wzyy(self, /) -> Vec4: ... + @property + def xwyy(self, /) -> Vec4: ... + @property + def ywyy(self, /) -> Vec4: ... + @property + def zwyy(self, /) -> Vec4: ... + @property + def wwyy(self, /) -> Vec4: ... + @property + def xxzy(self, /) -> Vec4: ... + @property + def yxzy(self, /) -> Vec4: ... + @property + def zxzy(self, /) -> Vec4: ... + @property + def wxzy(self, /) -> Vec4: ... + @property + def xyzy(self, /) -> Vec4: ... + @property + def yyzy(self, /) -> Vec4: ... + @property + def zyzy(self, /) -> Vec4: ... + @property + def wyzy(self, /) -> Vec4: ... + @property + def xzzy(self, /) -> Vec4: ... + @property + def yzzy(self, /) -> Vec4: ... + @property + def zzzy(self, /) -> Vec4: ... + @property + def wzzy(self, /) -> Vec4: ... + @property + def xwzy(self, /) -> Vec4: ... + @property + def ywzy(self, /) -> Vec4: ... + @property + def zwzy(self, /) -> Vec4: ... + @property + def wwzy(self, /) -> Vec4: ... + @property + def xxwy(self, /) -> Vec4: ... + @property + def yxwy(self, /) -> Vec4: ... + @property + def zxwy(self, /) -> Vec4: ... + @property + def wxwy(self, /) -> Vec4: ... + @property + def xywy(self, /) -> Vec4: ... + @property + def yywy(self, /) -> Vec4: ... + @property + def zywy(self, /) -> Vec4: ... + @property + def wywy(self, /) -> Vec4: ... + @property + def xzwy(self, /) -> Vec4: ... + @property + def yzwy(self, /) -> Vec4: ... + @property + def zzwy(self, /) -> Vec4: ... + @property + def wzwy(self, /) -> Vec4: ... + @property + def xwwy(self, /) -> Vec4: ... + @property + def ywwy(self, /) -> Vec4: ... + @property + def zwwy(self, /) -> Vec4: ... + @property + def wwwy(self, /) -> Vec4: ... + @property + def xxxz(self, /) -> Vec4: ... + @property + def yxxz(self, /) -> Vec4: ... + @property + def zxxz(self, /) -> Vec4: ... + @property + def wxxz(self, /) -> Vec4: ... + @property + def xyxz(self, /) -> Vec4: ... + @property + def yyxz(self, /) -> Vec4: ... + @property + def zyxz(self, /) -> Vec4: ... + @property + def wyxz(self, /) -> Vec4: ... + @property + def xzxz(self, /) -> Vec4: ... + @property + def yzxz(self, /) -> Vec4: ... + @property + def zzxz(self, /) -> Vec4: ... + @property + def wzxz(self, /) -> Vec4: ... + @property + def xwxz(self, /) -> Vec4: ... + @property + def ywxz(self, /) -> Vec4: ... + @property + def zwxz(self, /) -> Vec4: ... + @property + def wwxz(self, /) -> Vec4: ... + @property + def xxyz(self, /) -> Vec4: ... + @property + def yxyz(self, /) -> Vec4: ... + @property + def zxyz(self, /) -> Vec4: ... + @property + def wxyz(self, /) -> Vec4: ... + @property + def xyyz(self, /) -> Vec4: ... + @property + def yyyz(self, /) -> Vec4: ... + @property + def zyyz(self, /) -> Vec4: ... + @property + def wyyz(self, /) -> Vec4: ... + @property + def xzyz(self, /) -> Vec4: ... + @property + def yzyz(self, /) -> Vec4: ... + @property + def zzyz(self, /) -> Vec4: ... + @property + def wzyz(self, /) -> Vec4: ... + @property + def xwyz(self, /) -> Vec4: ... + @property + def ywyz(self, /) -> Vec4: ... + @property + def zwyz(self, /) -> Vec4: ... + @property + def wwyz(self, /) -> Vec4: ... + @property + def xxzz(self, /) -> Vec4: ... + @property + def yxzz(self, /) -> Vec4: ... + @property + def zxzz(self, /) -> Vec4: ... + @property + def wxzz(self, /) -> Vec4: ... + @property + def xyzz(self, /) -> Vec4: ... + @property + def yyzz(self, /) -> Vec4: ... + @property + def zyzz(self, /) -> Vec4: ... + @property + def wyzz(self, /) -> Vec4: ... + @property + def xzzz(self, /) -> Vec4: ... + @property + def yzzz(self, /) -> Vec4: ... + @property + def zzzz(self, /) -> Vec4: ... + @property + def wzzz(self, /) -> Vec4: ... + @property + def xwzz(self, /) -> Vec4: ... + @property + def ywzz(self, /) -> Vec4: ... + @property + def zwzz(self, /) -> Vec4: ... + @property + def wwzz(self, /) -> Vec4: ... + @property + def xxwz(self, /) -> Vec4: ... + @property + def yxwz(self, /) -> Vec4: ... + @property + def zxwz(self, /) -> Vec4: ... + @property + def wxwz(self, /) -> Vec4: ... + @property + def xywz(self, /) -> Vec4: ... + @property + def yywz(self, /) -> Vec4: ... + @property + def zywz(self, /) -> Vec4: ... + @property + def wywz(self, /) -> Vec4: ... + @property + def xzwz(self, /) -> Vec4: ... + @property + def yzwz(self, /) -> Vec4: ... + @property + def zzwz(self, /) -> Vec4: ... + @property + def wzwz(self, /) -> Vec4: ... + @property + def xwwz(self, /) -> Vec4: ... + @property + def ywwz(self, /) -> Vec4: ... + @property + def zwwz(self, /) -> Vec4: ... + @property + def wwwz(self, /) -> Vec4: ... + @property + def xxxw(self, /) -> Vec4: ... + @property + def yxxw(self, /) -> Vec4: ... + @property + def zxxw(self, /) -> Vec4: ... + @property + def wxxw(self, /) -> Vec4: ... + @property + def xyxw(self, /) -> Vec4: ... + @property + def yyxw(self, /) -> Vec4: ... + @property + def zyxw(self, /) -> Vec4: ... + @property + def wyxw(self, /) -> Vec4: ... + @property + def xzxw(self, /) -> Vec4: ... + @property + def yzxw(self, /) -> Vec4: ... + @property + def zzxw(self, /) -> Vec4: ... + @property + def wzxw(self, /) -> Vec4: ... + @property + def xwxw(self, /) -> Vec4: ... + @property + def ywxw(self, /) -> Vec4: ... + @property + def zwxw(self, /) -> Vec4: ... + @property + def wwxw(self, /) -> Vec4: ... + @property + def xxyw(self, /) -> Vec4: ... + @property + def yxyw(self, /) -> Vec4: ... + @property + def zxyw(self, /) -> Vec4: ... + @property + def wxyw(self, /) -> Vec4: ... + @property + def xyyw(self, /) -> Vec4: ... + @property + def yyyw(self, /) -> Vec4: ... + @property + def zyyw(self, /) -> Vec4: ... + @property + def wyyw(self, /) -> Vec4: ... + @property + def xzyw(self, /) -> Vec4: ... + @property + def yzyw(self, /) -> Vec4: ... + @property + def zzyw(self, /) -> Vec4: ... + @property + def wzyw(self, /) -> Vec4: ... + @property + def xwyw(self, /) -> Vec4: ... + @property + def ywyw(self, /) -> Vec4: ... + @property + def zwyw(self, /) -> Vec4: ... + @property + def wwyw(self, /) -> Vec4: ... + @property + def xxzw(self, /) -> Vec4: ... + @property + def yxzw(self, /) -> Vec4: ... + @property + def zxzw(self, /) -> Vec4: ... + @property + def wxzw(self, /) -> Vec4: ... + @property + def xyzw(self, /) -> Vec4: ... + @property + def yyzw(self, /) -> Vec4: ... + @property + def zyzw(self, /) -> Vec4: ... + @property + def wyzw(self, /) -> Vec4: ... + @property + def xzzw(self, /) -> Vec4: ... + @property + def yzzw(self, /) -> Vec4: ... + @property + def zzzw(self, /) -> Vec4: ... + @property + def wzzw(self, /) -> Vec4: ... + @property + def xwzw(self, /) -> Vec4: ... + @property + def ywzw(self, /) -> Vec4: ... + @property + def zwzw(self, /) -> Vec4: ... + @property + def wwzw(self, /) -> Vec4: ... + @property + def xxww(self, /) -> Vec4: ... + @property + def yxww(self, /) -> Vec4: ... + @property + def zxww(self, /) -> Vec4: ... + @property + def wxww(self, /) -> Vec4: ... + @property + def xyww(self, /) -> Vec4: ... + @property + def yyww(self, /) -> Vec4: ... + @property + def zyww(self, /) -> Vec4: ... + @property + def wyww(self, /) -> Vec4: ... + @property + def xzww(self, /) -> Vec4: ... + @property + def yzww(self, /) -> Vec4: ... + @property + def zzww(self, /) -> Vec4: ... + @property + def wzww(self, /) -> Vec4: ... + @property + def xwww(self, /) -> Vec4: ... + @property + def ywww(self, /) -> Vec4: ... + @property + def zwww(self, /) -> Vec4: ... + @property + def wwww(self, /) -> Vec4: ... + +def quat(*args) -> Quat: ... +def vec2(*args) -> Vec2: ... +def vec3(*args) -> Vec3: ... +def vec4(*args) -> Vec4: ... diff --git a/examples/background_image.rs b/examples/background_image.rs index 18c1f1b0..21605132 100644 --- a/examples/background_image.rs +++ b/examples/background_image.rs @@ -1,37 +1,24 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Image, Result, Settings, Sketch}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct BackgroundImage { + logo: Image, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let image = image_load("images/logo.png")?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for BackgroundImage { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command(graphics, DrawCommand::BackgroundImage(image))?; + fn setup(_g: &mut Graphics) -> Result { + let logo = Image::load("images/logo.png")?; + Ok(BackgroundImage { logo }) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background_image(&self.logo); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/blend_modes.rs b/examples/blend_modes.rs index e23cb810..632a797d 100644 --- a/examples/blend_modes.rs +++ b/examples/blend_modes.rs @@ -1,8 +1,6 @@ -use processing_glfw::GlfwContext; +use processing::{BlendMode, Graphics, Key, Result, Settings, Sketch}; -use processing::prelude::*; - -const MODES: &[BlendMode] = &[ +const MODES: [BlendMode; 10] = [ BlendMode::Blend, BlendMode::Add, BlendMode::Subtract, @@ -15,95 +13,43 @@ const MODES: &[BlendMode] = &[ BlendMode::Replace, ]; -fn main() { - match sketch() { - Ok(_) => exit(0).unwrap(), - Err(e) => { - eprintln!("Error: {e:?}"); - exit(1).unwrap(); - } - } +struct BlendModes { + index: usize, } -fn sketch() -> error::Result<()> { - let width = 500; - let height = 500; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; +impl Sketch for BlendModes { + fn settings() -> Settings { + Settings::size(500, 500) + } - let mut index: usize = 0; + fn setup(_g: &mut Graphics) -> Result { + Ok(BlendModes { index: 0 }) + } - while glfw_ctx.poll_events() { - if input_key_just_pressed(KeyCode::ArrowRight)? || input_key_just_pressed(KeyCode::Space)? { - index = (index + 1) % MODES.len(); - eprintln!("{}", MODES[index].name()); - } else if input_key_just_pressed(KeyCode::ArrowLeft)? { - index = (index + MODES.len() - 1) % MODES.len(); - eprintln!("{}", MODES[index].name()); + fn draw(&mut self, g: &mut Graphics) { + if g.key_just_pressed(Key::Right) || g.key_just_pressed(Key::Space) { + self.index = (self.index + 1) % MODES.len(); + eprintln!("{}", MODES[self.index].name()); + } else if g.key_just_pressed(Key::Left) { + self.index = (self.index + MODES.len() - 1) % MODES.len(); + eprintln!("{}", MODES[self.index].name()); } - graphics_begin_draw(graphics)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgba(0.15, 0.15, 0.15, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::NoStroke)?; - graphics_record_command( - graphics, - DrawCommand::BlendMode(MODES[index].to_blend_state()), - )?; + g.background((0.15, 0.15, 0.15)); + g.no_stroke(); + g.blend_mode(MODES[self.index]); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.9, 0.2, 0.2, 0.75)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 80.0, - y: 100.0, - w: 200.0, - h: 250.0, - radii: [0.0; 4], - }, - )?; + g.fill((0.9, 0.2, 0.2, 0.75)); + g.rect(80, 100, 200, 250); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.2, 0.8, 0.2, 0.75)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 180.0, - y: 80.0, - w: 200.0, - h: 250.0, - radii: [0.0; 4], - }, - )?; + g.fill((0.2, 0.8, 0.2, 0.75)); + g.rect(180, 80, 200, 250); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.2, 0.3, 0.9, 0.75)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 130.0, - y: 200.0, - w: 200.0, - h: 200.0, - radii: [0.0; 4], - }, - )?; - - graphics_end_draw(graphics)?; + g.fill((0.2, 0.3, 0.9, 0.75)); + g.rect(130, 200, 200, 200); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/create_graphics.rs b/examples/create_graphics.rs new file mode 100644 index 00000000..cef3179a --- /dev/null +++ b/examples/create_graphics.rs @@ -0,0 +1,40 @@ +use processing::{Graphics, Result, Settings, Sketch}; + +struct CreateGraphics { + pg: Graphics, +} + +impl Sketch for CreateGraphics { + fn settings() -> Settings { + Settings::size(640, 360) + } + + fn setup(_g: &mut Graphics) -> Result { + let pg = Graphics::create(400, 200)?; + Ok(CreateGraphics { pg }) + } + + fn draw(&mut self, g: &mut Graphics) { + let mx = g.mouse_x(); + let my = g.mouse_y(); + + g.fill((0, 12)); + g.rect(0, 0, g.width(), g.height()); + g.fill(255); + g.no_stroke(); + g.ellipse(mx, my, 60, 60); + + let mut pg = self.pg.begin_draw(); + pg.background(51); + pg.no_fill(); + pg.stroke(255); + pg.ellipse(mx - 120.0, my - 60.0, 60, 60); + drop(pg); + + g.image(&self.pg, 120, 60); + } +} + +fn main() -> Result<()> { + processing::run::() +} diff --git a/examples/curves.rs b/examples/curves.rs index b15ccdff..f75d68e9 100644 --- a/examples/curves.rs +++ b/examples/curves.rs @@ -1,105 +1,73 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Curves { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(800, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(800, 400, false)?; - let graphics = graphics_create(surface, 800, 400, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Curves { + fn settings() -> Settings { + Settings::size(800, 400) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.06)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Curves { t: 0.0 }) + } - graphics_record_command(graphics, DrawCommand::NoFill)?; + fn draw(&mut self, g: &mut Graphics) { + let t = self.t; + g.background((0.04, 0.04, 0.06)); + g.no_fill(); - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.5))?; + // bezier waves + g.stroke_weight(1.5); for i in 0..20 { - let y_base = 20.0 + i as f32 * 15.0; + let y = 20.0 + i as f32 * 15.0; let phase = t + i as f32 * 0.3; let amp = 30.0 + (i as f32 * 0.5).sin() * 20.0; - let v = 0.3 + (i as f32 / 20.0) * 0.5; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(v * 0.6, v, (v * 1.2).min(1.0))), - )?; - - graphics_record_command( - graphics, - DrawCommand::Bezier { - x1: 0.0, - y1: y_base, - x2: 250.0, - y2: y_base + amp * phase.sin(), - x3: 550.0, - y3: y_base - amp * (phase * 1.3).cos(), - x4: 800.0, - y4: y_base, - }, - )?; + g.stroke((v * 0.6, v, (v * 1.2).min(1.0))); + g.bezier( + 0, + y, + 250, + y + amp * phase.sin(), + 550, + y - amp * (phase * 1.3).cos(), + 800, + y, + ); } - graphics_record_command(graphics, DrawCommand::StrokeWeight(0.8))?; + // catmull-rom curves + g.stroke_weight(0.8); + g.stroke((1.0, 0.6, 0.2, 0.4)); for i in 0..8 { - let y_base = 50.0 + i as f32 * 40.0; + let y = 50.0 + i as f32 * 40.0; let phase = t * 0.7 + i as f32 * 0.5; - - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgba(1.0, 0.6, 0.2, 0.4)), - )?; - - graphics_record_command( - graphics, - DrawCommand::Curve { - x1: -50.0, - y1: y_base + 40.0 * phase.sin(), - x2: 200.0, - y2: y_base + 30.0 * (phase * 1.2).cos(), - x3: 600.0, - y3: y_base - 30.0 * (phase * 0.8).sin(), - x4: 850.0, - y4: y_base + 20.0 * phase.cos(), - }, - )?; + g.curve( + -50, + y + 40.0 * phase.sin(), + 200, + y + 30.0 * (phase * 1.2).cos(), + 600, + y - 30.0 * (phase * 0.8).sin(), + 850, + y + 20.0 * phase.cos(), + ); } - graphics_record_command(graphics, DrawCommand::StrokeWeight(0.3))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgba(1.0, 1.0, 1.0, 0.08)), - )?; + // guide lines + g.stroke_weight(0.3); + g.stroke((1.0, 1.0, 1.0, 0.08)); for i in 0..20 { - let y = 20.0 * i as f32; - graphics_record_command( - graphics, - DrawCommand::Line { - x1: 0.0, - y1: y, - x2: 800.0, - y2: y, - }, - )?; + let y = 20 * i; + g.line(0, y, 800, y); } - graphics_end_draw(graphics)?; - t += 0.012; + self.t += 0.012; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/input.rs b/examples/input.rs index fd335ac7..d4a52524 100644 --- a/examples/input.rs +++ b/examples/input.rs @@ -1,71 +1,32 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Key, Result, Settings, Sketch}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +struct Input; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let width = 400; - let height = 400; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - - let mx = input_mouse_x(surface)?; - let my = input_mouse_y(surface)?; +impl Sketch for Input { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.15, 0.15, 0.2)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Input) + } - if input_mouse_is_pressed()? { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.25, 0.15, 0.2)), - )?; - } + fn draw(&mut self, g: &mut Graphics) { + g.background((0.15, 0.15, 0.2)); - if input_mouse_is_pressed()? { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.55, 0.25, 0.2)), - )?; + if g.mouse_pressed() { + g.fill((0.55, 0.25, 0.2)); + } else { + g.fill(255); } + g.rect(g.mouse_x() - 25.0, g.mouse_y() - 25.0, 50, 50); - graphics_record_command( - graphics, - DrawCommand::Rect { - x: mx - 25.0, - y: my - 25.0, - w: 50.0, - h: 50.0, - radii: [0.0; 4], - }, - )?; - - if input_key_is_pressed()? && input_key_is_down(KeyCode::Escape)? { - break; + if g.key_down(Key::Escape) { + g.exit(); } - - graphics_end_draw(graphics)?; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/pbr.rs b/examples/pbr.rs index af13268e..072f953e 100644 --- a/examples/pbr.rs +++ b/examples/pbr.rs @@ -1,96 +1,56 @@ -use processing_glfw::GlfwContext; +use processing::{Color, Graphics, Light, Result, Settings, Sketch}; -use bevy::math::{Vec2, Vec3}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +const COLS: u32 = 11; +const ROWS: u32 = 5; +const SPACING: f32 = 70.0; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct Pbr { + sun: Light, + lamp: Light, } -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 600.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.98, 0.95), 1_500.0)?; - transform_set_position(dir_light, Vec3::new(300.0, -400.0, 300.0))?; - transform_look_at(dir_light, Vec3::new(0.0, 0.0, 0.0))?; - - let point_light = - light_create_point(graphics, bevy::color::Color::WHITE, 100_000.0, 800.0, 0.0)?; - transform_set_position(point_light, Vec3::new(200.0, -200.0, 400.0))?; - - let cols = 11; - let rows = 5; - let base_color = bevy::color::Color::srgb(1.0, 0.85, 0.57); - let spacing = 70.0; - let offset_x = (cols - 1) as f32 * spacing / 2.0; - let offset_y = (rows - 1) as f32 * spacing / 2.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - graphics_light(graphics, point_light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.07)), - )?; +impl Sketch for Pbr { + fn settings() -> Settings { + Settings::size(800, 600) + } - graphics_record_command(graphics, DrawCommand::Fill(base_color))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 600)); + g.camera_look_at((0, 0, 0)); - for row in 0..rows { - for col in 0..cols { - let roughness = col as f32 / (cols - 1) as f32; - let metallic = row as f32 / (rows - 1) as f32; + let sun = g.create_directional_light((1.0, 0.98, 0.95), 1500); + sun.position((300, -400, 300)).look_at((0, 0, 0)); + let lamp = g.create_point_light(Color::WHITE, 100_000, 800, 0); + lamp.position((200, -200, 400)); - graphics_record_command(graphics, DrawCommand::Roughness(roughness))?; - graphics_record_command(graphics, DrawCommand::Metallic(metallic))?; + Ok(Pbr { sun, lamp }) + } - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate( - Vec2::new( - col as f32 * spacing - offset_x, - offset_y - row as f32 * spacing, - ) - .extend(0.0), - ), - )?; - graphics_record_command( - graphics, - DrawCommand::Sphere { - radius: 30.0, - sectors: 32, - stacks: 18, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.05, 0.05, 0.07)); + g.light(&self.sun); + g.light(&self.lamp); + g.fill((1.0, 0.85, 0.57)); + + let offset_x = (COLS - 1) as f32 * SPACING / 2.0; + let offset_y = (ROWS - 1) as f32 * SPACING / 2.0; + for row in 0..ROWS { + for col in 0..COLS { + g.roughness(col as f32 / (COLS - 1) as f32); + g.metallic(row as f32 / (ROWS - 1) as f32); + + let mut g = g.push(); + g.translate(( + col as f32 * SPACING - offset_x, + offset_y - row as f32 * SPACING, + )); + g.sphere(30).detail(32, 18); } } - - graphics_end_draw(graphics)?; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/primitives_2d.rs b/examples/primitives_2d.rs index a257777b..1e82face 100644 --- a/examples/primitives_2d.rs +++ b/examples/primitives_2d.rs @@ -1,125 +1,72 @@ -use processing_glfw::GlfwContext; use std::f32::consts::PI; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +use processing::{Graphics, Result, Settings, Sketch}; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Primitives2d { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 600, false)?; - let graphics = graphics_create(surface, 600, 600, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Primitives2d { + fn settings() -> Settings { + Settings::size(600, 600) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.95, 0.93, 0.9)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Primitives2d { t: 0.0 }) + } + fn draw(&mut self, g: &mut Graphics) { + let t = self.t; let cx = 300.0; let cy = 300.0; + g.background((0.95, 0.93, 0.9)); - graphics_record_command(graphics, DrawCommand::NoFill)?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(2.0))?; - + // concentric arcs + g.no_fill(); + g.stroke_weight(2); for i in 0..12 { let r = 40.0 + i as f32 * 18.0; - let offset = t + i as f32 * 0.15; + let start = t + i as f32 * 0.15; let v = 0.2 + (i as f32 / 12.0) * 0.4; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(v, v * 0.8, v * 0.6)), - )?; - graphics_record_command( - graphics, - DrawCommand::Arc { - cx, - cy, - w: r * 2.0, - h: r * 2.0, - start: offset, - stop: offset + PI * 1.2, - mode: ArcMode::Open, - }, - )?; + g.stroke((v, v * 0.8, v * 0.6)); + g.arc(cx, cy, r * 2.0, r * 2.0, start, start + PI * 1.2); } - graphics_record_command(graphics, DrawCommand::NoStroke)?; + // dots riding the arcs + g.no_stroke(); for i in 0..12 { let r = 40.0 + i as f32 * 18.0; let angle = t + i as f32 * 0.15; - let x = cx + r * angle.cos(); - let y = cy + r * angle.sin(); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.85, 0.3 + i as f32 / 24.0, 0.2)), - )?; - graphics_record_command( - graphics, - DrawCommand::Ellipse { - cx: x, - cy: y, - w: 6.0, - h: 6.0, - }, - )?; + g.fill((0.85, 0.3 + i as f32 / 24.0, 0.2)); + g.circle(cx + r * angle.cos(), cy + r * angle.sin(), 6); } - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.1, 0.1, 0.1, 0.15)), - )?; + // orbiting triangles + g.fill((0.1, 0.1, 0.1, 0.15)); for i in 0..6 { let angle = t * 0.5 + i as f32 * PI / 3.0; - let d = 250.0; - let px = cx + d * angle.cos(); - let py = cy + d * angle.sin(); + let x = cx + 250.0 * angle.cos(); + let y = cy + 250.0 * angle.sin(); let s = 20.0; - graphics_record_command( - graphics, - DrawCommand::Triangle { - x1: px, - y1: py - s, - x2: px - s * 0.866, - y2: py + s * 0.5, - x3: px + s * 0.866, - y3: py + s * 0.5, - }, - )?; + g.triangle( + x, + y - s, + x - s * 0.866, + y + s * 0.5, + x + s * 0.866, + y + s * 0.5, + ); } + // pulsing diamond let d = 15.0 + 5.0 * (t * 3.0).sin(); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.9, 0.4, 0.1, 0.4)), - )?; - graphics_record_command( - graphics, - DrawCommand::Quad { - x1: cx, - y1: cy - d, - x2: cx + d, - y2: cy, - x3: cx, - y3: cy + d, - x4: cx - d, - y4: cy, - }, - )?; + g.fill((0.9, 0.4, 0.1, 0.4)); + g.quad(cx, cy - d, cx + d, cy, cx, cy + d, cx - d, cy); - graphics_end_draw(graphics)?; - t += 0.01; + self.t += 0.01; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/primitives_3d.rs b/examples/primitives_3d.rs index ceda4cd4..21b147e1 100644 --- a/examples/primitives_3d.rs +++ b/examples/primitives_3d.rs @@ -1,130 +1,63 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch}; -use bevy::math::{Vec2, Vec3}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Primitives3d { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 400, false)?; - let graphics = graphics_create(surface, 900, 400, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -80.0, 800.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; - - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.35))?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - - graphics_record_command(graphics, DrawCommand::Fill(bevy::color::Color::WHITE))?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; +impl Sketch for Primitives3d { + fn settings() -> Settings { + Settings::size(900, 400) + } - let shapes: Vec<(f32, Box DrawCommand>)> = vec![ - ( - -315.0, - Box::new(|_| DrawCommand::Box { - width: 50.0, - height: 50.0, - depth: 50.0, - }), - ), - ( - -225.0, - Box::new(|_| DrawCommand::Sphere { - radius: 30.0, - sectors: 24, - stacks: 16, - }), - ), - ( - -135.0, - Box::new(|_| DrawCommand::Cylinder { - radius: 25.0, - height: 60.0, - detail: 24, - }), - ), - ( - -45.0, - Box::new(|_| DrawCommand::Cone { - radius: 25.0, - height: 60.0, - detail: 24, - }), - ), - ( - 45.0, - Box::new(|_| DrawCommand::Torus { - radius: 30.0, - tube_radius: 10.0, - major_segments: 24, - minor_segments: 16, - }), - ), - ( - 135.0, - Box::new(|_| DrawCommand::Capsule { - radius: 15.0, - length: 40.0, - detail: 24, - }), - ), - ( - 225.0, - Box::new(|_| DrawCommand::ConicalFrustum { - radius_top: 15.0, - radius_bottom: 25.0, - height: 60.0, - detail: 24, - }), - ), - ( - 315.0, - Box::new(|_| DrawCommand::Tetrahedron { radius: 30.0 }), - ), - ]; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, -80, 800)); + g.camera_look_at((0, 0, 0)); + Ok(Primitives3d { t: 0.0 }) + } - for (x_offset, make_cmd) in &shapes { - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(*x_offset, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -t, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, make_cmd(t))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.06, 0.06, 0.08)); + g.directional_light((0.9, 0.85, 0.8), 300); + g.fill(255); + g.roughness(0.35); + + for i in 0..8 { + let mut g = g.push(); + g.translate((-315 + i * 90, 0)); + g.rotate(-self.t); + match i { + 0 => { + g.cube(50); + } + 1 => { + g.sphere(30).detail(24, 16); + } + 2 => { + g.cylinder(25, 60).detail(24); + } + 3 => { + g.cone(25, 60).detail(24); + } + 4 => { + g.torus(30, 10).detail(24, 16); + } + 5 => { + g.capsule(15, 40).detail(24); + } + 6 => { + g.conical_frustum(15, 25, 60).detail(24); + } + _ => { + g.tetrahedron(30); + } + } } - graphics_end_draw(graphics)?; - t += 0.015; + self.t += 0.015; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/rectangle.rs b/examples/rectangle.rs index 1f75466c..bde06d36 100644 --- a/examples/rectangle.rs +++ b/examples/rectangle.rs @@ -1,45 +1,21 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +struct Rectangle; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Rectangle { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 10.0, - y: 10.0, - w: 100.0, - h: 100.0, - radii: [0.0, 0.0, 0.0, 0.0], - }, - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Rectangle) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.rect(10, 10, 100, 100); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/shapes.rs b/examples/shapes.rs index 23820b68..b16742eb 100644 --- a/examples/shapes.rs +++ b/examples/shapes.rs @@ -1,162 +1,80 @@ -use processing_glfw::GlfwContext; use std::f32::consts::PI; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +use processing::{Graphics, Result, Settings, ShapeKind, Sketch}; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Shapes { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 600, false)?; - let graphics = graphics_create(surface, 600, 600, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Shapes { + fn settings() -> Settings { + Settings::size(600, 600) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.92, 0.90, 0.87)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Shapes { t: 0.0 }) + } - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.2, 0.3, 0.5, 0.25)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.5))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.15, 0.2, 0.35)), - )?; + fn draw(&mut self, g: &mut Graphics) { + let t = self.t; + g.background((235, 230, 222)); + // a wobbling blob made of curve vertices + g.fill((0.2, 0.3, 0.5, 0.25)); + g.stroke_weight(1.5); + g.stroke((38, 51, 89)); let n = 8; - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::Polygon, - }, - )?; - + let mut blob = g.begin_shape(ShapeKind::Polygon); for i in 0..n + 3 { let idx = (i + n - 1) % n; let angle = idx as f32 * 2.0 * PI / n as f32; let r = 100.0 + 30.0 * (t * 2.0 + idx as f32 * 0.8).sin(); - graphics_record_command( - graphics, - DrawCommand::ShapeCurveVertex { - x: 170.0 + r * angle.cos(), - y: 200.0 + r * angle.sin(), - }, - )?; + blob.curve_vertex(170.0 + r * angle.cos(), 200.0 + r * angle.sin()); } - - graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.15, 0.5, 0.3, 0.2)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.0))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.1, 0.35, 0.2)), - )?; - - let pcx = 430.0; - let pcy = 200.0; + blob.close(); + + // a pulsing lens made of two bezier segments + g.fill((0.15, 0.5, 0.3, 0.2)); + g.stroke_weight(1); + g.stroke((26, 89, 51)); + let cx = 430.0; + let cy = 200.0; let s = 70.0 + 10.0 * (t * 1.5).sin(); - - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::Polygon, - }, - )?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x: pcx, y: pcy - s })?; - graphics_record_command( - graphics, - DrawCommand::ShapeBezierVertex { - cx1: pcx + s, - cy1: pcy - s, - cx2: pcx + s, - cy2: pcy + s, - x: pcx, - y: pcy + s, - }, - )?; - graphics_record_command( - graphics, - DrawCommand::ShapeBezierVertex { - cx1: pcx - s, - cy1: pcy + s, - cx2: pcx - s, - cy2: pcy - s, - x: pcx, - y: pcy - s, - }, - )?; - graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.8, 0.35, 0.1, 0.15)), - )?; - graphics_record_command(graphics, DrawCommand::NoStroke)?; - - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::TriangleFan, - }, - )?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x: 170.0, y: 450.0 })?; + let mut lens = g.begin_shape(ShapeKind::Polygon); + lens.vertex(cx, cy - s); + lens.bezier_vertex(cx + s, cy - s, cx + s, cy + s, cx, cy + s); + lens.bezier_vertex(cx - s, cy + s, cx - s, cy - s, cx, cy - s); + lens.close(); + + // a flower as a triangle fan + g.fill((0.8, 0.35, 0.1, 0.15)); + g.no_stroke(); + let mut fan = g.begin_shape(ShapeKind::TriangleFan); + fan.vertex(170, 450); for i in 0..=16 { let angle = i as f32 * 2.0 * PI / 16.0; let r = 60.0 + 20.0 * (t * 3.0 + angle * 2.0).sin(); - graphics_record_command( - graphics, - DrawCommand::ShapeVertex { - x: 170.0 + r * angle.cos(), - y: 450.0 + r * angle.sin(), - }, - )?; + fan.vertex(170.0 + r * angle.cos(), 450.0 + r * angle.sin()); } - graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.5, 0.2, 0.6, 0.2)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(0.5))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgba(0.3, 0.1, 0.4, 0.4)), - )?; + fan.close(); - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::TriangleStrip, - }, - )?; + // a wave as a triangle strip + g.fill((0.5, 0.2, 0.6, 0.2)); + g.stroke_weight(0.5); + g.stroke((77, 26, 102, 102)); + let mut strip = g.begin_shape(ShapeKind::TriangleStrip); for i in 0..16 { let x = 320.0 + i as f32 * 17.0; let wave = 30.0 * (t * 2.0 + i as f32 * 0.4).sin(); - graphics_record_command(graphics, DrawCommand::ShapeVertex { x, y: 420.0 + wave })?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x, y: 480.0 + wave })?; + strip.vertex(x, 420.0 + wave); + strip.vertex(x, 480.0 + wave); } - graphics_record_command(graphics, DrawCommand::EndShape { close: false })?; + strip.end(); - graphics_end_draw(graphics)?; - t += 0.02; + self.t += 0.02; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/stroke_2d.rs b/examples/stroke_2d.rs index 3eafdf54..43c4c395 100644 --- a/examples/stroke_2d.rs +++ b/examples/stroke_2d.rs @@ -1,66 +1,31 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch, StrokeJoin}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +struct Stroke2d; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 300, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 300, false)?; - let graphics = graphics_create(surface, 600, 300, TextureFormat::Rgba16Float)?; - - let joins = [ - StrokeJoinMode::Round, - StrokeJoinMode::Miter, - StrokeJoinMode::Bevel, - ]; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.15, 0.15, 0.2)), - )?; - - graphics_record_command(graphics, DrawCommand::StrokeWeight(12.0))?; +impl Sketch for Stroke2d { + fn settings() -> Settings { + Settings::size(600, 300) + } - for (i, &join) in joins.iter().enumerate() { - let x = 30.0 + i as f32 * 190.0; - let y = 50.0; + fn setup(_g: &mut Graphics) -> Result { + Ok(Stroke2d) + } - graphics_record_command(graphics, DrawCommand::StrokeJoin(join))?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.15, 0.15, 0.2)); + g.stroke_weight(12); + g.stroke((1.0, 0.9, 0.3)); + let joins = [StrokeJoin::Round, StrokeJoin::Miter, StrokeJoin::Bevel]; + for (i, join) in joins.into_iter().enumerate() { let hue = i as f32 * 0.3; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.3 + hue, 0.5, 0.8 - hue)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(1.0, 0.9, 0.3)), - )?; - - graphics_record_command( - graphics, - DrawCommand::Rect { - x, - y, - w: 150.0, - h: 180.0, - radii: [0.0; 4], - }, - )?; + g.stroke_join(join); + g.fill((0.3 + hue, 0.5, 0.8 - hue)); + g.rect(30.0 + i as f32 * 190.0, 50, 150, 180); } - - graphics_end_draw(graphics)?; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/stroke_3d.rs b/examples/stroke_3d.rs index d2067946..a368b802 100644 --- a/examples/stroke_3d.rs +++ b/examples/stroke_3d.rs @@ -1,172 +1,73 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch}; -use bevy::math::{Vec2, Vec3}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Stroke3d { + angle: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 400, false)?; - let graphics = graphics_create(surface, 600, 400, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(200.0, -150.0, 350.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 800.0)?; - - let mut angle: f32 = 0.0; +impl Sketch for Stroke3d { + fn settings() -> Settings { + Settings::size(600, 400) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((200, -150, 350)); + g.camera_look_at((0, 0, 0)); + Ok(Stroke3d { angle: 0.0 }) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.08, 0.08, 0.12)), - )?; + fn draw(&mut self, g: &mut Graphics) { + let angle = self.angle; + g.background((0.08, 0.08, 0.12)); + g.directional_light((0.9, 0.85, 0.8), 800); // thin wireframe box - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(-80.0, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.3, 0.4, 0.7)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(1.0, 1.0, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.0))?; - - graphics_record_command( - graphics, - DrawCommand::Box { - width: 60.0, - height: 60.0, - depth: 60.0, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + { + let mut g = g.push(); + g.translate((-80, 0)); + g.rotate(-angle); + g.fill((0.3, 0.4, 0.7)); + g.stroke(255); + g.stroke_weight(1); + g.cube(60); + } // thick wireframe box - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command(graphics, DrawCommand::Translate(Vec2::ZERO.extend(0.0)))?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle * 0.7, - axis: Vec3::Z, - }, - )?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.7, 0.3, 0.4)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(1.0, 0.9, 0.2)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(3.0))?; - - graphics_record_command( - graphics, - DrawCommand::Box { - width: 50.0, - height: 70.0, - depth: 50.0, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + { + let mut g = g.push(); + g.rotate(-angle * 0.7); + g.fill((0.7, 0.3, 0.4)); + g.stroke((1.0, 0.9, 0.2)); + g.stroke_weight(3); + g.cube((50, 70, 50)); + } // thick wireframe sphere - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(80.0, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle * 0.5, - axis: Vec3::Z, - }, - )?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.3, 0.7, 0.4)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.9, 0.4, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(2.0))?; - - graphics_record_command( - graphics, - DrawCommand::Sphere { - radius: 35.0, - sectors: 16, - stacks: 12, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; - - // wireframe-only sphere (no fill) - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(160.0, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: angle * 0.3, - axis: Vec3::Z, - }, - )?; - - graphics_record_command(graphics, DrawCommand::NoFill)?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.2, 0.8, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.5))?; - - graphics_record_command( - graphics, - DrawCommand::Sphere { - radius: 30.0, - sectors: 24, - stacks: 16, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; - - graphics_end_draw(graphics)?; - angle += 0.015; + { + let mut g = g.push(); + g.translate((80, 0)); + g.rotate(-angle * 0.5); + g.fill((0.3, 0.7, 0.4)); + g.stroke((0.9, 0.4, 1.0)); + g.stroke_weight(2); + g.sphere(35).detail(16, 12); + } + + // wireframe-only sphere + { + let mut g = g.push(); + g.translate((160, 0)); + g.rotate(angle * 0.3); + g.no_fill(); + g.stroke((0.2, 0.8, 1.0)); + g.stroke_weight(1.5); + g.sphere(30).detail(24, 16); + } + + self.angle += 0.015; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/text.rs b/examples/text.rs index 956a56de..4364b48f 100644 --- a/examples/text.rs +++ b/examples/text.rs @@ -1,100 +1,41 @@ -use bevy::prelude::Color; -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch, TextAlignH, TextAlignV}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +struct Text; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 400, false)?; - init(Config::default())?; - - let width = 600; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - - graphics_record_command(graphics, DrawCommand::BackgroundColor(Color::WHITE))?; - graphics_record_command(graphics, DrawCommand::Fill(Color::BLACK))?; - graphics_record_command(graphics, DrawCommand::TextSize(32.0))?; - - graphics_record_command( - graphics, - DrawCommand::Text { - content: "Hello, Processing!".to_string(), - x: 50.0, - y: 100.0, - z: 0.0, - max_w: None, - max_h: None, - }, - )?; - - graphics_record_command(graphics, DrawCommand::TextSize(18.0))?; +impl Sketch for Text { + fn settings() -> Settings { + Settings::size(600, 400) + } - graphics_record_command( - graphics, - DrawCommand::Text { - content: "Text rendering with parley + skrifa + lyon".to_string(), - x: 50.0, - y: 160.0, - z: 0.0, - max_w: None, - max_h: None, - }, - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Text) + } - graphics_record_command(graphics, DrawCommand::TextSize(16.0))?; + fn draw(&mut self, g: &mut Graphics) { + g.background(255); + g.fill(0); - graphics_record_command( - graphics, - DrawCommand::Text { - content: "This is a longer paragraph of text that should wrap within its bounding box. The text uses parley for layout, skrifa for glyph outlines, and lyon for tessellation.".to_string(), - x: 50.0, - y: 220.0, - z: 0.0, - max_w: Some(300.0), - max_h: Some(200.0), - }, - )?; + g.text_size(32); + g.text("Hello, Processing!", 50, 100); - graphics_record_command( - graphics, - DrawCommand::TextAlign { - h: TextAlignH::Center, - v: TextAlignV::Top, - }, - )?; - graphics_record_command(graphics, DrawCommand::TextSize(24.0))?; + g.text_size(18); + g.text("Text rendering with parley + skrifa + lyon", 50, 160); - graphics_record_command( - graphics, - DrawCommand::Text { - content: "Centered".to_string(), - x: 450.0, - y: 100.0, - z: 0.0, - max_w: Some(200.0), - max_h: None, - }, - )?; + g.text_size(16); + g.text( + "This is a longer paragraph of text that should wrap within its bounding box. \ + The text uses parley for layout, skrifa for glyph outlines, and lyon for tessellation.", + 50, + 220, + ) + .bounds(300, 200); - graphics_end_draw(graphics)?; + g.text_align((TextAlignH::Center, TextAlignV::Top)); + g.text_size(24); + g.text("Centered", 450, 100).max_width(200); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/transforms.rs b/examples/transforms.rs index 87fb34af..010c662d 100644 --- a/examples/transforms.rs +++ b/examples/transforms.rs @@ -1,80 +1,38 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; use std::f32::consts::PI; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; +use processing::{Graphics, Result, Settings, Sketch}; - let surface = glfw_ctx.create_surface(400, 400, false)?; - let graphics = graphics_create(surface, 400, 400, TextureFormat::Rgba16Float)?; +struct Transforms { + t: f32, +} - let mut t: f32 = 0.0; +impl Sketch for Transforms { + fn settings() -> Settings { + Settings::size(400, 400) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Transforms { t: 0.0 }) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.1)), - )?; + fn draw(&mut self, g: &mut Graphics) { + g.background(25); for i in 0..4 { for j in 0..4 { - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - - graphics_record_command( - graphics, - DrawCommand::Translate( - Vec2::new(50.0 + j as f32 * 100.0, 50.0 + i as f32 * 100.0).extend(0.0), - ), - )?; - - let angle = t + (i + j) as f32 * PI / 8.0; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle, - axis: Vec3::Z, - }, - )?; - - let s = 0.8 + (t * 2.0 + (i * j) as f32).sin() * 0.2; - graphics_record_command(graphics, DrawCommand::Scale(Vec2::splat(s).extend(1.0)))?; - - let r = j as f32 / 3.0; - let g = i as f32 / 3.0; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(r, g, 0.8)), - )?; - - graphics_record_command( - graphics, - DrawCommand::Rect { - x: -20.0, - y: -20.0, - w: 40.0, - h: 40.0, - radii: [0.0; 4], - }, - )?; - - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + let mut g = g.push(); + g.translate((50 + j * 100, 50 + i * 100)); + g.rotate(self.t + (i + j) as f32 * PI / 8.0); + g.scale(0.8 + (self.t * 2.0 + (i * j) as f32).sin() * 0.2); + g.fill((j as f32 / 3.0, i as f32 / 3.0, 0.8)); + g.rect(-20, -20, 40, 40); } } - graphics_end_draw(graphics)?; - t += 0.02; + self.t += 0.02; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/update_pixels.rs b/examples/update_pixels.rs index 9d8218d7..b332be7e 100644 --- a/examples/update_pixels.rs +++ b/examples/update_pixels.rs @@ -1,82 +1,60 @@ -use processing_glfw::GlfwContext; +use processing::{Color, Graphics, Result, Settings, Sketch}; -use bevy::{color::Color, prelude::LinearRgba}; -use processing::prelude::*; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct UpdatePixels { + first_frame: bool, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(100, 100, false)?; - init(Config::default())?; - - let width = 100; - let height = 100; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let rect_w = 10; - let rect_h = 10; - let red = LinearRgba::new(1.0, 0.0, 0.0, 1.0); - let red_pixels: Vec = vec![red; rect_w * rect_h]; - - let blue = LinearRgba::new(0.0, 0.0, 1.0, 1.0); - let blue_pixels: Vec = vec![blue; rect_w * rect_h]; - - let mut first_frame = true; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for UpdatePixels { + fn settings() -> Settings { + Settings::size(100, 100) + } - graphics_record_command(graphics, DrawCommand::BackgroundColor(Color::BLACK))?; - graphics_flush(graphics)?; - graphics_update_region(graphics, 20, 20, rect_w as u32, rect_h as u32, &red_pixels)?; - graphics_update_region(graphics, 60, 60, rect_w as u32, rect_h as u32, &blue_pixels)?; + fn setup(_g: &mut Graphics) -> Result { + Ok(UpdatePixels { first_frame: true }) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background(0); - if first_frame { - first_frame = false; + let red = vec![Color::rgb(1.0, 0.0, 0.0); 10 * 10]; + let blue = vec![Color::rgb(0.0, 0.0, 1.0); 10 * 10]; + g.set_pixels_region(20, 20, 10, 10, &red).unwrap(); + g.set_pixels_region(60, 60, 10, 10, &blue).unwrap(); - let pixels = graphics_readback(graphics)?; - eprintln!("Total pixels: {}", pixels.len()); + if self.first_frame { + self.first_frame = false; + print_pixels(g); + } + } +} - for y in 0..height { - for x in 0..width { - let idx = (y * width + x) as usize; - if idx < pixels.len() { - let pixel = pixels[idx]; - if pixel.red > 0.5 { - eprint!("R"); - } else if pixel.blue > 0.5 { - eprint!("B"); - } else if pixel.alpha > 0.5 { - eprint!("."); - } else { - eprint!(" "); - } - } - } - eprintln!(); +fn print_pixels(g: &Graphics) { + let pixels = g.pixels().unwrap(); + let width = g.pixel_width() as usize; + eprintln!("Total pixels: {}", pixels.len()); + + for row in pixels.chunks(width) { + for pixel in row { + if pixel.red() > 0.5 { + eprint!("R"); + } else if pixel.blue() > 0.5 { + eprint!("B"); + } else if pixel.alpha() > 0.5 { + eprint!("."); + } else { + eprint!(" "); } - - eprintln!("\nSample pixels:"); - eprintln!("(25, 25): {:?}", pixels[25 * width as usize + 25]); - eprintln!("(65, 65): {:?}", pixels[65 * width as usize + 65]); - eprintln!("(0, 0): {:?}", pixels[0]); - eprintln!("(50, 50): {:?}", pixels[50 * width as usize + 50]); } + eprintln!(); } - Ok(()) + eprintln!("\nSample pixels:"); + eprintln!("(25, 25): {:?}", pixels[25 * width + 25]); + eprintln!("(65, 65): {:?}", pixels[65 * width + 65]); + eprintln!("(0, 0): {:?}", pixels[0]); + eprintln!("(50, 50): {:?}", pixels[50 * width + 50]); +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 00000000..8b6781ee --- /dev/null +++ b/src/args.rs @@ -0,0 +1,89 @@ +//! Argument traits that stand in for Processing's numeric and arity overloads. + +use bevy::math::{Vec2, Vec3}; + +mod sealed { + pub trait Sealed {} +} + +/// Any primitive number, converted to `f32`. +pub trait Scalar: sealed::Sealed + Copy { + fn to_f32(self) -> f32; +} + +macro_rules! scalar { + ($($t:ty),*) => {$( + impl sealed::Sealed for $t {} + impl Scalar for $t { + #[inline] + fn to_f32(self) -> f32 { + self as f32 + } + } + )*}; +} +scalar!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64); + +/// A 2D or 3D point: `(x, y)`, `(x, y, z)`, `Vec2` or `Vec3`. 2D points get `z = 0`. +pub trait IntoPoint { + fn into_point(self) -> Vec3; +} + +impl IntoPoint for (A, B) { + fn into_point(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), 0.0) + } +} + +impl IntoPoint for (A, B, C) { + fn into_point(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), self.2.to_f32()) + } +} + +impl IntoPoint for Vec2 { + fn into_point(self) -> Vec3 { + self.extend(0.0) + } +} + +impl IntoPoint for Vec3 { + fn into_point(self) -> Vec3 { + self + } +} + +/// A per-axis size: one number for all axes, or `(x, y)` / `(x, y, z)`. Missing axes are `1`. +pub trait IntoExtent { + fn into_extent(self) -> Vec3; +} + +impl IntoExtent for T { + fn into_extent(self) -> Vec3 { + Vec3::splat(self.to_f32()) + } +} + +impl IntoExtent for (A, B) { + fn into_extent(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), 1.0) + } +} + +impl IntoExtent for (A, B, C) { + fn into_extent(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), self.2.to_f32()) + } +} + +impl IntoExtent for Vec2 { + fn into_extent(self) -> Vec3 { + self.extend(1.0) + } +} + +impl IntoExtent for Vec3 { + fn into_extent(self) -> Vec3 { + self + } +} diff --git a/src/color.rs b/src/color.rs new file mode 100644 index 00000000..fa5cc98a --- /dev/null +++ b/src/color.rs @@ -0,0 +1,303 @@ +//! Colors and the `fill(..)`-style color arguments. + +use bevy::color::{Alpha, Color as BevyColor, Hsla, Hsva, LinearRgba, Mix, Oklcha, Srgba}; +use processing_render::color::ColorMode; + +pub use processing_render::color::ColorSpace; + +/// A resolved color. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Color(pub(crate) BevyColor); + +impl Color { + pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0); + pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0); + pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0); + + /// sRGB, channels 0-1. + pub const fn rgb(r: f32, g: f32, b: f32) -> Self { + Self::rgba(r, g, b, 1.0) + } + + /// sRGB with alpha, channels 0-1. + pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self { + Self(BevyColor::Srgba(Srgba::new(r, g, b, a))) + } + + /// sRGB, channels 0-255. + pub const fn rgb8(r: u8, g: u8, b: u8) -> Self { + Self::rgba8(r, g, b, 255) + } + + /// sRGB with alpha, channels 0-255. + pub const fn rgba8(r: u8, g: u8, b: u8, a: u8) -> Self { + Self::rgba( + r as f32 / 255.0, + g as f32 / 255.0, + b as f32 / 255.0, + a as f32 / 255.0, + ) + } + + /// `0xRRGGBB`. + pub const fn hex(rgb: u32) -> Self { + Self::rgb8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8) + } + + /// `0xRRGGBBAA`. + pub const fn hexa(rgba: u32) -> Self { + Self::rgba8( + (rgba >> 24) as u8, + (rgba >> 16) as u8, + (rgba >> 8) as u8, + rgba as u8, + ) + } + + /// Hue in degrees, saturation and lightness 0-1. + pub const fn hsl(h: f32, s: f32, l: f32) -> Self { + Self(BevyColor::Hsla(Hsla::new(h, s, l, 1.0))) + } + + /// Hue in degrees, saturation and value 0-1. + pub const fn hsv(h: f32, s: f32, v: f32) -> Self { + Self(BevyColor::Hsva(Hsva::new(h, s, v, 1.0))) + } + + /// Lightness 0-1, chroma 0-~0.4, hue in degrees. + pub const fn oklch(l: f32, c: f32, h: f32) -> Self { + Self(BevyColor::Oklcha(Oklcha::new(l, c, h, 1.0))) + } + + pub fn with_alpha(self, alpha: f32) -> Self { + let mut c = self.0; + c.set_alpha(alpha); + Self(c) + } + + /// Interpolates in Oklab, like Processing's `lerpColor`. + pub fn lerp(self, other: Color, t: f32) -> Self { + let a: bevy::color::Oklaba = self.0.into(); + let b: bevy::color::Oklaba = other.0.into(); + Self(a.mix(&b, t).into()) + } + + pub fn red(self) -> f32 { + self.0.to_srgba().red + } + + pub fn green(self) -> f32 { + self.0.to_srgba().green + } + + pub fn blue(self) -> f32 { + self.0.to_srgba().blue + } + + pub fn alpha(self) -> f32 { + self.0.alpha() + } + + pub(crate) fn from_linear(c: LinearRgba) -> Self { + Self(BevyColor::LinearRgba(c)) + } + + pub(crate) fn to_linear(self) -> LinearRgba { + self.0.to_linear() + } +} + +#[derive(Debug, Clone, Copy)] +pub enum Channel { + Int(i64), + Float(f32), +} + +/// A single color channel: integers are 0-255, floats are 0-1, unless `color_mode().max(..)` is set. +pub trait IntoChannel: Copy { + fn into_channel(self) -> Channel; +} + +macro_rules! int_channel { + ($($t:ty),*) => {$( + impl IntoChannel for $t { + fn into_channel(self) -> Channel { + Channel::Int(self as i64) + } + } + )*}; +} +int_channel!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); + +impl IntoChannel for f32 { + fn into_channel(self) -> Channel { + Channel::Float(self) + } +} + +impl IntoChannel for f64 { + fn into_channel(self) -> Channel { + Channel::Float(self as f32) + } +} + +/// An unresolved color, interpreted against the current color mode when used. +#[derive(Debug, Clone, Copy)] +pub enum ColorArg { + Color(Color), + Gray(Channel, Option), + Channels([Channel; 3], Option), +} + +impl From for ColorArg { + fn from(c: Color) -> Self { + Self::Color(c) + } +} + +impl From for ColorArg { + fn from(v: A) -> Self { + Self::Gray(v.into_channel(), None) + } +} + +impl From<(A, B)> for ColorArg { + fn from((v, a): (A, B)) -> Self { + Self::Gray(v.into_channel(), Some(a.into_channel())) + } +} + +impl From<(A, B, C)> for ColorArg { + fn from((c1, c2, c3): (A, B, C)) -> Self { + Self::Channels( + [c1.into_channel(), c2.into_channel(), c3.into_channel()], + None, + ) + } +} + +impl From<(A, B, C, D)> + for ColorArg +{ + fn from((c1, c2, c3, a): (A, B, C, D)) -> Self { + Self::Channels( + [c1.into_channel(), c2.into_channel(), c3.into_channel()], + Some(a.into_channel()), + ) + } +} + +/// Ranges for color channels: one number for all four, or `(c1, c2, c3)` / `(c1, c2, c3, alpha)`. +pub trait IntoColorMax { + fn into_color_max(self, space: ColorSpace) -> [f32; 4]; +} + +impl IntoColorMax for T { + fn into_color_max(self, _space: ColorSpace) -> [f32; 4] { + [self.to_f32(); 4] + } +} + +impl IntoColorMax for (A, B, C) { + fn into_color_max(self, space: ColorSpace) -> [f32; 4] { + [ + self.0.to_f32(), + self.1.to_f32(), + self.2.to_f32(), + space.default_maxes()[3], + ] + } +} + +impl IntoColorMax + for (A, B, C, D) +{ + fn into_color_max(self, _space: ColorSpace) -> [f32; 4] { + [ + self.0.to_f32(), + self.1.to_f32(), + self.2.to_f32(), + self.3.to_f32(), + ] + } +} + +/// The color mode as seen by a `Graphics`; `explicit_max` means `.max(..)` was set. +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct ColorState { + pub mode: ColorMode, + pub explicit_max: bool, +} + +fn int_maxes(space: ColorSpace) -> [f32; 4] { + match space { + ColorSpace::Srgb | ColorSpace::Linear => [255.0, 255.0, 255.0, 255.0], + ColorSpace::Hsl | ColorSpace::Hsv | ColorSpace::Hwb => [360.0, 100.0, 100.0, 255.0], + ColorSpace::Oklch | ColorSpace::Lch => [100.0, 100.0, 360.0, 255.0], + ColorSpace::Oklab | ColorSpace::Lab | ColorSpace::Xyz => [100.0, 100.0, 100.0, 255.0], + } +} + +impl ColorState { + fn channel(&self, c: Channel, i: usize) -> f32 { + let space = self.mode.space; + let native = space.default_maxes()[i]; + match c { + Channel::Int(v) if self.explicit_max => v as f32 / self.mode.max[i] * native, + Channel::Float(v) if self.explicit_max => v / self.mode.max[i] * native, + Channel::Int(v) => v as f32 / int_maxes(space)[i] * native, + Channel::Float(v) => v, + } + } + + pub fn resolve(&self, arg: ColorArg) -> Color { + let space = self.mode.space; + let alpha = |a: Option| match a { + Some(a) => self.channel(a, 3), + None => space.default_maxes()[3], + }; + match arg { + ColorArg::Color(c) => c, + ColorArg::Gray(v, a) => Color(space.gray(self.channel(v, 0), alpha(a))), + ColorArg::Channels([c1, c2, c3], a) => Color(space.color( + self.channel(c1, 0), + self.channel(c2, 1), + self.channel(c3, 2), + alpha(a), + )), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn srgba(state: &ColorState, arg: impl Into) -> [f32; 4] { + let s = state.resolve(arg.into()).0.to_srgba(); + [s.red, s.green, s.blue, s.alpha] + } + + #[test] + fn ints_are_255_floats_are_unit() { + let st = ColorState::default(); + assert_eq!(srgba(&st, 255), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(srgba(&st, 0.5), [0.5, 0.5, 0.5, 1.0]); + assert_eq!(srgba(&st, (255, 0, 0, 0.5)), [1.0, 0.0, 0.0, 0.5]); + } + + #[test] + fn explicit_max_governs_ints_and_floats() { + let st = ColorState { + mode: ColorMode::with_uniform_max(ColorSpace::Srgb, 100.0), + explicit_max: true, + }; + assert_eq!(srgba(&st, (50, 100.0, 0)), [0.5, 1.0, 0.0, 1.0]); + } + + #[test] + fn hex_round_trip() { + let c = Color::hex(0xFF8000).0.to_srgba(); + assert_eq!([c.red, c.green, c.blue], [1.0, 128.0 / 255.0, 0.0]); + } +} diff --git a/src/draw.rs b/src/draw.rs new file mode 100644 index 00000000..ffd82684 --- /dev/null +++ b/src/draw.rs @@ -0,0 +1,358 @@ +//! Builders for draw calls with optional trailing arguments. Each draws when dropped. + +use std::ops::{Deref, DerefMut}; + +use bevy::prelude::{Entity, Transform, Vec3}; +use processing_render::graphics_immediate_light; +use processing_render::render::command::{ArcMode, DrawCommand, LightKind}; + +use crate::graphics::expect; +use crate::{Graphics, IntoPoint, Scalar}; + +/// Returned by [`Graphics::rect`] and [`Graphics::square`]. +pub struct Rect<'g> { + g: &'g mut Graphics, + rect: [f32; 4], + radii: [f32; 4], +} + +impl<'g> Rect<'g> { + pub(crate) fn new(g: &'g mut Graphics, x: f32, y: f32, w: f32, h: f32) -> Self { + Self { + g, + rect: [x, y, w, h], + radii: [0.0; 4], + } + } + + /// Rounds every corner. + pub fn radius(mut self, r: impl Scalar) -> Self { + self.radii = [r.to_f32(); 4]; + self + } + + /// Rounds each corner: top-left, top-right, bottom-right, bottom-left. + pub fn radii( + mut self, + tl: impl Scalar, + tr: impl Scalar, + br: impl Scalar, + bl: impl Scalar, + ) -> Self { + self.radii = [tl.to_f32(), tr.to_f32(), br.to_f32(), bl.to_f32()]; + self + } +} + +impl Drop for Rect<'_> { + fn drop(&mut self) { + let [x, y, w, h] = self.rect; + self.g.record(DrawCommand::Rect { + x, + y, + w, + h, + radii: self.radii, + }); + } +} + +/// Returned by [`Graphics::arc`]. +pub struct Arc<'g> { + g: &'g mut Graphics, + bounds: [f32; 4], + start: f32, + stop: f32, + mode: ArcMode, +} + +impl<'g> Arc<'g> { + pub(crate) fn new(g: &'g mut Graphics, bounds: [f32; 4], start: f32, stop: f32) -> Self { + Self { + g, + bounds, + start, + stop, + mode: ArcMode::default(), + } + } + + pub fn mode(mut self, mode: ArcMode) -> Self { + self.mode = mode; + self + } +} + +impl Drop for Arc<'_> { + fn drop(&mut self) { + let [cx, cy, w, h] = self.bounds; + self.g.record(DrawCommand::Arc { + cx, + cy, + w, + h, + start: self.start, + stop: self.stop, + mode: self.mode, + }); + } +} + +/// Returned by [`Graphics::directional_light`], [`Graphics::point_light`] and [`Graphics::spot_light`]. +pub struct LightDraw<'g> { + g: &'g mut Graphics, + kind: LightKind, + transform: Transform, +} + +impl<'g> LightDraw<'g> { + pub(crate) fn new(g: &'g mut Graphics, kind: LightKind) -> Self { + Self { + g, + kind, + transform: Transform::default(), + } + } + + pub fn position(mut self, position: impl IntoPoint) -> Self { + self.transform.translation = position.into_point(); + self + } + + pub fn look_at(mut self, target: impl IntoPoint) -> Self { + self.transform.look_at(target.into_point(), Vec3::Y); + self + } +} + +impl Drop for LightDraw<'_> { + fn drop(&mut self) { + expect(graphics_immediate_light( + self.g.entity, + self.kind, + self.transform, + )); + } +} + +/// Returned by [`Graphics::image`]. +pub struct ImageDraw<'g> { + g: &'g mut Graphics, + entity: Entity, + x: f32, + y: f32, + size: Option<[f32; 2]>, + source: Option<[f32; 4]>, +} + +impl<'g> ImageDraw<'g> { + pub(crate) fn new(g: &'g mut Graphics, entity: Entity, x: f32, y: f32) -> Self { + Self { + g, + entity, + x, + y, + size: None, + source: None, + } + } + + /// Draws at this size instead of the image's own. + pub fn size(mut self, w: impl Scalar, h: impl Scalar) -> Self { + self.size = Some([w.to_f32(), h.to_f32()]); + self + } + + /// Draws only this pixel region of the image. + pub fn source( + mut self, + x: impl Scalar, + y: impl Scalar, + w: impl Scalar, + h: impl Scalar, + ) -> Self { + self.source = Some([x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()]); + self + } +} + +impl Drop for ImageDraw<'_> { + fn drop(&mut self) { + let size = self.size.map(|[w, h]| (w, h)); + let source = self.source.map(|[x, y, w, h]| (x, y, w, h)); + self.g.record(DrawCommand::Image { + entity: self.entity, + dx: self.x, + dy: self.y, + d_width: size.map(|s| s.0), + d_height: size.map(|s| s.1), + sx: source.map(|s| s.0), + sy: source.map(|s| s.1), + s_width: source.map(|s| s.2), + s_height: source.map(|s| s.3), + }); + } +} + +/// Returned by [`Graphics::text`]. +pub struct Text<'g> { + g: &'g mut Graphics, + content: String, + x: f32, + y: f32, + z: f32, + max_w: Option, + max_h: Option, +} + +impl<'g> Text<'g> { + pub(crate) fn new(g: &'g mut Graphics, content: String, x: f32, y: f32) -> Self { + Self { + g, + content, + x, + y, + z: 0.0, + max_w: None, + max_h: None, + } + } + + pub fn z(mut self, z: impl Scalar) -> Self { + self.z = z.to_f32(); + self + } + + /// Wraps the text at `w` wide. + pub fn max_width(mut self, w: impl Scalar) -> Self { + self.max_w = Some(w.to_f32()); + self + } + + /// Wraps the text inside a `w` by `h` box. + pub fn bounds(mut self, w: impl Scalar, h: impl Scalar) -> Self { + self.max_w = Some(w.to_f32()); + self.max_h = Some(h.to_f32()); + self + } +} + +impl Drop for Text<'_> { + fn drop(&mut self) { + self.g.record(DrawCommand::Text { + content: std::mem::take(&mut self.content), + x: self.x, + y: self.y, + z: self.z, + max_w: self.max_w, + max_h: self.max_h, + }); + } +} + +/// A 3D primitive with tessellation detail; chain `.detail(..)`. +pub struct Detail<'g, const N: usize> { + g: &'g mut Graphics, + size: [f32; 3], + detail: [u32; N], + build: fn([f32; 3], [u32; N]) -> DrawCommand, +} + +impl<'g, const N: usize> Detail<'g, N> { + pub(crate) fn new( + g: &'g mut Graphics, + size: [f32; 3], + detail: [u32; N], + build: fn([f32; 3], [u32; N]) -> DrawCommand, + ) -> Self { + Self { + g, + size, + detail, + build, + } + } +} + +impl Detail<'_, 1> { + pub fn detail(mut self, segments: u32) -> Self { + self.detail = [segments]; + self + } +} + +impl Detail<'_, 2> { + pub fn detail(mut self, a: u32, b: u32) -> Self { + self.detail = [a, b]; + self + } +} + +impl Drop for Detail<'_, N> { + fn drop(&mut self) { + self.g.record((self.build)(self.size, self.detail)); + } +} + +/// Returned by [`Graphics::push`]; restores style and transform when dropped. +pub struct Push<'g> { + g: &'g mut Graphics, +} + +impl<'g> Push<'g> { + pub(crate) fn new(g: &'g mut Graphics) -> Self { + Self { g } + } +} + +impl Deref for Push<'_> { + type Target = Graphics; + + fn deref(&self) -> &Graphics { + self.g + } +} + +impl DerefMut for Push<'_> { + fn deref_mut(&mut self) -> &mut Graphics { + self.g + } +} + +impl Drop for Push<'_> { + fn drop(&mut self) { + self.g.pop_matrix(); + self.g.pop_style(); + } +} + +/// Returned by [`Graphics::begin_draw`]; ends drawing when dropped. +pub struct BeginDraw<'g> { + g: &'g mut Graphics, +} + +impl<'g> BeginDraw<'g> { + pub(crate) fn new(g: &'g mut Graphics) -> Self { + Self { g } + } +} + +impl Deref for BeginDraw<'_> { + type Target = Graphics; + + fn deref(&self) -> &Graphics { + self.g + } +} + +impl DerefMut for BeginDraw<'_> { + fn deref_mut(&mut self) -> &mut Graphics { + self.g + } +} + +impl Drop for BeginDraw<'_> { + fn drop(&mut self) { + self.g.end_frame(); + } +} diff --git a/src/graphics.rs b/src/graphics.rs new file mode 100644 index 00000000..2fa05903 --- /dev/null +++ b/src/graphics.rs @@ -0,0 +1,1062 @@ +//! The drawing surface and its Processing-style drawing methods. + +use std::fmt::Display; + +use bevy::math::{Affine3A, Vec3, Vec4}; +use bevy::prelude::Entity; +use bevy::render::render_resource::TextureFormat; +use processing_core::error::Result; +use processing_input::{ + input_key, input_key_is_down, input_key_is_pressed, input_key_just_pressed, input_mouse_button, + input_mouse_is_pressed, input_mouse_wheel, input_mouse_x, input_mouse_y, input_moved_x, + input_moved_y, input_pmouse_x, input_pmouse_y, +}; +use processing_render::render::command::{ + BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, StrokeJoinMode, + TextAlignH, TextAlignV, TextStyle, TextWrapMode, +}; +use processing_render::{ + camera_reset, camera_set_center, camera_set_distance, delta_time, elapsed_time, frame_count, + graphics_begin_draw, graphics_create, graphics_destroy, graphics_disable_camera_controller, + graphics_end_draw, graphics_flush, graphics_free_camera, graphics_get_matrix, graphics_light, + graphics_mode_2d, graphics_mode_3d, graphics_orbit_camera, graphics_ortho, graphics_pan_camera, + graphics_perspective, graphics_readback, graphics_record_command, graphics_screen_point, + graphics_set_color_mode, graphics_text_ascent, graphics_text_descent, graphics_text_width, + graphics_update, graphics_update_region, light_create_directional, light_create_point, + light_create_spot, light_destroy, surface_create_offscreen, surface_destroy, + surface_physical_height, surface_physical_width, transform_look_at, transform_set_position, +}; + +use crate::color::{ColorArg, ColorSpace, ColorState, IntoColorMax}; +use crate::draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, Push, Rect, Text}; +use crate::input::{Key, MouseButton}; +use crate::shape::Shape; +use crate::{AsImage, Color, Font, IntoExtent, IntoPoint, Scalar}; + +/// Panics on engine errors that a valid handle can't produce. +pub(crate) fn expect(r: Result) -> T { + r.unwrap_or_else(|e| panic!("processing: {e}")) +} + +/// A drawing surface: the sketch window passed to [`crate::Sketch::draw`], or one made with [`Graphics::create`]. +pub struct Graphics { + pub(crate) entity: Entity, + pub(crate) surface: Entity, + width: u32, + height: u32, + color: ColorState, + style_stack: Vec, + offscreen: bool, + exit_requested: bool, +} + +impl Graphics { + pub(crate) fn new(entity: Entity, surface: Entity, width: u32, height: u32) -> Self { + Self { + entity, + surface, + width, + height, + color: ColorState::default(), + style_stack: Vec::new(), + offscreen: false, + exit_requested: false, + } + } + + /// An offscreen drawing surface (Processing's `createGraphics`). Draw into it inside + /// [`Graphics::begin_draw`], then show it with `g.image(&pg, x, y)`. + pub fn create(width: u32, height: u32) -> Result { + let format = TextureFormat::Rgba8UnormSrgb; + let surface = surface_create_offscreen(width, height, 1.0, format)?; + let entity = graphics_create(surface, width, height, format)?; + let mut g = Self::new(entity, surface, width, height); + g.offscreen = true; + Ok(g) + } + + /// Starts drawing into a [`Graphics::create`]d surface; drawing ends when the guard drops. + pub fn begin_draw(&mut self) -> BeginDraw<'_> { + assert!( + self.offscreen, + "processing: begin_draw is for Graphics::create surfaces; the sketch window is drawn every frame" + ); + self.begin_frame(); + BeginDraw::new(self) + } + + pub(crate) fn record(&mut self, cmd: DrawCommand) { + expect(graphics_record_command(self.entity, cmd)); + } + + pub(crate) fn begin_frame(&mut self) { + self.style_stack.clear(); + expect(graphics_begin_draw(self.entity)); + } + + pub(crate) fn end_frame(&mut self) { + expect(graphics_end_draw(self.entity)); + } + + pub(crate) fn resolve(&self, color: impl Into) -> bevy::color::Color { + self.color.resolve(color.into()).0 + } + + // -- size & time -------------------------------------------------------- + + pub fn width(&self) -> f32 { + self.width as f32 + } + + pub fn height(&self) -> f32 { + self.height as f32 + } + + /// Width in physical pixels; larger than `width()` on high-DPI displays. + pub fn pixel_width(&self) -> u32 { + if self.offscreen { + // offscreen surfaces are created at scale 1 + return self.width; + } + expect(surface_physical_width(self.surface)) + } + + /// Height in physical pixels; larger than `height()` on high-DPI displays. + pub fn pixel_height(&self) -> u32 { + if self.offscreen { + return self.height; + } + expect(surface_physical_height(self.surface)) + } + + /// Frames drawn so far, starting at 1 in the first `draw`. + pub fn frame_count(&self) -> u32 { + expect(frame_count()) + } + + /// Seconds since the previous frame. + pub fn delta_time(&self) -> f32 { + expect(delta_time()) + } + + /// Milliseconds since the sketch started. + pub fn millis(&self) -> u32 { + (expect(elapsed_time()) * 1000.0) as u32 + } + + /// Stops the sketch after this frame. + pub fn exit(&mut self) { + self.exit_requested = true; + } + + pub(crate) fn exit_requested(&self) -> bool { + self.exit_requested + } + + // -- color & style ------------------------------------------------------ + + /// Sets how color arguments are read. Chain `.max(..)` to set channel ranges. + pub fn color_mode(&mut self, space: ColorSpace) -> ColorModeBuilder<'_> { + ColorModeBuilder { + g: self, + space, + max: None, + } + } + + /// Resolves color arguments against the current color mode. + pub fn color(&self, color: impl Into) -> Color { + self.color.resolve(color.into()) + } + + pub fn background(&mut self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::BackgroundColor(c)); + } + + pub fn background_image(&mut self, image: &impl AsImage) { + self.record(DrawCommand::BackgroundImage(image.image_entity())); + } + + pub fn fill(&mut self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::Fill(c)); + } + + pub fn no_fill(&mut self) { + self.record(DrawCommand::NoFill); + } + + pub fn stroke(&mut self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::StrokeColor(c)); + } + + pub fn no_stroke(&mut self) { + self.record(DrawCommand::NoStroke); + } + + pub fn stroke_weight(&mut self, weight: impl Scalar) { + self.record(DrawCommand::StrokeWeight(weight.to_f32())); + } + + pub fn stroke_cap(&mut self, cap: StrokeCapMode) { + self.record(DrawCommand::StrokeCap(cap)); + } + + pub fn stroke_join(&mut self, join: StrokeJoinMode) { + self.record(DrawCommand::StrokeJoin(join)); + } + + pub fn tint(&mut self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::Tint(c)); + } + + pub fn no_tint(&mut self) { + self.record(DrawCommand::NoTint); + } + + pub fn blend_mode(&mut self, mode: BlendMode) { + self.record(DrawCommand::BlendMode(mode.to_blend_state())); + } + + pub fn rect_mode(&mut self, mode: ShapeMode) { + self.record(DrawCommand::RectMode(mode)); + } + + pub fn ellipse_mode(&mut self, mode: ShapeMode) { + self.record(DrawCommand::EllipseMode(mode)); + } + + pub fn image_mode(&mut self, mode: ShapeMode) { + self.record(DrawCommand::ImageMode(mode)); + } + + // -- 2D primitives ------------------------------------------------------ + + /// Chain `.radius(r)` or `.radii(tl, tr, br, bl)` for rounded corners. + pub fn rect( + &mut self, + x: impl Scalar, + y: impl Scalar, + w: impl Scalar, + h: impl Scalar, + ) -> Rect<'_> { + Rect::new(self, x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()) + } + + pub fn square(&mut self, x: impl Scalar, y: impl Scalar, size: impl Scalar) -> Rect<'_> { + let s = size.to_f32(); + Rect::new(self, x.to_f32(), y.to_f32(), s, s) + } + + pub fn ellipse(&mut self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) { + self.record(DrawCommand::Ellipse { + cx: x.to_f32(), + cy: y.to_f32(), + w: w.to_f32(), + h: h.to_f32(), + }); + } + + pub fn circle(&mut self, x: impl Scalar, y: impl Scalar, diameter: impl Scalar) { + let d = diameter.to_f32(); + self.ellipse(x, y, d, d); + } + + /// Chain `.mode(ArcMode::Pie)` or `.mode(ArcMode::Chord)` to close the arc. + pub fn arc( + &mut self, + x: impl Scalar, + y: impl Scalar, + w: impl Scalar, + h: impl Scalar, + start: impl Scalar, + stop: impl Scalar, + ) -> Arc<'_> { + Arc::new( + self, + [x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()], + start.to_f32(), + stop.to_f32(), + ) + } + + pub fn line(&mut self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, y2: impl Scalar) { + self.record(DrawCommand::Line { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + }); + } + + pub fn point(&mut self, x: impl Scalar, y: impl Scalar) { + self.record(DrawCommand::Point { + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn triangle( + &mut self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + ) { + self.record(DrawCommand::Triangle { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + }); + } + + pub fn quad( + &mut self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + x4: impl Scalar, + y4: impl Scalar, + ) { + self.record(DrawCommand::Quad { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + x4: x4.to_f32(), + y4: y4.to_f32(), + }); + } + + pub fn bezier( + &mut self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + x4: impl Scalar, + y4: impl Scalar, + ) { + self.record(DrawCommand::Bezier { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + x4: x4.to_f32(), + y4: y4.to_f32(), + }); + } + + pub fn curve( + &mut self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + x4: impl Scalar, + y4: impl Scalar, + ) { + self.record(DrawCommand::Curve { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + x4: x4.to_f32(), + y4: y4.to_f32(), + }); + } + + /// Starts a custom shape; it ends (open) when dropped, or call `.close()`. + pub fn begin_shape(&mut self, kind: ShapeKind) -> Shape<'_> { + Shape::new(self, kind) + } + + // -- images & text ------------------------------------------------------ + + /// Chain `.size(w, h)` to scale, `.source(x, y, w, h)` to draw a sub-region. + pub fn image(&mut self, image: &impl AsImage, x: impl Scalar, y: impl Scalar) -> ImageDraw<'_> { + ImageDraw::new(self, image.image_entity(), x.to_f32(), y.to_f32()) + } + + /// Chain `.z(z)` to place in depth, `.max_width(w)` or `.bounds(w, h)` to wrap. + pub fn text(&mut self, content: impl Display, x: impl Scalar, y: impl Scalar) -> Text<'_> { + Text::new(self, content.to_string(), x.to_f32(), y.to_f32()) + } + + pub fn text_font(&mut self, font: Font) { + self.record(DrawCommand::TextFont(Some(font.0))); + } + + pub fn text_size(&mut self, size: impl Scalar) { + self.record(DrawCommand::TextSize(size.to_f32())); + } + + pub fn text_leading(&mut self, leading: impl Scalar) { + self.record(DrawCommand::TextLeading(leading.to_f32())); + } + + /// `text_align(TextAlignH::Center)` or `text_align((TextAlignH::Center, TextAlignV::Top))`. + pub fn text_align(&mut self, align: impl Into) { + let TextAlign(h, v) = align.into(); + self.record(DrawCommand::TextAlign { h, v }); + } + + pub fn text_style(&mut self, style: TextStyle) { + self.record(DrawCommand::TextStyle(style)); + } + + pub fn text_wrap(&mut self, mode: TextWrapMode) { + self.record(DrawCommand::TextWrap(mode)); + } + + pub fn text_width(&self, content: &str) -> f32 { + expect(graphics_text_width(self.entity, content)) + } + + pub fn text_ascent(&self) -> f32 { + expect(graphics_text_ascent(self.entity)) + } + + pub fn text_descent(&self) -> f32 { + expect(graphics_text_descent(self.entity)) + } + + // -- transforms --------------------------------------------------------- + + /// Saves style and transform until the returned guard is dropped. + pub fn push(&mut self) -> Push<'_> { + self.push_style(); + self.push_matrix(); + Push::new(self) + } + + pub fn push_matrix(&mut self) { + self.record(DrawCommand::PushMatrix); + } + + pub fn pop_matrix(&mut self) { + self.record(DrawCommand::PopMatrix); + } + + pub fn push_style(&mut self) { + self.style_stack.push(self.color); + self.record(DrawCommand::PushStyle); + } + + pub fn pop_style(&mut self) { + if let Some(color) = self.style_stack.pop() { + self.set_color_state(color); + } + self.record(DrawCommand::PopStyle); + } + + pub fn translate(&mut self, offset: impl IntoPoint) { + self.record(DrawCommand::Translate(offset.into_point())); + } + + pub fn rotate(&mut self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::Z); + } + + pub fn rotate_x(&mut self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::X); + } + + pub fn rotate_y(&mut self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::Y); + } + + pub fn rotate_z(&mut self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::Z); + } + + pub fn rotate_axis(&mut self, angle: impl Scalar, axis: impl IntoPoint) { + self.record(DrawCommand::Rotate { + angle: angle.to_f32(), + axis: axis.into_point(), + }); + } + + /// `scale(2)`, `scale((2, 1))` or `scale((1, 2, 3))`. + pub fn scale(&mut self, factor: impl IntoExtent) { + self.record(DrawCommand::Scale(factor.into_extent())); + } + + pub fn shear_x(&mut self, angle: impl Scalar) { + self.record(DrawCommand::ShearX { + angle: angle.to_f32(), + }); + } + + pub fn shear_y(&mut self, angle: impl Scalar) { + self.record(DrawCommand::ShearY { + angle: angle.to_f32(), + }); + } + + pub fn reset_matrix(&mut self) { + self.record(DrawCommand::ResetMatrix); + } + + pub fn apply_matrix(&mut self, matrix: Affine3A) { + self.record(DrawCommand::ApplyMatrix(matrix)); + } + + pub fn matrix(&self) -> bevy::math::Mat4 { + expect(graphics_get_matrix(self.entity)) + } + + /// Where a point in the current transform lands on screen. + pub fn screen_point(&self, point: impl IntoPoint) -> Vec3 { + expect(graphics_screen_point(self.entity, point.into_point())) + } + + // -- 3D ----------------------------------------------------------------- + + pub fn mode_3d(&mut self) { + expect(graphics_mode_3d(self.entity)); + } + + pub fn mode_2d(&mut self) { + expect(graphics_mode_2d(self.entity)); + } + + /// `cube(size)` or `cube((w, h, d))`. + pub fn cube(&mut self, size: impl IntoExtent) { + let s = size.into_extent(); + self.record(DrawCommand::Box { + width: s.x, + height: s.y, + depth: s.z, + }); + } + + /// Chain `.detail(sectors, stacks)`. + pub fn sphere(&mut self, radius: impl Scalar) -> Detail<'_, 2> { + Detail::new( + self, + [radius.to_f32(), 0.0, 0.0], + [32, 16], + |[radius, _, _], [sectors, stacks]| DrawCommand::Sphere { + radius, + sectors, + stacks, + }, + ) + } + + /// Chain `.detail(n)`. + pub fn cylinder(&mut self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { + let size = [radius.to_f32(), height.to_f32(), 0.0]; + Detail::new(self, size, [24], |[radius, height, _], [detail]| { + DrawCommand::Cylinder { + radius, + height, + detail, + } + }) + } + + /// Chain `.detail(n)`. + pub fn cone(&mut self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { + let size = [radius.to_f32(), height.to_f32(), 0.0]; + Detail::new(self, size, [24], |[radius, height, _], [detail]| { + DrawCommand::Cone { + radius, + height, + detail, + } + }) + } + + /// Chain `.detail(major, minor)`. + pub fn torus(&mut self, radius: impl Scalar, tube_radius: impl Scalar) -> Detail<'_, 2> { + let size = [radius.to_f32(), tube_radius.to_f32(), 0.0]; + Detail::new( + self, + size, + [32, 16], + |[radius, tube_radius, _], [major, minor]| DrawCommand::Torus { + radius, + tube_radius, + major_segments: major, + minor_segments: minor, + }, + ) + } + + /// Chain `.detail(n)`. + pub fn capsule(&mut self, radius: impl Scalar, length: impl Scalar) -> Detail<'_, 1> { + let size = [radius.to_f32(), length.to_f32(), 0.0]; + Detail::new(self, size, [16], |[radius, length, _], [detail]| { + DrawCommand::Capsule { + radius, + length, + detail, + } + }) + } + + /// A cone with its tip cut off. Chain `.detail(n)`. + pub fn conical_frustum( + &mut self, + radius_top: impl Scalar, + radius_bottom: impl Scalar, + height: impl Scalar, + ) -> Detail<'_, 1> { + let size = [radius_top.to_f32(), radius_bottom.to_f32(), height.to_f32()]; + Detail::new( + self, + size, + [24], + |[radius_top, radius_bottom, height], [detail]| DrawCommand::ConicalFrustum { + radius_top, + radius_bottom, + height, + detail, + }, + ) + } + + pub fn plane(&mut self, width: impl Scalar, height: impl Scalar) { + self.record(DrawCommand::Plane { + width: width.to_f32(), + height: height.to_f32(), + }); + } + + pub fn tetrahedron(&mut self, radius: impl Scalar) { + self.record(DrawCommand::Tetrahedron { + radius: radius.to_f32(), + }); + } + + pub fn roughness(&mut self, value: impl Scalar) { + self.record(DrawCommand::Roughness(value.to_f32())); + } + + pub fn metallic(&mut self, value: impl Scalar) { + self.record(DrawCommand::Metallic(value.to_f32())); + } + + pub fn emissive(&mut self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::Emissive(c)); + } + + pub fn unlit(&mut self) { + self.record(DrawCommand::Unlit); + } + + pub fn texture(&mut self, image: &impl AsImage) { + self.record(DrawCommand::Texture(image.image_entity())); + } + + pub fn no_texture(&mut self) { + self.record(DrawCommand::NoTexture); + } + + pub fn camera_position(&mut self, eye: impl IntoPoint) { + expect(transform_set_position(self.entity, eye.into_point())); + } + + pub fn camera_look_at(&mut self, target: impl IntoPoint) { + expect(transform_look_at(self.entity, target.into_point())); + } + + pub fn perspective( + &mut self, + fov: impl Scalar, + aspect: impl Scalar, + near: impl Scalar, + far: impl Scalar, + ) { + let near = near.to_f32(); + expect(graphics_perspective( + self.entity, + fov.to_f32(), + aspect.to_f32(), + near, + far.to_f32(), + Vec4::new(0.0, 0.0, -1.0, -near), + )); + } + + pub fn ortho( + &mut self, + left: impl Scalar, + right: impl Scalar, + bottom: impl Scalar, + top: impl Scalar, + near: impl Scalar, + far: impl Scalar, + ) { + expect(graphics_ortho( + self.entity, + left.to_f32(), + right.to_f32(), + bottom.to_f32(), + top.to_f32(), + near.to_f32(), + far.to_f32(), + )); + } + + /// Mouse-driven orbit around `camera_center`. + pub fn orbit_camera(&mut self) { + expect(graphics_orbit_camera(self.entity)); + } + + pub fn free_camera(&mut self) { + expect(graphics_free_camera(self.entity)); + } + + pub fn pan_camera(&mut self) { + expect(graphics_pan_camera(self.entity)); + } + + pub fn disable_camera(&mut self) { + expect(graphics_disable_camera_controller(self.entity)); + } + + pub fn camera_distance(&mut self, distance: impl Scalar) { + expect(camera_set_distance(self.entity, distance.to_f32())); + } + + pub fn camera_center(&mut self, center: impl IntoPoint) { + expect(camera_set_center(self.entity, center.into_point())); + } + + pub fn camera_reset(&mut self) { + expect(camera_reset(self.entity)); + } + + /// Adds a light to the frame. + pub fn light(&mut self, light: &Light) { + expect(graphics_light(self.entity, light.0)); + } + + /// Adds a directional light to the frame. + pub fn directional_light( + &mut self, + color: impl Into, + illuminance: impl Scalar, + ) -> LightDraw<'_> { + let color = self.resolve(color); + LightDraw::new( + self, + LightKind::Directional { + color, + illuminance: illuminance.to_f32(), + }, + ) + } + + /// Adds a point light to the frame. + pub fn point_light( + &mut self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + ) -> LightDraw<'_> { + let color = self.resolve(color); + LightDraw::new( + self, + LightKind::Point { + color, + intensity: intensity.to_f32(), + range: range.to_f32(), + radius: radius.to_f32(), + }, + ) + } + + /// Adds a spot light to the frame. + pub fn spot_light( + &mut self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + inner_angle: impl Scalar, + outer_angle: impl Scalar, + ) -> LightDraw<'_> { + let color = self.resolve(color); + LightDraw::new( + self, + LightKind::Spot { + color, + intensity: intensity.to_f32(), + range: range.to_f32(), + radius: radius.to_f32(), + inner_angle: inner_angle.to_f32(), + outer_angle: outer_angle.to_f32(), + }, + ) + } + + /// Creates a directional light. + pub fn create_directional_light( + &mut self, + color: impl Into, + illuminance: impl Scalar, + ) -> Light { + let c = self.resolve(color); + Light(expect(light_create_directional( + self.entity, + c, + illuminance.to_f32(), + ))) + } + + /// Creates a point light. + pub fn create_point_light( + &mut self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + ) -> Light { + let c = self.resolve(color); + Light(expect(light_create_point( + self.entity, + c, + intensity.to_f32(), + range.to_f32(), + radius.to_f32(), + ))) + } + + /// Creates a spot light. + pub fn create_spot_light( + &mut self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + inner_angle: impl Scalar, + outer_angle: impl Scalar, + ) -> Light { + let c = self.resolve(color); + Light(expect(light_create_spot( + self.entity, + c, + intensity.to_f32(), + range.to_f32(), + radius.to_f32(), + inner_angle.to_f32(), + outer_angle.to_f32(), + ))) + } + + // -- pixels ------------------------------------------------------------- + + /// Reads the current frame back from the GPU, row-major. + pub fn pixels(&self) -> Result> { + Ok(graphics_readback(self.entity)? + .into_iter() + .map(Color::from_linear) + .collect()) + } + + /// Replaces every pixel; `pixels.len()` must be `pixel_width() * pixel_height()`. + pub fn set_pixels(&mut self, pixels: &[Color]) -> Result<()> { + let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); + // draw what's recorded so far so the write lands on top of it + graphics_flush(self.entity)?; + graphics_update(self.entity, &linear) + } + + /// Replaces a `w` by `h` block of pixels with its top-left corner at `(x, y)`. + pub fn set_pixels_region( + &mut self, + x: u32, + y: u32, + w: u32, + h: u32, + pixels: &[Color], + ) -> Result<()> { + let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); + graphics_flush(self.entity)?; + graphics_update_region(self.entity, x, y, w, h, &linear) + } + + // -- input -------------------------------------------------------------- + + pub fn mouse_x(&self) -> f32 { + expect(input_mouse_x(self.surface)).clamp(0.0, self.width()) + } + + pub fn mouse_y(&self) -> f32 { + expect(input_mouse_y(self.surface)).clamp(0.0, self.height()) + } + + pub fn pmouse_x(&self) -> f32 { + expect(input_pmouse_x(self.surface)).clamp(0.0, self.width()) + } + + pub fn pmouse_y(&self) -> f32 { + expect(input_pmouse_y(self.surface)).clamp(0.0, self.height()) + } + + pub fn moved_x(&self) -> f32 { + expect(input_moved_x()) + } + + pub fn moved_y(&self) -> f32 { + expect(input_moved_y()) + } + + pub fn mouse_wheel(&self) -> f32 { + expect(input_mouse_wheel()) + } + + pub fn mouse_pressed(&self) -> bool { + expect(input_mouse_is_pressed()) + } + + pub fn mouse_button(&self) -> Option { + expect(input_mouse_button()).map(MouseButton::from) + } + + /// Whether any key is held. + pub fn key_pressed(&self) -> bool { + expect(input_key_is_pressed()) + } + + /// The character of the most recent key press. + pub fn key(&self) -> Option { + expect(input_key()) + } + + /// The most recent key press, if it's one [`Key`] names. + pub fn key_code(&self) -> Option { + expect(processing_input::input_key_code()).and_then(Key::from_code) + } + + pub fn key_down(&self, key: Key) -> bool { + expect(input_key_is_down(key.code())) + } + + /// True only in the frame `key` went down. + pub fn key_just_pressed(&self, key: Key) -> bool { + expect(input_key_just_pressed(key.code())) + } + + fn set_color_state(&mut self, color: ColorState) { + self.color = color; + expect(graphics_set_color_mode(self.entity, color.mode)); + } +} + +impl AsImage for Graphics { + fn image_entity(&self) -> Entity { + // an offscreen surface is backed by an image + assert!( + self.offscreen, + "processing: only Graphics::create surfaces can be drawn as images" + ); + self.surface + } +} + +impl Drop for Graphics { + fn drop(&mut self) { + let _ = graphics_destroy(self.entity); + if self.offscreen { + let _ = surface_destroy(self.surface); + } + } +} + +/// Built by [`Graphics::color_mode`]; applies when dropped. +pub struct ColorModeBuilder<'g> { + g: &'g mut Graphics, + space: ColorSpace, + max: Option<[f32; 4]>, +} + +impl ColorModeBuilder<'_> { + /// `max(255)` for every channel, or `max((360, 100, 100))` / `max((360, 100, 100, 1))`. + pub fn max(mut self, max: impl IntoColorMax) -> Self { + self.max = Some(max.into_color_max(self.space)); + self + } +} + +impl Drop for ColorModeBuilder<'_> { + fn drop(&mut self) { + use processing_render::color::ColorMode; + let state = match self.max { + Some([m1, m2, m3, ma]) => ColorState { + mode: ColorMode::new(self.space, m1, m2, m3, ma), + explicit_max: true, + }, + None => ColorState { + mode: ColorMode::with_defaults(self.space), + explicit_max: false, + }, + }; + self.g.set_color_state(state); + } +} + +/// Horizontal alignment, optionally paired with vertical. +#[derive(Debug, Clone, Copy)] +pub struct TextAlign(TextAlignH, TextAlignV); + +impl From for TextAlign { + fn from(h: TextAlignH) -> Self { + Self(h, TextAlignV::default()) + } +} + +impl From<(TextAlignH, TextAlignV)> for TextAlign { + fn from((h, v): (TextAlignH, TextAlignV)) -> Self { + Self(h, v) + } +} + +/// A light, added to a frame with [`Graphics::light`]. +#[derive(Debug)] +pub struct Light(Entity); + +impl Light { + pub fn position(&self, position: impl IntoPoint) -> &Self { + expect(transform_set_position(self.0, position.into_point())); + self + } + + pub fn look_at(&self, target: impl IntoPoint) -> &Self { + expect(transform_look_at(self.0, target.into_point())); + self + } +} + +impl Drop for Light { + fn drop(&mut self) { + let _ = light_destroy(self.0); + } +} diff --git a/src/image.rs b/src/image.rs new file mode 100644 index 00000000..912ba7cd --- /dev/null +++ b/src/image.rs @@ -0,0 +1,109 @@ +//! Images and fonts. + +use bevy::prelude::Entity; +use bevy::render::render_resource::{Extent3d, TextureFormat}; +use processing_core::error::Result; +use processing_render::{ + font_create, font_list, font_load, image_create, image_destroy, image_load, image_readback, + image_size, image_update, +}; + +use crate::Color; + +/// A texture you can draw with `g.image(..)` or use as a `g.texture(..)`. +#[derive(Debug)] +pub struct Image { + pub(crate) entity: Entity, + width: u32, + height: u32, +} + +impl Image { + /// Loads an image relative to the sketch's asset directory. + pub fn load(path: &str) -> Result { + let entity = image_load(path)?; + let (width, height) = image_size(entity)?; + Ok(Self { + entity, + width, + height, + }) + } + + /// A blank, transparent image. + pub fn create(width: u32, height: u32) -> Result { + let size = Extent3d { + width, + height, + depth_or_array_layers: 1, + }; + let data = vec![0u8; (width * height * 4) as usize]; + let entity = image_create(size, data, TextureFormat::Rgba8UnormSrgb)?; + Ok(Self { + entity, + width, + height, + }) + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + /// Reads the pixels back from the GPU, row-major. + pub fn pixels(&self) -> Result> { + Ok(image_readback(self.entity)? + .into_iter() + .map(Color::from_linear) + .collect()) + } + + /// Replaces every pixel; `pixels.len()` must be `width * height`. + pub fn set_pixels(&mut self, pixels: &[Color]) -> Result<()> { + let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); + image_update(self.entity, &linear) + } +} + +impl Drop for Image { + fn drop(&mut self) { + let _ = image_destroy(self.entity); + } +} + +/// Anything that can be drawn with `g.image(..)` or used as a `g.texture(..)`. +pub trait AsImage { + #[doc(hidden)] + fn image_entity(&self) -> Entity; +} + +impl AsImage for Image { + fn image_entity(&self) -> Entity { + self.entity + } +} + +/// A font for `g.text_font(..)`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Font(pub(crate) Entity); + +impl Font { + /// Loads a font file relative to the sketch's asset directory. + pub fn load(path: &str) -> Result { + font_load(path).map(Self) + } + + /// Looks up an installed system font by family name. + pub fn system(name: &str) -> Result { + font_create(name).map(Self) + } + + /// Family names of the installed system fonts. + pub fn list() -> Result> { + font_list() + } +} diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 00000000..48d3c438 --- /dev/null +++ b/src/input.rs @@ -0,0 +1,70 @@ +//! Keyboard and mouse identifiers. + +use bevy::input::keyboard::KeyCode; +use bevy::input::mouse::MouseButton as BevyMouseButton; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MouseButton { + Left, + Right, + Middle, + Back, + Forward, + Other(u16), +} + +impl From for MouseButton { + fn from(b: BevyMouseButton) -> Self { + match b { + BevyMouseButton::Left => Self::Left, + BevyMouseButton::Right => Self::Right, + BevyMouseButton::Middle => Self::Middle, + BevyMouseButton::Back => Self::Back, + BevyMouseButton::Forward => Self::Forward, + BevyMouseButton::Other(n) => Self::Other(n), + } + } +} + +macro_rules! keys { + ($($key:ident => $code:ident),* $(,)?) => { + /// A physical key, named by its position on a US keyboard. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub enum Key { + $($key,)* + } + + impl Key { + pub(crate) fn code(self) -> KeyCode { + match self { + $(Self::$key => KeyCode::$code,)* + } + } + + pub(crate) fn from_code(code: KeyCode) -> Option { + match code { + $(KeyCode::$code => Some(Self::$key),)* + _ => None, + } + } + } + }; +} + +keys!( + A => KeyA, B => KeyB, C => KeyC, D => KeyD, E => KeyE, F => KeyF, G => KeyG, H => KeyH, + I => KeyI, J => KeyJ, K => KeyK, L => KeyL, M => KeyM, N => KeyN, O => KeyO, P => KeyP, + Q => KeyQ, R => KeyR, S => KeyS, T => KeyT, U => KeyU, V => KeyV, W => KeyW, X => KeyX, + Y => KeyY, Z => KeyZ, Num0 => Digit0, Num1 => Digit1, Num2 => Digit2, Num3 => Digit3, + Num4 => Digit4, Num5 => Digit5, Num6 => Digit6, Num7 => Digit7, Num8 => Digit8, Num9 => Digit9, + Up => ArrowUp, Down => ArrowDown, Left => ArrowLeft, Right => ArrowRight, Space => Space, + Enter => Enter, Escape => Escape, Tab => Tab, Backspace => Backspace, Delete => Delete, + Insert => Insert, Home => Home, End => End, PageUp => PageUp, PageDown => PageDown, + ShiftLeft => ShiftLeft, ShiftRight => ShiftRight, ControlLeft => ControlLeft, + ControlRight => ControlRight, AltLeft => AltLeft, AltRight => AltRight, SuperLeft => SuperLeft, + SuperRight => SuperRight, Minus => Minus, Equal => Equal, BracketLeft => BracketLeft, + BracketRight => BracketRight, Backslash => Backslash, Semicolon => Semicolon, Quote => Quote, + Backquote => Backquote, Comma => Comma, Period => Period, Slash => Slash, F1 => F1, F2 => F2, + F3 => F3, F4 => F4, F5 => F5, F6 => F6, F7 => F7, F8 => F8, F9 => F9, F10 => F10, F11 => F11, + F12 => F12, +); diff --git a/src/lib.rs b/src/lib.rs index 7620f21c..c3fcec4c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,40 @@ pub mod prelude; +#[cfg(not(target_arch = "wasm32"))] +mod args; +#[cfg(not(target_arch = "wasm32"))] +mod color; +#[cfg(not(target_arch = "wasm32"))] +mod draw; +#[cfg(not(target_arch = "wasm32"))] +mod graphics; +#[cfg(not(target_arch = "wasm32"))] +mod image; +#[cfg(not(target_arch = "wasm32"))] +mod input; +#[cfg(not(target_arch = "wasm32"))] +mod shape; +#[cfg(not(target_arch = "wasm32"))] +mod sketch; + +#[cfg(not(target_arch = "wasm32"))] +pub use crate::{ + args::{IntoExtent, IntoPoint, Scalar}, + color::{Channel, Color, ColorArg, ColorSpace, IntoChannel, IntoColorMax}, + draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, Push, Rect, Text}, + graphics::{ColorModeBuilder, Graphics, Light, TextAlign}, + image::{AsImage, Font, Image}, + input::{Key, MouseButton}, + shape::{Contour, Shape}, + sketch::{Settings, Sketch, run}, +}; +pub use bevy::math::{Affine3A, Mat4, Vec2, Vec3}; +pub use processing_core::error::{ProcessingError as Error, Result}; +pub use processing_render::render::command::{ + ArcMode, BlendMode, ShapeKind, ShapeMode, StrokeCapMode as StrokeCap, + StrokeJoinMode as StrokeJoin, TextAlignH, TextAlignV, TextStyle, TextWrapMode, +}; + use std::num::NonZero; use bevy::app::{App, AppExit}; diff --git a/src/shape.rs b/src/shape.rs new file mode 100644 index 00000000..94ff0925 --- /dev/null +++ b/src/shape.rs @@ -0,0 +1,113 @@ +//! `begin_shape` / `end_shape` as a value: vertices only exist inside a shape. + +use std::ops::{Deref, DerefMut}; + +use processing_render::render::command::{DrawCommand, ShapeKind}; + +use crate::{Graphics, Scalar}; + +/// Returned by [`Graphics::begin_shape`]. Ends with [`Shape::end`], [`Shape::close`], or when dropped. +pub struct Shape<'g> { + g: &'g mut Graphics, + close: bool, +} + +impl<'g> Shape<'g> { + pub(crate) fn new(g: &'g mut Graphics, kind: ShapeKind) -> Self { + g.record(DrawCommand::BeginShape { kind }); + Self { g, close: false } + } + + pub fn vertex(&mut self, x: impl Scalar, y: impl Scalar) { + self.g.record(DrawCommand::ShapeVertex { + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn bezier_vertex( + &mut self, + cx1: impl Scalar, + cy1: impl Scalar, + cx2: impl Scalar, + cy2: impl Scalar, + x: impl Scalar, + y: impl Scalar, + ) { + self.g.record(DrawCommand::ShapeBezierVertex { + cx1: cx1.to_f32(), + cy1: cy1.to_f32(), + cx2: cx2.to_f32(), + cy2: cy2.to_f32(), + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn quadratic_vertex( + &mut self, + cx: impl Scalar, + cy: impl Scalar, + x: impl Scalar, + y: impl Scalar, + ) { + self.g.record(DrawCommand::ShapeQuadraticVertex { + cx: cx.to_f32(), + cy: cy.to_f32(), + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn curve_vertex(&mut self, x: impl Scalar, y: impl Scalar) { + self.g.record(DrawCommand::ShapeCurveVertex { + x: x.to_f32(), + y: y.to_f32(), + }); + } + + /// Starts a hole; it ends when the returned guard is dropped. + pub fn contour(&mut self) -> Contour<'_, 'g> { + self.g.record(DrawCommand::BeginContour); + Contour { shape: self } + } + + /// Ends the shape open; same as dropping it. + pub fn end(self) {} + + /// Ends the shape, joining the last vertex to the first. + pub fn close(mut self) { + self.close = true; + } +} + +impl Drop for Shape<'_> { + fn drop(&mut self) { + self.g.record(DrawCommand::EndShape { close: self.close }); + } +} + +/// Returned by [`Shape::contour`]. +pub struct Contour<'s, 'g> { + shape: &'s mut Shape<'g>, +} + +impl<'g> Deref for Contour<'_, 'g> { + type Target = Shape<'g>; + + fn deref(&self) -> &Shape<'g> { + self.shape + } +} + +impl<'g> DerefMut for Contour<'_, 'g> { + fn deref_mut(&mut self) -> &mut Shape<'g> { + self.shape + } +} + +impl Drop for Contour<'_, '_> { + fn drop(&mut self) { + self.shape.g.record(DrawCommand::EndContour); + } +} diff --git a/src/sketch.rs b/src/sketch.rs new file mode 100644 index 00000000..8520d54a --- /dev/null +++ b/src/sketch.rs @@ -0,0 +1,128 @@ +//! The sketch runner: opens a window and calls `setup` once and `draw` every frame. + +use std::path::PathBuf; + +use bevy::render::render_resource::TextureFormat; +use processing_core::config::{Config, ConfigKey}; +use processing_core::error::Result; +use processing_glfw::GlfwContext; +use processing_render::{advance_frame_count, graphics_create, surface_set_title}; + +use crate::Graphics; + +/// Window and app options, returned from [`Sketch::settings`]. +#[derive(Debug, Clone)] +pub struct Settings { + width: u32, + height: u32, + title: String, + transparent: bool, + assets: Option, + log_level: Option, +} + +impl Settings { + pub fn size(width: u32, height: u32) -> Self { + Self { + width, + height, + title: "Processing".to_string(), + transparent: false, + assets: None, + log_level: None, + } + } + + pub fn title(mut self, title: impl Into) -> Self { + self.title = title.into(); + self + } + + /// A window with a transparent background. + pub fn transparent(mut self) -> Self { + self.transparent = true; + self + } + + /// Where `Image::load` and `Font::load` look for files. + pub fn assets(mut self, dir: impl Into) -> Self { + self.assets = Some(dir.into()); + self + } + + /// A `tracing` filter such as `"warn"` or `"processing=debug"`. + pub fn log_level(mut self, level: impl Into) -> Self { + self.log_level = Some(level.into()); + self + } +} + +impl Default for Settings { + fn default() -> Self { + Self::size(100, 100) + } +} + +/// A Processing sketch. State lives on `Self`. +pub trait Sketch: Sized { + fn settings() -> Settings { + Settings::default() + } + + /// Runs once, before the first `draw`, with the window ready to draw into. + fn setup(g: &mut Graphics) -> Result; + + fn draw(&mut self, _g: &mut Graphics) {} +} + +/// Runs `S` until its window closes. +pub fn run() -> Result<()> { + let settings = S::settings(); + let mut window = GlfwContext::new(settings.width, settings.height, settings.transparent)?; + + let mut config = Config::new(); + if let Some(dir) = &settings.assets { + config.set(ConfigKey::AssetRootPath, dir.to_string_lossy().into_owned()); + } + if let Some(level) = &settings.log_level { + config.set(ConfigKey::LogLevel, level.clone()); + } + crate::init(config)?; + + let result = run_loop::(&mut window, &settings); + crate::exit(if result.is_ok() { 0 } else { 1 })?; + result +} + +fn run_loop(window: &mut GlfwContext, settings: &Settings) -> Result<()> { + let surface = window.create_surface(settings.width, settings.height, settings.transparent)?; + let entity = graphics_create( + surface, + settings.width, + settings.height, + TextureFormat::Rgba16Float, + )?; + surface_set_title(surface, settings.title.clone())?; + let mut g = Graphics::new(entity, surface, settings.width, settings.height); + + if !window.poll_events() { + return Ok(()); + } + advance_frame_count()?; + g.begin_frame(); + let mut sketch = S::setup(&mut g)?; + sketch.draw(&mut g); + g.end_frame(); + + while !g.exit_requested() && window.poll_events() { + advance_frame_count()?; + g.begin_frame(); + sketch.draw(&mut g); + g.end_frame(); + } + + // handles release engine resources, so drop them while the app is still alive + drop(sketch); + drop(g); + Ok(()) +} From 0d1718b9fe09bfd29c7723f9cd8eb843307e502c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Sat, 7 Nov 2026 17:15:33 -0800 Subject: [PATCH 2/4] Rust. --- Cargo.lock | 1 + Cargo.toml | 1 + crates/processing_render/src/lib.rs | 23 +- crates/processing_render/src/render/mod.rs | 82 +---- .../src/render/primitive/text.rs | 25 +- crates/processing_render/src/render/style.rs | 50 ++- .../processing_render/src/shader_property.rs | 27 +- examples/alias_spike.rs | 83 ++--- examples/animated_mesh.rs | 139 +++----- examples/box.rs | 77 ++--- examples/camera_controllers.rs | 139 +++----- examples/compute_readback.rs | 87 ++--- examples/custom_attribute.rs | 98 +++--- examples/custom_material.rs | 100 ++---- examples/filter.rs | 133 +++---- examples/gltf_load.rs | 88 ++--- examples/lights.rs | 151 ++++---- examples/materials.rs | 155 ++++----- examples/midi.rs | 216 +++++------- examples/particles_animated.rs | 125 ++++--- examples/particles_basic.rs | 109 +++--- examples/particles_colored.rs | 121 +++---- examples/particles_colored_pbr.rs | 126 +++---- examples/particles_emit.rs | 112 +++--- examples/particles_emit_gpu.rs | 181 +++++----- examples/particles_from_mesh.rs | 116 +++---- examples/particles_lifecycle.rs | 179 +++++----- examples/particles_noise.rs | 128 ++++--- examples/particles_oriented.rs | 176 +++++----- examples/particles_scatter.rs | 161 +++++---- examples/particles_scatter_volume.rs | 149 ++++---- examples/particles_stress.rs | 192 +++++------ examples/particles_text_whirl.rs | 326 ++++++++---------- examples/text_3d.rs | 126 +++---- examples/webcam.rs | 58 +--- src/args.rs | 7 +- src/color.rs | 24 +- src/draw.rs | 61 +++- src/filter.rs | 47 +++ src/geometry.rs | 296 ++++++++++++++++ src/gltf.rs | 42 +++ src/graphics.rs | 132 +++---- src/image.rs | 18 +- src/input.rs | 4 +- src/lib.rs | 26 +- src/midi.rs | 31 ++ src/particles.rs | 128 +++++++ src/shader.rs | 266 ++++++++++++++ src/shape.rs | 9 +- src/sketch.rs | 54 ++- src/webcam.rs | 38 ++ 51 files changed, 2772 insertions(+), 2471 deletions(-) create mode 100644 src/filter.rs create mode 100644 src/geometry.rs create mode 100644 src/gltf.rs create mode 100644 src/midi.rs create mode 100644 src/particles.rs create mode 100644 src/shader.rs create mode 100644 src/webcam.rs diff --git a/Cargo.lock b/Cargo.lock index 805c9193..23e1d177 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6226,6 +6226,7 @@ name = "processing" version = "0.4.0" dependencies = [ "bevy", + "bytemuck", "js-sys", "processing_audio", "processing_core", diff --git a/Cargo.toml b/Cargo.toml index 4990f307..2ddb2b71 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -87,6 +87,7 @@ processing_audio = { workspace = true } processing_input = { workspace = true } processing_webcam = { workspace = true, optional = true } processing_cuda = { workspace = true, optional = true } +bytemuck = "1" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index c01747b3..bc8ec7e5 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -2821,11 +2821,28 @@ fn text_query_state( render::primitive::text::OwnedTextParams, text::font::TextContext, )> { - let state = app - .world() + let world = app.world(); + let state = world .get::(graphics_entity) .ok_or(error::ProcessingError::GraphicsNotFound)?; - let params = render::primitive::text::OwnedTextParams::from_render_state(state, max_w, max_h); + // include text settings recorded since the last flush + let mut style = state.style.clone(); + if let Some(buffer) = world.get::(graphics_entity) { + for cmd in &buffer.commands { + match cmd { + DrawCommand::PushStyle => style.push(), + DrawCommand::PopStyle => style.pop(), + cmd => { + style.apply_text(cmd, |font| { + world + .get::(font) + .map(|f| f.family_name.clone()) + }); + } + } + } + } + let params = render::primitive::text::OwnedTextParams::from_style(&style, max_w, max_h); let text_cx = app.world().resource::().clone(); Ok((params, text_cx)) } diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index 35ed401c..c254d1b5 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -218,6 +218,23 @@ pub fn flush_draw_commands( let opens_pass = |batch: &BatchState| batch.draw_index == 0 && batch.current_mesh.is_none(); match cmd { + DrawCommand::TextFont(_) + | DrawCommand::TextStyle(_) + | DrawCommand::TextWeight(_) + | DrawCommand::TextVariation { .. } + | DrawCommand::ClearTextVariations + | DrawCommand::TextFeature { .. } + | DrawCommand::NoTextFeature { .. } + | DrawCommand::ClearTextFeatures + | DrawCommand::TextSize(_) + | DrawCommand::TextAlign { .. } + | DrawCommand::TextLeading(_) + | DrawCommand::TextWrap(_) + | DrawCommand::TextGlyphColors(_) => { + state.style.apply_text(&cmd, |font| { + p_fonts.get(font).ok().map(|f| f.family_name.clone()) + }); + } DrawCommand::Light(entity) => { if let Ok((light, transform)) = p_lights.get(entity) { let placed = crate::light::place(state.transform.current(), transform); @@ -1282,71 +1299,6 @@ pub fn flush_draw_commands( &p_material_handles, ); } - DrawCommand::TextFont(font_entity) => { - if let Some(entity) = font_entity { - if let Ok(font) = p_fonts.get(entity) { - state.style.text_font_family = Some(font.family_name.clone()); - } - } else { - state.style.text_font_family = None; - } - } - DrawCommand::TextStyle(style) => { - state.style.text_style = style; - } - DrawCommand::TextWeight(weight) => { - state.style.text_weight = Some(weight); - } - DrawCommand::TextVariation { tag, value } => { - if let Some(existing) = state - .style - .text_variations - .iter_mut() - .find(|(t, _)| *t == tag) - { - existing.1 = value; - } else { - state.style.text_variations.push((tag, value)); - } - } - DrawCommand::ClearTextVariations => { - state.style.text_variations.clear(); - } - DrawCommand::TextFeature { tag, value } => { - if let Some(existing) = state - .style - .text_features - .iter_mut() - .find(|(t, _)| *t == tag) - { - existing.1 = value; - } else { - state.style.text_features.push((tag, value)); - } - } - DrawCommand::NoTextFeature { tag } => { - state.style.text_features.retain(|(t, _)| *t != tag); - } - DrawCommand::ClearTextFeatures => { - state.style.text_features.clear(); - } - DrawCommand::TextSize(size) => { - state.style.text_size = size; - state.style.text_leading = None; - } - DrawCommand::TextAlign { h, v } => { - state.style.text_align_h = h; - state.style.text_align_v = v; - } - DrawCommand::TextLeading(leading) => { - state.style.text_leading = Some(leading); - } - DrawCommand::TextWrap(mode) => { - state.style.text_wrap = mode; - } - DrawCommand::TextGlyphColors(colors) => { - state.style.text_glyph_colors = Some(colors); - } DrawCommand::Text { content, x, diff --git a/crates/processing_render/src/render/primitive/text.rs b/crates/processing_render/src/render/primitive/text.rs index 5cc4ab73..0cd3bb30 100644 --- a/crates/processing_render/src/render/primitive/text.rs +++ b/crates/processing_render/src/render/primitive/text.rs @@ -24,6 +24,7 @@ use skrifa::{ outline::{DrawSettings, OutlinePen}, }; +use crate::render::style::Style; use crate::render::{ RenderState, command::{TextAlignH, TextAlignV, TextStyle, TextWrapMode}, @@ -91,19 +92,23 @@ impl OwnedTextParams { /// Snapshot a `RenderState`'s text state. `glyph_colors` is left unset; the /// draw path fills it in, measurement queries don't need it. pub fn from_render_state(state: &RenderState, max_w: Option, max_h: Option) -> Self { + Self::from_style(&state.style, max_w, max_h) + } + + pub fn from_style(style: &Style, max_w: Option, max_h: Option) -> Self { Self { - text_size: state.style.text_size, - align_h: state.style.text_align_h, - align_v: state.style.text_align_v, - leading: state.style.text_leading, + text_size: style.text_size, + align_h: style.text_align_h, + align_v: style.text_align_v, + leading: style.text_leading, max_w, max_h, - wrap: state.style.text_wrap, - font_family: state.style.text_font_family.clone(), - text_style: state.style.text_style, - text_weight: state.style.text_weight, - text_variations: state.style.text_variations.clone(), - text_features: state.style.text_features.clone(), + wrap: style.text_wrap, + font_family: style.text_font_family.clone(), + text_style: style.text_style, + text_weight: style.text_weight, + text_variations: style.text_variations.clone(), + text_features: style.text_features.clone(), glyph_colors: None, } } diff --git a/crates/processing_render/src/render/style.rs b/crates/processing_render/src/render/style.rs index 63495c58..94dab92e 100644 --- a/crates/processing_render/src/render/style.rs +++ b/crates/processing_render/src/render/style.rs @@ -2,7 +2,7 @@ use std::ops::{Deref, DerefMut}; use bevy::{math::Affine2, prelude::*, render::render_resource::BlendState}; -use super::command::{ShapeMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode}; +use super::command::{DrawCommand, ShapeMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode}; use super::material::MaterialKey; use super::primitive::StrokeConfig; @@ -48,6 +48,54 @@ pub struct Style { pub text_glyph_colors: Option>, } +impl Style { + /// False if `cmd` isn't a text setting. + pub fn apply_text( + &mut self, + cmd: &DrawCommand, + font_family: impl FnOnce(Entity) -> Option, + ) -> bool { + match cmd { + DrawCommand::TextFont(Some(font)) => { + if let Some(family) = font_family(*font) { + self.text_font_family = Some(family); + } + } + DrawCommand::TextFont(None) => self.text_font_family = None, + DrawCommand::TextStyle(style) => self.text_style = *style, + DrawCommand::TextWeight(weight) => self.text_weight = Some(*weight), + DrawCommand::TextVariation { tag, value } => { + match self.text_variations.iter_mut().find(|(t, _)| t == tag) { + Some(existing) => existing.1 = *value, + None => self.text_variations.push((*tag, *value)), + } + } + DrawCommand::ClearTextVariations => self.text_variations.clear(), + DrawCommand::TextFeature { tag, value } => { + match self.text_features.iter_mut().find(|(t, _)| t == tag) { + Some(existing) => existing.1 = *value, + None => self.text_features.push((*tag, *value)), + } + } + DrawCommand::NoTextFeature { tag } => self.text_features.retain(|(t, _)| t != tag), + DrawCommand::ClearTextFeatures => self.text_features.clear(), + DrawCommand::TextSize(size) => { + self.text_size = *size; + self.text_leading = None; + } + DrawCommand::TextAlign { h, v } => { + self.text_align_h = *h; + self.text_align_v = *v; + } + DrawCommand::TextLeading(leading) => self.text_leading = Some(*leading), + DrawCommand::TextWrap(mode) => self.text_wrap = *mode, + DrawCommand::TextGlyphColors(colors) => self.text_glyph_colors = Some(colors.clone()), + _ => return false, + } + true + } +} + impl Default for Style { fn default() -> Self { Self { diff --git a/crates/processing_render/src/shader_property.rs b/crates/processing_render/src/shader_property.rs index f42e5a0c..0213b628 100644 --- a/crates/processing_render/src/shader_property.rs +++ b/crates/processing_render/src/shader_property.rs @@ -4,6 +4,7 @@ use bevy_naga_reflect::dynamic_shader::DynamicShader; use bevy_naga_reflect::reflect::ParameterCategory; use crate::compute::{Buffer, Compute, MeshBindingRef}; +use crate::geometry::Geometry; use crate::image::Image as PImage; use crate::material::custom::{apply_field_coerced, apply_reflect_field, shader_value_to_reflect}; use crate::particles::grid::Grid; @@ -30,10 +31,30 @@ fn require_read_only_storage(shader: &DynamicShader, name: &str, kind: &str) -> Ok(()) } -fn bind_compute_mesh(compute: &mut Compute, name: String, value: ShaderValue) -> Result<()> { +fn bind_compute_mesh( + compute: &mut Compute, + name: String, + value: ShaderValue, + geometries: &Query<&Geometry>, + meshes: &mut Assets, +) -> Result<()> { match value { ShaderValue::MeshAttribute(geom, attribute) => { require_read_only_storage(&compute.shader, &name, "mesh attribute")?; + // an attribute binds as its own vertex buffer + let handle = &geometries + .get(geom) + .map_err(|_| ProcessingError::GeometryNotFound)? + .handle; + let mesh = meshes + .get(handle) + .ok_or(ProcessingError::GeometryNotFound)?; + if mesh.binding_count() < mesh.attributes().count() { + meshes + .get_mut(handle) + .ok_or(ProcessingError::GeometryNotFound)? + .deinterleave(); + } compute .mesh_bindings .insert(name, MeshBindingRef::Attribute { geom, attribute }); @@ -155,10 +176,12 @@ pub fn set_property( mut p_buffers: Query<&mut Buffer>, mut p_images: Query<&mut PImage>, grids: Query<&Grid>, + geometries: Query<&Geometry>, + mut meshes: ResMut>, ) -> Result { let shader = if let Ok(compute) = computes.get_mut(entity) { if let ShaderValue::MeshAttribute(..) | ShaderValue::MeshIndex(..) = value { - bind_compute_mesh(compute.into_inner(), name, value)?; + bind_compute_mesh(compute.into_inner(), name, value, &geometries, &mut meshes)?; return Ok(true); } &mut compute.into_inner().shader diff --git a/examples/alias_spike.rs b/examples/alias_spike.rs index c76c61b5..8b11dbc9 100644 --- a/examples/alias_spike.rs +++ b/examples/alias_spike.rs @@ -1,4 +1,4 @@ -use processing::prelude::*; +use processing::{Buffer, Compute, Graphics, Result, Settings, Shader, Sketch}; const TWO_BINDING_SRC: &str = r#" @group(0) @binding(0) var src: array; @@ -21,57 +21,48 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn f32s(bytes: &[u8]) -> Vec { - bytes - .chunks_exact(4) - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} -fn to_bytes(v: &[f32]) -> Vec { - v.iter().flat_map(|f| f.to_le_bytes()).collect() -} +struct AliasSpike; -fn run() -> error::Result<()> { - init(Config::default())?; - let surface = surface_create_offscreen(1, 1, 1.0, TextureFormat::Rgba8Unorm)?; - let _graphics = graphics_create(surface, 1, 1, TextureFormat::Rgba8Unorm)?; +impl Sketch for AliasSpike { + fn settings() -> Settings { + Settings::size(1, 1).headless() + } - let base = [1.0f32, 2.0, 3.0, 4.0]; + fn setup(g: &mut Graphics) -> Result { + let base = [1.0f32, 2.0, 3.0, 4.0]; + let mut two = Compute::new(&Shader::new(TWO_BINDING_SRC)?)?; - let two = compute_create(shader_create(TWO_BINDING_SRC)?)?; - let a_src = buffer_create_with_data(to_bytes(&base))?; - let a_dst = buffer_create_with_data(to_bytes(&[0.0; 4]))?; - compute_set(two, "src", shader_value::ShaderValue::Buffer(a_src))?; - compute_set(two, "dst", shader_value::ShaderValue::Buffer(a_dst))?; - compute_dispatch(two, 1, 1, 1)?; - println!( - "A distinct read+read_write -> {:?}", - f32s(&buffer_read(a_dst)?) - ); + let a_src = Buffer::from_slice(&base)?; + let a_dst = Buffer::from_slice(&[0.0f32; 4])?; + two.set("src", &a_src); + two.set("dst", &a_dst); + two.dispatch(1, 1, 1); + println!("A distinct read+read_write -> {:?}", a_dst.read::()?); - let one = compute_create(shader_create(ONE_BINDING_SRC)?)?; - let c = buffer_create_with_data(to_bytes(&base))?; - compute_set(one, "data", shader_value::ShaderValue::Buffer(c))?; - compute_dispatch(one, 1, 1, 1)?; - println!( - "C single read_write in-place-> {:?} (want [2,4,6,8])", - f32s(&buffer_read(c)?) - ); + let mut one = Compute::new(&Shader::new(ONE_BINDING_SRC)?)?; + let c = Buffer::from_slice(&base)?; + one.set("data", &c); + one.dispatch(1, 1, 1); + println!( + "C single read_write in-place-> {:?} (want [2,4,6,8])", + c.read::()? + ); - let b = buffer_create_with_data(to_bytes(&base))?; - compute_set(two, "src", shader_value::ShaderValue::Buffer(b))?; - compute_set(two, "dst", shader_value::ShaderValue::Buffer(b))?; - println!("B aliased read+read_write -> dispatching (expect fatal Validation Error)..."); - compute_dispatch(two, 1, 1, 1)?; - println!( - "B aliased read+read_write -> {:?} (want [2,4,6,8])", - f32s(&buffer_read(b)?) - ); + let b = Buffer::from_slice(&base)?; + two.set("src", &b); + two.set("dst", &b); + println!("B aliased read+read_write -> dispatching (expect fatal Validation Error)..."); + two.dispatch(1, 1, 1); + println!( + "B aliased read+read_write -> {:?} (want [2,4,6,8])", + b.read::()? + ); - Ok(()) + g.exit(); + Ok(AliasSpike) + } } -fn main() { - run().unwrap(); - exit(0).unwrap(); +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/animated_mesh.rs b/examples/animated_mesh.rs index 8d5f7e84..e32611c4 100644 --- a/examples/animated_mesh.rs +++ b/examples/animated_mesh.rs @@ -1,102 +1,71 @@ -use processing_glfw::GlfwContext; +use processing::{Geometry, Graphics, Result, Settings, Sketch, Topology}; -use bevy::math::{Vec3, Vec4}; -use processing::prelude::*; -use processing_render::geometry::Topology; -use processing_render::render::command::DrawCommand; +const GRID: u32 = 20; +const SPACING: f32 = 10.0; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct AnimatedMesh { + mesh: Geometry, + time: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let width = 600; - let height = 600; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let grid_size = 20; - let spacing = 10.0; - let offset = (grid_size as f32 * spacing) / 2.0; - - let mesh = geometry_create(Topology::TriangleList)?; - - for z in 0..grid_size { - for x in 0..grid_size { - let px = x as f32 * spacing - offset; - let pz = z as f32 * spacing - offset; - geometry_color( - mesh, - Vec4::new( - x as f32 / grid_size as f32, - 0.5, - z as f32 / grid_size as f32, - 1.0, - ), - )?; - geometry_normal(mesh, Vec3::new(0.0, -1.0, 0.0))?; - geometry_vertex(mesh, Vec3::new(px, 0.0, pz))?; - } +impl Sketch for AnimatedMesh { + fn settings() -> Settings { + Settings::size(600, 600) } - for z in 0..(grid_size - 1) { - for x in 0..(grid_size - 1) { - let tl = z * grid_size + x; - let tr = tl + 1; - let bl = (z + 1) * grid_size + x; - let br = bl + 1; - - geometry_index(mesh, tl)?; - geometry_index(mesh, bl)?; - geometry_index(mesh, tr)?; - - geometry_index(mesh, tr)?; - geometry_index(mesh, bl)?; - geometry_index(mesh, br)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((150, -150, 150)); + g.camera_look_at((0, 0, 0)); + + let offset = GRID as f32 * SPACING / 2.0; + let mut mesh = Geometry::new(Topology::TriangleList)?; + for z in 0..GRID { + for x in 0..GRID { + let px = x as f32 * SPACING - offset; + let pz = z as f32 * SPACING - offset; + mesh.color((x as f32 / GRID as f32, 0.5, z as f32 / GRID as f32)); + mesh.normal((0, -1, 0)); + mesh.vertex((px, 0.0, pz)); + } } - } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(150.0, -150.0, 150.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + for z in 0..GRID - 1 { + for x in 0..GRID - 1 { + let top_left = z * GRID + x; + let top_right = top_left + 1; + let bottom_left = (z + 1) * GRID + x; + let bottom_right = bottom_left + 1; + mesh.index(top_left); + mesh.index(bottom_left); + mesh.index(top_right); + mesh.index(top_right); + mesh.index(bottom_left); + mesh.index(bottom_right); + } + } - let mut time = 0.0f32; + Ok(AnimatedMesh { mesh, time: 0.0 }) + } - while glfw_ctx.poll_events() { - for z in 0..grid_size { - for x in 0..grid_size { - let idx = z * grid_size + x; - let px = x as f32 * spacing - offset; - let pz = z as f32 * spacing - offset; - let wave = (px * 0.1 + time).sin() * (pz * 0.1 + time).cos() * 20.0; - geometry_set_vertex(mesh, idx, Vec3::new(px, -wave, pz))?; + fn draw(&mut self, g: &mut Graphics) { + let offset = GRID as f32 * SPACING / 2.0; + for z in 0..GRID { + for x in 0..GRID { + let px = x as f32 * SPACING - offset; + let pz = z as f32 * SPACING - offset; + let wave = (px * 0.1 + self.time).sin() * (pz * 0.1 + self.time).cos() * 20.0; + self.mesh.set_vertex(z * GRID + x, (px, -wave, pz)); } } - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.1)), - )?; - graphics_record_command(graphics, DrawCommand::Geometry(mesh))?; - graphics_end_draw(graphics)?; + g.background((0.05, 0.05, 0.1)); + g.model(&self.mesh); - time += 0.05; + self.time += 0.05; } +} - geometry_destroy(mesh)?; - - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/box.rs b/examples/box.rs index e687228f..05616d7e 100644 --- a/examples/box.rs +++ b/examples/box.rs @@ -1,60 +1,37 @@ -use processing_glfw::GlfwContext; +use processing::{Geometry, Graphics, Result, Settings, Sketch}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct BoxSketch { + cube: Geometry, + angle: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(100.0, -100.0, 300.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let mut angle: f32 = 0.0; +impl Sketch for BoxSketch { + fn settings() -> Settings { + Settings::size(400, 400) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((100, -100, 300)); + g.camera_look_at((0, 0, 0)); - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.15)), - )?; + let cube = Geometry::cube(100)?; + Ok(BoxSketch { cube, angle: 0.0 }) + } - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.15)); - graphics_end_draw(graphics)?; + { + let mut g = g.push(); + g.rotate(-self.angle); + g.model(&self.cube); + } - angle += 0.02; + self.angle += 0.02; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/camera_controllers.rs b/examples/camera_controllers.rs index 16f21bb1..5d9e1f87 100644 --- a/examples/camera_controllers.rs +++ b/examples/camera_controllers.rs @@ -1,104 +1,69 @@ -use processing_glfw::GlfwContext; +use processing::{Geometry, Graphics, Key, Light, Result, Settings, Sketch}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct CameraControllers { + cube: Geometry, + sun: Light, + angle: f32, + mode: u8, } -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; +impl Sketch for CameraControllers { + fn settings() -> Settings { + Settings::size(800, 600) + } - graphics_mode_3d(graphics)?; - graphics_orbit_camera(graphics)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.orbit_camera(); - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.98, 0.95), 1_500.0)?; - transform_set_position(dir_light, Vec3::new(300.0, -400.0, 300.0))?; - transform_look_at(dir_light, Vec3::ZERO)?; + let sun = g.create_directional_light((1.0, 0.98, 0.95), 1500); + sun.position((300, -400, 300)).look_at((0, 0, 0)); - let mut angle: f32 = 0.0; - let mut mode = 0u8; + let cube = Geometry::cube(100)?; + Ok(CameraControllers { + cube, + sun, + angle: 0.0, + mode: 0, + }) + } - while glfw_ctx.poll_events() { - if input_key_just_pressed(KeyCode::Digit1)? { - graphics_mode_3d(graphics)?; - graphics_orbit_camera(graphics)?; - mode = 0; + fn draw(&mut self, g: &mut Graphics) { + if g.key_just_pressed(Key::Num1) { + g.mode_3d(); + g.orbit_camera(); + self.mode = 0; } - if input_key_just_pressed(KeyCode::Digit2)? { - graphics_mode_3d(graphics)?; - graphics_free_camera(graphics)?; - mode = 1; + if g.key_just_pressed(Key::Num2) { + g.mode_3d(); + g.free_camera(); + self.mode = 1; } - if input_key_just_pressed(KeyCode::Digit3)? { - graphics_mode_2d(graphics)?; - graphics_pan_camera(graphics)?; - mode = 2; + if g.key_just_pressed(Key::Num3) { + g.mode_2d(); + g.pan_camera(); + self.mode = 2; } - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.07)), - )?; + g.light(&self.sun); + g.background((0.05, 0.05, 0.07)); - if mode < 2 { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(1.0, 0.85, 0.57)), - )?; - graphics_record_command(graphics, DrawCommand::Roughness(0.3))?; - graphics_record_command(graphics, DrawCommand::Metallic(0.8))?; - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + if self.mode < 2 { + g.fill((1.0, 0.85, 0.57)); + g.roughness(0.3); + g.metallic(0.8); + let mut g = g.push(); + g.rotate(-self.angle); + g.model(&self.cube); } else { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.8, 0.3, 0.2)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 300.0, - y: 200.0, - w: 200.0, - h: 200.0, - radii: [0.0; 4], - }, - )?; + g.fill((0.8, 0.3, 0.2)); + g.rect(300, 200, 200, 200); } - graphics_end_draw(graphics)?; - angle += 0.02; + self.angle += 0.02; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/compute_readback.rs b/examples/compute_readback.rs index cc160de7..8a4d4320 100644 --- a/examples/compute_readback.rs +++ b/examples/compute_readback.rs @@ -1,24 +1,6 @@ -use processing::prelude::*; +use processing::{Buffer, Compute, Graphics, Result, Settings, Shader, Sketch}; -fn main() { - match run() { - Ok(_) => exit(0).unwrap(), - Err(e) => { - eprintln!("{e:?}"); - exit(1).unwrap(); - } - } -} - -fn run() -> error::Result<()> { - init(Config::default())?; - - let surface = surface_create_offscreen(1, 1, 1.0, TextureFormat::Rgba8Unorm)?; - let _graphics = graphics_create(surface, 1, 1, TextureFormat::Rgba8Unorm)?; - - let buf = buffer_create(16)?; - - let shader_src = r#" +const FILL: &str = r#" @group(0) @binding(0) var output: array; @@ -30,21 +12,8 @@ fn main() { output[3] = 4u; } "#; - let shader = shader_create(shader_src)?; - let compute = compute_create(shader)?; - compute_set(compute, "output", shader_value::ShaderValue::Buffer(buf))?; - compute_dispatch(compute, 1, 1, 1)?; - - let data = buffer_read(buf)?; - let values: Vec = data - .chunks_exact(4) - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - - assert_eq!(values, vec![1, 2, 3, 4]); - - let double_src = r#" +const DOUBLE: &str = r#" @group(0) @binding(0) var data: array; @@ -53,29 +22,35 @@ fn main(@builtin(global_invocation_id) id: vec3) { data[id.x] = data[id.x] * 2.0; } "#; - let buf2_data: Vec = [1.0f32, 2.0, 3.0, 4.0] - .iter() - .flat_map(|f| f.to_le_bytes()) - .collect(); - let buf2 = buffer_create_with_data(buf2_data)?; - let shader2 = shader_create(double_src)?; - let compute2 = compute_create(shader2)?; - compute_set(compute2, "data", shader_value::ShaderValue::Buffer(buf2))?; - compute_dispatch(compute2, 1, 1, 1)?; - let data2 = buffer_read(buf2)?; - let floats: Vec = data2 - .chunks_exact(4) - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - assert_eq!(floats, vec![2.0, 4.0, 6.0, 8.0]); +struct ComputeReadback; - compute_destroy(compute)?; - compute_destroy(compute2)?; - shader_destroy(shader)?; - shader_destroy(shader2)?; - buffer_destroy(buf)?; - buffer_destroy(buf2)?; +impl Sketch for ComputeReadback { + fn settings() -> Settings { + Settings::size(1, 1).headless() + } + + fn setup(g: &mut Graphics) -> Result { + let output = Buffer::new(16)?; + let mut fill = Compute::new(&Shader::new(FILL)?)?; + fill.set("output", &output); + fill.dispatch(1, 1, 1); + let values: Vec = output.read()?; + assert_eq!(values, vec![1, 2, 3, 4]); + + let data = Buffer::from_slice(&[1.0f32, 2.0, 3.0, 4.0])?; + let mut double = Compute::new(&Shader::new(DOUBLE)?)?; + double.set("data", &data); + double.dispatch(1, 1, 1); + let doubled: Vec = data.read()?; + assert_eq!(doubled, vec![2.0, 4.0, 6.0, 8.0]); + + println!("{values:?} {doubled:?}"); + g.exit(); + Ok(ComputeReadback) + } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/custom_attribute.rs b/examples/custom_attribute.rs index 3bb2454c..ff097d9d 100644 --- a/examples/custom_attribute.rs +++ b/examples/custom_attribute.rs @@ -1,72 +1,52 @@ -use processing_glfw::GlfwContext; +use processing::{ + Attribute, AttributeFormat, Geometry, Graphics, Layout, Result, Settings, Sketch, Topology, +}; -use bevy::math::{Vec3, Vec4}; -use processing::prelude::*; -use processing_render::geometry::{AttributeFormat, Topology}; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct CustomAttribute { + mesh: Geometry, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let width = 600; - let height = 600; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let custom_attr = geometry_attribute_create("Custom", AttributeFormat::Float)?; +impl Sketch for CustomAttribute { + fn settings() -> Settings { + Settings::size(600, 600) + } - let layout = geometry_layout_create()?; - geometry_layout_add_position(layout)?; - geometry_layout_add_normal(layout)?; - geometry_layout_add_color(layout)?; - geometry_layout_add_attribute(layout, custom_attr)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 200)); + g.camera_look_at((0, 0, 0)); - let mesh = geometry_create_with_layout(layout, Topology::LineStrip)?; + let custom = Attribute::new("Custom", AttributeFormat::Float)?; + let layout = Layout::new()?.position().normal().color().attribute(custom); - geometry_color(mesh, Vec4::new(1.0, 0.0, 0.0, 1.0))?; - geometry_normal(mesh, Vec3::new(0.0, 0.0, 1.0))?; - geometry_attribute_float(mesh, custom_attr, 0.0)?; - geometry_vertex(mesh, Vec3::new(-50.0, 50.0, 0.0))?; + let mut mesh = Geometry::with_layout(&layout, Topology::LineStrip)?; + mesh.color((1.0, 0.0, 0.0)); + mesh.normal((0, 0, 1)); + mesh.attribute(custom, 0.0); + mesh.vertex((-50, 50)); - geometry_color(mesh, Vec4::new(0.0, 1.0, 0.0, 1.0))?; - geometry_attribute_float(mesh, custom_attr, 0.5)?; - geometry_vertex(mesh, Vec3::new(50.0, 50.0, 0.0))?; + mesh.color((0.0, 1.0, 0.0)); + mesh.attribute(custom, 0.5); + mesh.vertex((50, 50)); - geometry_color(mesh, Vec4::new(0.0, 0.0, 1.0, 1.0))?; - geometry_attribute_float(mesh, custom_attr, 1.0)?; - geometry_vertex(mesh, Vec3::new(0.0, -50.0, 0.0))?; + mesh.color((0.0, 0.0, 1.0)); + mesh.attribute(custom, 1.0); + mesh.vertex((0, -50)); - geometry_index(mesh, 0)?; - geometry_index(mesh, 1)?; - geometry_index(mesh, 2)?; - geometry_index(mesh, 0)?; + mesh.index(0); + mesh.index(1); + mesh.index(2); + mesh.index(0); - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 200.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + Ok(CustomAttribute { mesh }) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.12)), - )?; - graphics_record_command(graphics, DrawCommand::Geometry(mesh))?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.12)); + g.model(&self.mesh); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/custom_material.rs b/examples/custom_material.rs index 533a8124..ad95fa88 100644 --- a/examples/custom_material.rs +++ b/examples/custom_material.rs @@ -1,73 +1,47 @@ -use processing_glfw::GlfwContext; +use processing::{Geometry, Graphics, Material, Result, Settings, Shader, Sketch}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct CustomMaterial { + cube: Geometry, + material: Material, + angle: f32, } -fn sketch() -> error::Result<()> { - let width = 400; - let height = 400; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(100.0, -100.0, 300.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let shader = shader_load("shaders/custom_material.wesl")?; - let mat = material_create_custom(shader)?; - material_set( - mat, - "color", - shader_value::ShaderValue::Float4([1.0, 0.2, 0.4, 1.0]), - )?; - - let mut angle = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for CustomMaterial { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.15)), - )?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((100, -100, 300)); + g.camera_look_at((0, 0, 0)); + + let shader = Shader::load("shaders/custom_material.wesl")?; + let mut material = Material::new(&shader)?; + material.set("color", (1.0, 0.2, 0.4, 1.0)); + + let cube = Geometry::cube(100)?; + Ok(CustomMaterial { + cube, + material, + angle: 0.0, + }) + } - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.15)); - graphics_end_draw(graphics)?; + { + let mut g = g.push(); + g.rotate(-self.angle); + g.material(&self.material); + g.model(&self.cube); + } - angle += 0.02; + self.angle += 0.02; } +} - material_destroy(mat)?; - shader_destroy(shader)?; - - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/filter.rs b/examples/filter.rs index 6dc2fc87..04a4c0da 100644 --- a/examples/filter.rs +++ b/examples/filter.rs @@ -1,93 +1,50 @@ -//! Cycles through all implemented filters. -use std::time::Instant; - -use bevy::color::Color; -use processing_glfw::GlfwContext; +use processing::{Filter, Graphics, Result, Settings, Sketch}; + +const FILTERS: [Filter; 8] = [ + Filter::Invert, + Filter::Gray, + Filter::Threshold(0.5), + Filter::Posterize(4), + Filter::Opaque, + Filter::Erode, + Filter::Dilate, + Filter::Blur(4.0), +]; + +struct Filters; + +impl Sketch for Filters { + fn settings() -> Settings { + Settings::size(400, 400) + } -use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use processing_render::shader_value::ShaderValue; + fn setup(_g: &mut Graphics) -> Result { + Ok(Filters) + } -fn main() { - match sketch() { - Ok(_) => exit(0).unwrap(), - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.15)); + g.no_stroke(); + + g.fill((1.0, 0.2, 0.2)); + g.rect(40, 40, 160, 160); + g.fill((0.2, 1.0, 0.2)); + g.rect(200, 40, 160, 160); + g.fill((0.2, 0.4, 1.0)); + g.rect(40, 200, 160, 160); + g.fill((0.95, 0.85, 0.2)); + g.rect(200, 200, 160, 160); + + let seconds = g.millis() / 1000; + let filter = FILTERS[(seconds / 2) as usize % FILTERS.len()]; + g.filter(filter); + + // unfiltered + g.fill((0.0, 0.0, 1.0)); + g.rect(160, 160, 80, 80); + } } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(400, 400, false)?; - let graphics = graphics_create(surface, 400, 400, TextureFormat::Rgba16Float)?; - - let palette = [ - (40.0, 40.0, Color::srgb(1.0, 0.2, 0.2)), - (200.0, 40.0, Color::srgb(0.2, 1.0, 0.2)), - (40.0, 200.0, Color::srgb(0.2, 0.4, 1.0)), - (200.0, 200.0, Color::srgb(0.95, 0.85, 0.2)), - ]; - let threshold = filter_threshold()?; - filter_set(threshold, "cutoff", ShaderValue::Float(0.5))?; - let posterize = filter_posterize()?; - filter_set(posterize, "levels", ShaderValue::UInt(4))?; - let blur = filter_blur()?; - filter_set(blur, "radius", ShaderValue::Float(4.0))?; - let filters = [ - filter_invert()?, - filter_gray()?, - threshold, - posterize, - filter_opaque()?, - filter_erode()?, - filter_dilate()?, - blur, - ]; - - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(Color::srgb(0.1, 0.1, 0.15)), - )?; - graphics_record_command(graphics, DrawCommand::NoStroke)?; - - for &(x, y, color) in &palette { - graphics_record_command(graphics, DrawCommand::Fill(color))?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x, - y, - w: 160.0, - h: 160.0, - radii: [0.0; 4], - }, - )?; - } - - let idx = (start.elapsed().as_secs() / 2) as usize % filters.len(); - graphics_apply_filter(graphics, filters[idx])?; - - graphics_record_command(graphics, DrawCommand::Fill(Color::srgb(0.0, 0.0, 1.0)))?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 160.0, - y: 160.0, - w: 80.0, - h: 80.0, - radii: [0.0; 4], - }, - )?; - - graphics_end_draw(graphics)?; - } - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/gltf_load.rs b/examples/gltf_load.rs index 6fd09f42..5c700880 100644 --- a/examples/gltf_load.rs +++ b/examples/gltf_load.rs @@ -1,72 +1,48 @@ -use processing_glfw::GlfwContext; +use processing::{Geometry, Gltf, Graphics, Light, Material, Result, Settings, Sketch}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use processing_render::shader_value::ShaderValue; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct GltfLoad { + duck: Geometry, + skin: Material, + light: Light, } -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; +impl Sketch for GltfLoad { + fn settings() -> Settings { + Settings::size(800, 600) + } - let gltf = gltf_load(graphics, "gltf/Duck.glb")?; - let duck = gltf_geometry(gltf, "LOD3spShape")?; - let duck_mat = gltf_material(gltf, "blinn3-fx")?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); - graphics_mode_3d(graphics)?; - gltf_camera(gltf, 0)?; - let light = gltf_light(gltf, 0)?; + let gltf = Gltf::load(g, "gltf/Duck.glb")?; + let duck = gltf.geometry("LOD3spShape")?; + let skin = gltf.material("blinn3-fx")?; + gltf.camera(0)?; + let light = gltf.light(0)?; - let mut frame: u64 = 0; + Ok(GltfLoad { duck, skin, light }) + } - while glfw_ctx.poll_events() { - let t = frame as f32 * 0.02; + fn draw(&mut self, g: &mut Graphics) { + let t = (g.frame_count() - 1) as f32 * 0.02; let radius = 1.5; - let lx = t.cos() * radius; - let ly = -1.5; - let lz = t.sin() * radius; - transform_set_position(light, Vec3::new(lx, ly, lz))?; - transform_look_at(light, Vec3::new(0.0, -0.8, 0.0))?; + self.light + .position((t.cos() * radius, -1.5, t.sin() * radius)) + .look_at((0.0, -0.8, 0.0)); let r = (t * 8.0).sin() * 0.5 + 0.5; - let g = (t * 8.0 + 2.0).sin() * 0.5 + 0.5; + let green = (t * 8.0 + 2.0).sin() * 0.5 + 0.5; let b = (t * 8.0 + 4.0).sin() * 0.5 + 0.5; - material_set(duck_mat, "base_color", ShaderValue::Float4([r, g, b, 1.0]))?; - - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; + self.skin.set("base_color", (r, green, b, 1.0)); - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.12)), - )?; - - graphics_record_command(graphics, DrawCommand::Material(duck_mat))?; - graphics_record_command(graphics, DrawCommand::Geometry(duck))?; - - graphics_end_draw(graphics)?; - - frame += 1; + g.light(&self.light); + g.background((0.1, 0.1, 0.12)); + g.material(&self.skin); + g.model(&self.duck); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/lights.rs b/examples/lights.rs index c5bb3ff7..e624fc68 100644 --- a/examples/lights.rs +++ b/examples/lights.rs @@ -1,108 +1,73 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +use std::f32::consts::FRAC_PI_4; + +use processing::{Geometry, Graphics, Light, Material, Result, Settings, Sketch}; + +struct Lights { + cube: Geometry, + shiny: Material, + sun: Light, + warm: Light, + cool: Light, + spot: Light, + angle: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; - let pbr_mat = material_create_pbr()?; - material_set(pbr_mat, "roughness", shader_value::ShaderValue::Float(0.0))?; - - // create a directional light - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(0.35, 0.25, 0.5), 500.0)?; +impl Sketch for Lights { + fn settings() -> Settings { + Settings::size(400, 400) + } - // create a point light - let point_light_a = light_create_point( - graphics, - bevy::color::Color::srgb(1.0, 0.5, 0.25), - 1_000_000.0, - 200.0, - 0.5, - )?; - transform_set_position(point_light_a, Vec3::new(-25.0, -5.0, 51.0))?; - transform_look_at(point_light_a, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((100, -100, 300)); + g.camera_look_at((0, 0, 0)); - // create another point light - let point_light_b = light_create_point( - graphics, - bevy::color::Color::srgb(0.0, 0.5, 0.75), - 2_000_000.0, - 200.0, - 0.25, - )?; - transform_set_position(point_light_b, Vec3::new(0.0, -5.0, 50.5))?; - transform_look_at(point_light_b, Vec3::new(0.0, 0.0, 0.0))?; + let cube = Geometry::cube(100)?; + let mut shiny = Material::pbr()?; + shiny.set("roughness", 0.0); - // and a spot light, too! - let spot_light = light_create_spot( - graphics, - bevy::color::Color::srgb(0.25, 0.8, 0.19), - 15.0 * 1_000_000.0, - 200.0, - 0.84, - 0.0, - core::f32::consts::FRAC_PI_4, - )?; - transform_set_position(spot_light, Vec3::new(40.0, 0.0, 70.0))?; - transform_look_at(spot_light, Vec3::new(0.0, 0.0, 0.0))?; + let sun = g.create_directional_light((0.35, 0.25, 0.5), 500); - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(100.0, -100.0, 300.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + let warm = g.create_point_light((1.0, 0.5, 0.25), 1_000_000, 200, 0.5); + warm.position((-25, -5, 51)).look_at((0, 0, 0)); - let mut angle = 0.0; + let cool = g.create_point_light((0.0, 0.5, 0.75), 2_000_000, 200, 0.25); + cool.position((0.0, -5.0, 50.5)).look_at((0, 0, 0)); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - graphics_light(graphics, point_light_a)?; - graphics_light(graphics, point_light_b)?; - graphics_light(graphics, spot_light)?; + let spot = g.create_spot_light((0.25, 0.8, 0.19), 15_000_000, 200, 0.84, 0, FRAC_PI_4); + spot.position((40, 0, 70)).look_at((0, 0, 0)); - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.18, 0.20, 0.15)), - )?; + Ok(Lights { + cube, + shiny, + sun, + warm, + cool, + spot, + angle: 0.0, + }) + } - graphics_record_command(graphics, DrawCommand::Fill(bevy::color::Color::WHITE))?; - graphics_record_command(graphics, DrawCommand::Material(pbr_mat))?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.light(&self.warm); + g.light(&self.cool); + g.light(&self.spot); - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + g.background((0.18, 0.20, 0.15)); + g.fill(255); + g.material(&self.shiny); - graphics_end_draw(graphics)?; + { + let mut g = g.push(); + g.rotate(-self.angle); + g.model(&self.cube); + } - angle += 0.02; + self.angle += 0.02; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/materials.rs b/examples/materials.rs index c7c0294c..f35064a3 100644 --- a/examples/materials.rs +++ b/examples/materials.rs @@ -1,110 +1,73 @@ -use processing_glfw::GlfwContext; +use processing::{Color, Geometry, Graphics, Light, Material, Result, Settings, Sketch}; -use bevy::math::{Vec2, Vec3}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +const COLS: usize = 11; +const ROWS: usize = 5; +const SPACING: f32 = 70.0; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct Materials { + sphere: Geometry, + materials: Vec, + sun: Light, + lamp: Light, } -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let sphere = geometry_sphere(30.0, 32, 18)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 600.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.98, 0.95), 1_500.0)?; - transform_set_position(dir_light, Vec3::new(300.0, -400.0, 300.0))?; - transform_look_at(dir_light, Vec3::new(0.0, 0.0, 0.0))?; - - let point_light = - light_create_point(graphics, bevy::color::Color::WHITE, 100_000.0, 800.0, 0.0)?; - transform_set_position(point_light, Vec3::new(200.0, -200.0, 400.0))?; - - // Grid of materials varying roughness (x) and metallic (y) - let cols = 11; - let rows = 5; - let mut materials = Vec::new(); - - for row in 0..rows { - for col in 0..cols { - let mat = material_create_pbr()?; - let roughness = col as f32 / (cols - 1) as f32; - let metallic = row as f32 / (rows - 1) as f32; - - material_set( - mat, - "roughness", - shader_value::ShaderValue::Float(roughness), - )?; - material_set(mat, "metallic", shader_value::ShaderValue::Float(metallic))?; - materials.push(mat); - } +impl Sketch for Materials { + fn settings() -> Settings { + Settings::size(800, 600) } - let base_color = bevy::color::Color::srgb(1.0, 0.85, 0.57); - let spacing = 70.0; - let offset_x = (cols - 1) as f32 * spacing / 2.0; - let offset_y = (rows - 1) as f32 * spacing / 2.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - graphics_light(graphics, point_light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.07)), - )?; - - graphics_record_command(graphics, DrawCommand::Fill(base_color))?; - - for row in 0..rows { - for col in 0..cols { - let mat = materials[row * cols + col]; - - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate( - Vec2::new( - col as f32 * spacing - offset_x, - offset_y - row as f32 * spacing, - ) - .extend(0.0), - ), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command(graphics, DrawCommand::Geometry(sphere))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 600)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((1.0, 0.98, 0.95), 1500); + sun.position((300, -400, 300)).look_at((0, 0, 0)); + let lamp = g.create_point_light(Color::WHITE, 100_000, 800, 0); + lamp.position((200, -200, 400)); + + // roughness across, metallic down + let mut materials = Vec::new(); + for row in 0..ROWS { + for col in 0..COLS { + let mut material = Material::pbr()?; + material.set("roughness", col as f32 / (COLS - 1) as f32); + material.set("metallic", row as f32 / (ROWS - 1) as f32); + materials.push(material); } } - graphics_end_draw(graphics)?; + let sphere = Geometry::sphere(30, 32, 18)?; + Ok(Materials { + sphere, + materials, + sun, + lamp, + }) } - for mat in materials { - material_destroy(mat)?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.light(&self.lamp); + g.background((0.05, 0.05, 0.07)); + g.fill((1.0, 0.85, 0.57)); + + let offset_x = (COLS - 1) as f32 * SPACING / 2.0; + let offset_y = (ROWS - 1) as f32 * SPACING / 2.0; + for row in 0..ROWS { + for col in 0..COLS { + let mut g = g.push(); + g.translate(( + col as f32 * SPACING - offset_x, + offset_y - row as f32 * SPACING, + )); + g.material(&self.materials[row * COLS + col]); + g.model(&self.sphere); + } + } } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/midi.rs b/examples/midi.rs index 9113ae35..18638b95 100644 --- a/examples/midi.rs +++ b/examples/midi.rs @@ -1,7 +1,4 @@ -use bevy::color::{Color, ColorToComponents}; -use processing::prelude::*; -use processing_glfw::GlfwContext; -use processing_render::render::command::DrawCommand; +use processing::{Color, Graphics, Key, Result, Settings, Sketch, midi}; const PENTATONIC: [u8; 5] = [0, 3, 5, 7, 10]; const ROOT: u8 = 48; @@ -35,148 +32,115 @@ struct Ripple { color: Color, } -fn main() { - if let Err(e) = sketch() { - eprintln!("Sketch error: {e:?}"); - exit(1).unwrap(); - } - exit(0).unwrap(); +struct Midi { + held: Option, + ripples: Vec, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(WIDTH, HEIGHT, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(WIDTH, HEIGHT, false)?; - let graphics = graphics_create(surface, WIDTH, HEIGHT, TextureFormat::Rgba16Float)?; - - midi_refresh_ports()?; - let ports = midi_list_ports()?; - if ports.is_empty() { - eprintln!("no MIDI output ports found — connect a synth or virtual port and retry"); - return Ok(()); - } - for p in &ports { - println!("{p}"); +impl Midi { + fn play(&mut self, note: u8, x: f32, y: f32) -> Result<()> { + midi::note_on(note, velocity_at_y(y))?; + self.ripples.push(Ripple { + x, + y, + age: 0.0, + color: note_color(note), + }); + self.held = Some(note); + Ok(()) } - midi_connect(0)?; - - let mut held: Option = None; - let mut ripples: Vec = Vec::new(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - - let mx = input_mouse_x(surface)?; - let my = input_mouse_y(surface)?; - let pressed = input_mouse_is_pressed()?; - - match (pressed, held) { - (true, None) => { - let note = note_at_x(mx); - let velocity = velocity_at_y(my); - midi_note_on(note, velocity)?; - ripples.push(Ripple { - x: mx, - y: my, - age: 0.0, - color: note_color(note), - }); - held = Some(note); - } + + fn update_notes(&mut self, g: &Graphics) -> Result<()> { + let x = g.mouse_x(); + let y = g.mouse_y(); + match (g.mouse_pressed(), self.held) { + (true, None) => self.play(note_at_x(x), x, y)?, (true, Some(note)) => { - let target = note_at_x(mx); + let target = note_at_x(x); if target != note { - midi_note_off(note)?; - let velocity = velocity_at_y(my); - midi_note_on(target, velocity)?; - ripples.push(Ripple { - x: mx, - y: my, - age: 0.0, - color: note_color(target), - }); - held = Some(target); + midi::note_off(note)?; + self.play(target, x, y)?; } } (false, Some(note)) => { - midi_note_off(note)?; - held = None; + midi::note_off(note)?; + self.held = None; + } + (false, None) => {} + } + Ok(()) + } +} + +impl Sketch for Midi { + fn settings() -> Settings { + Settings::size(WIDTH, HEIGHT) + } + + fn setup(g: &mut Graphics) -> Result { + midi::refresh_ports()?; + let ports = midi::ports()?; + if ports.is_empty() { + eprintln!("no MIDI output ports found — connect a synth or virtual port and retry"); + g.exit(); + } else { + for port in &ports { + println!("{port}"); } - _ => {} + midi::connect(0)?; + } + Ok(Midi { + held: None, + ripples: Vec::new(), + }) + } + + fn draw(&mut self, g: &mut Graphics) { + if let Err(e) = self.update_notes(g) { + eprintln!("midi: {e}"); } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(Color::srgb(0.04, 0.04, 0.07)), - )?; + g.background((0.04, 0.04, 0.07)); + g.no_stroke(); let octave_w = WIDTH as f32 / OCTAVES as f32; for i in 0..OCTAVES { - let alpha = if i % 2 == 0 { 0.04 } else { 0.0 }; - graphics_record_command( - graphics, - DrawCommand::Fill(Color::srgba(1.0, 1.0, 1.0, alpha)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: i as f32 * octave_w, - y: 0.0, - w: octave_w, - h: HEIGHT as f32, - radii: [0.0; 4], - }, - )?; + if i % 2 == 0 { + g.fill((1.0, 1.0, 1.0, 0.04)); + g.rect(i as f32 * octave_w, 0, octave_w, HEIGHT); + } } - ripples.retain_mut(|r| { - r.age += 0.022; - r.age < 1.0 - }); - for r in &ripples { - let size = 24.0 + r.age * 220.0; - let alpha = (1.0 - r.age).powi(2); - let lin = r.color.to_linear().to_f32_array(); - graphics_record_command( - graphics, - DrawCommand::Fill(Color::linear_rgba(lin[0], lin[1], lin[2], alpha)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: r.x - size / 2.0, - y: r.y - size / 2.0, - w: size, - h: size, - radii: [size / 2.0; 4], - }, - )?; + for ripple in &mut self.ripples { + ripple.age += 0.022; } + self.ripples.retain(|r| r.age < 1.0); - let preview = note_color(note_at_x(mx)); - graphics_record_command(graphics, DrawCommand::Fill(preview))?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: mx - 8.0, - y: my - 8.0, - w: 16.0, - h: 16.0, - radii: [8.0; 4], - }, - )?; - - graphics_end_draw(graphics)?; - - if input_key_is_pressed()? && input_key_is_down(KeyCode::Escape)? { - break; + for ripple in &self.ripples { + let size = 24.0 + ripple.age * 220.0; + let alpha = (1.0 - ripple.age).powi(2); + g.fill(ripple.color.with_alpha(alpha)); + g.circle(ripple.x, ripple.y, size); + } + + g.fill(note_color(note_at_x(g.mouse_x()))); + g.circle(g.mouse_x(), g.mouse_y(), 16); + + if g.key_pressed() && g.key_down(Key::Escape) { + g.exit(); } } +} - if let Some(note) = held { - midi_note_off(note)?; +impl Drop for Midi { + fn drop(&mut self) { + if let Some(note) = self.held { + let _ = midi::note_off(note); + } + let _ = midi::disconnect(); } - midi_disconnect()?; - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_animated.rs b/examples/particles_animated.rs index 6f5d1760..614564f4 100644 --- a/examples/particles_animated.rs +++ b/examples/particles_animated.rs @@ -1,8 +1,7 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, + Sketch, +}; const SPIN_SHADER: &str = r#" struct Params { @@ -28,77 +27,69 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesAnimated { + sun: Light, + sphere: Geometry, + particles: Particles, + pbr: Material, + spin: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; +impl Sketch for ParticlesAnimated { + fn settings() -> Settings { + Settings::size(900, 700) + } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -8.0, 25.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -8.0, 25.0)); + g.camera_look_at((0, 0, 0)); - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; + let sun = g.create_directional_light((0.9, 0.85, 0.8), 300.0); - let sphere = geometry_sphere(0.25, 12, 8)?; + let sphere = Geometry::sphere(0.25, 12, 8)?; - let capacity: u32 = 1000; - let mut floats: Vec = Vec::with_capacity(capacity as usize * 3); - for x in 0..10 { - for y in 0..10 { - for z in 0..10 { - floats.push((x as f32 - 4.5) * 1.0); - floats.push((y as f32 - 4.5) * 1.0); - floats.push((z as f32 - 4.5) * 1.0); + let capacity: u32 = 1000; + let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + for x in 0..10 { + for y in 0..10 { + for z in 0..10 { + positions.push((x as f32 - 4.5) * 1.0); + positions.push((y as f32 - 4.5) * 1.0); + positions.push((z as f32 - 4.5) * 1.0); + } } } + + let particles = Particles::new(capacity, &[Attribute::position()])?; + particles.buffer(Attribute::position()).write(&positions); + + let mut pbr = Material::pbr()?; + pbr.set("roughness", 0.4); + + let spin = Compute::new(&Shader::new(SPIN_SHADER)?)?; + + Ok(ParticlesAnimated { + sun, + sphere, + particles, + pbr, + spin, + }) } - let bytes: Vec = floats.iter().flat_map(|f| f.to_le_bytes()).collect(); - - let position_attr = geometry_attribute_position(); - let p = particles_create(capacity, vec![position_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write(position_buf, bytes)?; - - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.4))?; - - let spin_shader = shader_create(SPIN_SHADER)?; - let spin = compute_create(spin_shader)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.9, 0.5, 0.3)), - )?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; - - compute_set(spin, "dt", shader_value::ShaderValue::Float(0.01))?; - particles_apply(p, spin)?; + + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.fill((0.9, 0.5, 0.3)); + g.material(&self.pbr); + g.particles(&self.particles).geometry(&self.sphere); + + self.spin.set("dt", 0.01); + self.particles.apply(&self.spin); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_basic.rs b/examples/particles_basic.rs index 2a383fc8..9f901945 100644 --- a/examples/particles_basic.rs +++ b/examples/particles_basic.rs @@ -1,74 +1,63 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +use processing::{ + Attribute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, +}; + +struct ParticlesBasic { + sun: Light, + sphere: Geometry, + particles: Particles, + pbr: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; +impl Sketch for ParticlesBasic { + fn settings() -> Settings { + Settings::size(900, 700) + } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 25.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, 0.0, 25.0)); + g.camera_look_at((0, 0, 0)); - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; + let sun = g.create_directional_light((0.9, 0.85, 0.8), 300.0); - let sphere = geometry_sphere(0.25, 12, 8)?; + let sphere = Geometry::sphere(0.25, 12, 8)?; - let capacity: u32 = 1000; - let mut floats: Vec = Vec::with_capacity(capacity as usize * 3); - for x in 0..10 { - for y in 0..10 { - for z in 0..10 { - floats.push((x as f32 - 4.5) * 1.0); - floats.push((y as f32 - 4.5) * 1.0); - floats.push((z as f32 - 4.5) * 1.0); + let capacity: u32 = 1000; + let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + for x in 0..10 { + for y in 0..10 { + for z in 0..10 { + positions.push(x as f32 - 4.5); + positions.push(y as f32 - 4.5); + positions.push(z as f32 - 4.5); + } } } - } - let bytes: Vec = floats.iter().flat_map(|f| f.to_le_bytes()).collect(); - let position_attr = geometry_attribute_position(); - let p = particles_create(capacity, vec![position_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write(position_buf, bytes)?; + let particles = Particles::new(capacity, &[Attribute::position()])?; + particles.buffer(Attribute::position()).write(&positions); + + let mut pbr = Material::pbr()?; + pbr.set("roughness", 0.4); - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.4))?; + Ok(ParticlesBasic { + sun, + sphere, + particles, + pbr, + }) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.9, 0.5, 0.3)), - )?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.fill((0.9, 0.5, 0.3)); + g.material(&self.pbr); + g.particles(&self.particles).geometry(&self.sphere); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_colored.rs b/examples/particles_colored.rs index e952f3d2..3e392bbc 100644 --- a/examples/particles_colored.rs +++ b/examples/particles_colored.rs @@ -1,83 +1,62 @@ -use processing_glfw::GlfwContext; +use processing::{Attribute, Geometry, Graphics, Material, Particles, Result, Settings, Sketch}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesColored { + sphere: Geometry, + particles: Particles, + material: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -6.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let sphere = geometry_sphere(0.25, 12, 8)?; +impl Sketch for ParticlesColored { + fn settings() -> Settings { + Settings::size(900, 700) + } - let capacity: u32 = 1000; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); - for x in 0..10 { - for y in 0..10 { - for z in 0..10 { - positions.push((x as f32 - 4.5) * 1.0); - positions.push((4.5 - y as f32) * 1.0); - positions.push((z as f32 - 4.5) * 1.0); - colors.push(x as f32 / 9.0); - colors.push(y as f32 / 9.0); - colors.push(z as f32 / 9.0); - colors.push(1.0); + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -6.0, 18.0)); + g.camera_look_at((0, 0, 0)); + + let sphere = Geometry::sphere(0.25, 12, 8)?; + + let capacity: u32 = 1000; + let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); + for x in 0..10 { + for y in 0..10 { + for z in 0..10 { + positions.push(x as f32 - 4.5); + positions.push(4.5 - y as f32); + positions.push(z as f32 - 4.5); + colors.push(x as f32 / 9.0); + colors.push(y as f32 / 9.0); + colors.push(z as f32 / 9.0); + colors.push(1.0); + } } } - } - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - color_buf, - colors.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; + particles.buffer(Attribute::position()).write(&positions); + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); + + let mut material = Material::unlit()?; + material.albedo_buffer(&color_buf); - let mat = { - let m = material_create_unlit()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + Ok(ParticlesColored { + sphere, + particles, + material, + }) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.sphere); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_colored_pbr.rs b/examples/particles_colored_pbr.rs index 4b121be4..e6deff85 100644 --- a/examples/particles_colored_pbr.rs +++ b/examples/particles_colored_pbr.rs @@ -1,87 +1,69 @@ -use processing_glfw::GlfwContext; +use processing::{ + Attribute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, +}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesColoredPbr { + sun: Light, + sphere: Geometry, + particles: Particles, + material: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; +impl Sketch for ParticlesColoredPbr { + fn settings() -> Settings { + Settings::size(900, 700) + } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -6.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -6.0, 18.0)); + g.camera_look_at((0, 0, 0)); - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 200.0)?; + let sun = g.create_directional_light((0.95, 0.9, 0.85), 200.0); - let sphere = geometry_sphere(0.3, 16, 12)?; + let sphere = Geometry::sphere(0.3, 16, 12)?; - let capacity: u32 = 512; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); - for x in 0..8 { - for y in 0..8 { - for z in 0..8 { - positions.push((x as f32 - 3.5) * 1.4); - positions.push((3.5 - y as f32) * 1.4); - positions.push((z as f32 - 3.5) * 1.4); - colors.push(x as f32 / 7.0); - colors.push(y as f32 / 7.0); - colors.push(z as f32 / 7.0); - colors.push(1.0); + let capacity: u32 = 512; + let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); + for x in 0..8 { + for y in 0..8 { + for z in 0..8 { + positions.push((x as f32 - 3.5) * 1.4); + positions.push((3.5 - y as f32) * 1.4); + positions.push((z as f32 - 3.5) * 1.4); + colors.push(x as f32 / 7.0); + colors.push(y as f32 / 7.0); + colors.push(z as f32 / 7.0); + colors.push(1.0); + } } } - } - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - color_buf, - colors.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; + particles.buffer(Attribute::position()).write(&positions); + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + let mut material = Material::pbr()?; + material.albedo_buffer(&color_buf); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + Ok(ParticlesColoredPbr { + sun, + sphere, + particles, + material, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.sphere); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_emit.rs b/examples/particles_emit.rs index 83f66909..63972535 100644 --- a/examples/particles_emit.rs +++ b/examples/particles_emit.rs @@ -1,77 +1,55 @@ -use processing_glfw::GlfwContext; +use processing::{Attribute, Geometry, Graphics, Material, Particles, Result, Settings, Sketch}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesEmit { + sphere: Geometry, + particles: Particles, + material: Material, + frame: u32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; +impl Sketch for ParticlesEmit { + fn settings() -> Settings { + Settings::size(900, 700) + } - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 14.0)); + g.camera_look_at((0, 0, 0)); - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 14.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + let sphere = Geometry::sphere(0.08, 8, 6)?; - let sphere = geometry_sphere(0.08, 8, 6)?; + let capacity: u32 = 2000; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; - let capacity: u32 = 2000; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; + // offscreen until emitted + let far_away: Vec = vec![1.0e6; capacity as usize * 3]; + particles.buffer(Attribute::position()).write(&far_away); - let init_positions: Vec = (0..capacity * 3).map(|_| 1.0e6).collect(); - buffer_write( - position_buf, - init_positions - .iter() - .flat_map(|f| f.to_le_bytes()) - .collect(), - )?; + let mut material = Material::unlit()?; + material.albedo_buffer(&particles.buffer(Attribute::color())); - let mat = { - let m = material_create_unlit()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + Ok(ParticlesEmit { + sphere, + particles, + material, + frame: 0, + }) + } - let mut frame: u32 = 0; - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.sphere); let burst = 4u32; let mut positions: Vec = Vec::with_capacity(burst as usize * 3); let mut colors: Vec = Vec::with_capacity(burst as usize * 4); for k in 0..burst { - let i = frame * burst + k; + let i = self.frame * burst + k; let t = i as f32 * 0.05; let radius = 1.5 + (t * 0.02).min(3.0); - let height = -((t * 0.1).sin()) * 2.0; + let height = -(t * 0.1).sin() * 2.0; positions.push(t.cos() * radius); positions.push(height); positions.push(t.sin() * radius); @@ -83,17 +61,15 @@ fn sketch() -> error::Result<()> { colors.push(1.0); } - let position_bytes: Vec = positions.iter().flat_map(|f| f.to_le_bytes()).collect(); - let color_bytes: Vec = colors.iter().flat_map(|f| f.to_le_bytes()).collect(); - particles_emit( - p, + self.particles.emit( burst, - vec![(position_attr, position_bytes), (color_attr, color_bytes)], - )?; - frame += 1; + &[ + (Attribute::position(), &positions), + (Attribute::color(), &colors), + ], + ); + self.frame += 1; } - - Ok(()) } fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { @@ -111,3 +87,7 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { _ => (v, p, q), } } + +fn main() -> Result<()> { + processing::run::() +} diff --git a/examples/particles_emit_gpu.rs b/examples/particles_emit_gpu.rs index 743ec55d..0298ff0d 100644 --- a/examples/particles_emit_gpu.rs +++ b/examples/particles_emit_gpu.rs @@ -1,10 +1,7 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, + Sketch, +}; const SPAWN_SHADER: &str = r#" struct Spawn { @@ -104,8 +101,8 @@ fn main(@builtin(global_invocation_id) gid: vec3) { position[i * 3u + 1u] = position[i * 3u + 1u] + velocity[i * 3u + 1u] * params.dt; position[i * 3u + 2u] = position[i * 3u + 2u] + velocity[i * 3u + 2u] * params.dt; - let life = clamp(1.0 - age[i] / params.ttl, 0.0, 1.0); - let s = life * life; + let remaining = clamp(1.0 - age[i] / params.ttl, 0.0, 1.0); + let s = remaining * remaining; scale[i * 3u + 0u] = s; scale[i * 3u + 1u] = s; scale[i * 3u + 2u] = s; @@ -114,106 +111,84 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 120; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 2.5; +const GRAVITY: f32 = -9.8; +const SPEED: f32 = 5.0; + +struct ParticlesEmitGpu { + sun: Light, + particle: Geometry, + particles: Particles, + mat: Material, + spawn: Compute, + motion: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 16.0))?; - transform_look_at(graphics, Vec3::new(0.0, -2.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 800.0)?; - - let particle = geometry_sphere(0.12, 8, 6)?; - - let capacity: u32 = 40000; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let velocity_attr = geometry_attribute_create("velocity", AttributeFormat::Float3)?; - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![ - position_attr, - color_attr, - scale_attr, - life_attr, - velocity_attr, - age_attr, - ], - )?; - - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - - let spawn_shader = shader_create(SPAWN_SHADER)?; - let spawn = compute_create(spawn_shader)?; - - let motion_shader = shader_create(MOTION_SHADER)?; - let motion = compute_create(motion_shader)?; - - let burst: u32 = 120; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 2.5; - let gravity: f32 = -9.8; - let speed: f32 = 5.0; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.07)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; +impl Sketch for ParticlesEmitGpu { + fn settings() -> Settings { + Settings::size(900, 700) + } - let t = start.elapsed().as_secs_f32(); - let sx = t.cos() * 0.4; - let sz = t.sin() * 0.4; - compute_set( - spawn, - "pos", - shader_value::ShaderValue::Float4([sx, -7.0, sz, 0.0]), + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 16.0)); + g.camera_look_at((0.0, -2.0, 0.0)); + + let sun = g.create_directional_light((0.95, 0.9, 0.85), 800.0); + + let particle = Geometry::sphere(0.12, 8, 6)?; + + let capacity: u32 = 40000; + let particles = Particles::new( + capacity, + &[ + Attribute::position(), + Attribute::color(), + Attribute::scale(), + Attribute::life(), + Attribute::velocity(), + Attribute::age(), + ], )?; - compute_set( + + let mut mat = Material::pbr()?; + mat.albedo_buffer(&particles.buffer(Attribute::color())); + + let spawn = Compute::new(&Shader::new(SPAWN_SHADER)?)?; + let motion = Compute::new(&Shader::new(MOTION_SHADER)?)?; + + Ok(ParticlesEmitGpu { + sun, + particle, + particles, + mat, spawn, - "speed", - shader_value::ShaderValue::Float4([speed, 0.0, 0.0, 0.0]), - )?; - particles_emit_gpu(p, burst, spawn)?; + motion, + }) + } - compute_set(motion, "dt", shader_value::ShaderValue::Float(dt))?; - compute_set(motion, "ttl", shader_value::ShaderValue::Float(ttl))?; - compute_set(motion, "gravity", shader_value::ShaderValue::Float(gravity))?; - particles_apply(p, motion)?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.04, 0.04, 0.07)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); + + let t = g.elapsed_time(); + let sx = t.cos() * 0.4; + let sz = t.sin() * 0.4; + self.spawn.set("pos", (sx, -7.0, sz, 0.0)); + self.spawn.set("speed", (SPEED, 0.0, 0.0, 0.0)); + self.particles.emit_gpu(BURST, &self.spawn); + + self.motion.set("dt", DT); + self.motion.set("ttl", TTL); + self.motion.set("gravity", GRAVITY); + self.particles.apply(&self.motion); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_from_mesh.rs b/examples/particles_from_mesh.rs index 13a88aac..836659f2 100644 --- a/examples/particles_from_mesh.rs +++ b/examples/particles_from_mesh.rs @@ -1,79 +1,63 @@ -use processing_glfw::GlfwContext; +use processing::{ + Attribute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, +}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesFromMesh { + sun: Light, + particle: Geometry, + particles: Particles, + material: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 200.0)?; +impl Sketch for ParticlesFromMesh { + fn settings() -> Settings { + Settings::size(900, 700) + } - let source = geometry_sphere(5.0, 32, 24)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 18.0)); + g.camera_look_at((0, 0, 0)); - let position_attr = geometry_attribute_position(); - let uv_attr = geometry_attribute_uv(); - let color_attr = geometry_attribute_color(); + let sun = g.create_directional_light((0.95, 0.9, 0.85), 200.0); - let p = particles_create_from_geometry(source, vec![position_attr, uv_attr, color_attr])?; - let uv_buf = particles_buffer(p, uv_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; + let source = Geometry::sphere(5.0, 32, 24)?; + let particles = Particles::from_geometry( + &source, + &[Attribute::position(), Attribute::uv(), Attribute::color()], + )?; - let uv_bytes = buffer_read(uv_buf)?; - let mut colors: Vec = Vec::with_capacity(uv_bytes.len() * 2); - for chunk in uv_bytes.chunks_exact(8) { - let u = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - let v = f32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); - let (r, g, b) = hsv_to_rgb(u, 0.85, 1.0); - for f in [r, g, b, 1.0] { - colors.extend_from_slice(&f.to_le_bytes()); + // hue from u + let uvs = particles.buffer(Attribute::uv()).read::()?; + let mut colors: Vec = Vec::with_capacity(uvs.len() * 2); + for uv in uvs.chunks_exact(2) { + let (r, g, b) = hsv_to_rgb(uv[0], 0.85, 1.0); + colors.push(r); + colors.push(g); + colors.push(b); + colors.push(1.0); } - let _ = v; - } - buffer_write(color_buf, colors)?; + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); - let particle = geometry_sphere(0.18, 10, 8)?; - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + let particle = Geometry::sphere(0.18, 10, 8)?; + let mut material = Material::pbr()?; + material.albedo_buffer(&color_buf); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + Ok(ParticlesFromMesh { + sun, + particle, + particles, + material, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.particle); + } } fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { @@ -91,3 +75,7 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { _ => (v, p, q), } } + +fn main() -> Result<()> { + processing::run::() +} diff --git a/examples/particles_lifecycle.rs b/examples/particles_lifecycle.rs index 1677789d..0087156d 100644 --- a/examples/particles_lifecycle.rs +++ b/examples/particles_lifecycle.rs @@ -1,9 +1,6 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, Compute, Geometry, Graphics, Material, Particles, Result, Settings, Shader, Sketch, +}; const AGING_SHADER: &str = r#" @group(0) @binding(0) var age: array; @@ -41,72 +38,68 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 6; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 1.0; + +struct ParticlesLifecycle { + sphere: Geometry, + particles: Particles, + mat: Material, + aging: Compute, + frame: u32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -2.0, 14.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let sphere = geometry_sphere(0.1, 8, 6)?; - - let capacity: u32 = 800; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![position_attr, color_attr, scale_attr, life_attr, age_attr], - )?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - - let mat = { - let m = material_create_unlit()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - let aging_shader = shader_create(AGING_SHADER)?; - let aging = compute_create(aging_shader)?; - - let burst: u32 = 6; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 1.0; - let mut frame: u32 = 0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.07)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, +impl Sketch for ParticlesLifecycle { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -2.0, 14.0)); + g.camera_look_at((0, 0, 0)); + + let sphere = Geometry::sphere(0.1, 8, 6)?; + + let capacity: u32 = 800; + let particles = Particles::new( + capacity, + &[ + Attribute::position(), + Attribute::color(), + Attribute::scale(), + Attribute::life(), + Attribute::age(), + ], )?; - graphics_end_draw(graphics)?; - let mut positions: Vec = Vec::with_capacity(burst as usize * 3); - let mut colors: Vec = Vec::with_capacity(burst as usize * 4); - for k in 0..burst { - let i = frame * burst + k; + let mut mat = Material::unlit()?; + mat.albedo_buffer(&particles.buffer(Attribute::color())); + + let aging = Compute::new(&Shader::new(AGING_SHADER)?)?; + + Ok(ParticlesLifecycle { + sphere, + particles, + mat, + aging, + frame: 0, + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.background((0.04, 0.04, 0.07)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.sphere); + + let mut positions: Vec = Vec::with_capacity(BURST as usize * 3); + let mut colors: Vec = Vec::with_capacity(BURST as usize * 4); + let mut scales: Vec = Vec::with_capacity(BURST as usize * 3); + let mut ages: Vec = Vec::with_capacity(BURST as usize); + let mut lives: Vec = Vec::with_capacity(BURST as usize); + for k in 0..BURST { + let i = self.frame * BURST + k; let u = ((i.wrapping_mul(2654435761) >> 8) & 0xFFFF) as f32 / 65535.0; let v = ((i.wrapping_mul(40503) >> 8) & 0xFFFF) as f32 / 65535.0; let theta = u * std::f32::consts::TAU; @@ -120,42 +113,32 @@ fn sketch() -> error::Result<()> { colors.push(cg); colors.push(cb); colors.push(1.0); + scales.push(1.0); + scales.push(1.0); + scales.push(1.0); + ages.push(0.0); + lives.push(1.0); } - let position_bytes: Vec = positions.iter().flat_map(|f| f.to_le_bytes()).collect(); - let color_bytes: Vec = colors.iter().flat_map(|f| f.to_le_bytes()).collect(); - let zero_floats: Vec = (0..burst).flat_map(|_| 0.0_f32.to_le_bytes()).collect(); - let one_floats: Vec = (0..burst).flat_map(|_| 1.0_f32.to_le_bytes()).collect(); - let one_scale: Vec = (0..burst) - .flat_map(|_| { - [1.0_f32, 1.0, 1.0] - .iter() - .flat_map(|f| f.to_le_bytes()) - .collect::>() - }) - .collect(); - particles_emit( - p, - burst, - vec![ - (position_attr, position_bytes), - (color_attr, color_bytes), - (scale_attr, one_scale), - (age_attr, zero_floats), - (life_attr, one_floats), + self.particles.emit( + BURST, + &[ + (Attribute::position(), &positions), + (Attribute::color(), &colors), + (Attribute::scale(), &scales), + (Attribute::age(), &ages), + (Attribute::life(), &lives), ], - )?; + ); - compute_set( - aging, - "params", - shader_value::ShaderValue::Float4([dt, ttl, 0.0, 0.0]), - )?; - particles_apply(p, aging)?; + self.aging.set("params", (DT, TTL, 0.0, 0.0)); + self.particles.apply(&self.aging); - frame += 1; + self.frame += 1; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { diff --git a/examples/particles_noise.rs b/examples/particles_noise.rs index 9ab17126..d5321f50 100644 --- a/examples/particles_noise.rs +++ b/examples/particles_noise.rs @@ -1,83 +1,73 @@ -use processing_glfw::GlfwContext; +use processing::{ + Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, +}; -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesNoise { + sun: Light, + particle: Geometry, + particles: Particles, + material: Material, + noise: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; +impl Sketch for ParticlesNoise { + fn settings() -> Settings { + Settings::size(900, 700) + } - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 200.0)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 18.0)); + g.camera_look_at((0, 0, 0)); - let source = geometry_sphere(5.0, 32, 24)?; - let position_attr = geometry_attribute_position(); - let uv_attr = geometry_attribute_uv(); - let color_attr = geometry_attribute_color(); - let p = particles_create_from_geometry(source, vec![position_attr, uv_attr, color_attr])?; + let sun = g.create_directional_light((0.95, 0.9, 0.85), 200.0); - let uv_buf = particles_buffer(p, uv_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; + let source = Geometry::sphere(5.0, 32, 24)?; + let particles = Particles::from_geometry( + &source, + &[Attribute::position(), Attribute::uv(), Attribute::color()], + )?; - let uv_bytes = buffer_read(uv_buf)?; - let mut colors: Vec = Vec::with_capacity(uv_bytes.len() * 2); - for chunk in uv_bytes.chunks_exact(8) { - let u = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - let (r, g, b) = hsv_to_rgb(u, 0.85, 1.0); - for f in [r, g, b, 1.0] { - colors.extend_from_slice(&f.to_le_bytes()); + // hue from u + let uvs = particles.buffer(Attribute::uv()).read::()?; + let mut colors: Vec = Vec::with_capacity(uvs.len() * 2); + for uv in uvs.chunks_exact(2) { + let (r, g, b) = hsv_to_rgb(uv[0], 0.85, 1.0); + colors.push(r); + colors.push(g); + colors.push(b); + colors.push(1.0); } - } - buffer_write(color_buf, colors)?; + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); - let particle = geometry_sphere(0.18, 10, 8)?; - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - let noise = particles_kernel_noise()?; + let particle = Geometry::sphere(0.18, 10, 8)?; + let mut material = Material::pbr()?; + material.albedo_buffer(&color_buf); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + let noise = Particles::noise()?; - let t = elapsed_time()?; - compute_set(noise, "scale", shader_value::ShaderValue::Float(0.25))?; - compute_set(noise, "strength", shader_value::ShaderValue::Float(0.02))?; - compute_set(noise, "time", shader_value::ShaderValue::Float(t * 0.5))?; - particles_apply(p, noise)?; + Ok(ParticlesNoise { + sun, + particle, + particles, + material, + noise, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.particle); + + let t = g.elapsed_time(); + self.noise.set("scale", 0.25); + self.noise.set("strength", 0.02); + self.noise.set("time", t * 0.5); + self.particles.apply(&self.noise); + } } fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { @@ -95,3 +85,7 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { _ => (v, p, q), } } + +fn main() -> Result<()> { + processing::run::() +} diff --git a/examples/particles_oriented.rs b/examples/particles_oriented.rs index bdb784ec..28a231cf 100644 --- a/examples/particles_oriented.rs +++ b/examples/particles_oriented.rs @@ -1,8 +1,7 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, + Sketch, +}; const SPIN_SHADER: &str = r#" @group(0) @binding(0) var rotation: array; @@ -39,107 +38,88 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesOriented { + sun: Light, + cube: Geometry, + particles: Particles, + pbr: Material, + spin: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -6.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; - - let cube = geometry_box(0.6, 0.6, 0.6)?; - - let capacity: u32 = 125; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut rotations: Vec = Vec::with_capacity(capacity as usize * 4); - let mut scales: Vec = Vec::with_capacity(capacity as usize * 3); - for x in 0..5 { - for y in 0..5 { - for z in 0..5 { - positions.push((x as f32 - 2.0) * 1.6); - positions.push((2.0 - y as f32) * 1.6); - positions.push((z as f32 - 2.0) * 1.6); - rotations.push(0.0); - rotations.push(0.0); - rotations.push(0.0); - rotations.push(1.0); - let s = 0.5 + ((x + y + z) as f32 * 0.06); - scales.push(s); - scales.push(s); - scales.push(s); +impl Sketch for ParticlesOriented { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -6.0, 18.0)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((0.9, 0.85, 0.8), 300.0); + + let cube = Geometry::cube((0.6, 0.6, 0.6))?; + + let capacity: u32 = 125; + let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + let mut rotations: Vec = Vec::with_capacity(capacity as usize * 4); + let mut scales: Vec = Vec::with_capacity(capacity as usize * 3); + for x in 0..5 { + for y in 0..5 { + for z in 0..5 { + positions.push((x as f32 - 2.0) * 1.6); + positions.push((2.0 - y as f32) * 1.6); + positions.push((z as f32 - 2.0) * 1.6); + rotations.push(0.0); + rotations.push(0.0); + rotations.push(0.0); + rotations.push(1.0); + let s = 0.5 + ((x + y + z) as f32 * 0.06); + scales.push(s); + scales.push(s); + scales.push(s); + } } } - } - let position_attr = geometry_attribute_position(); - let rotation_attr = geometry_attribute_rotation(); - let scale_attr = geometry_attribute_scale(); - let p = particles_create(capacity, vec![position_attr, rotation_attr, scale_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let rotation_buf = - particles_buffer(p, rotation_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let scale_buf = - particles_buffer(p, scale_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - rotation_buf, - rotations.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - scale_buf, - scales.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.4))?; - - let spin_shader = shader_create(SPIN_SHADER)?; - let spin = compute_create(spin_shader)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), + let particles = Particles::new( + capacity, + &[ + Attribute::position(), + Attribute::rotation(), + Attribute::scale(), + ], )?; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.9, 0.5, 0.3)), - )?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(cube), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + particles.buffer(Attribute::position()).write(&positions); + particles.buffer(Attribute::rotation()).write(&rotations); + particles.buffer(Attribute::scale()).write(&scales); + + let mut pbr = Material::pbr()?; + pbr.set("roughness", 0.4); - compute_set( + let spin = Compute::new(&Shader::new(SPIN_SHADER)?)?; + + Ok(ParticlesOriented { + sun, + cube, + particles, + pbr, spin, - "params", - shader_value::ShaderValue::Float4([0.015, 0.0, 0.0, 0.0]), - )?; - particles_apply(p, spin)?; + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.fill((0.9, 0.5, 0.3)); + g.material(&self.pbr); + g.particles(&self.particles).geometry(&self.cube); + + self.spin.set("params", (0.015, 0.0, 0.0, 0.0)); + self.particles.apply(&self.spin); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_scatter.rs b/examples/particles_scatter.rs index f1b51961..6debecd9 100644 --- a/examples/particles_scatter.rs +++ b/examples/particles_scatter.rs @@ -1,10 +1,7 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, AttributeFormat, Compute, Geometry, Graphics, Light, Material, Particles, Result, + Settings, Shader, Sketch, +}; const AGE_SHADER: &str = r#" struct Params { dt: f32, ttl: f32, _pad0: f32, _pad1: f32 } @@ -34,91 +31,87 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 600; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 4.0; + +struct ParticlesScatter { + particles: Particles, + particle: Geometry, + // read by the scatter kernel + _source: Geometry, + scatter: Compute, + aging: Compute, + mat: Material, + key: Light, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -0.4, 4.5))?; - transform_look_at(graphics, Vec3::ZERO)?; - - let key = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.95, 0.85), 4500.0)?; - - let source = geometry_sphere(1.2, 96, 48)?; - let scatter = particles_scatter_create(source)?; - - let particle = geometry_sphere(0.005, 6, 4)?; - - let capacity: u32 = 40_000; - let position_attr = geometry_attribute_position(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![position_attr, scale_attr, life_attr, age_attr], - )?; - - let age_shader = shader_create(AGE_SHADER)?; - let aging = compute_create(age_shader)?; - - let mat = material_create_pbr()?; - material_set( - mat, - "color", - shader_value::ShaderValue::Float4([0.9, 0.85, 1.0, 1.0]), - )?; - - let burst: u32 = 600; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 4.0; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, key)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.03, 0.03, 0.05)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, +impl Sketch for ParticlesScatter { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -0.4, 4.5)); + g.camera_look_at((0, 0, 0)); + + let key = g.create_directional_light((1.0, 0.95, 0.85), 4500.0); + + let source = Geometry::sphere(1.2, 96, 48)?; + let scatter = Particles::scatter_surface(&source)?; + + let particle = Geometry::sphere(0.005, 6, 4)?; + + let age = Attribute::new("age", AttributeFormat::Float)?; + let particles = Particles::new( + 40_000, + &[ + Attribute::position(), + Attribute::scale(), + Attribute::life(), + age, + ], )?; - graphics_end_draw(graphics)?; - let t = start.elapsed().as_secs_f32(); + let aging = Compute::new(&Shader::new(AGE_SHADER)?)?; + + let mut mat = Material::pbr()?; + mat.set("color", (0.9, 0.85, 1.0, 1.0)); + + Ok(ParticlesScatter { + particles, + particle, + _source: source, + scatter, + aging, + mat, + key, + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.key); + g.background((0.03, 0.03, 0.05)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); + + let t = g.elapsed_time(); let cam_x = (t * 0.25).cos() * 4.5; let cam_z = (t * 0.25).sin() * 4.5; - transform_set_position(graphics, Vec3::new(cam_x, -0.4, cam_z))?; - transform_look_at(graphics, Vec3::ZERO)?; + g.camera_position((cam_x, -0.4, cam_z)); + g.camera_look_at((0, 0, 0)); - compute_set( - scatter, - "seed", - shader_value::ShaderValue::UInt((t * 1000.0) as u32 ^ 0xc0ffeeu32), - )?; - particles_emit_gpu(p, burst, scatter)?; + let seed = (t * 1000.0) as u32 ^ 0xc0ffee; + self.scatter.set("seed", seed); + self.particles.emit_gpu(BURST, &self.scatter); - compute_set(aging, "dt", shader_value::ShaderValue::Float(dt))?; - compute_set(aging, "ttl", shader_value::ShaderValue::Float(ttl))?; - particles_apply(p, aging)?; + self.aging.set("dt", DT); + self.aging.set("ttl", TTL); + self.particles.apply(&self.aging); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_scatter_volume.rs b/examples/particles_scatter_volume.rs index 0f394077..01196997 100644 --- a/examples/particles_scatter_volume.rs +++ b/examples/particles_scatter_volume.rs @@ -1,10 +1,7 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, AttributeFormat, Compute, Geometry, Gltf, Graphics, Material, Particles, Result, + Settings, Shader, Sketch, +}; const AGE_SHADER: &str = r#" struct Params { dt: f32, ttl: f32, _pad0: f32, _pad1: f32 } @@ -34,85 +31,79 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 250; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 5.0; + +struct ParticlesScatterVolume { + particles: Particles, + particle: Geometry, + // read by the scatter kernel + _duck: Geometry, + scatter: Compute, + aging: Compute, + mat: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -100.0, 400.0))?; - transform_look_at(graphics, Vec3::new(0.0, -80.0, 0.0))?; - graphics_orbit_camera(graphics)?; - - let gltf = gltf_load(graphics, "gltf/Duck.glb")?; - let duck = gltf_geometry(gltf, "LOD3spShape")?; - let scatter = particles_scatter_volume_create(duck)?; - - let particle = geometry_sphere(0.15, 4, 3)?; - - let capacity: u32 = 30_000; - let position_attr = geometry_attribute_position(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![position_attr, scale_attr, life_attr, age_attr], - )?; - - let age_shader = shader_create(AGE_SHADER)?; - let aging = compute_create(age_shader)?; - - let mat = material_create_unlit()?; - material_set( - mat, - "color", - shader_value::ShaderValue::Float4([1.0, 1.0, 1.0, 1.0]), - )?; - - let burst: u32 = 250; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 5.0; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.03, 0.03, 0.05)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, +impl Sketch for ParticlesScatterVolume { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, -100, 400)); + g.camera_look_at((0, -80, 0)); + g.orbit_camera(); + + let gltf = Gltf::load(g, "gltf/Duck.glb")?; + let duck = gltf.geometry("LOD3spShape")?; + let scatter = Particles::scatter_volume(&duck)?; + + let particle = Geometry::sphere(0.15, 4, 3)?; + + let age = Attribute::new("age", AttributeFormat::Float)?; + let particles = Particles::new( + 30_000, + &[ + Attribute::position(), + Attribute::scale(), + Attribute::life(), + age, + ], )?; - graphics_end_draw(graphics)?; - let t = start.elapsed().as_secs_f32(); + let aging = Compute::new(&Shader::new(AGE_SHADER)?)?; + + let mut mat = Material::unlit()?; + mat.set("color", (1.0, 1.0, 1.0, 1.0)); - compute_set( + Ok(ParticlesScatterVolume { + particles, + particle, + _duck: duck, scatter, - "seed", - shader_value::ShaderValue::UInt((t * 1000.0) as u32 ^ 0xc0ffeeu32), - )?; - particles_emit_gpu(p, burst, scatter)?; + aging, + mat, + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.background((0.03, 0.03, 0.05)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); - compute_set(aging, "dt", shader_value::ShaderValue::Float(dt))?; - compute_set(aging, "ttl", shader_value::ShaderValue::Float(ttl))?; - particles_apply(p, aging)?; + let t = g.elapsed_time(); + let seed = (t * 1000.0) as u32 ^ 0xc0ffee; + self.scatter.set("seed", seed); + self.particles.emit_gpu(BURST, &self.scatter); + + self.aging.set("dt", DT); + self.aging.set("ttl", TTL); + self.particles.apply(&self.aging); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_stress.rs b/examples/particles_stress.rs index 006c4902..5e39a5a3 100644 --- a/examples/particles_stress.rs +++ b/examples/particles_stress.rs @@ -1,8 +1,7 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; +use processing::{ + Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, + Sketch, +}; const GRID: u32 = 100; // GRID^3 particles const SPACING: f32 = 1.0; @@ -29,11 +28,6 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); -} - fn hash_u32(mut x: u32) -> u32 { x = (x ^ 61).wrapping_add(x >> 16); x = x.wrapping_add(x << 3); @@ -47,100 +41,92 @@ fn hash_unit(seed: u32) -> f32 { (hash_u32(seed) as f32) / (u32::MAX as f32) } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - let extent = (GRID as f32) * SPACING * 0.5; - transform_set_position(graphics, Vec3::new(0.0, -extent * 0.6, extent * 2.5))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - graphics_orbit_camera(graphics)?; - - let red = light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.0, 0.0), 1000.0)?; - transform_set_position(red, Vec3::new(1.0, 0.0, 0.0))?; - transform_look_at(red, Vec3::ZERO)?; - - let green = - light_create_directional(graphics, bevy::color::Color::srgb(0.0, 1.0, 0.0), 1000.0)?; - transform_set_position(green, Vec3::new(0.0, -1.0, 0.0))?; - transform_look_at(green, Vec3::ZERO)?; - - let blue = light_create_directional(graphics, bevy::color::Color::srgb(0.0, 0.0, 1.0), 1000.0)?; - transform_set_position(blue, Vec3::new(0.0, 0.0, 1.0))?; - transform_look_at(blue, Vec3::ZERO)?; - - let cube = geometry_box(0.35, 0.35, 0.35)?; - - let capacity = GRID * GRID * GRID; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); - let extent_half = (GRID as f32) * SPACING * 0.5; - for i in 0..capacity { - let rx = hash_unit(i.wrapping_mul(2654435761).wrapping_add(0x9E37)); - let ry = hash_unit(i.wrapping_mul(40503).wrapping_add(0x68E1)); - let rz = hash_unit(i.wrapping_mul(2246822519).wrapping_add(0xC2B2)); - positions.push((rx * 2.0 - 1.0) * extent_half); - positions.push((1.0 - ry * 2.0) * extent_half); - positions.push((rz * 2.0 - 1.0) * extent_half); - colors.push(rx); - colors.push(ry); - colors.push(rz); - colors.push(1.0); +struct ParticlesStress { + red: Light, + green: Light, + blue: Light, + cube: Geometry, + particles: Particles, + mat: Material, + spin: Compute, +} + +impl Sketch for ParticlesStress { + fn settings() -> Settings { + Settings::size(900, 700) } - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - color_buf, - colors.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - let spin_shader = shader_create(SPIN_SHADER)?; - let spin = compute_create(spin_shader)?; - - eprintln!("{capacity} particles"); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, red)?; - graphics_light(graphics, green)?; - graphics_light(graphics, blue)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.07)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(cube), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; - - compute_set(spin, "dt", shader_value::ShaderValue::Float(0.003))?; - particles_apply(p, spin)?; + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + let extent = (GRID as f32) * SPACING * 0.5; + g.camera_position((0.0, -extent * 0.6, extent * 2.5)); + g.camera_look_at((0, 0, 0)); + g.orbit_camera(); + + let red = g.create_directional_light((1.0, 0.0, 0.0), 1000.0); + red.position((1, 0, 0)).look_at((0, 0, 0)); + + let green = g.create_directional_light((0.0, 1.0, 0.0), 1000.0); + green.position((0, -1, 0)).look_at((0, 0, 0)); + + let blue = g.create_directional_light((0.0, 0.0, 1.0), 1000.0); + blue.position((0, 0, 1)).look_at((0, 0, 0)); + + let cube = Geometry::cube((0.35, 0.35, 0.35))?; + + let capacity = GRID * GRID * GRID; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; + + let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); + let extent_half = (GRID as f32) * SPACING * 0.5; + for i in 0..capacity { + let rx = hash_unit(i.wrapping_mul(2654435761).wrapping_add(0x9E37)); + let ry = hash_unit(i.wrapping_mul(40503).wrapping_add(0x68E1)); + let rz = hash_unit(i.wrapping_mul(2246822519).wrapping_add(0xC2B2)); + positions.push((rx * 2.0 - 1.0) * extent_half); + positions.push((1.0 - ry * 2.0) * extent_half); + positions.push((rz * 2.0 - 1.0) * extent_half); + colors.push(rx); + colors.push(ry); + colors.push(rz); + colors.push(1.0); + } + particles.buffer(Attribute::position()).write(&positions); + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); + + let mut mat = Material::pbr()?; + mat.albedo_buffer(&color_buf); + + let spin = Compute::new(&Shader::new(SPIN_SHADER)?)?; + + eprintln!("{capacity} particles"); + + Ok(ParticlesStress { + red, + green, + blue, + cube, + particles, + mat, + spin, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.red); + g.light(&self.green); + g.light(&self.blue); + g.background((0.04, 0.04, 0.07)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.cube); + + self.spin.set("dt", 0.003); + self.particles.apply(&self.spin); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_text_whirl.rs b/examples/particles_text_whirl.rs index 3fc13afc..b0ab51b3 100644 --- a/examples/particles_text_whirl.rs +++ b/examples/particles_text_whirl.rs @@ -1,16 +1,13 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; -use processing::prelude::*; -use processing_render::render::command::{DrawCommand, TextStyle}; +use processing::{ + Attribute, Buffer, Compute, Geometry, Graphics, Material, Particles, Result, Settings, Shader, + Sketch, TextStyle, +}; const BASE_COUNT: u32 = 6000; const TRAIL_LEN_MIN: u32 = 8; const TRAIL_LEN_MAX: u32 = 150; const TRAIL_LEN: u32 = TRAIL_LEN_MAX; const CAPACITY: u32 = BASE_COUNT * TRAIL_LEN; -const TRAIL_STRIDE: u32 = 1; const NOISE_STRENGTH: f32 = 50.5; const SPHERE_RADIUS: f32 = 1.05; @@ -255,189 +252,148 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const TEXT_PT: f32 = 700.0; +const EXTRUSION: f32 = 70.0; + +struct TextWhirl { + particles: Particles, + particle: Geometry, + sim: Compute, + fade: Compute, + mat: Material, + // read by the sim kernel + _source: Geometry, + _buffers: Vec, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(1200, 800, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(1200, 800, false)?; - let graphics = graphics_create(surface, 1200, 800, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 1700.0))?; - transform_look_at(graphics, Vec3::ZERO)?; - graphics_orbit_camera(graphics)?; - - const TEXT_PT: f32 = 700.0; - const EXTRUSION: f32 = 70.0; - processing_core::app_mut(|app| { - let mut state = app - .world_mut() - .get_mut::(graphics) - .ok_or(error::ProcessingError::GraphicsNotFound)?; - state.style.text_size = TEXT_PT; - Ok(()) - })?; - graphics_record_command(graphics, DrawCommand::TextStyle(TextStyle::Bold))?; - - let text = "processing5"; - let w = graphics_text_width(graphics, text)?; - println!("text width = {w} (size = {TEXT_PT}, extrusion = {EXTRUSION})"); - let mesh = graphics_text_to_model(graphics, text, -w / 2.0, TEXT_PT * 0.4, EXTRUSION)?; - let source = geometry_create_from_mesh(mesh)?; - - let (cdf_bytes, indices_bytes, face_count) = processing_core::app_mut(|app| { - app.world_mut() - .run_system_cached_with(processing_render::particles::prepare_scatter_source, source) - .unwrap() - })?; - let cdf_buf = buffer_create_with_data(cdf_bytes)?; - let idx_buf = buffer_create_with_data(indices_bytes)?; - - let head_pos_buf = buffer_create(BASE_COUNT as u64 * 3 * 4)?; - let anchor_normal_buf = buffer_create(BASE_COUNT as u64 * 3 * 4)?; - let trail_len_buf = buffer_create(BASE_COUNT as u64 * 4)?; - let trail_head_buf = buffer_create(BASE_COUNT as u64 * 4)?; - - let particle = geometry_sphere(SPHERE_RADIUS, 5, 4)?; - - let p = particles_create( - CAPACITY, - vec![ - geometry_attribute_position(), - geometry_attribute_scale(), - geometry_attribute_life(), - geometry_attribute_color(), - ], - )?; - - let sim_src = sim_shader(); - let sim_shader_e = shader_create(&sim_src)?; - let sim = compute_create(sim_shader_e)?; - compute_set( - sim, - "source_position", - shader_value::ShaderValue::MeshAttribute(source, geometry_attribute_position()), - )?; - compute_set( - sim, - "source_indices", - shader_value::ShaderValue::Buffer(idx_buf), - )?; - compute_set(sim, "cdf", shader_value::ShaderValue::Buffer(cdf_buf))?; - compute_set( - sim, - "head_pos", - shader_value::ShaderValue::Buffer(head_pos_buf), - )?; - compute_set( - sim, - "anchor_normal", - shader_value::ShaderValue::Buffer(anchor_normal_buf), - )?; - compute_set( - sim, - "trail_len_buf", - shader_value::ShaderValue::Buffer(trail_len_buf), - )?; - compute_set( - sim, - "trail_head_buf", - shader_value::ShaderValue::Buffer(trail_head_buf), - )?; - compute_set( - sim, - "base_count", - shader_value::ShaderValue::UInt(BASE_COUNT), - )?; - compute_set( - sim, - "trail_len_max", - shader_value::ShaderValue::UInt(TRAIL_LEN_MAX), - )?; - compute_set( - sim, - "trail_len_min", - shader_value::ShaderValue::UInt(TRAIL_LEN_MIN), - )?; - compute_set( - sim, - "face_count", - shader_value::ShaderValue::UInt(face_count), - )?; - compute_set(sim, "seed", shader_value::ShaderValue::UInt(0xc0ffeeu32))?; - compute_set(sim, "noise_scale", shader_value::ShaderValue::Float(0.005))?; - compute_set( - sim, - "noise_strength", - shader_value::ShaderValue::Float(NOISE_STRENGTH), - )?; - compute_set(sim, "step_speed", shader_value::ShaderValue::Float(0.05))?; - - compute_set(sim, "time", shader_value::ShaderValue::Float(0.0))?; - particles_apply(p, sim)?; - - let color_buf = particles_buffer(p, geometry_attribute_color())? - .ok_or(error::ProcessingError::ParticlesNotFound)?; - let mat = material_create_unlit()?; - material_set_albedo_buffer(mat, color_buf)?; - - let fade_shader_e = shader_create(COLOR_FADE)?; - let fade = compute_create(fade_shader_e)?; - compute_set( - fade, - "base_count", - shader_value::ShaderValue::UInt(BASE_COUNT), - )?; - compute_set( - fade, - "trail_len_max", - shader_value::ShaderValue::UInt(TRAIL_LEN_MAX), - )?; - compute_set( - fade, - "trail_len_buf", - shader_value::ShaderValue::Buffer(trail_len_buf), - )?; - compute_set( - fade, - "trail_head_buf", - shader_value::ShaderValue::Buffer(trail_head_buf), - )?; - - particles_apply(p, fade)?; - - let start = Instant::now(); - let mut render_frame: u32 = 0; - while glfw_ctx.poll_events() { - if render_frame % TRAIL_STRIDE == 0 { - let t = start.elapsed().as_secs_f32(); - compute_set(sim, "time", shader_value::ShaderValue::Float(t * 0.015))?; - particles_apply(p, sim)?; - particles_apply(p, fade)?; +impl Sketch for TextWhirl { + fn settings() -> Settings { + Settings::size(1200, 800) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 1700)); + g.camera_look_at((0, 0, 0)); + g.orbit_camera(); + + g.text_size(TEXT_PT); + g.text_style(TextStyle::Bold); + + let text = "processing5"; + let w = g.text_width(text); + println!("text width = {w} (size = {TEXT_PT}, extrusion = {EXTRUSION})"); + let source = g.text_to_model(text, -w / 2.0, TEXT_PT * 0.4, EXTRUSION)?; + + let positions = source.positions(); + let mut indices = source.indices(); + if indices.is_empty() { + for i in 0..source.vertex_count() { + indices.push(i); + } + } + let face_count = (indices.len() / 3) as u32; + + // area-weighted CDF + let mut cdf = Vec::new(); + let mut total = 0.0; + for face in 0..face_count as usize { + let p0 = positions[indices[face * 3] as usize]; + let p1 = positions[indices[face * 3 + 1] as usize]; + let p2 = positions[indices[face * 3 + 2] as usize]; + let area = 0.5 * (p1 - p0).cross(p2 - p0).length(); + total += area; + cdf.push(total); + } + let inv = 1.0 / total; + for value in cdf.iter_mut() { + *value *= inv; } - render_frame = render_frame.wrapping_add(1); - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.02, 0.02, 0.04)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, + let cdf_buf = Buffer::from_slice(&cdf)?; + let idx_buf = Buffer::from_slice(&indices)?; + + let head_pos_buf = Buffer::new(BASE_COUNT as u64 * 3 * 4)?; + let anchor_normal_buf = Buffer::new(BASE_COUNT as u64 * 3 * 4)?; + let trail_len_buf = Buffer::new(BASE_COUNT as u64 * 4)?; + let trail_head_buf = Buffer::new(BASE_COUNT as u64 * 4)?; + + let particle = Geometry::sphere(SPHERE_RADIUS, 5, 4)?; + + let mut particles = Particles::new( + CAPACITY, + &[ + Attribute::position(), + Attribute::scale(), + Attribute::life(), + Attribute::color(), + ], )?; - graphics_end_draw(graphics)?; + + let mut sim = Compute::new(&Shader::new(&sim_shader())?)?; + sim.set( + "source_position", + source.attribute_data(Attribute::position()), + ); + sim.set("source_indices", &idx_buf); + sim.set("cdf", &cdf_buf); + sim.set("head_pos", &head_pos_buf); + sim.set("anchor_normal", &anchor_normal_buf); + sim.set("trail_len_buf", &trail_len_buf); + sim.set("trail_head_buf", &trail_head_buf); + sim.set("base_count", BASE_COUNT); + sim.set("trail_len_max", TRAIL_LEN_MAX); + sim.set("trail_len_min", TRAIL_LEN_MIN); + sim.set("face_count", face_count); + sim.set("seed", 0xc0ffee_u32); + sim.set("noise_scale", 0.005); + sim.set("noise_strength", NOISE_STRENGTH); + sim.set("step_speed", 0.05); + + sim.set("time", 0.0); + particles.apply(&sim); + + let mut mat = Material::unlit()?; + mat.albedo_buffer(&particles.buffer(Attribute::color())); + + let mut fade = Compute::new(&Shader::new(COLOR_FADE)?)?; + fade.set("base_count", BASE_COUNT); + fade.set("trail_len_max", TRAIL_LEN_MAX); + fade.set("trail_len_buf", &trail_len_buf); + fade.set("trail_head_buf", &trail_head_buf); + + particles.apply(&fade); + + Ok(TextWhirl { + particles, + particle, + sim, + fade, + mat, + _source: source, + _buffers: vec![ + cdf_buf, + idx_buf, + head_pos_buf, + anchor_normal_buf, + trail_len_buf, + trail_head_buf, + ], + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + let t = g.elapsed_time(); + self.sim.set("time", t * 0.015); + self.particles.apply(&self.sim); + self.particles.apply(&self.fade); + + g.background((0.02, 0.02, 0.04)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/text_3d.rs b/examples/text_3d.rs index 99abe875..af3cfda3 100644 --- a/examples/text_3d.rs +++ b/examples/text_3d.rs @@ -1,86 +1,60 @@ -use processing_glfw::GlfwContext; +use processing::{Geometry, Graphics, Light, Material, Result, Settings, Sketch, TextStyle}; -use bevy::math::{Vec2, Vec3}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Text3d { + word: Geometry, + glow: Material, + sun: Light, + t: f32, } -fn sketch() -> error::Result<()> { - let width = 1200; - let height = 700; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 800.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(0.3, 0.3, 0.4), 2000.0)?; - transform_set_position(dir_light, Vec3::new(200.0, -300.0, 500.0))?; - transform_look_at(dir_light, Vec3::new(0.0, 0.0, 0.0))?; - - let glow = material_create_pbr()?; - material_set(glow, "roughness", shader_value::ShaderValue::Float(0.3))?; - material_set(glow, "metallic", shader_value::ShaderValue::Float(0.5))?; - material_set( - glow, - "emissive", - shader_value::ShaderValue::Float4([2.0, 0.5, 3.0, 1.0]), - )?; - - graphics_record_command(graphics, DrawCommand::TextSize(120.0))?; - graphics_record_command(graphics, DrawCommand::TextStyle(TextStyle::Bold))?; - - // measure width to center the mesh on the origin - let w = graphics_text_width(graphics, "Processing")?; - let mesh = graphics_text_to_model(graphics, "Processing", -w / 2.0, 0.0, 40.0)?; - let geom = geometry_create_from_mesh(mesh)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; +impl Sketch for Text3d { + fn settings() -> Settings { + Settings::size(1200, 700) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.02, 0.02, 0.03)), - )?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 800)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((0.3, 0.3, 0.4), 2000); + sun.position((200, -300, 500)).look_at((0, 0, 0)); + + let mut glow = Material::pbr()?; + glow.set("roughness", 0.3); + glow.set("metallic", 0.5); + glow.set("emissive", (2.0, 0.5, 3.0, 1.0)); + + g.text_size(120); + g.text_style(TextStyle::Bold); + let w = g.text_width("Processing"); + let word = g.text_to_model("Processing", -w / 2.0, 0, 40)?; + + Ok(Text3d { + word, + glow, + sun, + t: 0.0, + }) + } - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.8, 0.3, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::Material(glow))?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.02, 0.02, 0.03)); + g.fill((0.8, 0.3, 1.0)); + g.material(&self.glow); - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Scale(Vec2::new(15.0, 15.0).extend(1.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -t * 0.3, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(geom))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + { + let mut g = g.push(); + g.scale((15, 15)); + g.rotate(-self.t * 0.3); + g.model(&self.word); + } - graphics_end_draw(graphics)?; - t += 0.016; + self.t += 0.016; } +} - material_destroy(glow)?; - - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/webcam.rs b/examples/webcam.rs index d2609d75..fc881296 100644 --- a/examples/webcam.rs +++ b/examples/webcam.rs @@ -1,50 +1,26 @@ -use processing_glfw::GlfwContext; +use processing::{Graphics, Result, Settings, Sketch, Webcam}; -use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use processing_webcam::{webcam_create, webcam_destroy, webcam_image, webcam_is_connected}; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct WebcamSketch { + camera: Webcam, } -fn sketch() -> error::Result<()> { - let width = 640; - let height = 480; - - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let webcam = webcam_create()?; - let mut image_entity = None; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for WebcamSketch { + fn settings() -> Settings { + Settings::size(640, 480) + } - // Once connected, grab an image entity from the webcam stream - if image_entity.is_none() && webcam_is_connected(webcam)? { - image_entity = Some(webcam_image(webcam)?); - } + fn setup(_g: &mut Graphics) -> Result { + let camera = Webcam::new()?; + Ok(WebcamSketch { camera }) + } - if let Some(img) = image_entity { - graphics_record_command(graphics, DrawCommand::BackgroundImage(img))?; + fn draw(&mut self, g: &mut Graphics) { + if self.camera.connected() { + g.background_image(&self.camera); } - - graphics_end_draw(graphics)?; } +} - webcam_destroy(webcam)?; - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/src/args.rs b/src/args.rs index 8b6781ee..280bd302 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1,12 +1,9 @@ -//! Argument traits that stand in for Processing's numeric and arity overloads. - use bevy::math::{Vec2, Vec3}; mod sealed { pub trait Sealed {} } -/// Any primitive number, converted to `f32`. pub trait Scalar: sealed::Sealed + Copy { fn to_f32(self) -> f32; } @@ -24,7 +21,7 @@ macro_rules! scalar { } scalar!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64); -/// A 2D or 3D point: `(x, y)`, `(x, y, z)`, `Vec2` or `Vec3`. 2D points get `z = 0`. +/// `(x, y)`, `(x, y, z)`, `Vec2` or `Vec3`. pub trait IntoPoint { fn into_point(self) -> Vec3; } @@ -53,7 +50,7 @@ impl IntoPoint for Vec3 { } } -/// A per-axis size: one number for all axes, or `(x, y)` / `(x, y, z)`. Missing axes are `1`. +/// One number, `(x, y)` or `(x, y, z)`. pub trait IntoExtent { fn into_extent(self) -> Vec3; } diff --git a/src/color.rs b/src/color.rs index fa5cc98a..b88a2588 100644 --- a/src/color.rs +++ b/src/color.rs @@ -1,11 +1,8 @@ -//! Colors and the `fill(..)`-style color arguments. - use bevy::color::{Alpha, Color as BevyColor, Hsla, Hsva, LinearRgba, Mix, Oklcha, Srgba}; use processing_render::color::ColorMode; pub use processing_render::color::ColorSpace; -/// A resolved color. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Color(pub(crate) BevyColor); @@ -14,22 +11,22 @@ impl Color { pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0); pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0); - /// sRGB, channels 0-1. + /// 0-1. pub const fn rgb(r: f32, g: f32, b: f32) -> Self { Self::rgba(r, g, b, 1.0) } - /// sRGB with alpha, channels 0-1. + /// 0-1. pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self { Self(BevyColor::Srgba(Srgba::new(r, g, b, a))) } - /// sRGB, channels 0-255. + /// 0-255. pub const fn rgb8(r: u8, g: u8, b: u8) -> Self { Self::rgba8(r, g, b, 255) } - /// sRGB with alpha, channels 0-255. + /// 0-255. pub const fn rgba8(r: u8, g: u8, b: u8, a: u8) -> Self { Self::rgba( r as f32 / 255.0, @@ -54,17 +51,17 @@ impl Color { ) } - /// Hue in degrees, saturation and lightness 0-1. + /// Hue in degrees, the rest 0-1. pub const fn hsl(h: f32, s: f32, l: f32) -> Self { Self(BevyColor::Hsla(Hsla::new(h, s, l, 1.0))) } - /// Hue in degrees, saturation and value 0-1. + /// Hue in degrees, the rest 0-1. pub const fn hsv(h: f32, s: f32, v: f32) -> Self { Self(BevyColor::Hsva(Hsva::new(h, s, v, 1.0))) } - /// Lightness 0-1, chroma 0-~0.4, hue in degrees. + /// Hue in degrees, chroma 0-~0.4. pub const fn oklch(l: f32, c: f32, h: f32) -> Self { Self(BevyColor::Oklcha(Oklcha::new(l, c, h, 1.0))) } @@ -75,7 +72,7 @@ impl Color { Self(c) } - /// Interpolates in Oklab, like Processing's `lerpColor`. + /// In Oklab. pub fn lerp(self, other: Color, t: f32) -> Self { let a: bevy::color::Oklaba = self.0.into(); let b: bevy::color::Oklaba = other.0.into(); @@ -113,7 +110,7 @@ pub enum Channel { Float(f32), } -/// A single color channel: integers are 0-255, floats are 0-1, unless `color_mode().max(..)` is set. +/// Ints 0-255, floats 0-1, unless `color_mode().max(..)` is set. pub trait IntoChannel: Copy { fn into_channel(self) -> Channel; } @@ -141,7 +138,6 @@ impl IntoChannel for f64 { } } -/// An unresolved color, interpreted against the current color mode when used. #[derive(Debug, Clone, Copy)] pub enum ColorArg { Color(Color), @@ -187,7 +183,6 @@ impl From<(A, B, } } -/// Ranges for color channels: one number for all four, or `(c1, c2, c3)` / `(c1, c2, c3, alpha)`. pub trait IntoColorMax { fn into_color_max(self, space: ColorSpace) -> [f32; 4]; } @@ -222,7 +217,6 @@ impl Int } } -/// The color mode as seen by a `Graphics`; `explicit_max` means `.max(..)` was set. #[derive(Debug, Clone, Copy, Default)] pub(crate) struct ColorState { pub mode: ColorMode, diff --git a/src/draw.rs b/src/draw.rs index ffd82684..36c1b7a8 100644 --- a/src/draw.rs +++ b/src/draw.rs @@ -1,15 +1,15 @@ -//! Builders for draw calls with optional trailing arguments. Each draws when dropped. +//! Draw-on-drop builders. use std::ops::{Deref, DerefMut}; use bevy::prelude::{Entity, Transform, Vec3}; +use processing_render::geometry::Topology; use processing_render::graphics_immediate_light; use processing_render::render::command::{ArcMode, DrawCommand, LightKind}; use crate::graphics::expect; -use crate::{Graphics, IntoPoint, Scalar}; +use crate::{Geometry, Graphics, IntoPoint, Scalar}; -/// Returned by [`Graphics::rect`] and [`Graphics::square`]. pub struct Rect<'g> { g: &'g mut Graphics, rect: [f32; 4], @@ -25,13 +25,12 @@ impl<'g> Rect<'g> { } } - /// Rounds every corner. pub fn radius(mut self, r: impl Scalar) -> Self { self.radii = [r.to_f32(); 4]; self } - /// Rounds each corner: top-left, top-right, bottom-right, bottom-left. + /// Top-left, top-right, bottom-right, bottom-left. pub fn radii( mut self, tl: impl Scalar, @@ -57,7 +56,6 @@ impl Drop for Rect<'_> { } } -/// Returned by [`Graphics::arc`]. pub struct Arc<'g> { g: &'g mut Graphics, bounds: [f32; 4], @@ -98,7 +96,6 @@ impl Drop for Arc<'_> { } } -/// Returned by [`Graphics::directional_light`], [`Graphics::point_light`] and [`Graphics::spot_light`]. pub struct LightDraw<'g> { g: &'g mut Graphics, kind: LightKind, @@ -135,7 +132,44 @@ impl Drop for LightDraw<'_> { } } -/// Returned by [`Graphics::image`]. +pub struct ParticlesDraw<'g> { + g: &'g mut Graphics, + particles: Entity, + geometry: Option, + topology: Topology, +} + +impl<'g> ParticlesDraw<'g> { + pub(crate) fn new(g: &'g mut Graphics, particles: Entity) -> Self { + Self { + g, + particles, + geometry: None, + topology: Topology::PointList, + } + } + + pub fn geometry(mut self, geometry: &Geometry) -> Self { + self.geometry = Some(geometry.0); + self + } + + pub fn topology(mut self, topology: Topology) -> Self { + self.topology = topology; + self + } +} + +impl Drop for ParticlesDraw<'_> { + fn drop(&mut self) { + self.g.record(DrawCommand::Particles { + particles: self.particles, + geometry: self.geometry, + topology: self.topology, + }); + } +} + pub struct ImageDraw<'g> { g: &'g mut Graphics, entity: Entity, @@ -157,13 +191,12 @@ impl<'g> ImageDraw<'g> { } } - /// Draws at this size instead of the image's own. pub fn size(mut self, w: impl Scalar, h: impl Scalar) -> Self { self.size = Some([w.to_f32(), h.to_f32()]); self } - /// Draws only this pixel region of the image. + /// Pixel region of the image. pub fn source( mut self, x: impl Scalar, @@ -194,7 +227,6 @@ impl Drop for ImageDraw<'_> { } } -/// Returned by [`Graphics::text`]. pub struct Text<'g> { g: &'g mut Graphics, content: String, @@ -223,13 +255,11 @@ impl<'g> Text<'g> { self } - /// Wraps the text at `w` wide. pub fn max_width(mut self, w: impl Scalar) -> Self { self.max_w = Some(w.to_f32()); self } - /// Wraps the text inside a `w` by `h` box. pub fn bounds(mut self, w: impl Scalar, h: impl Scalar) -> Self { self.max_w = Some(w.to_f32()); self.max_h = Some(h.to_f32()); @@ -250,7 +280,6 @@ impl Drop for Text<'_> { } } -/// A 3D primitive with tessellation detail; chain `.detail(..)`. pub struct Detail<'g, const N: usize> { g: &'g mut Graphics, size: [f32; 3], @@ -294,7 +323,7 @@ impl Drop for Detail<'_, N> { } } -/// Returned by [`Graphics::push`]; restores style and transform when dropped. +/// Pops when dropped. pub struct Push<'g> { g: &'g mut Graphics, } @@ -326,7 +355,7 @@ impl Drop for Push<'_> { } } -/// Returned by [`Graphics::begin_draw`]; ends drawing when dropped. +/// Ends drawing when dropped. pub struct BeginDraw<'g> { g: &'g mut Graphics, } diff --git a/src/filter.rs b/src/filter.rs new file mode 100644 index 00000000..4625f6cc --- /dev/null +++ b/src/filter.rs @@ -0,0 +1,47 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::shader_value::ShaderValue; +use processing_render::{ + filter_blur, filter_dilate, filter_erode, filter_gray, filter_invert, filter_opaque, + filter_posterize, filter_set, filter_threshold, +}; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Filter { + Invert, + Gray, + /// Cutoff 0-1. + Threshold(f32), + /// Levels 2-255. + Posterize(u32), + /// Radius in pixels. + Blur(f32), + Opaque, + Erode, + Dilate, +} + +impl Filter { + pub(crate) fn entity(self) -> Result { + let (entity, param) = match self { + Filter::Invert => (filter_invert()?, None), + Filter::Gray => (filter_gray()?, None), + Filter::Threshold(cutoff) => ( + filter_threshold()?, + Some(("cutoff", ShaderValue::Float(cutoff))), + ), + Filter::Posterize(levels) => ( + filter_posterize()?, + Some(("levels", ShaderValue::UInt(levels))), + ), + Filter::Blur(radius) => (filter_blur()?, Some(("radius", ShaderValue::Float(radius)))), + Filter::Opaque => (filter_opaque()?, None), + Filter::Erode => (filter_erode()?, None), + Filter::Dilate => (filter_dilate()?, None), + }; + if let Some((name, value)) = param { + filter_set(entity, name, value)?; + } + Ok(entity) + } +} diff --git a/src/geometry.rs b/src/geometry.rs new file mode 100644 index 00000000..8ef790e4 --- /dev/null +++ b/src/geometry.rs @@ -0,0 +1,296 @@ +use bevy::math::{Vec2, Vec3, Vec4}; +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::geometry::{AttributeFormat, Topology}; +use processing_render::shader_value::ShaderValue; +use processing_render::{ + geometry_attribute_age, geometry_attribute_color, geometry_attribute_create, + geometry_attribute_float, geometry_attribute_float2, geometry_attribute_float3, + geometry_attribute_float4, geometry_attribute_life, geometry_attribute_normal, + geometry_attribute_position, geometry_attribute_rotation, geometry_attribute_scale, + geometry_attribute_uv, geometry_attribute_velocity, geometry_box, geometry_color, + geometry_create, geometry_create_with_layout, geometry_destroy, geometry_get_indices, + geometry_get_positions, geometry_grid, geometry_index, geometry_index_count, + geometry_layout_add_attribute, geometry_layout_add_color, geometry_layout_add_normal, + geometry_layout_add_position, geometry_layout_add_uv, geometry_layout_create, + geometry_layout_destroy, geometry_normal, geometry_set_color, geometry_set_normal, + geometry_set_uv, geometry_set_vertex, geometry_sphere, geometry_uv, geometry_vertex, + geometry_vertex_count, +}; + +use crate::color::{ColorArg, ColorState}; +use crate::graphics::expect; +use crate::{IntoExtent, IntoPoint, IntoShaderValue, Scalar}; + +/// A retained mesh, drawn with `g.model(..)`. +#[derive(Debug)] +pub struct Geometry(pub(crate) Entity); + +impl Geometry { + pub fn new(topology: Topology) -> Result { + geometry_create(topology).map(Self) + } + + pub fn with_layout(layout: &Layout, topology: Topology) -> Result { + geometry_create_with_layout(layout.0, topology).map(Self) + } + + pub fn cube(size: impl IntoExtent) -> Result { + let s = size.into_extent(); + geometry_box(s.x, s.y, s.z).map(Self) + } + + pub fn sphere(radius: impl Scalar, sectors: u32, stacks: u32) -> Result { + geometry_sphere(radius.to_f32(), sectors, stacks).map(Self) + } + + pub fn grid(nx: u32, ny: u32, nz: u32, spacing: impl Scalar) -> Result { + geometry_grid(nx, ny, nz, spacing.to_f32()).map(Self) + } + + pub fn vertex(&mut self, position: impl IntoPoint) { + expect(geometry_vertex(self.0, position.into_point())); + } + + pub fn normal(&mut self, normal: impl IntoPoint) { + expect(geometry_normal(self.0, normal.into_point())); + } + + pub fn color(&mut self, color: impl Into) { + expect(geometry_color(self.0, color_vec4(color))); + } + + pub fn uv(&mut self, u: impl Scalar, v: impl Scalar) { + expect(geometry_uv(self.0, u.to_f32(), v.to_f32())); + } + + pub fn attribute(&mut self, attribute: Attribute, value: impl AttributeValue) { + let entity = self.0; + expect(match value.into_value() { + Value::Float(v) => geometry_attribute_float(entity, attribute.0, v), + Value::Float2(v) => geometry_attribute_float2(entity, attribute.0, v.x, v.y), + Value::Float3(v) => geometry_attribute_float3(entity, attribute.0, v.x, v.y, v.z), + Value::Float4(v) => geometry_attribute_float4(entity, attribute.0, v.x, v.y, v.z, v.w), + }); + } + + pub fn index(&mut self, i: u32) { + expect(geometry_index(self.0, i)); + } + + pub fn set_vertex(&mut self, i: u32, position: impl IntoPoint) { + expect(geometry_set_vertex(self.0, i, position.into_point())); + } + + pub fn set_normal(&mut self, i: u32, normal: impl IntoPoint) { + expect(geometry_set_normal(self.0, i, normal.into_point())); + } + + pub fn set_color(&mut self, i: u32, color: impl Into) { + expect(geometry_set_color(self.0, i, color_vec4(color))); + } + + pub fn set_uv(&mut self, i: u32, u: impl Scalar, v: impl Scalar) { + expect(geometry_set_uv( + self.0, + i, + Vec2::new(u.to_f32(), v.to_f32()), + )); + } + + pub fn vertex_count(&self) -> u32 { + expect(geometry_vertex_count(self.0)) + } + + pub fn index_count(&self) -> u32 { + expect(geometry_index_count(self.0)) + } + + pub fn positions(&self) -> Vec { + let count = self.vertex_count() as usize; + let positions = expect(geometry_get_positions(self.0, 0, count)); + positions.into_iter().map(Vec3::from_array).collect() + } + + /// Empty if the mesh has none. + pub fn indices(&self) -> Vec { + let count = self.index_count() as usize; + expect(geometry_get_indices(self.0, 0, count)) + } + + /// For `compute.set(..)`. + pub fn attribute_data(&self, attribute: Attribute) -> GeometryData { + GeometryData(ShaderValue::MeshAttribute(self.0, attribute.0)) + } + + /// For `compute.set(..)`. + pub fn index_data(&self) -> GeometryData { + GeometryData(ShaderValue::MeshIndex(self.0)) + } +} + +impl Drop for Geometry { + fn drop(&mut self) { + let _ = geometry_destroy(self.0); + } +} + +#[derive(Debug)] +pub struct GeometryData(ShaderValue); + +impl IntoShaderValue for GeometryData { + fn into_shader_value(self) -> ShaderValue { + self.0 + } +} + +fn color_vec4(color: impl Into) -> Vec4 { + let c = ColorState::default().resolve(color.into()); + Vec4::new(c.red(), c.green(), c.blue(), c.alpha()) +} + +#[derive(Debug)] +pub struct Layout(Entity); + +impl Layout { + pub fn new() -> Result { + geometry_layout_create().map(Self) + } + + pub fn position(self) -> Self { + expect(geometry_layout_add_position(self.0)); + self + } + + pub fn normal(self) -> Self { + expect(geometry_layout_add_normal(self.0)); + self + } + + pub fn color(self) -> Self { + expect(geometry_layout_add_color(self.0)); + self + } + + pub fn uv(self) -> Self { + expect(geometry_layout_add_uv(self.0)); + self + } + + pub fn attribute(self, attribute: Attribute) -> Self { + expect(geometry_layout_add_attribute(self.0, attribute.0)); + self + } +} + +impl Drop for Layout { + fn drop(&mut self) { + let _ = geometry_layout_destroy(self.0); + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Attribute(pub(crate) Entity); + +impl Attribute { + pub fn new(name: &str, format: AttributeFormat) -> Result { + geometry_attribute_create(name, format).map(Self) + } + + pub fn position() -> Self { + Self(geometry_attribute_position()) + } + + pub fn normal() -> Self { + Self(geometry_attribute_normal()) + } + + pub fn color() -> Self { + Self(geometry_attribute_color()) + } + + pub fn uv() -> Self { + Self(geometry_attribute_uv()) + } + + pub fn rotation() -> Self { + Self(geometry_attribute_rotation()) + } + + pub fn scale() -> Self { + Self(geometry_attribute_scale()) + } + + pub fn life() -> Self { + Self(geometry_attribute_life()) + } + + pub fn velocity() -> Self { + Self(geometry_attribute_velocity()) + } + + pub fn age() -> Self { + Self(geometry_attribute_age()) + } +} + +#[doc(hidden)] +pub enum Value { + Float(f32), + Float2(Vec2), + Float3(Vec3), + Float4(Vec4), +} + +/// A number, or a 2-4 tuple or vector. +pub trait AttributeValue { + #[doc(hidden)] + fn into_value(self) -> Value; +} + +impl AttributeValue for T { + fn into_value(self) -> Value { + Value::Float(self.to_f32()) + } +} + +impl AttributeValue for (A, B) { + fn into_value(self) -> Value { + Value::Float2(Vec2::new(self.0.to_f32(), self.1.to_f32())) + } +} + +impl AttributeValue for (A, B, C) { + fn into_value(self) -> Value { + Value::Float3(Vec3::new(self.0.to_f32(), self.1.to_f32(), self.2.to_f32())) + } +} + +impl AttributeValue for (A, B, C, D) { + fn into_value(self) -> Value { + Value::Float4(Vec4::new( + self.0.to_f32(), + self.1.to_f32(), + self.2.to_f32(), + self.3.to_f32(), + )) + } +} + +impl AttributeValue for Vec2 { + fn into_value(self) -> Value { + Value::Float2(self) + } +} + +impl AttributeValue for Vec3 { + fn into_value(self) -> Value { + Value::Float3(self) + } +} + +impl AttributeValue for Vec4 { + fn into_value(self) -> Value { + Value::Float4(self) + } +} diff --git a/src/gltf.rs b/src/gltf.rs new file mode 100644 index 00000000..a571d1c6 --- /dev/null +++ b/src/gltf.rs @@ -0,0 +1,42 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::{ + gltf_camera, gltf_geometry, gltf_light, gltf_load, gltf_material, gltf_material_names, + gltf_mesh_names, +}; + +use crate::{Geometry, Graphics, Light, Material}; + +#[derive(Debug)] +pub struct Gltf(Entity); + +impl Gltf { + pub fn load(g: &Graphics, path: &str) -> Result { + gltf_load(g.entity, path).map(Self) + } + + pub fn geometry(&self, name: &str) -> Result { + gltf_geometry(self.0, name).map(Geometry) + } + + pub fn material(&self, name: &str) -> Result { + gltf_material(self.0, name).map(Material) + } + + pub fn mesh_names(&self) -> Result> { + gltf_mesh_names(self.0) + } + + pub fn material_names(&self) -> Result> { + gltf_material_names(self.0) + } + + /// Moves the camera to the scene's camera. + pub fn camera(&self, index: usize) -> Result<()> { + gltf_camera(self.0, index) + } + + pub fn light(&self, index: usize) -> Result { + gltf_light(self.0, index).map(Light) + } +} diff --git a/src/graphics.rs b/src/graphics.rs index 2fa05903..c08fe684 100644 --- a/src/graphics.rs +++ b/src/graphics.rs @@ -1,5 +1,3 @@ -//! The drawing surface and its Processing-style drawing methods. - use std::fmt::Display; use bevy::math::{Affine3A, Vec3, Vec4}; @@ -17,28 +15,29 @@ use processing_render::render::command::{ }; use processing_render::{ camera_reset, camera_set_center, camera_set_distance, delta_time, elapsed_time, frame_count, - graphics_begin_draw, graphics_create, graphics_destroy, graphics_disable_camera_controller, - graphics_end_draw, graphics_flush, graphics_free_camera, graphics_get_matrix, graphics_light, - graphics_mode_2d, graphics_mode_3d, graphics_orbit_camera, graphics_ortho, graphics_pan_camera, - graphics_perspective, graphics_readback, graphics_record_command, graphics_screen_point, - graphics_set_color_mode, graphics_text_ascent, graphics_text_descent, graphics_text_width, + geometry_create_from_mesh, graphics_apply_filter, graphics_begin_draw, graphics_create, + graphics_destroy, graphics_disable_camera_controller, graphics_end_draw, graphics_flush, + graphics_free_camera, graphics_get_matrix, graphics_light, graphics_mode_2d, graphics_mode_3d, + graphics_orbit_camera, graphics_ortho, graphics_pan_camera, graphics_perspective, + graphics_readback, graphics_record_command, graphics_screen_point, graphics_set_color_mode, + graphics_text_ascent, graphics_text_descent, graphics_text_to_model, graphics_text_width, graphics_update, graphics_update_region, light_create_directional, light_create_point, light_create_spot, light_destroy, surface_create_offscreen, surface_destroy, surface_physical_height, surface_physical_width, transform_look_at, transform_set_position, }; use crate::color::{ColorArg, ColorSpace, ColorState, IntoColorMax}; -use crate::draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, Push, Rect, Text}; +use crate::draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, ParticlesDraw, Push, Rect, Text}; use crate::input::{Key, MouseButton}; use crate::shape::Shape; use crate::{AsImage, Color, Font, IntoExtent, IntoPoint, Scalar}; +use crate::{Buffer, Filter, Geometry, Material, Particles}; -/// Panics on engine errors that a valid handle can't produce. pub(crate) fn expect(r: Result) -> T { r.unwrap_or_else(|e| panic!("processing: {e}")) } -/// A drawing surface: the sketch window passed to [`crate::Sketch::draw`], or one made with [`Graphics::create`]. +/// The sketch window, or an offscreen surface. pub struct Graphics { pub(crate) entity: Entity, pub(crate) surface: Entity, @@ -64,8 +63,7 @@ impl Graphics { } } - /// An offscreen drawing surface (Processing's `createGraphics`). Draw into it inside - /// [`Graphics::begin_draw`], then show it with `g.image(&pg, x, y)`. + /// Processing's `createGraphics`. pub fn create(width: u32, height: u32) -> Result { let format = TextureFormat::Rgba8UnormSrgb; let surface = surface_create_offscreen(width, height, 1.0, format)?; @@ -75,7 +73,6 @@ impl Graphics { Ok(g) } - /// Starts drawing into a [`Graphics::create`]d surface; drawing ends when the guard drops. pub fn begin_draw(&mut self) -> BeginDraw<'_> { assert!( self.offscreen, @@ -102,8 +99,6 @@ impl Graphics { self.color.resolve(color.into()).0 } - // -- size & time -------------------------------------------------------- - pub fn width(&self) -> f32 { self.width as f32 } @@ -112,16 +107,15 @@ impl Graphics { self.height as f32 } - /// Width in physical pixels; larger than `width()` on high-DPI displays. + /// In physical pixels. pub fn pixel_width(&self) -> u32 { if self.offscreen { - // offscreen surfaces are created at scale 1 return self.width; } expect(surface_physical_width(self.surface)) } - /// Height in physical pixels; larger than `height()` on high-DPI displays. + /// In physical pixels. pub fn pixel_height(&self) -> u32 { if self.offscreen { return self.height; @@ -129,22 +123,25 @@ impl Graphics { expect(surface_physical_height(self.surface)) } - /// Frames drawn so far, starting at 1 in the first `draw`. + /// Starts at 1. pub fn frame_count(&self) -> u32 { expect(frame_count()) } - /// Seconds since the previous frame. + /// In seconds. pub fn delta_time(&self) -> f32 { expect(delta_time()) } - /// Milliseconds since the sketch started. + /// In seconds. + pub fn elapsed_time(&self) -> f32 { + expect(elapsed_time()) + } + pub fn millis(&self) -> u32 { (expect(elapsed_time()) * 1000.0) as u32 } - /// Stops the sketch after this frame. pub fn exit(&mut self) { self.exit_requested = true; } @@ -153,9 +150,6 @@ impl Graphics { self.exit_requested } - // -- color & style ------------------------------------------------------ - - /// Sets how color arguments are read. Chain `.max(..)` to set channel ranges. pub fn color_mode(&mut self, space: ColorSpace) -> ColorModeBuilder<'_> { ColorModeBuilder { g: self, @@ -164,7 +158,6 @@ impl Graphics { } } - /// Resolves color arguments against the current color mode. pub fn color(&self, color: impl Into) -> Color { self.color.resolve(color.into()) } @@ -233,9 +226,6 @@ impl Graphics { self.record(DrawCommand::ImageMode(mode)); } - // -- 2D primitives ------------------------------------------------------ - - /// Chain `.radius(r)` or `.radii(tl, tr, br, bl)` for rounded corners. pub fn rect( &mut self, x: impl Scalar, @@ -265,7 +255,6 @@ impl Graphics { self.ellipse(x, y, d, d); } - /// Chain `.mode(ArcMode::Pie)` or `.mode(ArcMode::Chord)` to close the arc. pub fn arc( &mut self, x: impl Scalar, @@ -387,19 +376,14 @@ impl Graphics { }); } - /// Starts a custom shape; it ends (open) when dropped, or call `.close()`. pub fn begin_shape(&mut self, kind: ShapeKind) -> Shape<'_> { Shape::new(self, kind) } - // -- images & text ------------------------------------------------------ - - /// Chain `.size(w, h)` to scale, `.source(x, y, w, h)` to draw a sub-region. pub fn image(&mut self, image: &impl AsImage, x: impl Scalar, y: impl Scalar) -> ImageDraw<'_> { ImageDraw::new(self, image.image_entity(), x.to_f32(), y.to_f32()) } - /// Chain `.z(z)` to place in depth, `.max_width(w)` or `.bounds(w, h)` to wrap. pub fn text(&mut self, content: impl Display, x: impl Scalar, y: impl Scalar) -> Text<'_> { Text::new(self, content.to_string(), x.to_f32(), y.to_f32()) } @@ -416,7 +400,6 @@ impl Graphics { self.record(DrawCommand::TextLeading(leading.to_f32())); } - /// `text_align(TextAlignH::Center)` or `text_align((TextAlignH::Center, TextAlignV::Top))`. pub fn text_align(&mut self, align: impl Into) { let TextAlign(h, v) = align.into(); self.record(DrawCommand::TextAlign { h, v }); @@ -442,9 +425,6 @@ impl Graphics { expect(graphics_text_descent(self.entity)) } - // -- transforms --------------------------------------------------------- - - /// Saves style and transform until the returned guard is dropped. pub fn push(&mut self) -> Push<'_> { self.push_style(); self.push_matrix(); @@ -498,7 +478,6 @@ impl Graphics { }); } - /// `scale(2)`, `scale((2, 1))` or `scale((1, 2, 3))`. pub fn scale(&mut self, factor: impl IntoExtent) { self.record(DrawCommand::Scale(factor.into_extent())); } @@ -527,13 +506,10 @@ impl Graphics { expect(graphics_get_matrix(self.entity)) } - /// Where a point in the current transform lands on screen. pub fn screen_point(&self, point: impl IntoPoint) -> Vec3 { expect(graphics_screen_point(self.entity, point.into_point())) } - // -- 3D ----------------------------------------------------------------- - pub fn mode_3d(&mut self) { expect(graphics_mode_3d(self.entity)); } @@ -542,7 +518,6 @@ impl Graphics { expect(graphics_mode_2d(self.entity)); } - /// `cube(size)` or `cube((w, h, d))`. pub fn cube(&mut self, size: impl IntoExtent) { let s = size.into_extent(); self.record(DrawCommand::Box { @@ -552,7 +527,6 @@ impl Graphics { }); } - /// Chain `.detail(sectors, stacks)`. pub fn sphere(&mut self, radius: impl Scalar) -> Detail<'_, 2> { Detail::new( self, @@ -566,7 +540,6 @@ impl Graphics { ) } - /// Chain `.detail(n)`. pub fn cylinder(&mut self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { let size = [radius.to_f32(), height.to_f32(), 0.0]; Detail::new(self, size, [24], |[radius, height, _], [detail]| { @@ -578,7 +551,6 @@ impl Graphics { }) } - /// Chain `.detail(n)`. pub fn cone(&mut self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { let size = [radius.to_f32(), height.to_f32(), 0.0]; Detail::new(self, size, [24], |[radius, height, _], [detail]| { @@ -590,7 +562,6 @@ impl Graphics { }) } - /// Chain `.detail(major, minor)`. pub fn torus(&mut self, radius: impl Scalar, tube_radius: impl Scalar) -> Detail<'_, 2> { let size = [radius.to_f32(), tube_radius.to_f32(), 0.0]; Detail::new( @@ -606,7 +577,6 @@ impl Graphics { ) } - /// Chain `.detail(n)`. pub fn capsule(&mut self, radius: impl Scalar, length: impl Scalar) -> Detail<'_, 1> { let size = [radius.to_f32(), length.to_f32(), 0.0]; Detail::new(self, size, [16], |[radius, length, _], [detail]| { @@ -618,7 +588,6 @@ impl Graphics { }) } - /// A cone with its tip cut off. Chain `.detail(n)`. pub fn conical_frustum( &mut self, radius_top: impl Scalar, @@ -723,7 +692,6 @@ impl Graphics { )); } - /// Mouse-driven orbit around `camera_center`. pub fn orbit_camera(&mut self) { expect(graphics_orbit_camera(self.entity)); } @@ -752,12 +720,10 @@ impl Graphics { expect(camera_reset(self.entity)); } - /// Adds a light to the frame. pub fn light(&mut self, light: &Light) { expect(graphics_light(self.entity, light.0)); } - /// Adds a directional light to the frame. pub fn directional_light( &mut self, color: impl Into, @@ -773,7 +739,6 @@ impl Graphics { ) } - /// Adds a point light to the frame. pub fn point_light( &mut self, color: impl Into, @@ -793,7 +758,6 @@ impl Graphics { ) } - /// Adds a spot light to the frame. pub fn spot_light( &mut self, color: impl Into, @@ -817,7 +781,6 @@ impl Graphics { ) } - /// Creates a directional light. pub fn create_directional_light( &mut self, color: impl Into, @@ -831,7 +794,6 @@ impl Graphics { ))) } - /// Creates a point light. pub fn create_point_light( &mut self, color: impl Into, @@ -849,7 +811,6 @@ impl Graphics { ))) } - /// Creates a spot light. pub fn create_spot_light( &mut self, color: impl Into, @@ -871,9 +832,42 @@ impl Graphics { ))) } - // -- pixels ------------------------------------------------------------- + pub fn model(&mut self, geometry: &Geometry) { + self.record(DrawCommand::Geometry(geometry.0)); + } + + pub fn material(&mut self, material: &Material) { + self.record(DrawCommand::Material(material.0)); + } - /// Reads the current frame back from the GPU, row-major. + /// One color per particle. + pub fn fill_buffer(&mut self, buffer: &Buffer) { + self.record(DrawCommand::FillBuffer(buffer.entity)); + } + + /// Points unless given a geometry. + pub fn particles(&mut self, particles: &Particles) -> ParticlesDraw<'_> { + ParticlesDraw::new(self, particles.0) + } + + pub fn filter(&mut self, filter: Filter) { + let entity = expect(filter.entity()); + expect(graphics_apply_filter(self.entity, entity)); + } + + pub fn text_to_model( + &self, + content: &str, + x: impl Scalar, + y: impl Scalar, + depth: impl Scalar, + ) -> Result { + let mesh = + graphics_text_to_model(self.entity, content, x.to_f32(), y.to_f32(), depth.to_f32())?; + geometry_create_from_mesh(mesh).map(Geometry) + } + + /// Row-major. pub fn pixels(&self) -> Result> { Ok(graphics_readback(self.entity)? .into_iter() @@ -881,15 +875,13 @@ impl Graphics { .collect()) } - /// Replaces every pixel; `pixels.len()` must be `pixel_width() * pixel_height()`. + /// `pixels.len()` must be `pixel_width() * pixel_height()`. pub fn set_pixels(&mut self, pixels: &[Color]) -> Result<()> { let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); - // draw what's recorded so far so the write lands on top of it graphics_flush(self.entity)?; graphics_update(self.entity, &linear) } - /// Replaces a `w` by `h` block of pixels with its top-left corner at `(x, y)`. pub fn set_pixels_region( &mut self, x: u32, @@ -903,8 +895,6 @@ impl Graphics { graphics_update_region(self.entity, x, y, w, h, &linear) } - // -- input -------------------------------------------------------------- - pub fn mouse_x(&self) -> f32 { expect(input_mouse_x(self.surface)).clamp(0.0, self.width()) } @@ -941,17 +931,14 @@ impl Graphics { expect(input_mouse_button()).map(MouseButton::from) } - /// Whether any key is held. pub fn key_pressed(&self) -> bool { expect(input_key_is_pressed()) } - /// The character of the most recent key press. pub fn key(&self) -> Option { expect(input_key()) } - /// The most recent key press, if it's one [`Key`] names. pub fn key_code(&self) -> Option { expect(processing_input::input_key_code()).and_then(Key::from_code) } @@ -960,7 +947,6 @@ impl Graphics { expect(input_key_is_down(key.code())) } - /// True only in the frame `key` went down. pub fn key_just_pressed(&self, key: Key) -> bool { expect(input_key_just_pressed(key.code())) } @@ -973,7 +959,6 @@ impl Graphics { impl AsImage for Graphics { fn image_entity(&self) -> Entity { - // an offscreen surface is backed by an image assert!( self.offscreen, "processing: only Graphics::create surfaces can be drawn as images" @@ -991,7 +976,6 @@ impl Drop for Graphics { } } -/// Built by [`Graphics::color_mode`]; applies when dropped. pub struct ColorModeBuilder<'g> { g: &'g mut Graphics, space: ColorSpace, @@ -999,7 +983,7 @@ pub struct ColorModeBuilder<'g> { } impl ColorModeBuilder<'_> { - /// `max(255)` for every channel, or `max((360, 100, 100))` / `max((360, 100, 100, 1))`. + /// `max(255)`, `max((360, 100, 100))` or `max((360, 100, 100, 1))`. pub fn max(mut self, max: impl IntoColorMax) -> Self { self.max = Some(max.into_color_max(self.space)); self @@ -1023,7 +1007,6 @@ impl Drop for ColorModeBuilder<'_> { } } -/// Horizontal alignment, optionally paired with vertical. #[derive(Debug, Clone, Copy)] pub struct TextAlign(TextAlignH, TextAlignV); @@ -1039,9 +1022,8 @@ impl From<(TextAlignH, TextAlignV)> for TextAlign { } } -/// A light, added to a frame with [`Graphics::light`]. #[derive(Debug)] -pub struct Light(Entity); +pub struct Light(pub(crate) Entity); impl Light { pub fn position(&self, position: impl IntoPoint) -> &Self { diff --git a/src/image.rs b/src/image.rs index 912ba7cd..8a646126 100644 --- a/src/image.rs +++ b/src/image.rs @@ -1,5 +1,3 @@ -//! Images and fonts. - use bevy::prelude::Entity; use bevy::render::render_resource::{Extent3d, TextureFormat}; use processing_core::error::Result; @@ -10,7 +8,6 @@ use processing_render::{ use crate::Color; -/// A texture you can draw with `g.image(..)` or use as a `g.texture(..)`. #[derive(Debug)] pub struct Image { pub(crate) entity: Entity, @@ -19,7 +16,6 @@ pub struct Image { } impl Image { - /// Loads an image relative to the sketch's asset directory. pub fn load(path: &str) -> Result { let entity = image_load(path)?; let (width, height) = image_size(entity)?; @@ -30,7 +26,7 @@ impl Image { }) } - /// A blank, transparent image. + /// Transparent. pub fn create(width: u32, height: u32) -> Result { let size = Extent3d { width, @@ -54,7 +50,7 @@ impl Image { self.height } - /// Reads the pixels back from the GPU, row-major. + /// Row-major. pub fn pixels(&self) -> Result> { Ok(image_readback(self.entity)? .into_iter() @@ -62,7 +58,7 @@ impl Image { .collect()) } - /// Replaces every pixel; `pixels.len()` must be `width * height`. + /// `pixels.len()` must be `width * height`. pub fn set_pixels(&mut self, pixels: &[Color]) -> Result<()> { let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); image_update(self.entity, &linear) @@ -75,7 +71,7 @@ impl Drop for Image { } } -/// Anything that can be drawn with `g.image(..)` or used as a `g.texture(..)`. +/// Anything `g.image(..)` can draw. pub trait AsImage { #[doc(hidden)] fn image_entity(&self) -> Entity; @@ -87,22 +83,20 @@ impl AsImage for Image { } } -/// A font for `g.text_font(..)`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Font(pub(crate) Entity); impl Font { - /// Loads a font file relative to the sketch's asset directory. pub fn load(path: &str) -> Result { font_load(path).map(Self) } - /// Looks up an installed system font by family name. + /// An installed font, by family name. pub fn system(name: &str) -> Result { font_create(name).map(Self) } - /// Family names of the installed system fonts. + /// Installed font families. pub fn list() -> Result> { font_list() } diff --git a/src/input.rs b/src/input.rs index 48d3c438..c9c0d9d8 100644 --- a/src/input.rs +++ b/src/input.rs @@ -1,5 +1,3 @@ -//! Keyboard and mouse identifiers. - use bevy::input::keyboard::KeyCode; use bevy::input::mouse::MouseButton as BevyMouseButton; @@ -28,7 +26,7 @@ impl From for MouseButton { macro_rules! keys { ($($key:ident => $code:ident),* $(,)?) => { - /// A physical key, named by its position on a US keyboard. + /// By position on a US keyboard. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Key { $($key,)* diff --git a/src/lib.rs b/src/lib.rs index c3fcec4c..56803ccc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,29 +7,51 @@ mod color; #[cfg(not(target_arch = "wasm32"))] mod draw; #[cfg(not(target_arch = "wasm32"))] +mod filter; +#[cfg(not(target_arch = "wasm32"))] +mod geometry; +#[cfg(not(target_arch = "wasm32"))] +mod gltf; +#[cfg(not(target_arch = "wasm32"))] mod graphics; #[cfg(not(target_arch = "wasm32"))] mod image; #[cfg(not(target_arch = "wasm32"))] mod input; #[cfg(not(target_arch = "wasm32"))] +pub mod midi; +#[cfg(not(target_arch = "wasm32"))] +mod particles; +#[cfg(not(target_arch = "wasm32"))] +mod shader; +#[cfg(not(target_arch = "wasm32"))] mod shape; #[cfg(not(target_arch = "wasm32"))] mod sketch; +#[cfg(all(feature = "webcam", not(target_arch = "wasm32")))] +mod webcam; +#[cfg(all(feature = "webcam", not(target_arch = "wasm32")))] +pub use crate::webcam::Webcam; #[cfg(not(target_arch = "wasm32"))] pub use crate::{ args::{IntoExtent, IntoPoint, Scalar}, color::{Channel, Color, ColorArg, ColorSpace, IntoChannel, IntoColorMax}, - draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, Push, Rect, Text}, + draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, ParticlesDraw, Push, Rect, Text}, + filter::Filter, + geometry::{Attribute, AttributeValue, Geometry, GeometryData, Layout}, + gltf::Gltf, graphics::{ColorModeBuilder, Graphics, Light, TextAlign}, image::{AsImage, Font, Image}, input::{Key, MouseButton}, + particles::Particles, + shader::{Buffer, BufferElement, Compute, IntoShaderValue, Material, Shader}, shape::{Contour, Shape}, sketch::{Settings, Sketch, run}, }; -pub use bevy::math::{Affine3A, Mat4, Vec2, Vec3}; +pub use bevy::math::{Affine3A, Mat4, Vec2, Vec3, Vec4}; pub use processing_core::error::{ProcessingError as Error, Result}; +pub use processing_render::geometry::{AttributeFormat, Topology}; pub use processing_render::render::command::{ ArcMode, BlendMode, ShapeKind, ShapeMode, StrokeCapMode as StrokeCap, StrokeJoinMode as StrokeJoin, TextAlignH, TextAlignV, TextStyle, TextWrapMode, diff --git a/src/midi.rs b/src/midi.rs new file mode 100644 index 00000000..2789b888 --- /dev/null +++ b/src/midi.rs @@ -0,0 +1,31 @@ +use processing_core::error::Result; + +pub fn refresh_ports() -> Result<()> { + processing_midi::midi_refresh_ports() +} + +/// Output port names, indexed as [`connect`] takes them. +pub fn ports() -> Result> { + processing_midi::midi_list_ports() +} + +pub fn connect(port: usize) -> Result<()> { + processing_midi::midi_connect(port) +} + +pub fn disconnect() -> Result<()> { + processing_midi::midi_disconnect() +} + +pub fn note_on(note: u8, velocity: u8) -> Result<()> { + processing_midi::midi_note_on(note, velocity) +} + +pub fn note_off(note: u8) -> Result<()> { + processing_midi::midi_note_off(note) +} + +/// `duration` in milliseconds. +pub fn play_note(note: u8, duration: u64) -> Result<()> { + processing_midi::midi_play_notes(note, duration) +} diff --git a/src/particles.rs b/src/particles.rs new file mode 100644 index 00000000..4ee3b50b --- /dev/null +++ b/src/particles.rs @@ -0,0 +1,128 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::particles::{ + particles_apply, particles_capacity, particles_create, particles_create_from_geometry, + particles_destroy, particles_emit, particles_emit_gpu, particles_ensure_attribute, + particles_kernel_age, particles_kernel_attract, particles_kernel_bounds_box, + particles_kernel_bounds_geometry, particles_kernel_bounds_sphere, particles_kernel_drag, + particles_kernel_field, particles_kernel_force, particles_kernel_impulse, + particles_kernel_integrate, particles_kernel_noise, particles_kernel_orient, + particles_kernel_transform, particles_kernel_vortex, particles_scatter_create, + particles_scatter_volume_create, +}; + +use crate::graphics::expect; +use crate::{Attribute, Buffer, Compute, Geometry}; + +#[derive(Debug)] +pub struct Particles(pub(crate) Entity); + +impl Particles { + pub fn new(capacity: u32, attributes: &[Attribute]) -> Result { + particles_create(capacity, attributes.iter().map(|a| a.0).collect()).map(Self) + } + + /// One particle per vertex. + pub fn from_geometry(geometry: &Geometry, attributes: &[Attribute]) -> Result { + particles_create_from_geometry(geometry.0, attributes.iter().map(|a| a.0).collect()) + .map(Self) + } + + pub fn capacity(&self) -> u32 { + expect(particles_capacity(self.0)) + } + + /// Adds the attribute if missing. + pub fn buffer(&self, attribute: Attribute) -> Buffer { + Buffer::borrowed(expect(particles_ensure_attribute(self.0, attribute.0))) + } + + pub fn apply(&mut self, compute: &Compute) { + expect(particles_apply(self.0, compute.0)); + } + + /// Replaces the oldest when full. + pub fn emit(&mut self, count: u32, values: &[(Attribute, &[f32])]) { + let data = values + .iter() + .map(|(attribute, v)| (attribute.0, bytemuck::cast_slice(v).to_vec())) + .collect(); + expect(particles_emit(self.0, count, data)); + } + + pub fn emit_gpu(&mut self, count: u32, compute: &Compute) { + expect(particles_emit_gpu(self.0, count, compute.0)); + } + + pub fn noise() -> Result { + particles_kernel_noise().map(Compute) + } + + pub fn transform() -> Result { + particles_kernel_transform().map(Compute) + } + + pub fn attract() -> Result { + particles_kernel_attract().map(Compute) + } + + pub fn drag() -> Result { + particles_kernel_drag().map(Compute) + } + + pub fn vortex() -> Result { + particles_kernel_vortex().map(Compute) + } + + pub fn force() -> Result { + particles_kernel_force().map(Compute) + } + + pub fn integrate() -> Result { + particles_kernel_integrate().map(Compute) + } + + pub fn age() -> Result { + particles_kernel_age().map(Compute) + } + + pub fn bounds_sphere() -> Result { + particles_kernel_bounds_sphere().map(Compute) + } + + pub fn bounds_box() -> Result { + particles_kernel_bounds_box().map(Compute) + } + + pub fn bounds_geometry(geometry: &Geometry) -> Result { + particles_kernel_bounds_geometry(geometry.0).map(Compute) + } + + pub fn impulse() -> Result { + particles_kernel_impulse().map(Compute) + } + + pub fn orient() -> Result { + particles_kernel_orient().map(Compute) + } + + pub fn field() -> Result { + particles_kernel_field().map(Compute) + } + + /// For [`Particles::emit_gpu`]. + pub fn scatter_surface(geometry: &Geometry) -> Result { + particles_scatter_create(geometry.0).map(Compute) + } + + /// For [`Particles::emit_gpu`]. + pub fn scatter_volume(geometry: &Geometry) -> Result { + particles_scatter_volume_create(geometry.0).map(Compute) + } +} + +impl Drop for Particles { + fn drop(&mut self) { + let _ = particles_destroy(self.0); + } +} diff --git a/src/shader.rs b/src/shader.rs new file mode 100644 index 00000000..6e835c89 --- /dev/null +++ b/src/shader.rs @@ -0,0 +1,266 @@ +use bevy::math::{Mat4, Vec2, Vec3, Vec4}; +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::shader_value::ShaderValue; +use processing_render::{ + buffer_create, buffer_create_with_data, buffer_destroy, buffer_read, buffer_size, buffer_write, + compute_create, compute_destroy, compute_dispatch, compute_set, material_create_custom, + material_create_pbr, material_create_unlit, material_destroy, material_set, + material_set_albedo_buffer, material_set_double_sided, material_set_emissive_buffer, + shader_create, shader_destroy, shader_load, +}; + +use crate::AsImage; +use crate::graphics::expect; + +/// WGSL or WESL. +#[derive(Debug)] +pub struct Shader(pub(crate) Entity); + +impl Shader { + pub fn new(source: &str) -> Result { + shader_create(source).map(Self) + } + + pub fn load(path: &str) -> Result { + shader_load(path).map(Self) + } +} + +impl Drop for Shader { + fn drop(&mut self) { + let _ = shader_destroy(self.0); + } +} + +#[derive(Debug)] +pub struct Material(pub(crate) Entity); + +impl Material { + pub fn pbr() -> Result { + material_create_pbr().map(Self) + } + + pub fn unlit() -> Result { + material_create_unlit().map(Self) + } + + pub fn new(shader: &Shader) -> Result { + material_create_custom(shader.0).map(Self) + } + + pub fn set(&mut self, name: &str, value: impl IntoShaderValue) { + expect(material_set(self.0, name, value.into_shader_value())); + } + + /// One RGBA per particle. + pub fn albedo_buffer(&mut self, buffer: &Buffer) { + expect(material_set_albedo_buffer(self.0, buffer.entity)); + } + + /// One RGBA per particle. + pub fn emissive_buffer(&mut self, buffer: &Buffer) { + expect(material_set_emissive_buffer(self.0, buffer.entity)); + } + + pub fn double_sided(&mut self, value: bool) { + expect(material_set_double_sided(self.0, value)); + } +} + +impl Drop for Material { + fn drop(&mut self) { + let _ = material_destroy(self.0); + } +} + +#[derive(Debug)] +pub struct Buffer { + pub(crate) entity: Entity, + owned: bool, +} + +impl Buffer { + /// Zeroed, `size` in bytes. + pub fn new(size: u64) -> Result { + buffer_create(size).map(Self::owned) + } + + pub fn from_slice(data: &[T]) -> Result { + buffer_create_with_data(bytemuck::cast_slice(data).to_vec()).map(Self::owned) + } + + fn owned(entity: Entity) -> Self { + Self { + entity, + owned: true, + } + } + + /// Not destroyed on drop. + pub(crate) fn borrowed(entity: Entity) -> Self { + Self { + entity, + owned: false, + } + } + + /// In bytes. + pub fn size(&self) -> u64 { + expect(buffer_size(self.entity)) + } + + pub fn write(&mut self, data: &[T]) { + expect(buffer_write( + self.entity, + bytemuck::cast_slice(data).to_vec(), + )); + } + + pub fn read(&self) -> Result> { + let bytes = buffer_read(self.entity)?; + Ok(bytemuck::pod_collect_to_vec(&bytes)) + } +} + +impl Drop for Buffer { + fn drop(&mut self) { + if self.owned { + let _ = buffer_destroy(self.entity); + } + } +} + +mod sealed { + pub trait Sealed {} +} + +/// `f32`, `i32`, `u32`, or arrays of 2-4 of them. +pub trait BufferElement: sealed::Sealed + bytemuck::Pod {} + +macro_rules! buffer_element { + ($($t:ty),*) => {$( + impl sealed::Sealed for $t {} + impl BufferElement for $t {} + impl sealed::Sealed for [$t; 2] {} + impl BufferElement for [$t; 2] {} + impl sealed::Sealed for [$t; 3] {} + impl BufferElement for [$t; 3] {} + impl sealed::Sealed for [$t; 4] {} + impl BufferElement for [$t; 4] {} + )*}; +} +buffer_element!(f32, i32, u32); + +#[derive(Debug)] +pub struct Compute(pub(crate) Entity); + +impl Compute { + pub fn new(shader: &Shader) -> Result { + compute_create(shader.0).map(Self) + } + + pub fn set(&mut self, name: &str, value: impl IntoShaderValue) { + expect(compute_set(self.0, name, value.into_shader_value())); + } + + /// Blocks until done. + pub fn dispatch(&mut self, x: u32, y: u32, z: u32) { + expect(compute_dispatch(self.0, x, y, z)); + } +} + +impl Drop for Compute { + fn drop(&mut self) { + let _ = compute_destroy(self.0); + } +} + +pub trait IntoShaderValue { + #[doc(hidden)] + fn into_shader_value(self) -> ShaderValue; +} + +impl IntoShaderValue for f32 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float(self) + } +} + +impl IntoShaderValue for f64 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float(self as f32) + } +} + +impl IntoShaderValue for i32 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Int(self) + } +} + +impl IntoShaderValue for u32 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::UInt(self) + } +} + +impl IntoShaderValue for bool { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::UInt(self as u32) + } +} + +impl IntoShaderValue for (f32, f32) { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float2([self.0, self.1]) + } +} + +impl IntoShaderValue for (f32, f32, f32) { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float3([self.0, self.1, self.2]) + } +} + +impl IntoShaderValue for (f32, f32, f32, f32) { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float4([self.0, self.1, self.2, self.3]) + } +} + +impl IntoShaderValue for Vec2 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float2(self.to_array()) + } +} + +impl IntoShaderValue for Vec3 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float3(self.to_array()) + } +} + +impl IntoShaderValue for Vec4 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float4(self.to_array()) + } +} + +impl IntoShaderValue for Mat4 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Mat4(self.to_cols_array()) + } +} + +impl IntoShaderValue for &Buffer { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Buffer(self.entity) + } +} + +impl IntoShaderValue for &T { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Texture(self.image_entity()) + } +} diff --git a/src/shape.rs b/src/shape.rs index 94ff0925..22212415 100644 --- a/src/shape.rs +++ b/src/shape.rs @@ -1,12 +1,10 @@ -//! `begin_shape` / `end_shape` as a value: vertices only exist inside a shape. - use std::ops::{Deref, DerefMut}; use processing_render::render::command::{DrawCommand, ShapeKind}; use crate::{Graphics, Scalar}; -/// Returned by [`Graphics::begin_shape`]. Ends with [`Shape::end`], [`Shape::close`], or when dropped. +/// Ends open when dropped. pub struct Shape<'g> { g: &'g mut Graphics, close: bool, @@ -66,16 +64,14 @@ impl<'g> Shape<'g> { }); } - /// Starts a hole; it ends when the returned guard is dropped. + /// A hole, ended when dropped. pub fn contour(&mut self) -> Contour<'_, 'g> { self.g.record(DrawCommand::BeginContour); Contour { shape: self } } - /// Ends the shape open; same as dropping it. pub fn end(self) {} - /// Ends the shape, joining the last vertex to the first. pub fn close(mut self) { self.close = true; } @@ -87,7 +83,6 @@ impl Drop for Shape<'_> { } } -/// Returned by [`Shape::contour`]. pub struct Contour<'s, 'g> { shape: &'s mut Shape<'g>, } diff --git a/src/sketch.rs b/src/sketch.rs index 8520d54a..3ff9e674 100644 --- a/src/sketch.rs +++ b/src/sketch.rs @@ -1,5 +1,3 @@ -//! The sketch runner: opens a window and calls `setup` once and `draw` every frame. - use std::path::PathBuf; use bevy::render::render_resource::TextureFormat; @@ -10,13 +8,13 @@ use processing_render::{advance_frame_count, graphics_create, surface_set_title} use crate::Graphics; -/// Window and app options, returned from [`Sketch::settings`]. #[derive(Debug, Clone)] pub struct Settings { width: u32, height: u32, title: String, transparent: bool, + headless: bool, assets: Option, log_level: Option, } @@ -28,6 +26,7 @@ impl Settings { height, title: "Processing".to_string(), transparent: false, + headless: false, assets: None, log_level: None, } @@ -38,19 +37,24 @@ impl Settings { self } - /// A window with a transparent background. pub fn transparent(mut self) -> Self { self.transparent = true; self } - /// Where `Image::load` and `Font::load` look for files. + /// No window; runs until [`Graphics::exit`]. + pub fn headless(mut self) -> Self { + self.headless = true; + self + } + + /// The asset directory. pub fn assets(mut self, dir: impl Into) -> Self { self.assets = Some(dir.into()); self } - /// A `tracing` filter such as `"warn"` or `"processing=debug"`. + /// A `tracing` filter, e.g. `"warn"`. pub fn log_level(mut self, level: impl Into) -> Self { self.log_level = Some(level.into()); self @@ -63,22 +67,27 @@ impl Default for Settings { } } -/// A Processing sketch. State lives on `Self`. pub trait Sketch: Sized { fn settings() -> Settings { Settings::default() } - /// Runs once, before the first `draw`, with the window ready to draw into. fn setup(g: &mut Graphics) -> Result; fn draw(&mut self, _g: &mut Graphics) {} } -/// Runs `S` until its window closes. pub fn run() -> Result<()> { let settings = S::settings(); - let mut window = GlfwContext::new(settings.width, settings.height, settings.transparent)?; + let mut window = if settings.headless { + None + } else { + Some(GlfwContext::new( + settings.width, + settings.height, + settings.transparent, + )?) + }; let mut config = Config::new(); if let Some(dir) = &settings.assets { @@ -89,12 +98,18 @@ pub fn run() -> Result<()> { } crate::init(config)?; - let result = run_loop::(&mut window, &settings); + let result = match &mut window { + Some(window) => { + open_window(window, &settings).and_then(|g| run_frames::(g, || window.poll_events())) + } + None => Graphics::create(settings.width, settings.height) + .and_then(|g| run_frames::(g, || true)), + }; crate::exit(if result.is_ok() { 0 } else { 1 })?; result } -fn run_loop(window: &mut GlfwContext, settings: &Settings) -> Result<()> { +fn open_window(window: &mut GlfwContext, settings: &Settings) -> Result { let surface = window.create_surface(settings.width, settings.height, settings.transparent)?; let entity = graphics_create( surface, @@ -103,9 +118,16 @@ fn run_loop(window: &mut GlfwContext, settings: &Settings) -> Result< TextureFormat::Rgba16Float, )?; surface_set_title(surface, settings.title.clone())?; - let mut g = Graphics::new(entity, surface, settings.width, settings.height); + Ok(Graphics::new( + entity, + surface, + settings.width, + settings.height, + )) +} - if !window.poll_events() { +fn run_frames(mut g: Graphics, mut poll: impl FnMut() -> bool) -> Result<()> { + if !poll() { return Ok(()); } advance_frame_count()?; @@ -114,14 +136,14 @@ fn run_loop(window: &mut GlfwContext, settings: &Settings) -> Result< sketch.draw(&mut g); g.end_frame(); - while !g.exit_requested() && window.poll_events() { + while !g.exit_requested() && poll() { advance_frame_count()?; g.begin_frame(); sketch.draw(&mut g); g.end_frame(); } - // handles release engine resources, so drop them while the app is still alive + // handles must drop while the app is alive drop(sketch); drop(g); Ok(()) diff --git a/src/webcam.rs b/src/webcam.rs new file mode 100644 index 00000000..b505d126 --- /dev/null +++ b/src/webcam.rs @@ -0,0 +1,38 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_webcam::{ + webcam_create, webcam_destroy, webcam_image, webcam_is_connected, webcam_resolution, +}; + +use crate::AsImage; +use crate::graphics::expect; + +/// The default camera. +#[derive(Debug)] +pub struct Webcam(Entity); + +impl Webcam { + pub fn new() -> Result { + webcam_create().map(Self) + } + + pub fn connected(&self) -> bool { + expect(webcam_is_connected(self.0)) + } + + pub fn resolution(&self) -> (u32, u32) { + expect(webcam_resolution(self.0)) + } +} + +impl AsImage for Webcam { + fn image_entity(&self) -> Entity { + expect(webcam_image(self.0)) + } +} + +impl Drop for Webcam { + fn drop(&mut self) { + let _ = webcam_destroy(self.0); + } +} From bdfb95e98988a77a723c6be8e57be94392dadfa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Fri, 20 Nov 2026 12:09:32 -0800 Subject: [PATCH 3/4] Rebase and more change.s --- crates/processing_ffi/src/color.rs | 2 +- crates/processing_ffi/src/error.rs | 2 +- crates/processing_ffi/src/lib.rs | 30 +- crates/processing_node/src/lib.rs | 8 +- crates/processing_pyo3/src/color.rs | 2 +- crates/processing_pyo3/src/compute.rs | 4 +- crates/processing_pyo3/src/constants.rs | 4 +- crates/processing_pyo3/src/cuda.rs | 2 +- crates/processing_pyo3/src/filter.rs | 2 +- crates/processing_pyo3/src/gltf.rs | 2 +- crates/processing_pyo3/src/graphics.rs | 11 +- crates/processing_pyo3/src/host.rs | 2 +- crates/processing_pyo3/src/input.rs | 30 +- crates/processing_pyo3/src/lib.rs | 26 +- crates/processing_pyo3/src/material.rs | 2 +- crates/processing_pyo3/src/midi.rs | 2 +- crates/processing_pyo3/src/monitor.rs | 2 +- crates/processing_pyo3/src/particles.rs | 4 +- crates/processing_pyo3/src/shader.rs | 2 +- crates/processing_pyo3/src/surface.rs | 2 +- crates/processing_pyo3/src/time.rs | 6 +- crates/processing_render/src/graphics.rs | 16 +- crates/processing_render/src/lib.rs | 37 +- .../processing_render/src/render/command.rs | 55 ++- crates/processing_render/src/render/mod.rs | 6 +- .../src/render/primitive/text.rs | 5 +- crates/processing_wasm/src/lib.rs | 28 +- examples/alias_spike.rs | 2 +- examples/animated_mesh.rs | 2 +- examples/background_image.rs | 2 +- examples/blend_modes.rs | 2 +- examples/box.rs | 4 +- examples/camera_controllers.rs | 4 +- examples/compute_readback.rs | 2 +- examples/create_graphics.rs | 6 +- examples/curves.rs | 5 +- examples/custom_attribute.rs | 4 +- examples/custom_material.rs | 4 +- examples/filter.rs | 3 +- examples/gltf_load.rs | 2 +- examples/input.rs | 2 +- examples/lights.rs | 8 +- examples/materials.rs | 5 +- examples/midi.rs | 2 +- examples/particles_animated.rs | 15 +- examples/particles_basic.rs | 10 +- examples/particles_colored.rs | 15 +- examples/particles_colored_pbr.rs | 21 +- examples/particles_emit.rs | 34 +- examples/particles_emit_gpu.rs | 5 +- examples/particles_from_mesh.rs | 33 +- examples/particles_lifecycle.rs | 42 +- examples/particles_noise.rs | 33 +- examples/particles_oriented.rs | 28 +- examples/particles_scatter.rs | 5 +- examples/particles_scatter_volume.rs | 5 +- examples/particles_stress.rs | 22 +- examples/particles_text_whirl.rs | 5 +- examples/pbr.rs | 4 +- examples/primitives_2d.rs | 8 +- examples/primitives_3d.rs | 4 +- examples/rectangle.rs | 2 +- examples/shapes.rs | 16 +- examples/stroke_2d.rs | 2 +- examples/stroke_3d.rs | 10 +- examples/text.rs | 2 +- examples/text_3d.rs | 6 +- examples/transforms.rs | 6 +- examples/update_pixels.rs | 4 +- examples/webcam.rs | 2 +- src/draw.rs | 369 +++++++++--------- src/engine.rs | 21 + src/graphics.rs | 296 +++++++------- src/lib.rs | 12 +- src/particles.rs | 80 +++- src/prelude.rs | 28 +- src/shader.rs | 72 +++- src/shape.rs | 14 +- 78 files changed, 806 insertions(+), 778 deletions(-) create mode 100644 src/engine.rs diff --git a/crates/processing_ffi/src/color.rs b/crates/processing_ffi/src/color.rs index ae0ea82a..9c7ab31e 100644 --- a/crates/processing_ffi/src/color.rs +++ b/crates/processing_ffi/src/color.rs @@ -1,5 +1,5 @@ use bevy::color::LinearRgba; -use processing::prelude::color::{ColorMode, ColorSpace}; +use processing::engine::color::{ColorMode, ColorSpace}; /// A color with 4 float components and its color space. #[repr(C)] diff --git a/crates/processing_ffi/src/error.rs b/crates/processing_ffi/src/error.rs index fe8d5edf..a9ac84d4 100644 --- a/crates/processing_ffi/src/error.rs +++ b/crates/processing_ffi/src/error.rs @@ -4,7 +4,7 @@ use std::{ panic, }; -pub(crate) use processing::prelude::error::ProcessingError; +pub(crate) use processing::engine::error::ProcessingError; thread_local! { static LAST_ERROR: RefCell> = const { RefCell::new(None) }; diff --git a/crates/processing_ffi/src/lib.rs b/crates/processing_ffi/src/lib.rs index 2b1e8c79..9ee5b997 100644 --- a/crates/processing_ffi/src/lib.rs +++ b/crates/processing_ffi/src/lib.rs @@ -3,7 +3,7 @@ use bevy::{ prelude::Entity, render::render_resource::{Extent3d, TextureFormat}, }; -use processing::prelude::{error::ProcessingError, shader_value::ShaderValue, *}; +use processing::engine::{error::ProcessingError, shader_value::ShaderValue, *}; use crate::color::Color; @@ -333,12 +333,12 @@ pub extern "C" fn processing_color_mode( error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); error::check(|| { - let space = processing::prelude::color::ColorSpace::from_u8(space).ok_or_else(|| { - processing::prelude::error::ProcessingError::InvalidArgument(format!( + let space = processing::engine::color::ColorSpace::from_u8(space).ok_or_else(|| { + processing::engine::error::ProcessingError::InvalidArgument(format!( "unknown color space: {space}" )) })?; - let mode = processing::prelude::color::ColorMode::new(space, max1, max2, max3, max_alpha); + let mode = processing::engine::color::ColorMode::new(space, max1, max2, max3, max_alpha); graphics_set_color_mode(graphics_entity, mode) }); } @@ -396,7 +396,7 @@ pub extern "C" fn processing_set_stroke_cap(graphics_id: u64, cap: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::StrokeCap(processing::prelude::StrokeCapMode::from(cap)), + DrawCommand::StrokeCap(processing::engine::StrokeCapMode::from(cap)), ) }); } @@ -409,7 +409,7 @@ pub extern "C" fn processing_set_stroke_join(graphics_id: u64, join: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::StrokeJoin(processing::prelude::StrokeJoinMode::from(join)), + DrawCommand::StrokeJoin(processing::engine::StrokeJoinMode::from(join)), ) }); } @@ -422,7 +422,7 @@ pub extern "C" fn processing_rect_mode(graphics_id: u64, mode: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::RectMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::RectMode(processing::engine::ShapeMode::from(mode)), ) }); } @@ -435,7 +435,7 @@ pub extern "C" fn processing_ellipse_mode(graphics_id: u64, mode: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::EllipseMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::EllipseMode(processing::engine::ShapeMode::from(mode)), ) }); } @@ -631,7 +631,7 @@ pub extern "C" fn processing_set_blend_mode(graphics_id: u64, mode: u8) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); error::check(|| { - let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state(); + let blend_state = processing::engine::BlendMode::try_from(mode)?.to_blend_state(); graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state)) }); } @@ -828,7 +828,7 @@ pub extern "C" fn processing_arc( h, start, stop, - mode: processing::prelude::ArcMode::from(mode), + mode: processing::engine::ArcMode::from(mode), }, ) }); @@ -1022,7 +1022,7 @@ pub extern "C" fn processing_begin_shape(graphics_id: u64, kind: u8) { graphics_record_command( graphics_entity, DrawCommand::BeginShape { - kind: processing::prelude::ShapeKind::from(kind), + kind: processing::engine::ShapeKind::from(kind), }, ) }); @@ -1827,7 +1827,7 @@ pub extern "C" fn processing_image_mode(graphics_id: u64, mode: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::ImageMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::ImageMode(processing::engine::ShapeMode::from(mode)), ) }); } @@ -4009,8 +4009,8 @@ pub extern "C" fn processing_graphics_tonemapping(graphics_id: u64, mode: u8) { error::clear_error(); error::check(|| { let tonemapping = - processing::prelude::graphics::tonemapping_from_u8(mode).ok_or_else(|| { - processing::prelude::error::ProcessingError::InvalidArgument(format!( + processing::engine::graphics::tonemapping_from_u8(mode).ok_or_else(|| { + processing::engine::error::ProcessingError::InvalidArgument(format!( "unknown tonemapping: {mode}" )) })?; @@ -4348,7 +4348,7 @@ pub extern "C" fn processing_mouse_wheel() -> f32 { error::check(input_mouse_wheel).unwrap_or(0.0) } -fn key_code_from_u32(val: u32) -> processing::prelude::error::Result { +fn key_code_from_u32(val: u32) -> processing::engine::error::Result { match val { PROCESSING_KEY_SPACE => Ok(KeyCode::Space), PROCESSING_KEY_QUOTE => Ok(KeyCode::Quote), diff --git a/crates/processing_node/src/lib.rs b/crates/processing_node/src/lib.rs index 7fb6a8d7..1ce730cf 100644 --- a/crates/processing_node/src/lib.rs +++ b/crates/processing_node/src/lib.rs @@ -12,9 +12,9 @@ use napi::bindgen_prelude::{ }; use napi::{Env, Error, Result}; use napi_derive::napi; -use processing::prelude::color::{ColorMode, ColorSpace}; -use processing::prelude::error::ProcessingError; -use processing::prelude::{shader_value::ShaderValue, *}; +use processing::engine::color::{ColorMode, ColorSpace}; +use processing::engine::error::ProcessingError; +use processing::engine::{shader_value::ShaderValue, *}; use processing_glfw::GlfwContext; fn check(result: std::result::Result) -> Result { @@ -3123,7 +3123,7 @@ pub fn js_mouse_wheel() -> Result { check(input_mouse_wheel()).map(f64::from) } -fn key_code_from_u32(val: u32) -> processing::prelude::error::Result { +fn key_code_from_u32(val: u32) -> processing::engine::error::Result { match val { PROCESSING_KEY_SPACE => Ok(KeyCode::Space), PROCESSING_KEY_QUOTE => Ok(KeyCode::Quote), diff --git a/crates/processing_pyo3/src/color.rs b/crates/processing_pyo3/src/color.rs index 6aef7072..9914ac55 100644 --- a/crates/processing_pyo3/src/color.rs +++ b/crates/processing_pyo3/src/color.rs @@ -6,7 +6,7 @@ use pyo3::{exceptions::PyTypeError, prelude::*, types::PyTuple}; use crate::math::{PyVec3, PyVec4, PyVecIter, hash_f32}; -pub use processing::prelude::color::{ColorMode, ColorSpace}; +pub use processing::engine::color::{ColorMode, ColorSpace}; fn int_maxes(space: &ColorSpace) -> [f32; 4] { match space { diff --git a/crates/processing_pyo3/src/compute.rs b/crates/processing_pyo3/src/compute.rs index 9f7208fb..8bb03629 100644 --- a/crates/processing_pyo3/src/compute.rs +++ b/crates/processing_pyo3/src/compute.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyIndexError, PyRuntimeError, PyTypeError, PyValueError}, prelude::*, @@ -184,7 +184,7 @@ impl Buffer { #[pyo3(signature = (op = "sum"))] pub fn reduce(&self, op: &str) -> PyResult { - use processing::prelude::constants as c; + use processing::engine::constants as c; use processing_render::particles::reduce::{ REDUCE_OP_MAX, REDUCE_OP_MIN, REDUCE_OP_SUM, reduce as reduce_buffer, }; diff --git a/crates/processing_pyo3/src/constants.rs b/crates/processing_pyo3/src/constants.rs index 99486f82..15eeab7d 100644 --- a/crates/processing_pyo3/src/constants.rs +++ b/crates/processing_pyo3/src/constants.rs @@ -1,5 +1,5 @@ -use processing::prelude::BlendMode; -use processing::prelude::constants as c; +use processing::engine::BlendMode; +use processing::engine::constants as c; use pyo3::prelude::*; use pyo3::types::PyModule; diff --git a/crates/processing_pyo3/src/cuda.rs b/crates/processing_pyo3/src/cuda.rs index 6716b297..1da4ce65 100644 --- a/crates/processing_pyo3/src/cuda.rs +++ b/crates/processing_pyo3/src/cuda.rs @@ -1,4 +1,4 @@ -use processing::prelude::image::pixel_size; +use processing::engine::image::pixel_size; use processing_cuda::{cuda_buffer, cuda_write_back, typestr_for_format}; use pyo3::{exceptions::PyRuntimeError, prelude::*, types::PyDict}; diff --git a/crates/processing_pyo3/src/filter.rs b/crates/processing_pyo3/src/filter.rs index c59aeaef..85155668 100644 --- a/crates/processing_pyo3/src/filter.rs +++ b/crates/processing_pyo3/src/filter.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyRuntimeError, PyTypeError, PyValueError}, prelude::*, diff --git a/crates/processing_pyo3/src/gltf.rs b/crates/processing_pyo3/src/gltf.rs index 081c213d..354d51eb 100644 --- a/crates/processing_pyo3/src/gltf.rs +++ b/crates/processing_pyo3/src/gltf.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; use crate::graphics::{Geometry, Light}; diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index d3b16919..f363aed2 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -8,7 +8,7 @@ use bevy::{ prelude::{Entity, Transform}, render::render_resource::{Extent3d, TextureFormat}, }; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, prelude::*, @@ -1594,7 +1594,7 @@ impl Graphics { } pub fn text_style(&self, style: &str) -> PyResult<()> { - use processing::prelude::TextStyle; + use processing::engine::TextStyle; let style = TextStyle::parse(style) .ok_or_else(|| PyValueError::new_err(format!("unknown text style: {style:?}")))?; graphics_text_style(self.entity, style as u8) @@ -1723,7 +1723,7 @@ impl Graphics { #[pyo3(signature = (h, v=None))] pub fn text_align(&self, h: &str, v: Option<&str>) -> PyResult<()> { - use processing::prelude::{TextAlignH, TextAlignV}; + use processing::engine::{TextAlignH, TextAlignV}; let h = TextAlignH::parse(h).ok_or_else(|| { PyValueError::new_err(format!("unknown horizontal text align: {h:?}")) })?; @@ -1743,7 +1743,7 @@ impl Graphics { } pub fn text_wrap(&self, mode: &str) -> PyResult<()> { - use processing::prelude::TextWrapMode; + use processing::engine::TextWrapMode; let mode = TextWrapMode::parse(mode) .ok_or_else(|| PyValueError::new_err(format!("unknown text wrap mode: {mode:?}")))?; graphics_record_command(self.entity, DrawCommand::TextWrap(mode)) @@ -2333,7 +2333,7 @@ impl Graphics { graphics_no_bloom(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - #[pyo3(signature = (mode=processing::prelude::constants::PBR_NEUTRAL))] + #[pyo3(signature = (mode=processing::engine::constants::PBR_NEUTRAL))] pub fn tonemapping(&self, mode: &str) -> PyResult<()> { let tonemapping = processing_render::graphics::parse_tonemapping(mode) .ok_or_else(|| PyValueError::new_err(format!("unknown tonemapping {mode:?}")))?; @@ -2774,6 +2774,7 @@ impl Graphics { transform.look_at(target.into_vec3(), Vec3::Y); } graphics_immediate_light(self.entity, kind, transform) + .map(|_| ()) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } } diff --git a/crates/processing_pyo3/src/host.rs b/crates/processing_pyo3/src/host.rs index fb7071f7..024bc2ef 100644 --- a/crates/processing_pyo3/src/host.rs +++ b/crates/processing_pyo3/src/host.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use processing_render::geometry::AttributeFormat; use pyo3::buffer::PyBuffer; use pyo3::exceptions::{PyRuntimeError, PyValueError}; diff --git a/crates/processing_pyo3/src/input.rs b/crates/processing_pyo3/src/input.rs index 1126d3fb..2233182c 100644 --- a/crates/processing_pyo3/src/input.rs +++ b/crates/processing_pyo3/src/input.rs @@ -1,41 +1,41 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, prelude::*, }; pub fn mouse_x(surface: Entity, width: u32) -> PyResult { - let raw = processing::prelude::input_mouse_x(surface) + let raw = processing::engine::input_mouse_x(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, width as f32)) } pub fn mouse_y(surface: Entity, height: u32) -> PyResult { - let raw = processing::prelude::input_mouse_y(surface) + let raw = processing::engine::input_mouse_y(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, height as f32)) } pub fn pmouse_x(surface: Entity, width: u32) -> PyResult { - let raw = processing::prelude::input_pmouse_x(surface) + let raw = processing::engine::input_pmouse_x(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, width as f32)) } pub fn pmouse_y(surface: Entity, height: u32) -> PyResult { - let raw = processing::prelude::input_pmouse_y(surface) + let raw = processing::engine::input_pmouse_y(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, height as f32)) } pub fn mouse_is_pressed() -> PyResult { - processing::prelude::input_mouse_is_pressed() + processing::engine::input_mouse_is_pressed() .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn mouse_button() -> PyResult> { - processing::prelude::input_mouse_button() + processing::engine::input_mouse_button() .map(|opt| { opt.map(|b| match b { MouseButton::Left => constants::LEFT.to_string(), @@ -48,40 +48,40 @@ pub fn mouse_button() -> PyResult> { } pub fn moved_x() -> PyResult { - processing::prelude::input_moved_x().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_moved_x().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn moved_y() -> PyResult { - processing::prelude::input_moved_y().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_moved_y().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn mouse_wheel() -> PyResult { - processing::prelude::input_mouse_wheel().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_mouse_wheel().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_is_pressed() -> PyResult { - processing::prelude::input_key_is_pressed().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_key_is_pressed().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_is_down(key_code: u32) -> PyResult { let kc = u32_to_key_code(key_code)?; - processing::prelude::input_key_is_down(kc).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_key_is_down(kc).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_just_pressed(key_code: u32) -> PyResult { let kc = u32_to_key_code(key_code)?; - processing::prelude::input_key_just_pressed(kc) + processing::engine::input_key_just_pressed(kc) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key() -> PyResult> { - processing::prelude::input_key() + processing::engine::input_key() .map(|opt| opt.map(String::from)) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_code() -> PyResult> { - processing::prelude::input_key_code() + processing::engine::input_key_code() .map(|opt| opt.map(key_code_to_u32)) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index f0235caa..10a5213a 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -184,10 +184,10 @@ pub(crate) fn reset_tracked_globals() { fn sync_globals(module: &Bound<'_, PyModule>, globals: &Bound<'_, PyAny>) -> PyResult<()> { let graphics = get_graphics(module)?.ok_or_else(|| PyRuntimeError::new_err("call size() first"))?; - let width = ::processing::prelude::surface_width(graphics.surface.entity) + let width = ::processing::engine::surface_width(graphics.surface.entity) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let width = if width == 0 { graphics.width } else { width }; - let height = ::processing::prelude::surface_height(graphics.surface.entity) + let height = ::processing::engine::surface_height(graphics.surface.entity) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let height = if height == 0 { graphics.height } else { height }; input::sync_globals(globals, graphics.surface.entity, width, height)?; @@ -207,9 +207,9 @@ fn try_call(locals: &Bound<'_, PyAny>, name: &str) -> PyResult<()> { } fn dispatch_event_callbacks(locals: &Bound<'_, PyAny>) -> PyResult<()> { - use processing::prelude::*; + use processing::engine::*; let err = - |e: processing::prelude::error::ProcessingError| PyRuntimeError::new_err(format!("{e}")); + |e: processing::engine::error::ProcessingError| PyRuntimeError::new_err(format!("{e}")); if input_mouse_any_just_pressed().map_err(err)? { try_call(locals, "mouse_pressed")?; @@ -620,7 +620,7 @@ pub mod processing_py { fn load_gltf(module: &Bound<'_, PyModule>, path: &str) -> PyResult { let graphics = get_graphics(module)?.ok_or_else(|| PyRuntimeError::new_err("call size() first"))?; - let entity = ::processing::prelude::gltf_load(graphics.entity, path) + let entity = ::processing::engine::gltf_load(graphics.entity, path) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(Gltf::from_entity(entity)) } @@ -836,7 +836,7 @@ pub mod processing_py { return Ok(false); } - processing::prelude::advance_frame_count() + processing::engine::advance_frame_count() .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let windows = collect_windows(module)?; @@ -919,7 +919,7 @@ pub mod processing_py { let Some(graphics) = get_graphics(module)? else { return Ok(()); }; - ::processing::prelude::surface_resize(graphics.surface.entity, w, h) + ::processing::engine::surface_resize(graphics.surface.entity, w, h) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } @@ -1162,7 +1162,7 @@ pub mod processing_py { } first_frame = false; - processing::prelude::advance_frame_count() + processing::engine::advance_frame_count() .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; // One draw() per frame drives every window. Globals target the @@ -1511,7 +1511,7 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (mode=processing::prelude::constants::PBR_NEUTRAL))] + #[pyo3(pass_module, signature = (mode=processing::engine::constants::PBR_NEUTRAL))] fn tonemapping(module: &Bound<'_, PyModule>, mode: &str) -> PyResult<()> { graphics!(module).tonemapping(mode) } @@ -1630,7 +1630,7 @@ pub mod processing_py { }; // The GLFW window is created with the title, but the Window component // (which the per-frame sync applies) defaults otherwise — set it too. - ::processing::prelude::surface_set_title(surface_entity, title.to_string()) + ::processing::engine::surface_set_title(surface_entity, title.to_string()) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let window = Py::new( module.py(), @@ -2198,7 +2198,7 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (cx, cy, w, h, start, stop, mode=processing::prelude::constants::OPEN))] + #[pyo3(pass_module, signature = (cx, cy, w, h, start, stop, mode=processing::engine::constants::OPEN))] fn arc( module: &Bound<'_, PyModule>, cx: f32, @@ -2245,7 +2245,7 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (kind=processing::prelude::constants::POLYGON))] + #[pyo3(pass_module, signature = (kind=processing::engine::constants::POLYGON))] fn begin_shape(module: &Bound<'_, PyModule>, kind: &str) -> PyResult<()> { graphics!(module).begin_shape(kind) } @@ -2426,7 +2426,7 @@ pub mod processing_py { #[pyfunction] #[pyo3(pass_module, signature = (filename=None))] fn save_frame(module: &Bound<'_, PyModule>, filename: Option<&str>) -> PyResult<()> { - let count = ::processing::prelude::frame_count() + let count = ::processing::engine::frame_count() .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let name = match filename { Some(f) => substitute_frame_number(f, count), diff --git a/crates/processing_pyo3/src/material.rs b/crates/processing_pyo3/src/material.rs index 95cf57a9..a69224b5 100644 --- a/crates/processing_pyo3/src/material.rs +++ b/crates/processing_pyo3/src/material.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::types::{PyDict, PyInt}; use pyo3::{exceptions::PyRuntimeError, prelude::*}; diff --git a/crates/processing_pyo3/src/midi.rs b/crates/processing_pyo3/src/midi.rs index 494b5fee..fa8aa853 100644 --- a/crates/processing_pyo3/src/midi.rs +++ b/crates/processing_pyo3/src/midi.rs @@ -1,4 +1,4 @@ -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; pub fn connect(port: usize) -> PyResult<()> { diff --git a/crates/processing_pyo3/src/monitor.rs b/crates/processing_pyo3/src/monitor.rs index c4826434..24689076 100644 --- a/crates/processing_pyo3/src/monitor.rs +++ b/crates/processing_pyo3/src/monitor.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; #[pyclass(unsendable)] diff --git a/crates/processing_pyo3/src/particles.rs b/crates/processing_pyo3/src/particles.rs index 788f0d6d..bf0877ca 100644 --- a/crates/processing_pyo3/src/particles.rs +++ b/crates/processing_pyo3/src/particles.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use processing_render::geometry; use pyo3::types::{PyDict, PyTuple}; use pyo3::{ @@ -18,7 +18,7 @@ use processing_render::particles::compact::compact as compact_indices; use crate::compute::{Buffer, Compute}; use crate::graphics::{Geometry, Image}; -use processing::prelude::constants as c; +use processing::engine::constants as c; use processing_render::{ COMBINE_ADD, COMBINE_DIV, COMBINE_MAX, COMBINE_MIN, COMBINE_MUL, COMBINE_POW, COMBINE_SUB, }; diff --git a/crates/processing_pyo3/src/shader.rs b/crates/processing_pyo3/src/shader.rs index 60817010..d61422c6 100644 --- a/crates/processing_pyo3/src/shader.rs +++ b/crates/processing_pyo3/src/shader.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; #[pyclass(unsendable)] diff --git a/crates/processing_pyo3/src/surface.rs b/crates/processing_pyo3/src/surface.rs index 6aa70901..485a7bad 100644 --- a/crates/processing_pyo3/src/surface.rs +++ b/crates/processing_pyo3/src/surface.rs @@ -1,6 +1,6 @@ use bevy::prelude::Entity; use bevy::window::{MonitorSelection, WindowLevel, WindowMode}; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; use crate::glfw::GlfwContext; diff --git a/crates/processing_pyo3/src/time.rs b/crates/processing_pyo3/src/time.rs index d638a568..01ba42ea 100644 --- a/crates/processing_pyo3/src/time.rs +++ b/crates/processing_pyo3/src/time.rs @@ -1,15 +1,15 @@ use pyo3::{exceptions::PyRuntimeError, prelude::*}; pub fn frame_count() -> PyResult { - processing::prelude::frame_count().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::frame_count().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn delta_time() -> PyResult { - processing::prelude::delta_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::delta_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn elapsed_time() -> PyResult { - processing::prelude::elapsed_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::elapsed_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn sync_globals(globals: &Bound<'_, PyAny>) -> PyResult<()> { diff --git a/crates/processing_render/src/graphics.rs b/crates/processing_render/src/graphics.rs index 436546e7..9c6a852c 100644 --- a/crates/processing_render/src/graphics.rs +++ b/crates/processing_render/src/graphics.rs @@ -33,7 +33,7 @@ use crate::{ image::{Image, create_readback_buffer, pixel_size, pixels_to_bytes}, render::{ BATCH_INDEX_STEP, DrawTransients, RenderState, - command::{CommandBuffer, DrawCommand}, + command::{CommandBuffer, CommandSlot, DrawCommand}, filter, }, surface::Surface, @@ -714,7 +714,7 @@ pub fn flush(app: &mut App, entity: Entity) -> Result<()> { app.update(); let pending = graphics_mut!(app, entity) .get::() - .is_some_and(|buffer| !buffer.commands.is_empty()); + .is_some_and(|buffer| !buffer.is_empty()); if !pending { break; } @@ -726,7 +726,7 @@ pub fn flush(app: &mut App, entity: Entity) -> Result<()> { fn has_commands(app: &App, entity: Entity) -> bool { app.world() .get::(entity) - .is_some_and(|buffer| !buffer.commands.is_empty()) + .is_some_and(|buffer| !buffer.is_empty()) } /// Uploads the canvas pixels `set` wrote since the last upload @@ -1004,6 +1004,16 @@ pub fn record_command( Ok(()) } +pub fn record_command_slot( + In((graphics_entity, cmd)): In<(Entity, DrawCommand)>, + mut graphics_query: Query<&mut CommandBuffer>, +) -> Result { + let mut command_buffer = graphics_query + .get_mut(graphics_entity) + .map_err(|_| ProcessingError::GraphicsNotFound)?; + Ok(command_buffer.push_slot(graphics_entity, cmd)) +} + pub struct ReadbackData { pub bytes: Vec, pub format: TextureFormat, diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index bc8ec7e5..d54f7c04 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -762,6 +762,34 @@ pub fn graphics_record_command(graphics_entity: Entity, cmd: DrawCommand) -> err }) } +pub fn graphics_record_command_slot( + graphics_entity: Entity, + cmd: DrawCommand, +) -> error::Result { + app_mut(|app| { + app.world_mut() + .run_system_cached_with(graphics::record_command_slot, (graphics_entity, cmd)) + .unwrap() + }) +} + +pub fn graphics_amend_command( + slot: render::command::CommandSlot, + amend: impl FnOnce(&mut DrawCommand), +) -> error::Result<()> { + app_mut(|app| { + let mut buffer = app + .world_mut() + .get_mut::(slot.graphics()) + .ok_or(error::ProcessingError::GraphicsNotFound)?; + let cmd = buffer.get_mut(slot).ok_or_else(|| { + error::ProcessingError::InvalidArgument("command was already flushed".to_string()) + })?; + amend(cmd); + Ok(()) + }) +} + pub fn graphics_mode_3d(graphics_entity: Entity) -> error::Result<()> { app_mut(|app| { flush(app, graphics_entity)?; @@ -1397,7 +1425,7 @@ pub fn graphics_immediate_light( graphics_entity: Entity, kind: render::command::LightKind, transform: Transform, -) -> error::Result<()> { +) -> error::Result { app_mut(|app| { let light_entity = app .world_mut() @@ -1411,7 +1439,8 @@ pub fn graphics_immediate_light( graphics::record_command, (graphics_entity, DrawCommand::Light(light_entity)), ) - .unwrap() + .unwrap()?; + Ok(light_entity) }) } @@ -2825,10 +2854,10 @@ fn text_query_state( let state = world .get::(graphics_entity) .ok_or(error::ProcessingError::GraphicsNotFound)?; - // include text settings recorded since the last flush + // plus unflushed text settings let mut style = state.style.clone(); if let Some(buffer) = world.get::(graphics_entity) { - for cmd in &buffer.commands { + for cmd in buffer.iter() { match cmd { DrawCommand::PushStyle => style.push(), DrawCommand::PopStyle => style.pop(), diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index 7e19f613..812e36be 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -765,21 +765,68 @@ pub enum DrawCommand { #[derive(Debug, Default, Component)] pub struct CommandBuffer { - pub commands: Vec, + commands: Vec, + generation: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CommandSlot { + graphics: Entity, + index: usize, + generation: u64, +} + +impl CommandSlot { + pub fn graphics(&self) -> Entity { + self.graphics + } } impl CommandBuffer { pub fn new() -> Self { - Self { - commands: Vec::new(), - } + Self::default() } pub fn push(&mut self, cmd: DrawCommand) { self.commands.push(cmd); } + pub fn push_slot(&mut self, graphics: Entity, cmd: DrawCommand) -> CommandSlot { + self.commands.push(cmd); + CommandSlot { + graphics, + index: self.commands.len() - 1, + generation: self.generation, + } + } + + pub fn get_mut(&mut self, slot: CommandSlot) -> Option<&mut DrawCommand> { + if slot.generation != self.generation { + return None; + } + self.commands.get_mut(slot.index) + } + + pub fn is_empty(&self) -> bool { + self.commands.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.commands.iter() + } + + pub fn take(&mut self) -> Vec { + self.generation += 1; + std::mem::take(&mut self.commands) + } + + pub fn requeue(&mut self, commands: impl IntoIterator) { + self.generation += 1; + self.commands = commands.into_iter().collect(); + } + pub fn clear(&mut self) { + self.generation += 1; self.commands.clear(); } } diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index c254d1b5..bf0aec61 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -208,7 +208,7 @@ pub fn flush_draw_commands( } } - let draw_commands = std::mem::take(&mut cmd_buffer.commands); + let draw_commands = cmd_buffer.take(); let mut batch = BatchState::new(graphics_entity, render_layers.clone()); let mut pending = draw_commands.into_iter(); let mut drained = true; @@ -917,7 +917,7 @@ pub fn flush_draw_commands( } DrawCommand::BackgroundColor(color) => { if !opens_pass(&batch) { - cmd_buffer.commands = std::iter::once(cmd).chain(pending).collect(); + cmd_buffer.requeue(std::iter::once(cmd).chain(pending)); drained = false; break; } @@ -930,7 +930,7 @@ pub fn flush_draw_commands( continue; }; if !opens_pass(&batch) { - cmd_buffer.commands = std::iter::once(cmd).chain(pending).collect(); + cmd_buffer.requeue(std::iter::once(cmd).chain(pending)); drained = false; break; } diff --git a/crates/processing_render/src/render/primitive/text.rs b/crates/processing_render/src/render/primitive/text.rs index 0cd3bb30..fb8f0567 100644 --- a/crates/processing_render/src/render/primitive/text.rs +++ b/crates/processing_render/src/render/primitive/text.rs @@ -478,8 +478,7 @@ pub fn text_to_points( }) } -/// 3D extruded mesh from text outlines: front and back faces plus side walls, -/// in Bevy's Y-up convention. +/// 3D extruded mesh from text outlines: front and back faces plus side walls. pub fn text_to_model( content: &str, x: f32, @@ -615,6 +614,8 @@ pub fn text_to_model( } }); + // built y-up + crate::geometry::mirror_y(&mut mesh); mesh } diff --git a/crates/processing_wasm/src/lib.rs b/crates/processing_wasm/src/lib.rs index 3153b783..61dda412 100644 --- a/crates/processing_wasm/src/lib.rs +++ b/crates/processing_wasm/src/lib.rs @@ -5,9 +5,9 @@ use bevy::color::LinearRgba; use bevy::math::{Vec2, Vec3, Vec4}; use bevy::prelude::Entity; use bevy::render::render_resource::{Extent3d, TextureFormat}; -use processing::prelude::color::{ColorMode, ColorSpace}; -use processing::prelude::error::ProcessingError; -use processing::prelude::*; +use processing::engine::color::{ColorMode, ColorSpace}; +use processing::engine::error::ProcessingError; +use processing::engine::*; use wasm_bindgen::prelude::*; fn check(result: Result) -> Result { @@ -160,12 +160,12 @@ pub fn js_color_mode( ) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check((|| { - let space = processing::prelude::color::ColorSpace::from_u8(space).ok_or_else(|| { - processing::prelude::error::ProcessingError::InvalidArgument(format!( + let space = processing::engine::color::ColorSpace::from_u8(space).ok_or_else(|| { + processing::engine::error::ProcessingError::InvalidArgument(format!( "unknown color space: {space}" )) })?; - let mode = processing::prelude::color::ColorMode::new(space, max1, max2, max3, max_alpha); + let mode = processing::engine::color::ColorMode::new(space, max1, max2, max3, max_alpha); graphics_set_color_mode(graphics_entity, mode) })()) } @@ -233,7 +233,7 @@ pub fn js_set_stroke_cap(graphics_id: u64, cap: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::StrokeCap(processing::prelude::StrokeCapMode::from(cap)), + DrawCommand::StrokeCap(processing::engine::StrokeCapMode::from(cap)), )) } @@ -242,7 +242,7 @@ pub fn js_set_stroke_join(graphics_id: u64, join: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::StrokeJoin(processing::prelude::StrokeJoinMode::from(join)), + DrawCommand::StrokeJoin(processing::engine::StrokeJoinMode::from(join)), )) } @@ -251,7 +251,7 @@ pub fn js_rect_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::RectMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::RectMode(processing::engine::ShapeMode::from(mode)), )) } @@ -260,7 +260,7 @@ pub fn js_ellipse_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::EllipseMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::EllipseMode(processing::engine::ShapeMode::from(mode)), )) } @@ -361,7 +361,7 @@ pub fn js_shear_y(graphics_id: u64, angle: f32) -> Result<(), JsValue> { pub fn js_set_blend_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check((|| { - let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state(); + let blend_state = processing::engine::BlendMode::try_from(mode)?.to_blend_state(); graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state)) })()) } @@ -534,7 +534,7 @@ pub fn js_arc( h, start, stop, - mode: processing::prelude::ArcMode::from(mode), + mode: processing::engine::ArcMode::from(mode), }, )) } @@ -698,7 +698,7 @@ pub fn js_begin_shape(graphics_id: u64, kind: u8) -> Result<(), JsValue> { check(graphics_record_command( graphics_entity, DrawCommand::BeginShape { - kind: processing::prelude::ShapeKind::from(kind), + kind: processing::engine::ShapeKind::from(kind), }, )) } @@ -2059,7 +2059,7 @@ pub fn js_mouse_wheel() -> Result { check(input_mouse_wheel()) } -fn key_code_from_u32(val: u32) -> processing::prelude::error::Result { +fn key_code_from_u32(val: u32) -> processing::engine::error::Result { match val { PROCESSING_KEY_SPACE => Ok(KeyCode::Space), PROCESSING_KEY_QUOTE => Ok(KeyCode::Quote), diff --git a/examples/alias_spike.rs b/examples/alias_spike.rs index 8b11dbc9..d99bdd9b 100644 --- a/examples/alias_spike.rs +++ b/examples/alias_spike.rs @@ -1,4 +1,4 @@ -use processing::{Buffer, Compute, Graphics, Result, Settings, Shader, Sketch}; +use processing::prelude::*; const TWO_BINDING_SRC: &str = r#" @group(0) @binding(0) var src: array; diff --git a/examples/animated_mesh.rs b/examples/animated_mesh.rs index e32611c4..80f1c8c0 100644 --- a/examples/animated_mesh.rs +++ b/examples/animated_mesh.rs @@ -1,4 +1,4 @@ -use processing::{Geometry, Graphics, Result, Settings, Sketch, Topology}; +use processing::prelude::*; const GRID: u32 = 20; const SPACING: f32 = 10.0; diff --git a/examples/background_image.rs b/examples/background_image.rs index 21605132..658001af 100644 --- a/examples/background_image.rs +++ b/examples/background_image.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Image, Result, Settings, Sketch}; +use processing::prelude::*; struct BackgroundImage { logo: Image, diff --git a/examples/blend_modes.rs b/examples/blend_modes.rs index 632a797d..9ece9cfe 100644 --- a/examples/blend_modes.rs +++ b/examples/blend_modes.rs @@ -1,4 +1,4 @@ -use processing::{BlendMode, Graphics, Key, Result, Settings, Sketch}; +use processing::prelude::*; const MODES: [BlendMode; 10] = [ BlendMode::Blend, diff --git a/examples/box.rs b/examples/box.rs index 05616d7e..f2e08751 100644 --- a/examples/box.rs +++ b/examples/box.rs @@ -1,4 +1,4 @@ -use processing::{Geometry, Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct BoxSketch { cube: Geometry, @@ -23,7 +23,7 @@ impl Sketch for BoxSketch { g.background((0.1, 0.1, 0.15)); { - let mut g = g.push(); + let g = g.push(); g.rotate(-self.angle); g.model(&self.cube); } diff --git a/examples/camera_controllers.rs b/examples/camera_controllers.rs index 5d9e1f87..3a902631 100644 --- a/examples/camera_controllers.rs +++ b/examples/camera_controllers.rs @@ -1,4 +1,4 @@ -use processing::{Geometry, Graphics, Key, Light, Result, Settings, Sketch}; +use processing::prelude::*; struct CameraControllers { cube: Geometry, @@ -52,7 +52,7 @@ impl Sketch for CameraControllers { g.fill((1.0, 0.85, 0.57)); g.roughness(0.3); g.metallic(0.8); - let mut g = g.push(); + let g = g.push(); g.rotate(-self.angle); g.model(&self.cube); } else { diff --git a/examples/compute_readback.rs b/examples/compute_readback.rs index 8a4d4320..4d3ad42d 100644 --- a/examples/compute_readback.rs +++ b/examples/compute_readback.rs @@ -1,4 +1,4 @@ -use processing::{Buffer, Compute, Graphics, Result, Settings, Shader, Sketch}; +use processing::prelude::*; const FILL: &str = r#" @group(0) @binding(0) diff --git a/examples/create_graphics.rs b/examples/create_graphics.rs index cef3179a..28656178 100644 --- a/examples/create_graphics.rs +++ b/examples/create_graphics.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct CreateGraphics { pg: Graphics, @@ -24,12 +24,12 @@ impl Sketch for CreateGraphics { g.no_stroke(); g.ellipse(mx, my, 60, 60); - let mut pg = self.pg.begin_draw(); + let pg = self.pg.begin_draw(); pg.background(51); pg.no_fill(); pg.stroke(255); pg.ellipse(mx - 120.0, my - 60.0, 60, 60); - drop(pg); + pg.end_draw(); g.image(&self.pg, 120, 60); } diff --git a/examples/curves.rs b/examples/curves.rs index f75d68e9..04d36765 100644 --- a/examples/curves.rs +++ b/examples/curves.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct Curves { t: f32, @@ -18,7 +18,6 @@ impl Sketch for Curves { g.background((0.04, 0.04, 0.06)); g.no_fill(); - // bezier waves g.stroke_weight(1.5); for i in 0..20 { let y = 20.0 + i as f32 * 15.0; @@ -38,7 +37,6 @@ impl Sketch for Curves { ); } - // catmull-rom curves g.stroke_weight(0.8); g.stroke((1.0, 0.6, 0.2, 0.4)); for i in 0..8 { @@ -56,7 +54,6 @@ impl Sketch for Curves { ); } - // guide lines g.stroke_weight(0.3); g.stroke((1.0, 1.0, 1.0, 0.08)); for i in 0..20 { diff --git a/examples/custom_attribute.rs b/examples/custom_attribute.rs index ff097d9d..041f6085 100644 --- a/examples/custom_attribute.rs +++ b/examples/custom_attribute.rs @@ -1,6 +1,4 @@ -use processing::{ - Attribute, AttributeFormat, Geometry, Graphics, Layout, Result, Settings, Sketch, Topology, -}; +use processing::prelude::*; struct CustomAttribute { mesh: Geometry, diff --git a/examples/custom_material.rs b/examples/custom_material.rs index ad95fa88..4441c69d 100644 --- a/examples/custom_material.rs +++ b/examples/custom_material.rs @@ -1,4 +1,4 @@ -use processing::{Geometry, Graphics, Material, Result, Settings, Shader, Sketch}; +use processing::prelude::*; struct CustomMaterial { cube: Geometry, @@ -32,7 +32,7 @@ impl Sketch for CustomMaterial { g.background((0.1, 0.1, 0.15)); { - let mut g = g.push(); + let g = g.push(); g.rotate(-self.angle); g.material(&self.material); g.model(&self.cube); diff --git a/examples/filter.rs b/examples/filter.rs index 04a4c0da..152559df 100644 --- a/examples/filter.rs +++ b/examples/filter.rs @@ -1,4 +1,4 @@ -use processing::{Filter, Graphics, Result, Settings, Sketch}; +use processing::prelude::*; const FILTERS: [Filter; 8] = [ Filter::Invert, @@ -39,7 +39,6 @@ impl Sketch for Filters { let filter = FILTERS[(seconds / 2) as usize % FILTERS.len()]; g.filter(filter); - // unfiltered g.fill((0.0, 0.0, 1.0)); g.rect(160, 160, 80, 80); } diff --git a/examples/gltf_load.rs b/examples/gltf_load.rs index 5c700880..595ca5c3 100644 --- a/examples/gltf_load.rs +++ b/examples/gltf_load.rs @@ -1,4 +1,4 @@ -use processing::{Geometry, Gltf, Graphics, Light, Material, Result, Settings, Sketch}; +use processing::prelude::*; struct GltfLoad { duck: Geometry, diff --git a/examples/input.rs b/examples/input.rs index d4a52524..ea30bf08 100644 --- a/examples/input.rs +++ b/examples/input.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Key, Result, Settings, Sketch}; +use processing::prelude::*; struct Input; diff --git a/examples/lights.rs b/examples/lights.rs index e624fc68..1213d1c6 100644 --- a/examples/lights.rs +++ b/examples/lights.rs @@ -1,6 +1,4 @@ -use std::f32::consts::FRAC_PI_4; - -use processing::{Geometry, Graphics, Light, Material, Result, Settings, Sketch}; +use processing::prelude::*; struct Lights { cube: Geometry, @@ -34,7 +32,7 @@ impl Sketch for Lights { let cool = g.create_point_light((0.0, 0.5, 0.75), 2_000_000, 200, 0.25); cool.position((0.0, -5.0, 50.5)).look_at((0, 0, 0)); - let spot = g.create_spot_light((0.25, 0.8, 0.19), 15_000_000, 200, 0.84, 0, FRAC_PI_4); + let spot = g.create_spot_light((0.25, 0.8, 0.19), 15_000_000, 200, 0.84, 0, QUARTER_PI); spot.position((40, 0, 70)).look_at((0, 0, 0)); Ok(Lights { @@ -59,7 +57,7 @@ impl Sketch for Lights { g.material(&self.shiny); { - let mut g = g.push(); + let g = g.push(); g.rotate(-self.angle); g.model(&self.cube); } diff --git a/examples/materials.rs b/examples/materials.rs index f35064a3..6f38559d 100644 --- a/examples/materials.rs +++ b/examples/materials.rs @@ -1,4 +1,4 @@ -use processing::{Color, Geometry, Graphics, Light, Material, Result, Settings, Sketch}; +use processing::prelude::*; const COLS: usize = 11; const ROWS: usize = 5; @@ -26,7 +26,6 @@ impl Sketch for Materials { let lamp = g.create_point_light(Color::WHITE, 100_000, 800, 0); lamp.position((200, -200, 400)); - // roughness across, metallic down let mut materials = Vec::new(); for row in 0..ROWS { for col in 0..COLS { @@ -56,7 +55,7 @@ impl Sketch for Materials { let offset_y = (ROWS - 1) as f32 * SPACING / 2.0; for row in 0..ROWS { for col in 0..COLS { - let mut g = g.push(); + let g = g.push(); g.translate(( col as f32 * SPACING - offset_x, offset_y - row as f32 * SPACING, diff --git a/examples/midi.rs b/examples/midi.rs index 18638b95..510f61f4 100644 --- a/examples/midi.rs +++ b/examples/midi.rs @@ -1,4 +1,4 @@ -use processing::{Color, Graphics, Key, Result, Settings, Sketch, midi}; +use processing::prelude::*; const PENTATONIC: [u8; 5] = [0, 3, 5, 7, 10]; const ROOT: u8 = 48; diff --git a/examples/particles_animated.rs b/examples/particles_animated.rs index 614564f4..29e50945 100644 --- a/examples/particles_animated.rs +++ b/examples/particles_animated.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, - Sketch, -}; +use processing::prelude::*; const SPIN_SHADER: &str = r#" struct Params { @@ -50,13 +47,15 @@ impl Sketch for ParticlesAnimated { let sphere = Geometry::sphere(0.25, 12, 8)?; let capacity: u32 = 1000; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + let mut positions: Vec = Vec::with_capacity(capacity as usize); for x in 0..10 { for y in 0..10 { for z in 0..10 { - positions.push((x as f32 - 4.5) * 1.0); - positions.push((y as f32 - 4.5) * 1.0); - positions.push((z as f32 - 4.5) * 1.0); + positions.push(Vec3::new( + (x as f32 - 4.5) * 1.0, + (y as f32 - 4.5) * 1.0, + (z as f32 - 4.5) * 1.0, + )); } } } diff --git a/examples/particles_basic.rs b/examples/particles_basic.rs index 9f901945..f1d9b98f 100644 --- a/examples/particles_basic.rs +++ b/examples/particles_basic.rs @@ -1,6 +1,4 @@ -use processing::{ - Attribute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, -}; +use processing::prelude::*; struct ParticlesBasic { sun: Light, @@ -24,13 +22,11 @@ impl Sketch for ParticlesBasic { let sphere = Geometry::sphere(0.25, 12, 8)?; let capacity: u32 = 1000; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); + let mut positions: Vec = Vec::with_capacity(capacity as usize); for x in 0..10 { for y in 0..10 { for z in 0..10 { - positions.push(x as f32 - 4.5); - positions.push(y as f32 - 4.5); - positions.push(z as f32 - 4.5); + positions.push(Vec3::new(x as f32 - 4.5, y as f32 - 4.5, z as f32 - 4.5)); } } } diff --git a/examples/particles_colored.rs b/examples/particles_colored.rs index 3e392bbc..50a5e7f7 100644 --- a/examples/particles_colored.rs +++ b/examples/particles_colored.rs @@ -1,4 +1,4 @@ -use processing::{Attribute, Geometry, Graphics, Material, Particles, Result, Settings, Sketch}; +use processing::prelude::*; struct ParticlesColored { sphere: Geometry, @@ -19,18 +19,13 @@ impl Sketch for ParticlesColored { let sphere = Geometry::sphere(0.25, 12, 8)?; let capacity: u32 = 1000; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut colors: Vec = Vec::with_capacity(capacity as usize); for x in 0..10 { for y in 0..10 { for z in 0..10 { - positions.push(x as f32 - 4.5); - positions.push(4.5 - y as f32); - positions.push(z as f32 - 4.5); - colors.push(x as f32 / 9.0); - colors.push(y as f32 / 9.0); - colors.push(z as f32 / 9.0); - colors.push(1.0); + positions.push(Vec3::new(x as f32 - 4.5, 4.5 - y as f32, z as f32 - 4.5)); + colors.push(Color::rgb(x as f32 / 9.0, y as f32 / 9.0, z as f32 / 9.0)); } } } diff --git a/examples/particles_colored_pbr.rs b/examples/particles_colored_pbr.rs index e6deff85..f7664118 100644 --- a/examples/particles_colored_pbr.rs +++ b/examples/particles_colored_pbr.rs @@ -1,6 +1,4 @@ -use processing::{ - Attribute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, -}; +use processing::prelude::*; struct ParticlesColoredPbr { sun: Light, @@ -24,18 +22,17 @@ impl Sketch for ParticlesColoredPbr { let sphere = Geometry::sphere(0.3, 16, 12)?; let capacity: u32 = 512; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut colors: Vec = Vec::with_capacity(capacity as usize); for x in 0..8 { for y in 0..8 { for z in 0..8 { - positions.push((x as f32 - 3.5) * 1.4); - positions.push((3.5 - y as f32) * 1.4); - positions.push((z as f32 - 3.5) * 1.4); - colors.push(x as f32 / 7.0); - colors.push(y as f32 / 7.0); - colors.push(z as f32 / 7.0); - colors.push(1.0); + positions.push(Vec3::new( + (x as f32 - 3.5) * 1.4, + (3.5 - y as f32) * 1.4, + (z as f32 - 3.5) * 1.4, + )); + colors.push(Color::rgb(x as f32 / 7.0, y as f32 / 7.0, z as f32 / 7.0)); } } } diff --git a/examples/particles_emit.rs b/examples/particles_emit.rs index 63972535..928085f1 100644 --- a/examples/particles_emit.rs +++ b/examples/particles_emit.rs @@ -1,4 +1,4 @@ -use processing::{Attribute, Geometry, Graphics, Material, Particles, Result, Settings, Sketch}; +use processing::prelude::*; struct ParticlesEmit { sphere: Geometry, @@ -23,7 +23,7 @@ impl Sketch for ParticlesEmit { let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; // offscreen until emitted - let far_away: Vec = vec![1.0e6; capacity as usize * 3]; + let far_away = vec![Vec3::splat(1.0e6); capacity as usize]; particles.buffer(Attribute::position()).write(&far_away); let mut material = Material::unlit()?; @@ -43,22 +43,16 @@ impl Sketch for ParticlesEmit { g.particles(&self.particles).geometry(&self.sphere); let burst = 4u32; - let mut positions: Vec = Vec::with_capacity(burst as usize * 3); - let mut colors: Vec = Vec::with_capacity(burst as usize * 4); + let mut positions: Vec = Vec::with_capacity(burst as usize); + let mut colors: Vec = Vec::with_capacity(burst as usize); for k in 0..burst { let i = self.frame * burst + k; let t = i as f32 * 0.05; let radius = 1.5 + (t * 0.02).min(3.0); let height = -(t * 0.1).sin() * 2.0; - positions.push(t.cos() * radius); - positions.push(height); - positions.push(t.sin() * radius); + positions.push(Vec3::new(t.cos() * radius, height, t.sin() * radius)); let h = (i as f32 * 0.012) % 1.0; - let (r, g, b) = hsv_to_rgb(h, 0.85, 1.0); - colors.push(r); - colors.push(g); - colors.push(b); - colors.push(1.0); + colors.push(Color::hsv(h * 360.0, 0.85, 1.0)); } self.particles.emit( @@ -72,22 +66,6 @@ impl Sketch for ParticlesEmit { } } -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32) % 6 { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } -} - fn main() -> Result<()> { processing::run::() } diff --git a/examples/particles_emit_gpu.rs b/examples/particles_emit_gpu.rs index 0298ff0d..a78033d7 100644 --- a/examples/particles_emit_gpu.rs +++ b/examples/particles_emit_gpu.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, - Sketch, -}; +use processing::prelude::*; const SPAWN_SHADER: &str = r#" struct Spawn { diff --git a/examples/particles_from_mesh.rs b/examples/particles_from_mesh.rs index 836659f2..733839f7 100644 --- a/examples/particles_from_mesh.rs +++ b/examples/particles_from_mesh.rs @@ -1,6 +1,4 @@ -use processing::{ - Attribute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, -}; +use processing::prelude::*; struct ParticlesFromMesh { sun: Light, @@ -27,15 +25,10 @@ impl Sketch for ParticlesFromMesh { &[Attribute::position(), Attribute::uv(), Attribute::color()], )?; - // hue from u - let uvs = particles.buffer(Attribute::uv()).read::()?; - let mut colors: Vec = Vec::with_capacity(uvs.len() * 2); - for uv in uvs.chunks_exact(2) { - let (r, g, b) = hsv_to_rgb(uv[0], 0.85, 1.0); - colors.push(r); - colors.push(g); - colors.push(b); - colors.push(1.0); + let uvs = particles.buffer(Attribute::uv()).read::()?; + let mut colors: Vec = Vec::with_capacity(uvs.len()); + for uv in &uvs { + colors.push(Color::hsv(uv.x * 360.0, 0.85, 1.0)); } let mut color_buf = particles.buffer(Attribute::color()); color_buf.write(&colors); @@ -60,22 +53,6 @@ impl Sketch for ParticlesFromMesh { } } -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32).rem_euclid(6) { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } -} - fn main() -> Result<()> { processing::run::() } diff --git a/examples/particles_lifecycle.rs b/examples/particles_lifecycle.rs index 0087156d..8a66c006 100644 --- a/examples/particles_lifecycle.rs +++ b/examples/particles_lifecycle.rs @@ -1,6 +1,4 @@ -use processing::{ - Attribute, Compute, Geometry, Graphics, Material, Particles, Result, Settings, Shader, Sketch, -}; +use processing::prelude::*; const AGING_SHADER: &str = r#" @group(0) @binding(0) var age: array; @@ -93,29 +91,21 @@ impl Sketch for ParticlesLifecycle { g.material(&self.mat); g.particles(&self.particles).geometry(&self.sphere); - let mut positions: Vec = Vec::with_capacity(BURST as usize * 3); - let mut colors: Vec = Vec::with_capacity(BURST as usize * 4); - let mut scales: Vec = Vec::with_capacity(BURST as usize * 3); + let mut positions: Vec = Vec::with_capacity(BURST as usize); + let mut colors: Vec = Vec::with_capacity(BURST as usize); + let mut scales: Vec = Vec::with_capacity(BURST as usize); let mut ages: Vec = Vec::with_capacity(BURST as usize); let mut lives: Vec = Vec::with_capacity(BURST as usize); for k in 0..BURST { let i = self.frame * BURST + k; let u = ((i.wrapping_mul(2654435761) >> 8) & 0xFFFF) as f32 / 65535.0; let v = ((i.wrapping_mul(40503) >> 8) & 0xFFFF) as f32 / 65535.0; - let theta = u * std::f32::consts::TAU; + let theta = u * TAU; let r = v * 0.6; - positions.push(theta.cos() * r); - positions.push(-2.5); - positions.push(theta.sin() * r); + positions.push(Vec3::new(theta.cos() * r, -2.5, theta.sin() * r)); let h = (i as f32 * 0.013) % 1.0; - let (cr, cg, cb) = hsv_to_rgb(h, 0.85, 1.0); - colors.push(cr); - colors.push(cg); - colors.push(cb); - colors.push(1.0); - scales.push(1.0); - scales.push(1.0); - scales.push(1.0); + colors.push(Color::hsv(h * 360.0, 0.85, 1.0)); + scales.push(Vec3::new(1.0, 1.0, 1.0)); ages.push(0.0); lives.push(1.0); } @@ -140,19 +130,3 @@ impl Sketch for ParticlesLifecycle { fn main() -> Result<()> { processing::run::() } - -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32) % 6 { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } -} diff --git a/examples/particles_noise.rs b/examples/particles_noise.rs index d5321f50..6e89f1da 100644 --- a/examples/particles_noise.rs +++ b/examples/particles_noise.rs @@ -1,6 +1,4 @@ -use processing::{ - Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Sketch, -}; +use processing::prelude::*; struct ParticlesNoise { sun: Light, @@ -28,15 +26,10 @@ impl Sketch for ParticlesNoise { &[Attribute::position(), Attribute::uv(), Attribute::color()], )?; - // hue from u - let uvs = particles.buffer(Attribute::uv()).read::()?; - let mut colors: Vec = Vec::with_capacity(uvs.len() * 2); - for uv in uvs.chunks_exact(2) { - let (r, g, b) = hsv_to_rgb(uv[0], 0.85, 1.0); - colors.push(r); - colors.push(g); - colors.push(b); - colors.push(1.0); + let uvs = particles.buffer(Attribute::uv()).read::()?; + let mut colors: Vec = Vec::with_capacity(uvs.len()); + for uv in &uvs { + colors.push(Color::hsv(uv.x * 360.0, 0.85, 1.0)); } let mut color_buf = particles.buffer(Attribute::color()); color_buf.write(&colors); @@ -70,22 +63,6 @@ impl Sketch for ParticlesNoise { } } -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32).rem_euclid(6) { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } -} - fn main() -> Result<()> { processing::run::() } diff --git a/examples/particles_oriented.rs b/examples/particles_oriented.rs index 28a231cf..3d553fb6 100644 --- a/examples/particles_oriented.rs +++ b/examples/particles_oriented.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, - Sketch, -}; +use processing::prelude::*; const SPIN_SHADER: &str = r#" @group(0) @binding(0) var rotation: array; @@ -61,23 +58,20 @@ impl Sketch for ParticlesOriented { let cube = Geometry::cube((0.6, 0.6, 0.6))?; let capacity: u32 = 125; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut rotations: Vec = Vec::with_capacity(capacity as usize * 4); - let mut scales: Vec = Vec::with_capacity(capacity as usize * 3); + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut rotations: Vec = Vec::with_capacity(capacity as usize); + let mut scales: Vec = Vec::with_capacity(capacity as usize); for x in 0..5 { for y in 0..5 { for z in 0..5 { - positions.push((x as f32 - 2.0) * 1.6); - positions.push((2.0 - y as f32) * 1.6); - positions.push((z as f32 - 2.0) * 1.6); - rotations.push(0.0); - rotations.push(0.0); - rotations.push(0.0); - rotations.push(1.0); + positions.push(Vec3::new( + (x as f32 - 2.0) * 1.6, + (2.0 - y as f32) * 1.6, + (z as f32 - 2.0) * 1.6, + )); + rotations.push(Vec4::new(0.0, 0.0, 0.0, 1.0)); let s = 0.5 + ((x + y + z) as f32 * 0.06); - scales.push(s); - scales.push(s); - scales.push(s); + scales.push(Vec3::new(s, s, s)); } } } diff --git a/examples/particles_scatter.rs b/examples/particles_scatter.rs index 6debecd9..16d517f0 100644 --- a/examples/particles_scatter.rs +++ b/examples/particles_scatter.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, AttributeFormat, Compute, Geometry, Graphics, Light, Material, Particles, Result, - Settings, Shader, Sketch, -}; +use processing::prelude::*; const AGE_SHADER: &str = r#" struct Params { dt: f32, ttl: f32, _pad0: f32, _pad1: f32 } diff --git a/examples/particles_scatter_volume.rs b/examples/particles_scatter_volume.rs index 01196997..59a13755 100644 --- a/examples/particles_scatter_volume.rs +++ b/examples/particles_scatter_volume.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, AttributeFormat, Compute, Geometry, Gltf, Graphics, Material, Particles, Result, - Settings, Shader, Sketch, -}; +use processing::prelude::*; const AGE_SHADER: &str = r#" struct Params { dt: f32, ttl: f32, _pad0: f32, _pad1: f32 } diff --git a/examples/particles_stress.rs b/examples/particles_stress.rs index 5e39a5a3..bad2a8fc 100644 --- a/examples/particles_stress.rs +++ b/examples/particles_stress.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, Compute, Geometry, Graphics, Light, Material, Particles, Result, Settings, Shader, - Sketch, -}; +use processing::prelude::*; const GRID: u32 = 100; // GRID^3 particles const SPACING: f32 = 1.0; @@ -77,20 +74,19 @@ impl Sketch for ParticlesStress { let capacity = GRID * GRID * GRID; let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut colors: Vec = Vec::with_capacity(capacity as usize); let extent_half = (GRID as f32) * SPACING * 0.5; for i in 0..capacity { let rx = hash_unit(i.wrapping_mul(2654435761).wrapping_add(0x9E37)); let ry = hash_unit(i.wrapping_mul(40503).wrapping_add(0x68E1)); let rz = hash_unit(i.wrapping_mul(2246822519).wrapping_add(0xC2B2)); - positions.push((rx * 2.0 - 1.0) * extent_half); - positions.push((1.0 - ry * 2.0) * extent_half); - positions.push((rz * 2.0 - 1.0) * extent_half); - colors.push(rx); - colors.push(ry); - colors.push(rz); - colors.push(1.0); + positions.push(Vec3::new( + (rx * 2.0 - 1.0) * extent_half, + (1.0 - ry * 2.0) * extent_half, + (rz * 2.0 - 1.0) * extent_half, + )); + colors.push(Color::rgb(rx, ry, rz)); } particles.buffer(Attribute::position()).write(&positions); let mut color_buf = particles.buffer(Attribute::color()); diff --git a/examples/particles_text_whirl.rs b/examples/particles_text_whirl.rs index b0ab51b3..943f459e 100644 --- a/examples/particles_text_whirl.rs +++ b/examples/particles_text_whirl.rs @@ -1,7 +1,4 @@ -use processing::{ - Attribute, Buffer, Compute, Geometry, Graphics, Material, Particles, Result, Settings, Shader, - Sketch, TextStyle, -}; +use processing::prelude::*; const BASE_COUNT: u32 = 6000; const TRAIL_LEN_MIN: u32 = 8; diff --git a/examples/pbr.rs b/examples/pbr.rs index 072f953e..6aa32a47 100644 --- a/examples/pbr.rs +++ b/examples/pbr.rs @@ -1,4 +1,4 @@ -use processing::{Color, Graphics, Light, Result, Settings, Sketch}; +use processing::prelude::*; const COLS: u32 = 11; const ROWS: u32 = 5; @@ -40,7 +40,7 @@ impl Sketch for Pbr { g.roughness(col as f32 / (COLS - 1) as f32); g.metallic(row as f32 / (ROWS - 1) as f32); - let mut g = g.push(); + let g = g.push(); g.translate(( col as f32 * SPACING - offset_x, offset_y - row as f32 * SPACING, diff --git a/examples/primitives_2d.rs b/examples/primitives_2d.rs index 1e82face..770c33df 100644 --- a/examples/primitives_2d.rs +++ b/examples/primitives_2d.rs @@ -1,6 +1,4 @@ -use std::f32::consts::PI; - -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct Primitives2d { t: f32, @@ -21,7 +19,6 @@ impl Sketch for Primitives2d { let cy = 300.0; g.background((0.95, 0.93, 0.9)); - // concentric arcs g.no_fill(); g.stroke_weight(2); for i in 0..12 { @@ -32,7 +29,6 @@ impl Sketch for Primitives2d { g.arc(cx, cy, r * 2.0, r * 2.0, start, start + PI * 1.2); } - // dots riding the arcs g.no_stroke(); for i in 0..12 { let r = 40.0 + i as f32 * 18.0; @@ -41,7 +37,6 @@ impl Sketch for Primitives2d { g.circle(cx + r * angle.cos(), cy + r * angle.sin(), 6); } - // orbiting triangles g.fill((0.1, 0.1, 0.1, 0.15)); for i in 0..6 { let angle = t * 0.5 + i as f32 * PI / 3.0; @@ -58,7 +53,6 @@ impl Sketch for Primitives2d { ); } - // pulsing diamond let d = 15.0 + 5.0 * (t * 3.0).sin(); g.fill((0.9, 0.4, 0.1, 0.4)); g.quad(cx, cy - d, cx + d, cy, cx, cy + d, cx - d, cy); diff --git a/examples/primitives_3d.rs b/examples/primitives_3d.rs index 21b147e1..1954666c 100644 --- a/examples/primitives_3d.rs +++ b/examples/primitives_3d.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct Primitives3d { t: f32, @@ -23,7 +23,7 @@ impl Sketch for Primitives3d { g.roughness(0.35); for i in 0..8 { - let mut g = g.push(); + let g = g.push(); g.translate((-315 + i * 90, 0)); g.rotate(-self.t); match i { diff --git a/examples/rectangle.rs b/examples/rectangle.rs index bde06d36..f7db5b28 100644 --- a/examples/rectangle.rs +++ b/examples/rectangle.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct Rectangle; diff --git a/examples/shapes.rs b/examples/shapes.rs index b16742eb..3fc56292 100644 --- a/examples/shapes.rs +++ b/examples/shapes.rs @@ -1,6 +1,4 @@ -use std::f32::consts::PI; - -use processing::{Graphics, Result, Settings, ShapeKind, Sketch}; +use processing::prelude::*; struct Shapes { t: f32, @@ -19,12 +17,11 @@ impl Sketch for Shapes { let t = self.t; g.background((235, 230, 222)); - // a wobbling blob made of curve vertices g.fill((0.2, 0.3, 0.5, 0.25)); g.stroke_weight(1.5); g.stroke((38, 51, 89)); let n = 8; - let mut blob = g.begin_shape(ShapeKind::Polygon); + let blob = g.begin_shape(ShapeKind::Polygon); for i in 0..n + 3 { let idx = (i + n - 1) % n; let angle = idx as f32 * 2.0 * PI / n as f32; @@ -33,23 +30,21 @@ impl Sketch for Shapes { } blob.close(); - // a pulsing lens made of two bezier segments g.fill((0.15, 0.5, 0.3, 0.2)); g.stroke_weight(1); g.stroke((26, 89, 51)); let cx = 430.0; let cy = 200.0; let s = 70.0 + 10.0 * (t * 1.5).sin(); - let mut lens = g.begin_shape(ShapeKind::Polygon); + let lens = g.begin_shape(ShapeKind::Polygon); lens.vertex(cx, cy - s); lens.bezier_vertex(cx + s, cy - s, cx + s, cy + s, cx, cy + s); lens.bezier_vertex(cx - s, cy + s, cx - s, cy - s, cx, cy - s); lens.close(); - // a flower as a triangle fan g.fill((0.8, 0.35, 0.1, 0.15)); g.no_stroke(); - let mut fan = g.begin_shape(ShapeKind::TriangleFan); + let fan = g.begin_shape(ShapeKind::TriangleFan); fan.vertex(170, 450); for i in 0..=16 { let angle = i as f32 * 2.0 * PI / 16.0; @@ -58,11 +53,10 @@ impl Sketch for Shapes { } fan.close(); - // a wave as a triangle strip g.fill((0.5, 0.2, 0.6, 0.2)); g.stroke_weight(0.5); g.stroke((77, 26, 102, 102)); - let mut strip = g.begin_shape(ShapeKind::TriangleStrip); + let strip = g.begin_shape(ShapeKind::TriangleStrip); for i in 0..16 { let x = 320.0 + i as f32 * 17.0; let wave = 30.0 * (t * 2.0 + i as f32 * 0.4).sin(); diff --git a/examples/stroke_2d.rs b/examples/stroke_2d.rs index 43c4c395..49ae49d1 100644 --- a/examples/stroke_2d.rs +++ b/examples/stroke_2d.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch, StrokeJoin}; +use processing::prelude::*; struct Stroke2d; diff --git a/examples/stroke_3d.rs b/examples/stroke_3d.rs index a368b802..00998327 100644 --- a/examples/stroke_3d.rs +++ b/examples/stroke_3d.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct Stroke3d { angle: f32, @@ -23,7 +23,7 @@ impl Sketch for Stroke3d { // thin wireframe box { - let mut g = g.push(); + let g = g.push(); g.translate((-80, 0)); g.rotate(-angle); g.fill((0.3, 0.4, 0.7)); @@ -34,7 +34,7 @@ impl Sketch for Stroke3d { // thick wireframe box { - let mut g = g.push(); + let g = g.push(); g.rotate(-angle * 0.7); g.fill((0.7, 0.3, 0.4)); g.stroke((1.0, 0.9, 0.2)); @@ -44,7 +44,7 @@ impl Sketch for Stroke3d { // thick wireframe sphere { - let mut g = g.push(); + let g = g.push(); g.translate((80, 0)); g.rotate(-angle * 0.5); g.fill((0.3, 0.7, 0.4)); @@ -55,7 +55,7 @@ impl Sketch for Stroke3d { // wireframe-only sphere { - let mut g = g.push(); + let g = g.push(); g.translate((160, 0)); g.rotate(angle * 0.3); g.no_fill(); diff --git a/examples/text.rs b/examples/text.rs index 4364b48f..61b04293 100644 --- a/examples/text.rs +++ b/examples/text.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch, TextAlignH, TextAlignV}; +use processing::prelude::*; struct Text; diff --git a/examples/text_3d.rs b/examples/text_3d.rs index af3cfda3..24fdff4c 100644 --- a/examples/text_3d.rs +++ b/examples/text_3d.rs @@ -1,4 +1,4 @@ -use processing::{Geometry, Graphics, Light, Material, Result, Settings, Sketch, TextStyle}; +use processing::prelude::*; struct Text3d { word: Geometry, @@ -45,8 +45,8 @@ impl Sketch for Text3d { g.material(&self.glow); { - let mut g = g.push(); - g.scale((15, 15)); + let g = g.push(); + g.scale((1.5, 1.5)); g.rotate(-self.t * 0.3); g.model(&self.word); } diff --git a/examples/transforms.rs b/examples/transforms.rs index 010c662d..766b7d22 100644 --- a/examples/transforms.rs +++ b/examples/transforms.rs @@ -1,6 +1,4 @@ -use std::f32::consts::PI; - -use processing::{Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct Transforms { t: f32, @@ -20,7 +18,7 @@ impl Sketch for Transforms { for i in 0..4 { for j in 0..4 { - let mut g = g.push(); + let g = g.push(); g.translate((50 + j * 100, 50 + i * 100)); g.rotate(self.t + (i + j) as f32 * PI / 8.0); g.scale(0.8 + (self.t * 2.0 + (i * j) as f32).sin() * 0.2); diff --git a/examples/update_pixels.rs b/examples/update_pixels.rs index b332be7e..9cb726f3 100644 --- a/examples/update_pixels.rs +++ b/examples/update_pixels.rs @@ -1,4 +1,4 @@ -use processing::{Color, Graphics, Result, Settings, Sketch}; +use processing::prelude::*; struct UpdatePixels { first_frame: bool, @@ -28,7 +28,7 @@ impl Sketch for UpdatePixels { } } -fn print_pixels(g: &Graphics) { +fn print_pixels(g: &mut Graphics) { let pixels = g.pixels().unwrap(); let width = g.pixel_width() as usize; eprintln!("Total pixels: {}", pixels.len()); diff --git a/examples/webcam.rs b/examples/webcam.rs index fc881296..ad6ce100 100644 --- a/examples/webcam.rs +++ b/examples/webcam.rs @@ -1,4 +1,4 @@ -use processing::{Graphics, Result, Settings, Sketch, Webcam}; +use processing::prelude::*; struct WebcamSketch { camera: Webcam, diff --git a/src/draw.rs b/src/draw.rs index 36c1b7a8..c7b08b3f 100644 --- a/src/draw.rs +++ b/src/draw.rs @@ -1,329 +1,303 @@ -//! Draw-on-drop builders. - +use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; -use bevy::prelude::{Entity, Transform, Vec3}; +use bevy::prelude::{Entity, Transform}; use processing_render::geometry::Topology; -use processing_render::graphics_immediate_light; -use processing_render::render::command::{ArcMode, DrawCommand, LightKind}; +use processing_render::render::command::{ArcMode, CommandSlot, DrawCommand, LightKind}; +use processing_render::{graphics_immediate_light, transform_look_at, transform_set_position}; use crate::graphics::expect; use crate::{Geometry, Graphics, IntoPoint, Scalar}; pub struct Rect<'g> { - g: &'g mut Graphics, - rect: [f32; 4], - radii: [f32; 4], + g: &'g Graphics, + slot: CommandSlot, } impl<'g> Rect<'g> { - pub(crate) fn new(g: &'g mut Graphics, x: f32, y: f32, w: f32, h: f32) -> Self { - Self { - g, - rect: [x, y, w, h], + pub(crate) fn new(g: &'g Graphics, x: f32, y: f32, w: f32, h: f32) -> Self { + let slot = g.record_slot(DrawCommand::Rect { + x, + y, + w, + h, radii: [0.0; 4], - } + }); + Self { g, slot } } - pub fn radius(mut self, r: impl Scalar) -> Self { - self.radii = [r.to_f32(); 4]; - self + pub fn radius(self, r: impl Scalar) -> Self { + self.set_radii([r.to_f32(); 4]) } /// Top-left, top-right, bottom-right, bottom-left. - pub fn radii( - mut self, - tl: impl Scalar, - tr: impl Scalar, - br: impl Scalar, - bl: impl Scalar, - ) -> Self { - self.radii = [tl.to_f32(), tr.to_f32(), br.to_f32(), bl.to_f32()]; - self + pub fn radii(self, tl: impl Scalar, tr: impl Scalar, br: impl Scalar, bl: impl Scalar) -> Self { + self.set_radii([tl.to_f32(), tr.to_f32(), br.to_f32(), bl.to_f32()]) } -} -impl Drop for Rect<'_> { - fn drop(&mut self) { - let [x, y, w, h] = self.rect; - self.g.record(DrawCommand::Rect { - x, - y, - w, - h, - radii: self.radii, + fn set_radii(self, value: [f32; 4]) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Rect { radii, .. } = cmd else { + unreachable!() + }; + *radii = value; }); + self } } pub struct Arc<'g> { - g: &'g mut Graphics, - bounds: [f32; 4], - start: f32, - stop: f32, - mode: ArcMode, + g: &'g Graphics, + slot: CommandSlot, } impl<'g> Arc<'g> { - pub(crate) fn new(g: &'g mut Graphics, bounds: [f32; 4], start: f32, stop: f32) -> Self { - Self { - g, - bounds, + pub(crate) fn new(g: &'g Graphics, bounds: [f32; 4], start: f32, stop: f32) -> Self { + let [cx, cy, w, h] = bounds; + let slot = g.record_slot(DrawCommand::Arc { + cx, + cy, + w, + h, start, stop, mode: ArcMode::default(), - } - } - - pub fn mode(mut self, mode: ArcMode) -> Self { - self.mode = mode; - self + }); + Self { g, slot } } -} -impl Drop for Arc<'_> { - fn drop(&mut self) { - let [cx, cy, w, h] = self.bounds; - self.g.record(DrawCommand::Arc { - cx, - cy, - w, - h, - start: self.start, - stop: self.stop, - mode: self.mode, + pub fn mode(self, value: ArcMode) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Arc { mode, .. } = cmd else { + unreachable!() + }; + *mode = value; }); + self } } pub struct LightDraw<'g> { - g: &'g mut Graphics, - kind: LightKind, - transform: Transform, + light: Entity, + _g: PhantomData<&'g Graphics>, } impl<'g> LightDraw<'g> { - pub(crate) fn new(g: &'g mut Graphics, kind: LightKind) -> Self { - Self { - g, + pub(crate) fn new(g: &'g Graphics, kind: LightKind) -> Self { + let light = expect(graphics_immediate_light( + g.entity, kind, - transform: Transform::default(), + Transform::default(), + )); + Self { + light, + _g: PhantomData, } } - pub fn position(mut self, position: impl IntoPoint) -> Self { - self.transform.translation = position.into_point(); + pub fn position(self, position: impl IntoPoint) -> Self { + expect(transform_set_position(self.light, position.into_point())); self } - pub fn look_at(mut self, target: impl IntoPoint) -> Self { - self.transform.look_at(target.into_point(), Vec3::Y); + pub fn look_at(self, target: impl IntoPoint) -> Self { + expect(transform_look_at(self.light, target.into_point())); self } } -impl Drop for LightDraw<'_> { - fn drop(&mut self) { - expect(graphics_immediate_light( - self.g.entity, - self.kind, - self.transform, - )); - } -} - pub struct ParticlesDraw<'g> { - g: &'g mut Graphics, - particles: Entity, - geometry: Option, - topology: Topology, + g: &'g Graphics, + slot: CommandSlot, } impl<'g> ParticlesDraw<'g> { - pub(crate) fn new(g: &'g mut Graphics, particles: Entity) -> Self { - Self { - g, + pub(crate) fn new(g: &'g Graphics, particles: Entity) -> Self { + let slot = g.record_slot(DrawCommand::Particles { particles, geometry: None, topology: Topology::PointList, - } + }); + Self { g, slot } } - pub fn geometry(mut self, geometry: &Geometry) -> Self { - self.geometry = Some(geometry.0); + pub fn geometry(self, value: &Geometry) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Particles { geometry, .. } = cmd else { + unreachable!() + }; + *geometry = Some(value.0); + }); self } - pub fn topology(mut self, topology: Topology) -> Self { - self.topology = topology; - self - } -} - -impl Drop for ParticlesDraw<'_> { - fn drop(&mut self) { - self.g.record(DrawCommand::Particles { - particles: self.particles, - geometry: self.geometry, - topology: self.topology, + pub fn topology(self, value: Topology) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Particles { topology, .. } = cmd else { + unreachable!() + }; + *topology = value; }); + self } } pub struct ImageDraw<'g> { - g: &'g mut Graphics, - entity: Entity, - x: f32, - y: f32, - size: Option<[f32; 2]>, - source: Option<[f32; 4]>, + g: &'g Graphics, + slot: CommandSlot, } impl<'g> ImageDraw<'g> { - pub(crate) fn new(g: &'g mut Graphics, entity: Entity, x: f32, y: f32) -> Self { - Self { - g, + pub(crate) fn new(g: &'g Graphics, entity: Entity, x: f32, y: f32) -> Self { + let slot = g.record_slot(DrawCommand::Image { entity, - x, - y, - size: None, - source: None, - } - } - - pub fn size(mut self, w: impl Scalar, h: impl Scalar) -> Self { - self.size = Some([w.to_f32(), h.to_f32()]); + dx: x, + dy: y, + d_width: None, + d_height: None, + sx: None, + sy: None, + s_width: None, + s_height: None, + }); + Self { g, slot } + } + + pub fn size(self, w: impl Scalar, h: impl Scalar) -> Self { + let (w, h) = (w.to_f32(), h.to_f32()); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Image { + d_width, d_height, .. + } = cmd + else { + unreachable!() + }; + *d_width = Some(w); + *d_height = Some(h); + }); self } /// Pixel region of the image. - pub fn source( - mut self, - x: impl Scalar, - y: impl Scalar, - w: impl Scalar, - h: impl Scalar, - ) -> Self { - self.source = Some([x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()]); - self - } -} - -impl Drop for ImageDraw<'_> { - fn drop(&mut self) { - let size = self.size.map(|[w, h]| (w, h)); - let source = self.source.map(|[x, y, w, h]| (x, y, w, h)); - self.g.record(DrawCommand::Image { - entity: self.entity, - dx: self.x, - dy: self.y, - d_width: size.map(|s| s.0), - d_height: size.map(|s| s.1), - sx: source.map(|s| s.0), - sy: source.map(|s| s.1), - s_width: source.map(|s| s.2), - s_height: source.map(|s| s.3), + pub fn source(self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) -> Self { + let (x, y, w, h) = (x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Image { + sx, + sy, + s_width, + s_height, + .. + } = cmd + else { + unreachable!() + }; + *sx = Some(x); + *sy = Some(y); + *s_width = Some(w); + *s_height = Some(h); }); + self } } pub struct Text<'g> { - g: &'g mut Graphics, - content: String, - x: f32, - y: f32, - z: f32, - max_w: Option, - max_h: Option, + g: &'g Graphics, + slot: CommandSlot, } impl<'g> Text<'g> { - pub(crate) fn new(g: &'g mut Graphics, content: String, x: f32, y: f32) -> Self { - Self { - g, + pub(crate) fn new(g: &'g Graphics, content: String, x: f32, y: f32) -> Self { + let slot = g.record_slot(DrawCommand::Text { content, x, y, z: 0.0, max_w: None, max_h: None, - } - } - - pub fn z(mut self, z: impl Scalar) -> Self { - self.z = z.to_f32(); - self + }); + Self { g, slot } } - pub fn max_width(mut self, w: impl Scalar) -> Self { - self.max_w = Some(w.to_f32()); + pub fn z(self, value: impl Scalar) -> Self { + let value = value.to_f32(); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Text { z, .. } = cmd else { + unreachable!() + }; + *z = value; + }); self } - pub fn bounds(mut self, w: impl Scalar, h: impl Scalar) -> Self { - self.max_w = Some(w.to_f32()); - self.max_h = Some(h.to_f32()); + pub fn max_width(self, w: impl Scalar) -> Self { + let w = w.to_f32(); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Text { max_w, .. } = cmd else { + unreachable!() + }; + *max_w = Some(w); + }); self } -} -impl Drop for Text<'_> { - fn drop(&mut self) { - self.g.record(DrawCommand::Text { - content: std::mem::take(&mut self.content), - x: self.x, - y: self.y, - z: self.z, - max_w: self.max_w, - max_h: self.max_h, + pub fn bounds(self, w: impl Scalar, h: impl Scalar) -> Self { + let (w, h) = (w.to_f32(), h.to_f32()); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Text { max_w, max_h, .. } = cmd else { + unreachable!() + }; + *max_w = Some(w); + *max_h = Some(h); }); + self } } pub struct Detail<'g, const N: usize> { - g: &'g mut Graphics, + g: &'g Graphics, + slot: CommandSlot, size: [f32; 3], - detail: [u32; N], build: fn([f32; 3], [u32; N]) -> DrawCommand, } impl<'g, const N: usize> Detail<'g, N> { pub(crate) fn new( - g: &'g mut Graphics, + g: &'g Graphics, size: [f32; 3], detail: [u32; N], build: fn([f32; 3], [u32; N]) -> DrawCommand, ) -> Self { + let slot = g.record_slot(build(size, detail)); Self { g, + slot, size, - detail, build, } } -} -impl Detail<'_, 1> { - pub fn detail(mut self, segments: u32) -> Self { - self.detail = [segments]; + fn set_detail(self, detail: [u32; N]) -> Self { + let rebuilt = (self.build)(self.size, detail); + self.g.amend(self.slot, |cmd| *cmd = rebuilt); self } } -impl Detail<'_, 2> { - pub fn detail(mut self, a: u32, b: u32) -> Self { - self.detail = [a, b]; - self +impl Detail<'_, 1> { + pub fn detail(self, segments: u32) -> Self { + self.set_detail([segments]) } } -impl Drop for Detail<'_, N> { - fn drop(&mut self) { - self.g.record((self.build)(self.size, self.detail)); +impl Detail<'_, 2> { + pub fn detail(self, a: u32, b: u32) -> Self { + self.set_detail([a, b]) } } /// Pops when dropped. +#[must_use] pub struct Push<'g> { g: &'g mut Graphics, } @@ -332,6 +306,8 @@ impl<'g> Push<'g> { pub(crate) fn new(g: &'g mut Graphics) -> Self { Self { g } } + + pub fn pop(self) {} } impl Deref for Push<'_> { @@ -356,6 +332,7 @@ impl Drop for Push<'_> { } /// Ends drawing when dropped. +#[must_use] pub struct BeginDraw<'g> { g: &'g mut Graphics, } @@ -364,6 +341,8 @@ impl<'g> BeginDraw<'g> { pub(crate) fn new(g: &'g mut Graphics) -> Self { Self { g } } + + pub fn end_draw(self) {} } impl Deref for BeginDraw<'_> { diff --git a/src/engine.rs b/src/engine.rs new file mode 100644 index 00000000..cf6287f8 --- /dev/null +++ b/src/engine.rs @@ -0,0 +1,21 @@ +pub use bevy::input::keyboard::KeyCode; +pub use bevy::input::mouse::MouseButton; +pub use bevy::prelude::default; +pub use bevy::render::render_resource::TextureFormat; +pub use processing_core::{config::*, constants, error}; +pub use processing_input::*; +#[cfg(not(target_arch = "wasm32"))] +pub use processing_midi::{ + midi_connect, midi_disconnect, midi_list_ports, midi_note_off, midi_note_on, midi_play_notes, + midi_refresh_ports, +}; +pub use processing_render::{ + render::command::{ + ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, + StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, custom_blend_state, + }, + render::filter::Filter, + *, +}; + +pub use crate::{exit, init}; diff --git a/src/graphics.rs b/src/graphics.rs index c08fe684..36d799b4 100644 --- a/src/graphics.rs +++ b/src/graphics.rs @@ -1,3 +1,4 @@ +use std::cell::{Cell, RefCell}; use std::fmt::Display; use bevy::math::{Affine3A, Vec3, Vec4}; @@ -9,21 +10,23 @@ use processing_input::{ input_mouse_is_pressed, input_mouse_wheel, input_mouse_x, input_mouse_y, input_moved_x, input_moved_y, input_pmouse_x, input_pmouse_y, }; +use processing_render::color::ColorMode; use processing_render::render::command::{ - BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, StrokeJoinMode, - TextAlignH, TextAlignV, TextStyle, TextWrapMode, + BlendMode, CommandSlot, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, + StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, }; use processing_render::{ camera_reset, camera_set_center, camera_set_distance, delta_time, elapsed_time, frame_count, - geometry_create_from_mesh, graphics_apply_filter, graphics_begin_draw, graphics_create, - graphics_destroy, graphics_disable_camera_controller, graphics_end_draw, graphics_flush, - graphics_free_camera, graphics_get_matrix, graphics_light, graphics_mode_2d, graphics_mode_3d, - graphics_orbit_camera, graphics_ortho, graphics_pan_camera, graphics_perspective, - graphics_readback, graphics_record_command, graphics_screen_point, graphics_set_color_mode, - graphics_text_ascent, graphics_text_descent, graphics_text_to_model, graphics_text_width, - graphics_update, graphics_update_region, light_create_directional, light_create_point, - light_create_spot, light_destroy, surface_create_offscreen, surface_destroy, - surface_physical_height, surface_physical_width, transform_look_at, transform_set_position, + geometry_create_from_mesh, graphics_amend_command, graphics_apply_filter, graphics_begin_draw, + graphics_create, graphics_destroy, graphics_disable_camera_controller, graphics_end_draw, + graphics_flush, graphics_free_camera, graphics_get_matrix, graphics_light, graphics_mode_2d, + graphics_mode_3d, graphics_orbit_camera, graphics_ortho, graphics_pan_camera, + graphics_perspective, graphics_readback, graphics_record_command, graphics_record_command_slot, + graphics_screen_point, graphics_set_color_mode, graphics_text_ascent, graphics_text_descent, + graphics_text_to_model, graphics_text_width, graphics_update, graphics_update_region, + light_create_directional, light_create_point, light_create_spot, light_destroy, + surface_create_offscreen, surface_destroy, surface_physical_height, surface_physical_width, + transform_look_at, transform_set_position, }; use crate::color::{ColorArg, ColorSpace, ColorState, IntoColorMax}; @@ -43,10 +46,10 @@ pub struct Graphics { pub(crate) surface: Entity, width: u32, height: u32, - color: ColorState, - style_stack: Vec, + color: Cell, + style_stack: RefCell>, offscreen: bool, - exit_requested: bool, + exit_requested: Cell, } impl Graphics { @@ -56,10 +59,10 @@ impl Graphics { surface, width, height, - color: ColorState::default(), - style_stack: Vec::new(), + color: Cell::new(ColorState::default()), + style_stack: RefCell::new(Vec::new()), offscreen: false, - exit_requested: false, + exit_requested: Cell::new(false), } } @@ -76,18 +79,26 @@ impl Graphics { pub fn begin_draw(&mut self) -> BeginDraw<'_> { assert!( self.offscreen, - "processing: begin_draw is for Graphics::create surfaces; the sketch window is drawn every frame" + "processing: begin_draw needs a Graphics::create surface" ); self.begin_frame(); BeginDraw::new(self) } - pub(crate) fn record(&mut self, cmd: DrawCommand) { + pub(crate) fn record(&self, cmd: DrawCommand) { expect(graphics_record_command(self.entity, cmd)); } + pub(crate) fn record_slot(&self, cmd: DrawCommand) -> CommandSlot { + expect(graphics_record_command_slot(self.entity, cmd)) + } + + pub(crate) fn amend(&self, slot: CommandSlot, amend: impl FnOnce(&mut DrawCommand)) { + expect(graphics_amend_command(slot, amend)); + } + pub(crate) fn begin_frame(&mut self) { - self.style_stack.clear(); + self.style_stack.get_mut().clear(); expect(graphics_begin_draw(self.entity)); } @@ -96,7 +107,7 @@ impl Graphics { } pub(crate) fn resolve(&self, color: impl Into) -> bevy::color::Color { - self.color.resolve(color.into()).0 + self.color.get().resolve(color.into()).0 } pub fn width(&self) -> f32 { @@ -142,106 +153,100 @@ impl Graphics { (expect(elapsed_time()) * 1000.0) as u32 } - pub fn exit(&mut self) { - self.exit_requested = true; + pub fn exit(&self) { + self.exit_requested.set(true); } pub(crate) fn exit_requested(&self) -> bool { - self.exit_requested + self.exit_requested.get() } - pub fn color_mode(&mut self, space: ColorSpace) -> ColorModeBuilder<'_> { - ColorModeBuilder { - g: self, - space, - max: None, - } + pub fn color_mode(&self, space: ColorSpace) -> ColorModeBuilder<'_> { + self.set_color_state(ColorState { + mode: ColorMode::with_defaults(space), + explicit_max: false, + }); + ColorModeBuilder { g: self, space } } pub fn color(&self, color: impl Into) -> Color { - self.color.resolve(color.into()) + self.color.get().resolve(color.into()) } - pub fn background(&mut self, color: impl Into) { + pub fn background(&self, color: impl Into) { let c = self.resolve(color); self.record(DrawCommand::BackgroundColor(c)); } - pub fn background_image(&mut self, image: &impl AsImage) { + pub fn background_image(&self, image: &impl AsImage) { self.record(DrawCommand::BackgroundImage(image.image_entity())); } - pub fn fill(&mut self, color: impl Into) { + pub fn fill(&self, color: impl Into) { let c = self.resolve(color); self.record(DrawCommand::Fill(c)); } - pub fn no_fill(&mut self) { + pub fn no_fill(&self) { self.record(DrawCommand::NoFill); } - pub fn stroke(&mut self, color: impl Into) { + pub fn stroke(&self, color: impl Into) { let c = self.resolve(color); self.record(DrawCommand::StrokeColor(c)); } - pub fn no_stroke(&mut self) { + pub fn no_stroke(&self) { self.record(DrawCommand::NoStroke); } - pub fn stroke_weight(&mut self, weight: impl Scalar) { + pub fn stroke_weight(&self, weight: impl Scalar) { self.record(DrawCommand::StrokeWeight(weight.to_f32())); } - pub fn stroke_cap(&mut self, cap: StrokeCapMode) { + pub fn stroke_cap(&self, cap: StrokeCapMode) { self.record(DrawCommand::StrokeCap(cap)); } - pub fn stroke_join(&mut self, join: StrokeJoinMode) { + pub fn stroke_join(&self, join: StrokeJoinMode) { self.record(DrawCommand::StrokeJoin(join)); } - pub fn tint(&mut self, color: impl Into) { + pub fn tint(&self, color: impl Into) { let c = self.resolve(color); self.record(DrawCommand::Tint(c)); } - pub fn no_tint(&mut self) { + pub fn no_tint(&self) { self.record(DrawCommand::NoTint); } - pub fn blend_mode(&mut self, mode: BlendMode) { + pub fn blend_mode(&self, mode: BlendMode) { self.record(DrawCommand::BlendMode(mode.to_blend_state())); } - pub fn rect_mode(&mut self, mode: ShapeMode) { + pub fn rect_mode(&self, mode: ShapeMode) { self.record(DrawCommand::RectMode(mode)); } - pub fn ellipse_mode(&mut self, mode: ShapeMode) { + pub fn ellipse_mode(&self, mode: ShapeMode) { self.record(DrawCommand::EllipseMode(mode)); } - pub fn image_mode(&mut self, mode: ShapeMode) { + pub fn image_mode(&self, mode: ShapeMode) { self.record(DrawCommand::ImageMode(mode)); } - pub fn rect( - &mut self, - x: impl Scalar, - y: impl Scalar, - w: impl Scalar, - h: impl Scalar, - ) -> Rect<'_> { + pub fn rect(&self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) -> Rect<'_> { Rect::new(self, x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()) } - pub fn square(&mut self, x: impl Scalar, y: impl Scalar, size: impl Scalar) -> Rect<'_> { + pub fn square(&self, x: impl Scalar, y: impl Scalar, size: impl Scalar) -> Rect<'_> { let s = size.to_f32(); Rect::new(self, x.to_f32(), y.to_f32(), s, s) } - pub fn ellipse(&mut self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) { + pub fn ellipse(&self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) { self.record(DrawCommand::Ellipse { cx: x.to_f32(), cy: y.to_f32(), @@ -250,13 +255,13 @@ impl Graphics { }); } - pub fn circle(&mut self, x: impl Scalar, y: impl Scalar, diameter: impl Scalar) { + pub fn circle(&self, x: impl Scalar, y: impl Scalar, diameter: impl Scalar) { let d = diameter.to_f32(); self.ellipse(x, y, d, d); } pub fn arc( - &mut self, + &self, x: impl Scalar, y: impl Scalar, w: impl Scalar, @@ -272,7 +277,7 @@ impl Graphics { ) } - pub fn line(&mut self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, y2: impl Scalar) { + pub fn line(&self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, y2: impl Scalar) { self.record(DrawCommand::Line { x1: x1.to_f32(), y1: y1.to_f32(), @@ -281,7 +286,7 @@ impl Graphics { }); } - pub fn point(&mut self, x: impl Scalar, y: impl Scalar) { + pub fn point(&self, x: impl Scalar, y: impl Scalar) { self.record(DrawCommand::Point { x: x.to_f32(), y: y.to_f32(), @@ -289,7 +294,7 @@ impl Graphics { } pub fn triangle( - &mut self, + &self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, @@ -308,7 +313,7 @@ impl Graphics { } pub fn quad( - &mut self, + &self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, @@ -331,7 +336,7 @@ impl Graphics { } pub fn bezier( - &mut self, + &self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, @@ -354,7 +359,7 @@ impl Graphics { } pub fn curve( - &mut self, + &self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, @@ -380,36 +385,36 @@ impl Graphics { Shape::new(self, kind) } - pub fn image(&mut self, image: &impl AsImage, x: impl Scalar, y: impl Scalar) -> ImageDraw<'_> { + pub fn image(&self, image: &impl AsImage, x: impl Scalar, y: impl Scalar) -> ImageDraw<'_> { ImageDraw::new(self, image.image_entity(), x.to_f32(), y.to_f32()) } - pub fn text(&mut self, content: impl Display, x: impl Scalar, y: impl Scalar) -> Text<'_> { + pub fn text(&self, content: impl Display, x: impl Scalar, y: impl Scalar) -> Text<'_> { Text::new(self, content.to_string(), x.to_f32(), y.to_f32()) } - pub fn text_font(&mut self, font: Font) { + pub fn text_font(&self, font: Font) { self.record(DrawCommand::TextFont(Some(font.0))); } - pub fn text_size(&mut self, size: impl Scalar) { + pub fn text_size(&self, size: impl Scalar) { self.record(DrawCommand::TextSize(size.to_f32())); } - pub fn text_leading(&mut self, leading: impl Scalar) { + pub fn text_leading(&self, leading: impl Scalar) { self.record(DrawCommand::TextLeading(leading.to_f32())); } - pub fn text_align(&mut self, align: impl Into) { + pub fn text_align(&self, align: impl Into) { let TextAlign(h, v) = align.into(); self.record(DrawCommand::TextAlign { h, v }); } - pub fn text_style(&mut self, style: TextStyle) { + pub fn text_style(&self, style: TextStyle) { self.record(DrawCommand::TextStyle(style)); } - pub fn text_wrap(&mut self, mode: TextWrapMode) { + pub fn text_wrap(&self, mode: TextWrapMode) { self.record(DrawCommand::TextWrap(mode)); } @@ -431,82 +436,83 @@ impl Graphics { Push::new(self) } - pub fn push_matrix(&mut self) { + pub fn push_matrix(&self) { self.record(DrawCommand::PushMatrix); } - pub fn pop_matrix(&mut self) { + pub fn pop_matrix(&self) { self.record(DrawCommand::PopMatrix); } - pub fn push_style(&mut self) { - self.style_stack.push(self.color); + pub fn push_style(&self) { + self.style_stack.borrow_mut().push(self.color.get()); self.record(DrawCommand::PushStyle); } - pub fn pop_style(&mut self) { - if let Some(color) = self.style_stack.pop() { + pub fn pop_style(&self) { + let color = self.style_stack.borrow_mut().pop(); + if let Some(color) = color { self.set_color_state(color); } self.record(DrawCommand::PopStyle); } - pub fn translate(&mut self, offset: impl IntoPoint) { + pub fn translate(&self, offset: impl IntoPoint) { self.record(DrawCommand::Translate(offset.into_point())); } - pub fn rotate(&mut self, angle: impl Scalar) { + pub fn rotate(&self, angle: impl Scalar) { self.rotate_axis(angle, Vec3::Z); } - pub fn rotate_x(&mut self, angle: impl Scalar) { + pub fn rotate_x(&self, angle: impl Scalar) { self.rotate_axis(angle, Vec3::X); } - pub fn rotate_y(&mut self, angle: impl Scalar) { + pub fn rotate_y(&self, angle: impl Scalar) { self.rotate_axis(angle, Vec3::Y); } - pub fn rotate_z(&mut self, angle: impl Scalar) { + pub fn rotate_z(&self, angle: impl Scalar) { self.rotate_axis(angle, Vec3::Z); } - pub fn rotate_axis(&mut self, angle: impl Scalar, axis: impl IntoPoint) { + pub fn rotate_axis(&self, angle: impl Scalar, axis: impl IntoPoint) { self.record(DrawCommand::Rotate { angle: angle.to_f32(), axis: axis.into_point(), }); } - pub fn scale(&mut self, factor: impl IntoExtent) { + pub fn scale(&self, factor: impl IntoExtent) { self.record(DrawCommand::Scale(factor.into_extent())); } - pub fn shear_x(&mut self, angle: impl Scalar) { + pub fn shear_x(&self, angle: impl Scalar) { self.record(DrawCommand::ShearX { angle: angle.to_f32(), }); } - pub fn shear_y(&mut self, angle: impl Scalar) { + pub fn shear_y(&self, angle: impl Scalar) { self.record(DrawCommand::ShearY { angle: angle.to_f32(), }); } - pub fn reset_matrix(&mut self) { + pub fn reset_matrix(&self) { self.record(DrawCommand::ResetMatrix); } - pub fn apply_matrix(&mut self, matrix: Affine3A) { + pub fn apply_matrix(&self, matrix: Affine3A) { self.record(DrawCommand::ApplyMatrix(matrix)); } - pub fn matrix(&self) -> bevy::math::Mat4 { + pub fn matrix(&mut self) -> bevy::math::Mat4 { expect(graphics_get_matrix(self.entity)) } - pub fn screen_point(&self, point: impl IntoPoint) -> Vec3 { + pub fn screen_point(&mut self, point: impl IntoPoint) -> Vec3 { expect(graphics_screen_point(self.entity, point.into_point())) } @@ -518,7 +524,7 @@ impl Graphics { expect(graphics_mode_2d(self.entity)); } - pub fn cube(&mut self, size: impl IntoExtent) { + pub fn cube(&self, size: impl IntoExtent) { let s = size.into_extent(); self.record(DrawCommand::Box { width: s.x, @@ -527,7 +533,7 @@ impl Graphics { }); } - pub fn sphere(&mut self, radius: impl Scalar) -> Detail<'_, 2> { + pub fn sphere(&self, radius: impl Scalar) -> Detail<'_, 2> { Detail::new( self, [radius.to_f32(), 0.0, 0.0], @@ -540,7 +546,7 @@ impl Graphics { ) } - pub fn cylinder(&mut self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { + pub fn cylinder(&self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { let size = [radius.to_f32(), height.to_f32(), 0.0]; Detail::new(self, size, [24], |[radius, height, _], [detail]| { DrawCommand::Cylinder { @@ -551,7 +557,7 @@ impl Graphics { }) } - pub fn cone(&mut self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { + pub fn cone(&self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { let size = [radius.to_f32(), height.to_f32(), 0.0]; Detail::new(self, size, [24], |[radius, height, _], [detail]| { DrawCommand::Cone { @@ -562,7 +568,7 @@ impl Graphics { }) } - pub fn torus(&mut self, radius: impl Scalar, tube_radius: impl Scalar) -> Detail<'_, 2> { + pub fn torus(&self, radius: impl Scalar, tube_radius: impl Scalar) -> Detail<'_, 2> { let size = [radius.to_f32(), tube_radius.to_f32(), 0.0]; Detail::new( self, @@ -577,7 +583,7 @@ impl Graphics { ) } - pub fn capsule(&mut self, radius: impl Scalar, length: impl Scalar) -> Detail<'_, 1> { + pub fn capsule(&self, radius: impl Scalar, length: impl Scalar) -> Detail<'_, 1> { let size = [radius.to_f32(), length.to_f32(), 0.0]; Detail::new(self, size, [16], |[radius, length, _], [detail]| { DrawCommand::Capsule { @@ -589,7 +595,7 @@ impl Graphics { } pub fn conical_frustum( - &mut self, + &self, radius_top: impl Scalar, radius_bottom: impl Scalar, height: impl Scalar, @@ -608,49 +614,49 @@ impl Graphics { ) } - pub fn plane(&mut self, width: impl Scalar, height: impl Scalar) { + pub fn plane(&self, width: impl Scalar, height: impl Scalar) { self.record(DrawCommand::Plane { width: width.to_f32(), height: height.to_f32(), }); } - pub fn tetrahedron(&mut self, radius: impl Scalar) { + pub fn tetrahedron(&self, radius: impl Scalar) { self.record(DrawCommand::Tetrahedron { radius: radius.to_f32(), }); } - pub fn roughness(&mut self, value: impl Scalar) { + pub fn roughness(&self, value: impl Scalar) { self.record(DrawCommand::Roughness(value.to_f32())); } - pub fn metallic(&mut self, value: impl Scalar) { + pub fn metallic(&self, value: impl Scalar) { self.record(DrawCommand::Metallic(value.to_f32())); } - pub fn emissive(&mut self, color: impl Into) { + pub fn emissive(&self, color: impl Into) { let c = self.resolve(color); self.record(DrawCommand::Emissive(c)); } - pub fn unlit(&mut self) { + pub fn unlit(&self) { self.record(DrawCommand::Unlit); } - pub fn texture(&mut self, image: &impl AsImage) { + pub fn texture(&self, image: &impl AsImage) { self.record(DrawCommand::Texture(image.image_entity())); } - pub fn no_texture(&mut self) { + pub fn no_texture(&self) { self.record(DrawCommand::NoTexture); } - pub fn camera_position(&mut self, eye: impl IntoPoint) { + pub fn camera_position(&self, eye: impl IntoPoint) { expect(transform_set_position(self.entity, eye.into_point())); } - pub fn camera_look_at(&mut self, target: impl IntoPoint) { + pub fn camera_look_at(&self, target: impl IntoPoint) { expect(transform_look_at(self.entity, target.into_point())); } @@ -692,40 +698,40 @@ impl Graphics { )); } - pub fn orbit_camera(&mut self) { + pub fn orbit_camera(&self) { expect(graphics_orbit_camera(self.entity)); } - pub fn free_camera(&mut self) { + pub fn free_camera(&self) { expect(graphics_free_camera(self.entity)); } - pub fn pan_camera(&mut self) { + pub fn pan_camera(&self) { expect(graphics_pan_camera(self.entity)); } - pub fn disable_camera(&mut self) { + pub fn disable_camera(&self) { expect(graphics_disable_camera_controller(self.entity)); } - pub fn camera_distance(&mut self, distance: impl Scalar) { + pub fn camera_distance(&self, distance: impl Scalar) { expect(camera_set_distance(self.entity, distance.to_f32())); } - pub fn camera_center(&mut self, center: impl IntoPoint) { + pub fn camera_center(&self, center: impl IntoPoint) { expect(camera_set_center(self.entity, center.into_point())); } - pub fn camera_reset(&mut self) { + pub fn camera_reset(&self) { expect(camera_reset(self.entity)); } - pub fn light(&mut self, light: &Light) { + pub fn light(&self, light: &Light) { expect(graphics_light(self.entity, light.0)); } pub fn directional_light( - &mut self, + &self, color: impl Into, illuminance: impl Scalar, ) -> LightDraw<'_> { @@ -740,7 +746,7 @@ impl Graphics { } pub fn point_light( - &mut self, + &self, color: impl Into, intensity: impl Scalar, range: impl Scalar, @@ -759,7 +765,7 @@ impl Graphics { } pub fn spot_light( - &mut self, + &self, color: impl Into, intensity: impl Scalar, range: impl Scalar, @@ -782,7 +788,7 @@ impl Graphics { } pub fn create_directional_light( - &mut self, + &self, color: impl Into, illuminance: impl Scalar, ) -> Light { @@ -795,7 +801,7 @@ impl Graphics { } pub fn create_point_light( - &mut self, + &self, color: impl Into, intensity: impl Scalar, range: impl Scalar, @@ -812,7 +818,7 @@ impl Graphics { } pub fn create_spot_light( - &mut self, + &self, color: impl Into, intensity: impl Scalar, range: impl Scalar, @@ -832,21 +838,21 @@ impl Graphics { ))) } - pub fn model(&mut self, geometry: &Geometry) { + pub fn model(&self, geometry: &Geometry) { self.record(DrawCommand::Geometry(geometry.0)); } - pub fn material(&mut self, material: &Material) { + pub fn material(&self, material: &Material) { self.record(DrawCommand::Material(material.0)); } /// One color per particle. - pub fn fill_buffer(&mut self, buffer: &Buffer) { + pub fn fill_buffer(&self, buffer: &Buffer) { self.record(DrawCommand::FillBuffer(buffer.entity)); } /// Points unless given a geometry. - pub fn particles(&mut self, particles: &Particles) -> ParticlesDraw<'_> { + pub fn particles(&self, particles: &Particles) -> ParticlesDraw<'_> { ParticlesDraw::new(self, particles.0) } @@ -868,7 +874,7 @@ impl Graphics { } /// Row-major. - pub fn pixels(&self) -> Result> { + pub fn pixels(&mut self) -> Result> { Ok(graphics_readback(self.entity)? .into_iter() .map(Color::from_linear) @@ -884,15 +890,15 @@ impl Graphics { pub fn set_pixels_region( &mut self, - x: u32, - y: u32, + x: i32, + y: i32, w: u32, h: u32, pixels: &[Color], ) -> Result<()> { let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); graphics_flush(self.entity)?; - graphics_update_region(self.entity, x, y, w, h, &linear) + graphics_update_region(self.entity, x.into(), y.into(), w, h, &linear) } pub fn mouse_x(&self) -> f32 { @@ -951,8 +957,8 @@ impl Graphics { expect(input_key_just_pressed(key.code())) } - fn set_color_state(&mut self, color: ColorState) { - self.color = color; + fn set_color_state(&self, color: ColorState) { + self.color.set(color); expect(graphics_set_color_mode(self.entity, color.mode)); } } @@ -977,36 +983,22 @@ impl Drop for Graphics { } pub struct ColorModeBuilder<'g> { - g: &'g mut Graphics, + g: &'g Graphics, space: ColorSpace, - max: Option<[f32; 4]>, } impl ColorModeBuilder<'_> { /// `max(255)`, `max((360, 100, 100))` or `max((360, 100, 100, 1))`. - pub fn max(mut self, max: impl IntoColorMax) -> Self { - self.max = Some(max.into_color_max(self.space)); + pub fn max(self, max: impl IntoColorMax) -> Self { + let [m1, m2, m3, ma] = max.into_color_max(self.space); + self.g.set_color_state(ColorState { + mode: ColorMode::new(self.space, m1, m2, m3, ma), + explicit_max: true, + }); self } } -impl Drop for ColorModeBuilder<'_> { - fn drop(&mut self) { - use processing_render::color::ColorMode; - let state = match self.max { - Some([m1, m2, m3, ma]) => ColorState { - mode: ColorMode::new(self.space, m1, m2, m3, ma), - explicit_max: true, - }, - None => ColorState { - mode: ColorMode::with_defaults(self.space), - explicit_max: false, - }, - }; - self.g.set_color_state(state); - } -} - #[derive(Debug, Clone, Copy)] pub struct TextAlign(TextAlignH, TextAlignV); diff --git a/src/lib.rs b/src/lib.rs index 56803ccc..f078abaa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +pub mod engine; +#[cfg(not(target_arch = "wasm32"))] pub mod prelude; #[cfg(not(target_arch = "wasm32"))] @@ -44,13 +46,19 @@ pub use crate::{ graphics::{ColorModeBuilder, Graphics, Light, TextAlign}, image::{AsImage, Font, Image}, input::{Key, MouseButton}, - particles::Particles, + particles::{BufferData, Particles}, shader::{Buffer, BufferElement, Compute, IntoShaderValue, Material, Shader}, shape::{Contour, Shape}, sketch::{Settings, Sketch, run}, }; pub use bevy::math::{Affine3A, Mat4, Vec2, Vec3, Vec4}; -pub use processing_core::error::{ProcessingError as Error, Result}; +pub use std::f32::consts::{PI, TAU}; +pub const HALF_PI: f32 = std::f32::consts::FRAC_PI_2; +pub const QUARTER_PI: f32 = std::f32::consts::FRAC_PI_4; +pub const TWO_PI: f32 = TAU; +pub use processing_core::error::ProcessingError as Error; + +pub type Result = std::result::Result; pub use processing_render::geometry::{AttributeFormat, Topology}; pub use processing_render::render::command::{ ArcMode, BlendMode, ShapeKind, ShapeMode, StrokeCapMode as StrokeCap, diff --git a/src/particles.rs b/src/particles.rs index 4ee3b50b..a4c57618 100644 --- a/src/particles.rs +++ b/src/particles.rs @@ -1,5 +1,6 @@ use bevy::prelude::Entity; -use processing_core::error::Result; +use processing_core::error::{ProcessingError, Result}; +use processing_render::geometry_attribute_info; use processing_render::particles::{ particles_apply, particles_capacity, particles_create, particles_create_from_geometry, particles_destroy, particles_emit, particles_emit_gpu, particles_ensure_attribute, @@ -12,7 +13,71 @@ use processing_render::particles::{ }; use crate::graphics::expect; -use crate::{Attribute, Buffer, Compute, Geometry}; +use crate::{Attribute, Buffer, BufferElement, Compute, Geometry}; + +/// A slice or `Vec` of [`BufferElement`]s. +pub trait BufferData { + #[doc(hidden)] + fn bytes(&self) -> Vec; + #[doc(hidden)] + fn element(&self) -> ElementInfo; +} + +#[doc(hidden)] +pub struct ElementInfo { + name: &'static str, + float: bool, + components: usize, +} + +impl ElementInfo { + fn of() -> Self { + Self { + name: std::any::type_name::(), + float: T::FLOAT, + components: T::COMPONENTS, + } + } +} + +impl BufferData for [T] { + fn bytes(&self) -> Vec { + T::to_bytes(self) + } + fn element(&self) -> ElementInfo { + ElementInfo::of::() + } +} + +impl BufferData for Vec { + fn bytes(&self) -> Vec { + T::to_bytes(self) + } + fn element(&self) -> ElementInfo { + ElementInfo::of::() + } +} + +impl BufferData for [T; N] { + fn bytes(&self) -> Vec { + T::to_bytes(self) + } + fn element(&self) -> ElementInfo { + ElementInfo::of::() + } +} + +fn check_element(attribute: &Attribute, element: &ElementInfo) -> Result<()> { + let (name, format) = geometry_attribute_info(attribute.0)?; + let components = format as usize; + if element.float && (element.components == 1 || element.components == components) { + return Ok(()); + } + Err(ProcessingError::InvalidArgument(format!( + "can't write {} to {format:?} attribute `{name}`", + element.name + ))) +} #[derive(Debug)] pub struct Particles(pub(crate) Entity); @@ -42,11 +107,12 @@ impl Particles { } /// Replaces the oldest when full. - pub fn emit(&mut self, count: u32, values: &[(Attribute, &[f32])]) { - let data = values - .iter() - .map(|(attribute, v)| (attribute.0, bytemuck::cast_slice(v).to_vec())) - .collect(); + pub fn emit(&mut self, count: u32, values: &[(Attribute, &dyn BufferData)]) { + let mut data = Vec::with_capacity(values.len()); + for (attribute, v) in values { + expect(check_element(attribute, &v.element())); + data.push((attribute.0, v.bytes())); + } expect(particles_emit(self.0, count, data)); } diff --git a/src/prelude.rs b/src/prelude.rs index cf6287f8..55e69108 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,21 +1,9 @@ -pub use bevy::input::keyboard::KeyCode; -pub use bevy::input::mouse::MouseButton; -pub use bevy::prelude::default; -pub use bevy::render::render_resource::TextureFormat; -pub use processing_core::{config::*, constants, error}; -pub use processing_input::*; -#[cfg(not(target_arch = "wasm32"))] -pub use processing_midi::{ - midi_connect, midi_disconnect, midi_list_ports, midi_note_off, midi_note_on, midi_play_notes, - midi_refresh_ports, +#[cfg(feature = "webcam")] +pub use crate::Webcam; +pub use crate::{ + ArcMode, Attribute, AttributeFormat, BlendMode, Buffer, Color, ColorSpace, Compute, Filter, + Font, Geometry, Gltf, Graphics, HALF_PI, Image, Key, Layout, Light, Mat4, Material, + MouseButton, PI, Particles, QUARTER_PI, Result, Settings, Shader, ShapeKind, ShapeMode, Sketch, + StrokeCap, StrokeJoin, TAU, TWO_PI, TextAlignH, TextAlignV, TextStyle, TextWrapMode, Topology, + Vec2, Vec3, Vec4, midi, }; -pub use processing_render::{ - render::command::{ - ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, - StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, custom_blend_state, - }, - render::filter::Filter, - *, -}; - -pub use crate::{exit, init}; diff --git a/src/shader.rs b/src/shader.rs index 6e835c89..0a64bf76 100644 --- a/src/shader.rs +++ b/src/shader.rs @@ -1,3 +1,4 @@ +use bevy::color::{ColorToComponents, LinearRgba}; use bevy::math::{Mat4, Vec2, Vec3, Vec4}; use bevy::prelude::Entity; use processing_core::error::Result; @@ -10,8 +11,8 @@ use processing_render::{ shader_create, shader_destroy, shader_load, }; -use crate::AsImage; use crate::graphics::expect; +use crate::{AsImage, Color}; /// WGSL or WESL. #[derive(Debug)] @@ -87,7 +88,7 @@ impl Buffer { } pub fn from_slice(data: &[T]) -> Result { - buffer_create_with_data(bytemuck::cast_slice(data).to_vec()).map(Self::owned) + buffer_create_with_data(T::to_bytes(data)).map(Self::owned) } fn owned(entity: Entity) -> Self { @@ -111,15 +112,11 @@ impl Buffer { } pub fn write(&mut self, data: &[T]) { - expect(buffer_write( - self.entity, - bytemuck::cast_slice(data).to_vec(), - )); + expect(buffer_write(self.entity, T::to_bytes(data))); } pub fn read(&self) -> Result> { - let bytes = buffer_read(self.entity)?; - Ok(bytemuck::pod_collect_to_vec(&bytes)) + Ok(T::from_bytes(&buffer_read(self.entity)?)) } } @@ -135,22 +132,57 @@ mod sealed { pub trait Sealed {} } -/// `f32`, `i32`, `u32`, or arrays of 2-4 of them. -pub trait BufferElement: sealed::Sealed + bytemuck::Pod {} +/// `f32`, `i32`, `u32`, arrays of 2-4 of them, `Vec2`-`Vec4`, or `Color` (linear RGBA). +pub trait BufferElement: sealed::Sealed + Sized { + #[doc(hidden)] + const FLOAT: bool; + #[doc(hidden)] + const COMPONENTS: usize; + #[doc(hidden)] + fn to_bytes(data: &[Self]) -> Vec; + #[doc(hidden)] + fn from_bytes(bytes: &[u8]) -> Vec; +} -macro_rules! buffer_element { - ($($t:ty),*) => {$( +macro_rules! pod_element { + ($($t:ty => $float:expr, $n:expr);* $(;)?) => {$( impl sealed::Sealed for $t {} - impl BufferElement for $t {} - impl sealed::Sealed for [$t; 2] {} - impl BufferElement for [$t; 2] {} - impl sealed::Sealed for [$t; 3] {} - impl BufferElement for [$t; 3] {} - impl sealed::Sealed for [$t; 4] {} - impl BufferElement for [$t; 4] {} + impl BufferElement for $t { + const FLOAT: bool = $float; + const COMPONENTS: usize = $n; + fn to_bytes(data: &[Self]) -> Vec { + bytemuck::cast_slice(data).to_vec() + } + fn from_bytes(bytes: &[u8]) -> Vec { + bytemuck::pod_collect_to_vec(bytes) + } + } )*}; } -buffer_element!(f32, i32, u32); + +macro_rules! buffer_element { + ($($t:ty => $float:expr),*) => {$( + pod_element!($t => $float, 1; [$t; 2] => $float, 2; [$t; 3] => $float, 3; [$t; 4] => $float, 4); + )*}; +} +buffer_element!(f32 => true, i32 => false, u32 => false); +pod_element!(Vec2 => true, 2; Vec3 => true, 3; Vec4 => true, 4); + +impl sealed::Sealed for Color {} +impl BufferElement for Color { + const FLOAT: bool = true; + const COMPONENTS: usize = 4; + fn to_bytes(data: &[Self]) -> Vec { + let linear: Vec<[f32; 4]> = data.iter().map(|c| c.to_linear().to_f32_array()).collect(); + bytemuck::cast_slice(&linear).to_vec() + } + fn from_bytes(bytes: &[u8]) -> Vec { + bytemuck::pod_collect_to_vec::(bytes) + .into_iter() + .map(|c| Color::from_linear(LinearRgba::from_f32_array(c))) + .collect() + } +} #[derive(Debug)] pub struct Compute(pub(crate) Entity); diff --git a/src/shape.rs b/src/shape.rs index 22212415..5506ce22 100644 --- a/src/shape.rs +++ b/src/shape.rs @@ -5,6 +5,7 @@ use processing_render::render::command::{DrawCommand, ShapeKind}; use crate::{Graphics, Scalar}; /// Ends open when dropped. +#[must_use] pub struct Shape<'g> { g: &'g mut Graphics, close: bool, @@ -16,7 +17,7 @@ impl<'g> Shape<'g> { Self { g, close: false } } - pub fn vertex(&mut self, x: impl Scalar, y: impl Scalar) { + pub fn vertex(&self, x: impl Scalar, y: impl Scalar) { self.g.record(DrawCommand::ShapeVertex { x: x.to_f32(), y: y.to_f32(), @@ -24,7 +25,7 @@ impl<'g> Shape<'g> { } pub fn bezier_vertex( - &mut self, + &self, cx1: impl Scalar, cy1: impl Scalar, cx2: impl Scalar, @@ -43,7 +44,7 @@ impl<'g> Shape<'g> { } pub fn quadratic_vertex( - &mut self, + &self, cx: impl Scalar, cy: impl Scalar, x: impl Scalar, @@ -57,7 +58,7 @@ impl<'g> Shape<'g> { }); } - pub fn curve_vertex(&mut self, x: impl Scalar, y: impl Scalar) { + pub fn curve_vertex(&self, x: impl Scalar, y: impl Scalar) { self.g.record(DrawCommand::ShapeCurveVertex { x: x.to_f32(), y: y.to_f32(), @@ -83,10 +84,15 @@ impl Drop for Shape<'_> { } } +#[must_use] pub struct Contour<'s, 'g> { shape: &'s mut Shape<'g>, } +impl Contour<'_, '_> { + pub fn end(self) {} +} + impl<'g> Deref for Contour<'_, 'g> { type Target = Shape<'g>; From 565a1713420002a40c9d7991bb53d1b21b552f78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Fri, 20 Nov 2026 12:10:40 -0800 Subject: [PATCH 4/4] Cleanup. --- .../processing_pyo3/processing_py/color.pyi | 96 -- crates/processing_pyo3/processing_py/math.pyi | 1277 ----------------- 2 files changed, 1373 deletions(-) delete mode 100644 crates/processing_pyo3/processing_py/color.pyi delete mode 100644 crates/processing_pyo3/processing_py/math.pyi diff --git a/crates/processing_pyo3/processing_py/color.pyi b/crates/processing_pyo3/processing_py/color.pyi deleted file mode 100644 index 74229cd3..00000000 --- a/crates/processing_pyo3/processing_py/color.pyi +++ /dev/null @@ -1,96 +0,0 @@ -from mewnala.math import PyVecIter, Vec3, Vec4 -from typing import final - -@final -class Color: - def __eq__(self, /, other: object) -> bool: ... - def __getitem__(self, /, idx: int) -> float: ... - def __hash__(self, /) -> int: ... - def __iter__(self, /) -> PyVecIter: ... - def __len__(self, /) -> int: ... - def __new__(cls, /, *args) -> Color: ... - def __repr__(self, /) -> str: ... - def __str__(self, /) -> str: ... - @property - def a(self, /) -> float: ... - @a.setter - def a(self, /, val: float) -> None: ... - @property - def b(self, /) -> float: ... - @b.setter - def b(self, /, val: float) -> None: ... - def darker(self, /, amount: float) -> Color: ... - def distance(self, /, other: Color) -> float: ... - def distance_squared(self, /, other: Color) -> float: ... - @property - def g(self, /) -> float: ... - @g.setter - def g(self, /, val: float) -> None: ... - @staticmethod - def gray(lightness: float) -> Color: ... - @staticmethod - def hex(s: str) -> Color: ... - @staticmethod - def hsla(h: float, s: float, l: float, a: float = 1.0) -> Color: ... - @staticmethod - def hsva(h: float, s: float, v: float, a: float = 1.0) -> Color: ... - def hue(self, /) -> float: ... - @staticmethod - def hwba(h: float, w: float, b: float, a: float = 1.0) -> Color: ... - def is_fully_opaque(self, /) -> bool: ... - def is_fully_transparent(self, /) -> bool: ... - @staticmethod - def lab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... - @staticmethod - def lch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... - def lerp(self, /, other: Color, t: float) -> Color: ... - def lighter(self, /, amount: float) -> Color: ... - @staticmethod - def linear(r: float, g: float, b: float, a: float = 1.0) -> Color: ... - def luminance(self, /) -> float: ... - def mix(self, /, other: Color, t: float) -> Color: ... - @staticmethod - def oklab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... - @staticmethod - def oklch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... - @property - def r(self, /) -> float: ... - @r.setter - def r(self, /, val: float) -> None: ... - def rotate_hue(self, /, degrees: float) -> Color: ... - def saturation(self, /) -> float: ... - @staticmethod - def srgb(r: float, g: float, b: float, a: float = 1.0) -> Color: ... - def to_hex(self, /) -> str: ... - def to_hsla(self, /) -> Color: ... - def to_hsva(self, /) -> Color: ... - def to_hwba(self, /) -> Color: ... - def to_lab(self, /) -> Color: ... - def to_lch(self, /) -> Color: ... - def to_linear(self, /) -> Color: ... - def to_list(self, /) -> list[float]: ... - def to_oklab(self, /) -> Color: ... - def to_oklch(self, /) -> Color: ... - def to_srgba(self, /) -> Color: ... - def to_tuple(self, /) -> tuple: ... - def to_vec3(self, /) -> Vec3: ... - def to_vec4(self, /) -> Vec4: ... - def to_xyz(self, /) -> Color: ... - def with_alpha(self, /, a: float) -> Color: ... - def with_hue(self, /, hue: float) -> Color: ... - def with_luminance(self, /, value: float) -> Color: ... - def with_saturation(self, /, saturation: float) -> Color: ... - @staticmethod - def xyz(x: float, y: float, z: float, a: float = 1.0) -> Color: ... - -def hex(s: str) -> Color: ... -def hsla(h: float, s: float, l: float, a: float = 1.0) -> Color: ... -def hsva(h: float, s: float, v: float, a: float = 1.0) -> Color: ... -def hwba(h: float, w: float, b: float, a: float = 1.0) -> Color: ... -def lab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... -def lch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... -def linear(r: float, g: float, b: float, a: float = 1.0) -> Color: ... -def oklab(l: float, a_axis: float, b_axis: float, alpha: float = 1.0) -> Color: ... -def oklch(l: float, c: float, h: float, a: float = 1.0) -> Color: ... -def srgb(r: float, g: float, b: float, a: float = 1.0) -> Color: ... -def xyz(x: float, y: float, z: float, a: float = 1.0) -> Color: ... diff --git a/crates/processing_pyo3/processing_py/math.pyi b/crates/processing_pyo3/processing_py/math.pyi deleted file mode 100644 index 3f946342..00000000 --- a/crates/processing_pyo3/processing_py/math.pyi +++ /dev/null @@ -1,1277 +0,0 @@ -from collections.abc import Sequence -from typing import Any, Final, final - -@final -class Affine2: - def __eq__(self, other: object, /) -> bool: ... - def __hash__(self, /) -> int: ... - def __new__(cls, /, matrix: Mat2 | None = None, translation: Vec2 | None = None) -> Affine2: ... - def __repr__(self, /) -> str: ... - def __str__(self, /) -> str: ... - @staticmethod - def from_scale(scale: Vec2) -> Affine2: ... - @staticmethod - def from_scale_angle_translation(scale: Vec2, angle: float, translation: Vec2) -> Affine2: ... - def inverse(self, /) -> Affine2: ... - @property - def matrix(self, /) -> Mat2: ... - @property - def translation(self, /) -> Vec2: ... - -@final -class Mat2: - def __eq__(self, other: object, /) -> bool: ... - def __hash__(self, /) -> int: ... - def __mul__(self, rhs: object, /) -> Any: ... - def __new__(cls, /, *args) -> Mat2: ... - def __repr__(self, /) -> str: ... - def __str__(self, /) -> str: ... - def determinant(self, /) -> float: ... - @staticmethod - def from_angle(angle: float) -> Mat2: ... - @staticmethod - def from_scale(scale: Vec2) -> Mat2: ... - def inverse(self, /) -> Mat2: ... - def transpose(self, /) -> Mat2: ... - -@final -class PyVecIter: - def __iter__(self, /) -> PyVecIter: ... - def __next__(self, /) -> float | None: ... - -@final -class Quat: - def __eq__(self, other: object, /) -> bool: ... - def __hash__(self, /) -> int: ... - def __mul__(self, rhs: object, /) -> Any: ... - def __new__(cls, /, *args) -> Quat: ... - def __repr__(self, /) -> str: ... - def __str__(self, /) -> str: ... - def dot(self, /, other: Quat) -> float: ... - @staticmethod - def from_axis_angle(axis: Vec3 | tuple[float, float, float] | Sequence[float], angle: float) -> Quat: ... - @staticmethod - def from_euler(x: float, y: float, z: float) -> Quat: ... - @staticmethod - def from_rotation_x(angle: float) -> Quat: ... - @staticmethod - def from_rotation_y(angle: float) -> Quat: ... - @staticmethod - def from_rotation_z(angle: float) -> Quat: ... - @staticmethod - def identity() -> Quat: ... - def inverse(self, /) -> Quat: ... - def length(self, /) -> float: ... - def mul_vec3(self, /, v: Vec3 | tuple[float, float, float] | Sequence[float]) -> Vec3: ... - def normalize(self, /) -> Quat: ... - def slerp(self, /, other: Quat, t: float) -> Quat: ... - def to_euler(self, /) -> Vec3: ... - @property - def w(self, /) -> float: ... - @w.setter - def w(self, /, val: float) -> None: ... - @property - def x(self, /) -> float: ... - @x.setter - def x(self, /, val: float) -> None: ... - @property - def y(self, /) -> float: ... - @y.setter - def y(self, /, val: float) -> None: ... - @property - def z(self, /) -> float: ... - @z.setter - def z(self, /, val: float) -> None: ... - -@final -class Vec2: - ONE: Final[Vec2] - X: Final[Vec2] - Y: Final[Vec2] - ZERO: Final[Vec2] - def __add__(self, other: object, /) -> Vec2: ... - def __eq__(self, other: object, /) -> bool: ... - def __getattr__(self, name: str, /) -> Any: ... - def __getitem__(self, idx: int, /) -> float: ... - def __hash__(self, /) -> int: ... - def __iadd__(self, other: object, /) -> None: ... - def __imul__(self, rhs: object, /) -> None: ... - def __isub__(self, other: object, /) -> None: ... - def __iter__(self, /) -> PyVecIter: ... - def __itruediv__(self, rhs: object, /) -> None: ... - def __len__(self, /) -> int: ... - def __mul__(self, rhs: object, /) -> Vec2: ... - def __neg__(self, /) -> Vec2: ... - def __new__(cls, /, *args) -> Vec2: ... - def __radd__(self, other: object, /) -> Vec2: ... - def __repr__(self, /) -> str: ... - def __rmul__(self, lhs: object, /) -> Vec2: ... - def __rsub__(self, other: object, /) -> Vec2: ... - def __rtruediv__(self, lhs: object, /) -> Vec2: ... - def __setitem__(self, idx: int, val: float, /) -> None: ... - def __str__(self, /) -> str: ... - def __sub__(self, other: object, /) -> Vec2: ... - def __truediv__(self, rhs: object, /) -> Vec2: ... - def abs(self, /) -> Vec2: ... - def add(self, /, *args) -> None: ... - def angle(self, /) -> float: ... - @staticmethod - def angle_between(v1: Vec2, v2: Vec2) -> float: ... - def clamp(self, /, min: Vec2, max: Vec2) -> Vec2: ... - def copy(self, /) -> Vec2: ... - def dist(self, /, other: Vec2) -> float: ... - def distance(self, /, other: Vec2) -> float: ... - def div(self, /, n: float) -> None: ... - def dot(self, /, other: Vec2) -> float: ... - def equals(self, /, other: Vec2) -> bool: ... - def extend(self, /, z: float) -> Vec3: ... - @staticmethod - def from_angle(angle: float) -> Vec2: ... - def hash_code(self, /) -> int: ... - def heading(self, /) -> float: ... - def length(self, /) -> float: ... - def length_squared(self, /) -> float: ... - def lerp(self, /, other: Vec2, t: float) -> Vec2: ... - def limit(self, /, max: float) -> None: ... - def mag(self, /) -> float: ... - def mag_sq(self, /) -> float: ... - def max(self, /, other: Vec2) -> Vec2: ... - def min(self, /, other: Vec2) -> Vec2: ... - def mult(self, /, n: float) -> None: ... - def normalize(self, /) -> Vec2: ... - def perpendicular(self, /) -> Vec2: ... - @staticmethod - def random() -> Vec2: ... - def rotate(self, /, angle: float) -> Vec2: ... - def set(self, /, *args) -> None: ... - def set_heading(self, /, angle: float) -> None: ... - def set_mag(self, /, len: float) -> None: ... - def sub(self, /, *args) -> None: ... - def to_list(self, /) -> list[float]: ... - def to_tuple(self, /) -> tuple: ... - @property - def x(self, /) -> float: ... - @x.setter - def x(self, /, val: float) -> None: ... - @property - def y(self, /) -> float: ... - @y.setter - def y(self, /, val: float) -> None: ... - @property - def xx(self, /) -> Vec2: ... - @property - def yx(self, /) -> Vec2: ... - @property - def xy(self, /) -> Vec2: ... - @property - def yy(self, /) -> Vec2: ... - @property - def xxx(self, /) -> Vec3: ... - @property - def yxx(self, /) -> Vec3: ... - @property - def xyx(self, /) -> Vec3: ... - @property - def yyx(self, /) -> Vec3: ... - @property - def xxy(self, /) -> Vec3: ... - @property - def yxy(self, /) -> Vec3: ... - @property - def xyy(self, /) -> Vec3: ... - @property - def yyy(self, /) -> Vec3: ... - @property - def xxxx(self, /) -> Vec4: ... - @property - def yxxx(self, /) -> Vec4: ... - @property - def xyxx(self, /) -> Vec4: ... - @property - def yyxx(self, /) -> Vec4: ... - @property - def xxyx(self, /) -> Vec4: ... - @property - def yxyx(self, /) -> Vec4: ... - @property - def xyyx(self, /) -> Vec4: ... - @property - def yyyx(self, /) -> Vec4: ... - @property - def xxxy(self, /) -> Vec4: ... - @property - def yxxy(self, /) -> Vec4: ... - @property - def xyxy(self, /) -> Vec4: ... - @property - def yyxy(self, /) -> Vec4: ... - @property - def xxyy(self, /) -> Vec4: ... - @property - def yxyy(self, /) -> Vec4: ... - @property - def xyyy(self, /) -> Vec4: ... - @property - def yyyy(self, /) -> Vec4: ... - -@final -class Vec3: - ONE: Final[Vec3] - X: Final[Vec3] - Y: Final[Vec3] - Z: Final[Vec3] - ZERO: Final[Vec3] - def __add__(self, other: object, /) -> Vec3: ... - def __eq__(self, other: object, /) -> bool: ... - def __getattr__(self, name: str, /) -> Any: ... - def __getitem__(self, idx: int, /) -> float: ... - def __hash__(self, /) -> int: ... - def __iadd__(self, other: object, /) -> None: ... - def __imul__(self, rhs: object, /) -> None: ... - def __isub__(self, other: object, /) -> None: ... - def __iter__(self, /) -> PyVecIter: ... - def __itruediv__(self, rhs: object, /) -> None: ... - def __len__(self, /) -> int: ... - def __mul__(self, rhs: object, /) -> Vec3: ... - def __neg__(self, /) -> Vec3: ... - def __new__(cls, /, *args) -> Vec3: ... - def __radd__(self, other: object, /) -> Vec3: ... - def __repr__(self, /) -> str: ... - def __rmul__(self, lhs: object, /) -> Vec3: ... - def __rsub__(self, other: object, /) -> Vec3: ... - def __rtruediv__(self, lhs: object, /) -> Vec3: ... - def __setitem__(self, idx: int, val: float, /) -> None: ... - def __str__(self, /) -> str: ... - def __sub__(self, other: object, /) -> Vec3: ... - def __truediv__(self, rhs: object, /) -> Vec3: ... - def abs(self, /) -> Vec3: ... - def add(self, /, *args) -> None: ... - @staticmethod - def angle_between(v1: Vec3, v2: Vec3) -> float: ... - def clamp(self, /, min: Vec3, max: Vec3) -> Vec3: ... - def copy(self, /) -> Vec3: ... - def cross(self, /, other: Vec3) -> Vec3: ... - def dist(self, /, other: Vec3) -> float: ... - def distance(self, /, other: Vec3) -> float: ... - def div(self, /, n: float) -> None: ... - def dot(self, /, other: Vec3) -> float: ... - def equals(self, /, other: Vec3) -> bool: ... - def extend(self, /, w: float) -> Vec4: ... - def hash_code(self, /) -> int: ... - def length(self, /) -> float: ... - def length_squared(self, /) -> float: ... - def lerp(self, /, other: Vec3, t: float) -> Vec3: ... - def limit(self, /, max: float) -> None: ... - def mag(self, /) -> float: ... - def mag_sq(self, /) -> float: ... - def max(self, /, other: Vec3) -> Vec3: ... - def min(self, /, other: Vec3) -> Vec3: ... - def mult(self, /, n: float) -> None: ... - def normalize(self, /) -> Vec3: ... - @staticmethod - def random() -> Vec3: ... - def set(self, /, *args) -> None: ... - def set_mag(self, /, len: float) -> None: ... - def sub(self, /, *args) -> None: ... - def to_list(self, /) -> list[float]: ... - def to_tuple(self, /) -> tuple: ... - def truncate(self, /) -> Vec2: ... - @property - def x(self, /) -> float: ... - @x.setter - def x(self, /, val: float) -> None: ... - @property - def y(self, /) -> float: ... - @y.setter - def y(self, /, val: float) -> None: ... - @property - def z(self, /) -> float: ... - @z.setter - def z(self, /, val: float) -> None: ... - @property - def xx(self, /) -> Vec2: ... - @property - def yx(self, /) -> Vec2: ... - @property - def zx(self, /) -> Vec2: ... - @property - def xy(self, /) -> Vec2: ... - @property - def yy(self, /) -> Vec2: ... - @property - def zy(self, /) -> Vec2: ... - @property - def xz(self, /) -> Vec2: ... - @property - def yz(self, /) -> Vec2: ... - @property - def zz(self, /) -> Vec2: ... - @property - def xxx(self, /) -> Vec3: ... - @property - def yxx(self, /) -> Vec3: ... - @property - def zxx(self, /) -> Vec3: ... - @property - def xyx(self, /) -> Vec3: ... - @property - def yyx(self, /) -> Vec3: ... - @property - def zyx(self, /) -> Vec3: ... - @property - def xzx(self, /) -> Vec3: ... - @property - def yzx(self, /) -> Vec3: ... - @property - def zzx(self, /) -> Vec3: ... - @property - def xxy(self, /) -> Vec3: ... - @property - def yxy(self, /) -> Vec3: ... - @property - def zxy(self, /) -> Vec3: ... - @property - def xyy(self, /) -> Vec3: ... - @property - def yyy(self, /) -> Vec3: ... - @property - def zyy(self, /) -> Vec3: ... - @property - def xzy(self, /) -> Vec3: ... - @property - def yzy(self, /) -> Vec3: ... - @property - def zzy(self, /) -> Vec3: ... - @property - def xxz(self, /) -> Vec3: ... - @property - def yxz(self, /) -> Vec3: ... - @property - def zxz(self, /) -> Vec3: ... - @property - def xyz(self, /) -> Vec3: ... - @property - def yyz(self, /) -> Vec3: ... - @property - def zyz(self, /) -> Vec3: ... - @property - def xzz(self, /) -> Vec3: ... - @property - def yzz(self, /) -> Vec3: ... - @property - def zzz(self, /) -> Vec3: ... - @property - def xxxx(self, /) -> Vec4: ... - @property - def yxxx(self, /) -> Vec4: ... - @property - def zxxx(self, /) -> Vec4: ... - @property - def xyxx(self, /) -> Vec4: ... - @property - def yyxx(self, /) -> Vec4: ... - @property - def zyxx(self, /) -> Vec4: ... - @property - def xzxx(self, /) -> Vec4: ... - @property - def yzxx(self, /) -> Vec4: ... - @property - def zzxx(self, /) -> Vec4: ... - @property - def xxyx(self, /) -> Vec4: ... - @property - def yxyx(self, /) -> Vec4: ... - @property - def zxyx(self, /) -> Vec4: ... - @property - def xyyx(self, /) -> Vec4: ... - @property - def yyyx(self, /) -> Vec4: ... - @property - def zyyx(self, /) -> Vec4: ... - @property - def xzyx(self, /) -> Vec4: ... - @property - def yzyx(self, /) -> Vec4: ... - @property - def zzyx(self, /) -> Vec4: ... - @property - def xxzx(self, /) -> Vec4: ... - @property - def yxzx(self, /) -> Vec4: ... - @property - def zxzx(self, /) -> Vec4: ... - @property - def xyzx(self, /) -> Vec4: ... - @property - def yyzx(self, /) -> Vec4: ... - @property - def zyzx(self, /) -> Vec4: ... - @property - def xzzx(self, /) -> Vec4: ... - @property - def yzzx(self, /) -> Vec4: ... - @property - def zzzx(self, /) -> Vec4: ... - @property - def xxxy(self, /) -> Vec4: ... - @property - def yxxy(self, /) -> Vec4: ... - @property - def zxxy(self, /) -> Vec4: ... - @property - def xyxy(self, /) -> Vec4: ... - @property - def yyxy(self, /) -> Vec4: ... - @property - def zyxy(self, /) -> Vec4: ... - @property - def xzxy(self, /) -> Vec4: ... - @property - def yzxy(self, /) -> Vec4: ... - @property - def zzxy(self, /) -> Vec4: ... - @property - def xxyy(self, /) -> Vec4: ... - @property - def yxyy(self, /) -> Vec4: ... - @property - def zxyy(self, /) -> Vec4: ... - @property - def xyyy(self, /) -> Vec4: ... - @property - def yyyy(self, /) -> Vec4: ... - @property - def zyyy(self, /) -> Vec4: ... - @property - def xzyy(self, /) -> Vec4: ... - @property - def yzyy(self, /) -> Vec4: ... - @property - def zzyy(self, /) -> Vec4: ... - @property - def xxzy(self, /) -> Vec4: ... - @property - def yxzy(self, /) -> Vec4: ... - @property - def zxzy(self, /) -> Vec4: ... - @property - def xyzy(self, /) -> Vec4: ... - @property - def yyzy(self, /) -> Vec4: ... - @property - def zyzy(self, /) -> Vec4: ... - @property - def xzzy(self, /) -> Vec4: ... - @property - def yzzy(self, /) -> Vec4: ... - @property - def zzzy(self, /) -> Vec4: ... - @property - def xxxz(self, /) -> Vec4: ... - @property - def yxxz(self, /) -> Vec4: ... - @property - def zxxz(self, /) -> Vec4: ... - @property - def xyxz(self, /) -> Vec4: ... - @property - def yyxz(self, /) -> Vec4: ... - @property - def zyxz(self, /) -> Vec4: ... - @property - def xzxz(self, /) -> Vec4: ... - @property - def yzxz(self, /) -> Vec4: ... - @property - def zzxz(self, /) -> Vec4: ... - @property - def xxyz(self, /) -> Vec4: ... - @property - def yxyz(self, /) -> Vec4: ... - @property - def zxyz(self, /) -> Vec4: ... - @property - def xyyz(self, /) -> Vec4: ... - @property - def yyyz(self, /) -> Vec4: ... - @property - def zyyz(self, /) -> Vec4: ... - @property - def xzyz(self, /) -> Vec4: ... - @property - def yzyz(self, /) -> Vec4: ... - @property - def zzyz(self, /) -> Vec4: ... - @property - def xxzz(self, /) -> Vec4: ... - @property - def yxzz(self, /) -> Vec4: ... - @property - def zxzz(self, /) -> Vec4: ... - @property - def xyzz(self, /) -> Vec4: ... - @property - def yyzz(self, /) -> Vec4: ... - @property - def zyzz(self, /) -> Vec4: ... - @property - def xzzz(self, /) -> Vec4: ... - @property - def yzzz(self, /) -> Vec4: ... - @property - def zzzz(self, /) -> Vec4: ... - -@final -class Vec4: - ONE: Final[Vec4] - W: Final[Vec4] - X: Final[Vec4] - Y: Final[Vec4] - Z: Final[Vec4] - ZERO: Final[Vec4] - def __add__(self, other: object, /) -> Vec4: ... - def __eq__(self, other: object, /) -> bool: ... - def __getattr__(self, name: str, /) -> Any: ... - def __getitem__(self, idx: int, /) -> float: ... - def __hash__(self, /) -> int: ... - def __iadd__(self, other: object, /) -> None: ... - def __imul__(self, rhs: object, /) -> None: ... - def __isub__(self, other: object, /) -> None: ... - def __iter__(self, /) -> PyVecIter: ... - def __itruediv__(self, rhs: object, /) -> None: ... - def __len__(self, /) -> int: ... - def __mul__(self, rhs: object, /) -> Vec4: ... - def __neg__(self, /) -> Vec4: ... - def __new__(cls, /, *args) -> Vec4: ... - def __radd__(self, other: object, /) -> Vec4: ... - def __repr__(self, /) -> str: ... - def __rmul__(self, lhs: object, /) -> Vec4: ... - def __rsub__(self, other: object, /) -> Vec4: ... - def __rtruediv__(self, lhs: object, /) -> Vec4: ... - def __setitem__(self, idx: int, val: float, /) -> None: ... - def __str__(self, /) -> str: ... - def __sub__(self, other: object, /) -> Vec4: ... - def __truediv__(self, rhs: object, /) -> Vec4: ... - def abs(self, /) -> Vec4: ... - def add(self, /, *args) -> None: ... - @staticmethod - def angle_between(v1: Vec4, v2: Vec4) -> float: ... - def clamp(self, /, min: Vec4, max: Vec4) -> Vec4: ... - def copy(self, /) -> Vec4: ... - def dist(self, /, other: Vec4) -> float: ... - def distance(self, /, other: Vec4) -> float: ... - def div(self, /, n: float) -> None: ... - def dot(self, /, other: Vec4) -> float: ... - def equals(self, /, other: Vec4) -> bool: ... - def hash_code(self, /) -> int: ... - def length(self, /) -> float: ... - def length_squared(self, /) -> float: ... - def lerp(self, /, other: Vec4, t: float) -> Vec4: ... - def limit(self, /, max: float) -> None: ... - def mag(self, /) -> float: ... - def mag_sq(self, /) -> float: ... - def max(self, /, other: Vec4) -> Vec4: ... - def min(self, /, other: Vec4) -> Vec4: ... - def mult(self, /, n: float) -> None: ... - def normalize(self, /) -> Vec4: ... - def set(self, /, *args) -> None: ... - def set_mag(self, /, len: float) -> None: ... - def sub(self, /, *args) -> None: ... - def to_list(self, /) -> list[float]: ... - def to_tuple(self, /) -> tuple: ... - def truncate(self, /) -> Vec3: ... - @property - def w(self, /) -> float: ... - @w.setter - def w(self, /, val: float) -> None: ... - @property - def x(self, /) -> float: ... - @x.setter - def x(self, /, val: float) -> None: ... - @property - def y(self, /) -> float: ... - @y.setter - def y(self, /, val: float) -> None: ... - @property - def z(self, /) -> float: ... - @z.setter - def z(self, /, val: float) -> None: ... - @property - def xx(self, /) -> Vec2: ... - @property - def yx(self, /) -> Vec2: ... - @property - def zx(self, /) -> Vec2: ... - @property - def wx(self, /) -> Vec2: ... - @property - def xy(self, /) -> Vec2: ... - @property - def yy(self, /) -> Vec2: ... - @property - def zy(self, /) -> Vec2: ... - @property - def wy(self, /) -> Vec2: ... - @property - def xz(self, /) -> Vec2: ... - @property - def yz(self, /) -> Vec2: ... - @property - def zz(self, /) -> Vec2: ... - @property - def wz(self, /) -> Vec2: ... - @property - def xw(self, /) -> Vec2: ... - @property - def yw(self, /) -> Vec2: ... - @property - def zw(self, /) -> Vec2: ... - @property - def ww(self, /) -> Vec2: ... - @property - def xxx(self, /) -> Vec3: ... - @property - def yxx(self, /) -> Vec3: ... - @property - def zxx(self, /) -> Vec3: ... - @property - def wxx(self, /) -> Vec3: ... - @property - def xyx(self, /) -> Vec3: ... - @property - def yyx(self, /) -> Vec3: ... - @property - def zyx(self, /) -> Vec3: ... - @property - def wyx(self, /) -> Vec3: ... - @property - def xzx(self, /) -> Vec3: ... - @property - def yzx(self, /) -> Vec3: ... - @property - def zzx(self, /) -> Vec3: ... - @property - def wzx(self, /) -> Vec3: ... - @property - def xwx(self, /) -> Vec3: ... - @property - def ywx(self, /) -> Vec3: ... - @property - def zwx(self, /) -> Vec3: ... - @property - def wwx(self, /) -> Vec3: ... - @property - def xxy(self, /) -> Vec3: ... - @property - def yxy(self, /) -> Vec3: ... - @property - def zxy(self, /) -> Vec3: ... - @property - def wxy(self, /) -> Vec3: ... - @property - def xyy(self, /) -> Vec3: ... - @property - def yyy(self, /) -> Vec3: ... - @property - def zyy(self, /) -> Vec3: ... - @property - def wyy(self, /) -> Vec3: ... - @property - def xzy(self, /) -> Vec3: ... - @property - def yzy(self, /) -> Vec3: ... - @property - def zzy(self, /) -> Vec3: ... - @property - def wzy(self, /) -> Vec3: ... - @property - def xwy(self, /) -> Vec3: ... - @property - def ywy(self, /) -> Vec3: ... - @property - def zwy(self, /) -> Vec3: ... - @property - def wwy(self, /) -> Vec3: ... - @property - def xxz(self, /) -> Vec3: ... - @property - def yxz(self, /) -> Vec3: ... - @property - def zxz(self, /) -> Vec3: ... - @property - def wxz(self, /) -> Vec3: ... - @property - def xyz(self, /) -> Vec3: ... - @property - def yyz(self, /) -> Vec3: ... - @property - def zyz(self, /) -> Vec3: ... - @property - def wyz(self, /) -> Vec3: ... - @property - def xzz(self, /) -> Vec3: ... - @property - def yzz(self, /) -> Vec3: ... - @property - def zzz(self, /) -> Vec3: ... - @property - def wzz(self, /) -> Vec3: ... - @property - def xwz(self, /) -> Vec3: ... - @property - def ywz(self, /) -> Vec3: ... - @property - def zwz(self, /) -> Vec3: ... - @property - def wwz(self, /) -> Vec3: ... - @property - def xxw(self, /) -> Vec3: ... - @property - def yxw(self, /) -> Vec3: ... - @property - def zxw(self, /) -> Vec3: ... - @property - def wxw(self, /) -> Vec3: ... - @property - def xyw(self, /) -> Vec3: ... - @property - def yyw(self, /) -> Vec3: ... - @property - def zyw(self, /) -> Vec3: ... - @property - def wyw(self, /) -> Vec3: ... - @property - def xzw(self, /) -> Vec3: ... - @property - def yzw(self, /) -> Vec3: ... - @property - def zzw(self, /) -> Vec3: ... - @property - def wzw(self, /) -> Vec3: ... - @property - def xww(self, /) -> Vec3: ... - @property - def yww(self, /) -> Vec3: ... - @property - def zww(self, /) -> Vec3: ... - @property - def www(self, /) -> Vec3: ... - @property - def xxxx(self, /) -> Vec4: ... - @property - def yxxx(self, /) -> Vec4: ... - @property - def zxxx(self, /) -> Vec4: ... - @property - def wxxx(self, /) -> Vec4: ... - @property - def xyxx(self, /) -> Vec4: ... - @property - def yyxx(self, /) -> Vec4: ... - @property - def zyxx(self, /) -> Vec4: ... - @property - def wyxx(self, /) -> Vec4: ... - @property - def xzxx(self, /) -> Vec4: ... - @property - def yzxx(self, /) -> Vec4: ... - @property - def zzxx(self, /) -> Vec4: ... - @property - def wzxx(self, /) -> Vec4: ... - @property - def xwxx(self, /) -> Vec4: ... - @property - def ywxx(self, /) -> Vec4: ... - @property - def zwxx(self, /) -> Vec4: ... - @property - def wwxx(self, /) -> Vec4: ... - @property - def xxyx(self, /) -> Vec4: ... - @property - def yxyx(self, /) -> Vec4: ... - @property - def zxyx(self, /) -> Vec4: ... - @property - def wxyx(self, /) -> Vec4: ... - @property - def xyyx(self, /) -> Vec4: ... - @property - def yyyx(self, /) -> Vec4: ... - @property - def zyyx(self, /) -> Vec4: ... - @property - def wyyx(self, /) -> Vec4: ... - @property - def xzyx(self, /) -> Vec4: ... - @property - def yzyx(self, /) -> Vec4: ... - @property - def zzyx(self, /) -> Vec4: ... - @property - def wzyx(self, /) -> Vec4: ... - @property - def xwyx(self, /) -> Vec4: ... - @property - def ywyx(self, /) -> Vec4: ... - @property - def zwyx(self, /) -> Vec4: ... - @property - def wwyx(self, /) -> Vec4: ... - @property - def xxzx(self, /) -> Vec4: ... - @property - def yxzx(self, /) -> Vec4: ... - @property - def zxzx(self, /) -> Vec4: ... - @property - def wxzx(self, /) -> Vec4: ... - @property - def xyzx(self, /) -> Vec4: ... - @property - def yyzx(self, /) -> Vec4: ... - @property - def zyzx(self, /) -> Vec4: ... - @property - def wyzx(self, /) -> Vec4: ... - @property - def xzzx(self, /) -> Vec4: ... - @property - def yzzx(self, /) -> Vec4: ... - @property - def zzzx(self, /) -> Vec4: ... - @property - def wzzx(self, /) -> Vec4: ... - @property - def xwzx(self, /) -> Vec4: ... - @property - def ywzx(self, /) -> Vec4: ... - @property - def zwzx(self, /) -> Vec4: ... - @property - def wwzx(self, /) -> Vec4: ... - @property - def xxwx(self, /) -> Vec4: ... - @property - def yxwx(self, /) -> Vec4: ... - @property - def zxwx(self, /) -> Vec4: ... - @property - def wxwx(self, /) -> Vec4: ... - @property - def xywx(self, /) -> Vec4: ... - @property - def yywx(self, /) -> Vec4: ... - @property - def zywx(self, /) -> Vec4: ... - @property - def wywx(self, /) -> Vec4: ... - @property - def xzwx(self, /) -> Vec4: ... - @property - def yzwx(self, /) -> Vec4: ... - @property - def zzwx(self, /) -> Vec4: ... - @property - def wzwx(self, /) -> Vec4: ... - @property - def xwwx(self, /) -> Vec4: ... - @property - def ywwx(self, /) -> Vec4: ... - @property - def zwwx(self, /) -> Vec4: ... - @property - def wwwx(self, /) -> Vec4: ... - @property - def xxxy(self, /) -> Vec4: ... - @property - def yxxy(self, /) -> Vec4: ... - @property - def zxxy(self, /) -> Vec4: ... - @property - def wxxy(self, /) -> Vec4: ... - @property - def xyxy(self, /) -> Vec4: ... - @property - def yyxy(self, /) -> Vec4: ... - @property - def zyxy(self, /) -> Vec4: ... - @property - def wyxy(self, /) -> Vec4: ... - @property - def xzxy(self, /) -> Vec4: ... - @property - def yzxy(self, /) -> Vec4: ... - @property - def zzxy(self, /) -> Vec4: ... - @property - def wzxy(self, /) -> Vec4: ... - @property - def xwxy(self, /) -> Vec4: ... - @property - def ywxy(self, /) -> Vec4: ... - @property - def zwxy(self, /) -> Vec4: ... - @property - def wwxy(self, /) -> Vec4: ... - @property - def xxyy(self, /) -> Vec4: ... - @property - def yxyy(self, /) -> Vec4: ... - @property - def zxyy(self, /) -> Vec4: ... - @property - def wxyy(self, /) -> Vec4: ... - @property - def xyyy(self, /) -> Vec4: ... - @property - def yyyy(self, /) -> Vec4: ... - @property - def zyyy(self, /) -> Vec4: ... - @property - def wyyy(self, /) -> Vec4: ... - @property - def xzyy(self, /) -> Vec4: ... - @property - def yzyy(self, /) -> Vec4: ... - @property - def zzyy(self, /) -> Vec4: ... - @property - def wzyy(self, /) -> Vec4: ... - @property - def xwyy(self, /) -> Vec4: ... - @property - def ywyy(self, /) -> Vec4: ... - @property - def zwyy(self, /) -> Vec4: ... - @property - def wwyy(self, /) -> Vec4: ... - @property - def xxzy(self, /) -> Vec4: ... - @property - def yxzy(self, /) -> Vec4: ... - @property - def zxzy(self, /) -> Vec4: ... - @property - def wxzy(self, /) -> Vec4: ... - @property - def xyzy(self, /) -> Vec4: ... - @property - def yyzy(self, /) -> Vec4: ... - @property - def zyzy(self, /) -> Vec4: ... - @property - def wyzy(self, /) -> Vec4: ... - @property - def xzzy(self, /) -> Vec4: ... - @property - def yzzy(self, /) -> Vec4: ... - @property - def zzzy(self, /) -> Vec4: ... - @property - def wzzy(self, /) -> Vec4: ... - @property - def xwzy(self, /) -> Vec4: ... - @property - def ywzy(self, /) -> Vec4: ... - @property - def zwzy(self, /) -> Vec4: ... - @property - def wwzy(self, /) -> Vec4: ... - @property - def xxwy(self, /) -> Vec4: ... - @property - def yxwy(self, /) -> Vec4: ... - @property - def zxwy(self, /) -> Vec4: ... - @property - def wxwy(self, /) -> Vec4: ... - @property - def xywy(self, /) -> Vec4: ... - @property - def yywy(self, /) -> Vec4: ... - @property - def zywy(self, /) -> Vec4: ... - @property - def wywy(self, /) -> Vec4: ... - @property - def xzwy(self, /) -> Vec4: ... - @property - def yzwy(self, /) -> Vec4: ... - @property - def zzwy(self, /) -> Vec4: ... - @property - def wzwy(self, /) -> Vec4: ... - @property - def xwwy(self, /) -> Vec4: ... - @property - def ywwy(self, /) -> Vec4: ... - @property - def zwwy(self, /) -> Vec4: ... - @property - def wwwy(self, /) -> Vec4: ... - @property - def xxxz(self, /) -> Vec4: ... - @property - def yxxz(self, /) -> Vec4: ... - @property - def zxxz(self, /) -> Vec4: ... - @property - def wxxz(self, /) -> Vec4: ... - @property - def xyxz(self, /) -> Vec4: ... - @property - def yyxz(self, /) -> Vec4: ... - @property - def zyxz(self, /) -> Vec4: ... - @property - def wyxz(self, /) -> Vec4: ... - @property - def xzxz(self, /) -> Vec4: ... - @property - def yzxz(self, /) -> Vec4: ... - @property - def zzxz(self, /) -> Vec4: ... - @property - def wzxz(self, /) -> Vec4: ... - @property - def xwxz(self, /) -> Vec4: ... - @property - def ywxz(self, /) -> Vec4: ... - @property - def zwxz(self, /) -> Vec4: ... - @property - def wwxz(self, /) -> Vec4: ... - @property - def xxyz(self, /) -> Vec4: ... - @property - def yxyz(self, /) -> Vec4: ... - @property - def zxyz(self, /) -> Vec4: ... - @property - def wxyz(self, /) -> Vec4: ... - @property - def xyyz(self, /) -> Vec4: ... - @property - def yyyz(self, /) -> Vec4: ... - @property - def zyyz(self, /) -> Vec4: ... - @property - def wyyz(self, /) -> Vec4: ... - @property - def xzyz(self, /) -> Vec4: ... - @property - def yzyz(self, /) -> Vec4: ... - @property - def zzyz(self, /) -> Vec4: ... - @property - def wzyz(self, /) -> Vec4: ... - @property - def xwyz(self, /) -> Vec4: ... - @property - def ywyz(self, /) -> Vec4: ... - @property - def zwyz(self, /) -> Vec4: ... - @property - def wwyz(self, /) -> Vec4: ... - @property - def xxzz(self, /) -> Vec4: ... - @property - def yxzz(self, /) -> Vec4: ... - @property - def zxzz(self, /) -> Vec4: ... - @property - def wxzz(self, /) -> Vec4: ... - @property - def xyzz(self, /) -> Vec4: ... - @property - def yyzz(self, /) -> Vec4: ... - @property - def zyzz(self, /) -> Vec4: ... - @property - def wyzz(self, /) -> Vec4: ... - @property - def xzzz(self, /) -> Vec4: ... - @property - def yzzz(self, /) -> Vec4: ... - @property - def zzzz(self, /) -> Vec4: ... - @property - def wzzz(self, /) -> Vec4: ... - @property - def xwzz(self, /) -> Vec4: ... - @property - def ywzz(self, /) -> Vec4: ... - @property - def zwzz(self, /) -> Vec4: ... - @property - def wwzz(self, /) -> Vec4: ... - @property - def xxwz(self, /) -> Vec4: ... - @property - def yxwz(self, /) -> Vec4: ... - @property - def zxwz(self, /) -> Vec4: ... - @property - def wxwz(self, /) -> Vec4: ... - @property - def xywz(self, /) -> Vec4: ... - @property - def yywz(self, /) -> Vec4: ... - @property - def zywz(self, /) -> Vec4: ... - @property - def wywz(self, /) -> Vec4: ... - @property - def xzwz(self, /) -> Vec4: ... - @property - def yzwz(self, /) -> Vec4: ... - @property - def zzwz(self, /) -> Vec4: ... - @property - def wzwz(self, /) -> Vec4: ... - @property - def xwwz(self, /) -> Vec4: ... - @property - def ywwz(self, /) -> Vec4: ... - @property - def zwwz(self, /) -> Vec4: ... - @property - def wwwz(self, /) -> Vec4: ... - @property - def xxxw(self, /) -> Vec4: ... - @property - def yxxw(self, /) -> Vec4: ... - @property - def zxxw(self, /) -> Vec4: ... - @property - def wxxw(self, /) -> Vec4: ... - @property - def xyxw(self, /) -> Vec4: ... - @property - def yyxw(self, /) -> Vec4: ... - @property - def zyxw(self, /) -> Vec4: ... - @property - def wyxw(self, /) -> Vec4: ... - @property - def xzxw(self, /) -> Vec4: ... - @property - def yzxw(self, /) -> Vec4: ... - @property - def zzxw(self, /) -> Vec4: ... - @property - def wzxw(self, /) -> Vec4: ... - @property - def xwxw(self, /) -> Vec4: ... - @property - def ywxw(self, /) -> Vec4: ... - @property - def zwxw(self, /) -> Vec4: ... - @property - def wwxw(self, /) -> Vec4: ... - @property - def xxyw(self, /) -> Vec4: ... - @property - def yxyw(self, /) -> Vec4: ... - @property - def zxyw(self, /) -> Vec4: ... - @property - def wxyw(self, /) -> Vec4: ... - @property - def xyyw(self, /) -> Vec4: ... - @property - def yyyw(self, /) -> Vec4: ... - @property - def zyyw(self, /) -> Vec4: ... - @property - def wyyw(self, /) -> Vec4: ... - @property - def xzyw(self, /) -> Vec4: ... - @property - def yzyw(self, /) -> Vec4: ... - @property - def zzyw(self, /) -> Vec4: ... - @property - def wzyw(self, /) -> Vec4: ... - @property - def xwyw(self, /) -> Vec4: ... - @property - def ywyw(self, /) -> Vec4: ... - @property - def zwyw(self, /) -> Vec4: ... - @property - def wwyw(self, /) -> Vec4: ... - @property - def xxzw(self, /) -> Vec4: ... - @property - def yxzw(self, /) -> Vec4: ... - @property - def zxzw(self, /) -> Vec4: ... - @property - def wxzw(self, /) -> Vec4: ... - @property - def xyzw(self, /) -> Vec4: ... - @property - def yyzw(self, /) -> Vec4: ... - @property - def zyzw(self, /) -> Vec4: ... - @property - def wyzw(self, /) -> Vec4: ... - @property - def xzzw(self, /) -> Vec4: ... - @property - def yzzw(self, /) -> Vec4: ... - @property - def zzzw(self, /) -> Vec4: ... - @property - def wzzw(self, /) -> Vec4: ... - @property - def xwzw(self, /) -> Vec4: ... - @property - def ywzw(self, /) -> Vec4: ... - @property - def zwzw(self, /) -> Vec4: ... - @property - def wwzw(self, /) -> Vec4: ... - @property - def xxww(self, /) -> Vec4: ... - @property - def yxww(self, /) -> Vec4: ... - @property - def zxww(self, /) -> Vec4: ... - @property - def wxww(self, /) -> Vec4: ... - @property - def xyww(self, /) -> Vec4: ... - @property - def yyww(self, /) -> Vec4: ... - @property - def zyww(self, /) -> Vec4: ... - @property - def wyww(self, /) -> Vec4: ... - @property - def xzww(self, /) -> Vec4: ... - @property - def yzww(self, /) -> Vec4: ... - @property - def zzww(self, /) -> Vec4: ... - @property - def wzww(self, /) -> Vec4: ... - @property - def xwww(self, /) -> Vec4: ... - @property - def ywww(self, /) -> Vec4: ... - @property - def zwww(self, /) -> Vec4: ... - @property - def wwww(self, /) -> Vec4: ... - -def quat(*args) -> Quat: ... -def vec2(*args) -> Vec2: ... -def vec3(*args) -> Vec3: ... -def vec4(*args) -> Vec4: ...