remove pyglet_rs (it just look useless #28

Merged
shenjackyuanjie merged 1 commits from feature/remove_pyglet_rs into main 2023-06-16 00:09:05 +08:00
16 changed files with 0 additions and 1695 deletions

8
DR.py
View File

@ -53,14 +53,6 @@ def main() -> int:
from Difficult_Rocket.exception import TestError
from Difficult_Rocket import crash
from Difficult_Rocket import DR_option
try:
from libs.pyglet_rs import get_version_str, patch_vector
print('pyglet_rs available:', get_version_str())
print('trying to patch pyglet_rs')
patch_vector()
except ImportError:
print('pyglet_rs import error')
traceback.print_exc()
try:
from libs import pyglet # 导入pyglet
pyglet.resource.path = ['/textures/']

View File

@ -7,7 +7,6 @@ env.version.python = "Python version: {}"
env.version.DR = "Difficult_Rocket version: {}"
env.version.DR_rs = "Difficult_Rocket_rs version: {}"
env.version.pyglet = "pyglet version: {}"
env.version.pyglet_rs = "pyglet_rs version: {}"
version.now_on = "Difficult Rocket is running on Python Vision"
version.need3p = "Difficult Rocket depends on Python vision 3.0+"
version.best38p = "Difficult Rocket is writen in Python {write_py_v}, and now is running on Python {py_v} may cause BUG"

View File

@ -7,7 +7,6 @@ env.version.python = "Python 版本: {}"
env.version.DR = "Difficult_Rocket 版本: {}"
env.version.DR_rs = "Difficult_Rocket_rs 版本: {}"
env.version.pyglet = "pyglet 版本: {}"
env.version.pyglet_rs = "pyglet_rs 版本: {}"
version.now_on = "困难火箭的运行 Python 环境为"
version.need3p = "困难火箭需要 Python3.0+ 的环境"
version.best38p = "困难火箭是在 Python {write_py_v} 的环境下编写的目前正在运行在Python {py_v}的环境下可能产生BUG"

View File

@ -1,64 +0,0 @@
# pyglet_rs
This is a folder about pyglet_rs.
## What is pyglet_rs?
pyglet_rs is a python library that patches pyglet to use rust to make it faster!
## Notice
**This Folder may be move to an individual repo. here is just a temp location**
## requirements
- `python 3.8+`
- `pyglet 2.0+`
- `rustc 1.68.1+`
- no more
## status
- still writing
## usage
```python
import pyglet_rs
pyglet_rs.patch_sprite()
import pyglet
...
```
## how to build
```powershell
cd src
./build.ps1
```
## roadmap
- [ ] `pyglet.sprite.Sprite` patch
- [ ] `pyglet.math.Vec2` patch (doing)
- [ ] main Calculate protocol
- [ ] other protocols
- [ ] `pyglet.math.Vec3` patch (doing)
- [ ] main Calculate protocol
- [ ] other protocols
- [ ] `pyglet.math.Vec4` patch (doing)
- [ ] main Calculate protocol
- [ ] other protocols
- [ ] `pyglet.math.Mat3(tuple)` patch (doing)
- [ ] main Calculate protocol
- [ ] other protocols
- [ ] `pyglet.math.Mat4(tuple)` patch (doing)
- [ ] main Calculate protocol
- [ ] other protocols
## Thanks
Great thanks to Github Copilot!
It helps me a lot in Vector and Matrix calculation and protocol implementation.
(there are A LOT of code generated by copilot)
(even this sentence is generated by copilot)

View File

@ -1,112 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
"""
from .lib import (get_version_str)
from .lib import (Sprite_rs,
Vector2_rs, Vector3_rs, Vector4_rs,
Matrix3_rs, Matrix4_rs)
"""
from .lib import *
from typing import TYPE_CHECKING, Union
# noinspection PyUnresolvedReferences
__version__ = get_version_str()
__all__ = ['patch_sprite', 'patch_vector', 'patch_matrix', 'patch_all',
'Sprite_rs',
'Vector2_rs', 'Vector3_rs', 'Vector4_rs',
'Matrix3_rs', 'Matrix4_rs']
if TYPE_CHECKING:
from pyglet.event import EventDispatcher
Number = Union[int, float]
def get_version_str() -> str: ...
class Sprite_rs(EventDispatcher): ...
class Vector2_rs:
def __init__(self, x: Number, y: Number): ...
def __add__(self, other: "Vector2_rs") -> "Vector2_rs": ...
def __sub__(self, other: "Vector2_rs") -> "Vector2_rs": ...
def __mul__(self, other: "Vector2_rs") -> "Vector2_rs": ...
def __truediv__(self, other: "Vector2_rs") -> "Vector2_rs": ...
def __floordiv__(self, other: "Vector2_rs") -> "Vector2_rs": ...
def __repr__(self) -> str: ...
@property
def x(self) -> float: ...
@property
def y(self) -> float: ...
class Vector3_rs:
def __init__(self, x: Number, y: Number, z: Number): ...
def __add__(self, other: "Vector3_rs") -> "Vector3_rs": ...
def __sub__(self, other: "Vector3_rs") -> "Vector3_rs": ...
def __mul__(self, other: "Vector3_rs") -> "Vector3_rs": ...
def __truediv__(self, other: "Vector3_rs") -> "Vector3_rs": ...
def __floordiv__(self, other: "Vector3_rs") -> "Vector3_rs": ...
def __repr__(self) -> str: ...
@property
def x(self) -> float: ...
@property
def y(self) -> float: ...
@property
def z(self) -> float: ...
class Vector4_rs:
def __init__(self, x: Number, y: Number, z: Number, w: Number): ...
def __add__(self, other: "Vector4_rs") -> "Vector4_rs": ...
def __sub__(self, other: "Vector4_rs") -> "Vector4_rs": ...
def __mul__(self, other: "Vector4_rs") -> "Vector4_rs": ...
def __truediv__(self, other: "Vector4_rs") -> "Vector4_rs": ...
def __floordiv__(self, other: "Vector4_rs") -> "Vector4_rs": ...
def __repr__(self) -> str: ...
@property
def x(self) -> float: ...
@property
def y(self) -> float: ...
@property
def z(self) -> float: ...
@property
def w(self) -> float: ...
class Matrix3_rs: ...
class Matrix4_rs: ...
def patch_sprite():
from pyglet import sprite
sprite.Sprite = Sprite_rs
def patch_vector():
from pyglet import math
math.Vector2 = Vector2_rs
math.Vector3 = Vector3_rs
math.Vector4 = Vector4_rs
def patch_matrix():
from pyglet import math
math.Matrix3 = Matrix3_rs
math.Matrix4 = Matrix4_rs
def patch_all():
patch_sprite()
patch_vector()
patch_matrix()

View File

@ -1,325 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "ctor"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096"
dependencies = [
"quote",
"syn 1.0.109",
]
[[package]]
name = "ghost"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e77ac7b51b8e6313251737fcef4b1c01a2ea102bde68415b62c0ee9268fec357"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.5",
]
[[package]]
name = "indoc"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa799dd5ed20a7e349f3b4639aa80d74549c81716d9ec4f994c9b5815598306"
[[package]]
name = "inventory"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "498ae1c9c329c7972b917506239b557a60386839192f1cf0ca034f345b65db99"
dependencies = [
"ctor",
"ghost",
]
[[package]]
name = "libc"
version = "0.2.140"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99227334921fae1a979cf0bfdfcc6b3e5ce376ef57e16fb6fb3ea2ed6095f80c"
[[package]]
name = "lock_api"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "memoffset"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-sys",
]
[[package]]
name = "proc-macro2"
version = "1.0.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba466839c78239c09faf015484e5cc04860f88242cff4d03eb038f04b4699b73"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pyglet_rs"
version = "0.1.0"
dependencies = [
"pyo3",
]
[[package]]
name = "pyo3"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06a3d8e8a46ab2738109347433cb7b96dffda2e4a218b03ef27090238886b147"
dependencies = [
"cfg-if",
"indoc",
"inventory",
"libc",
"memoffset",
"parking_lot",
"pyo3-build-config",
"pyo3-ffi",
"pyo3-macros",
"unindent",
]
[[package]]
name = "pyo3-build-config"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75439f995d07ddfad42b192dfcf3bc66a7ecfd8b4a1f5f6f046aa5c2c5d7677d"
dependencies = [
"once_cell",
"target-lexicon",
]
[[package]]
name = "pyo3-ffi"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "839526a5c07a17ff44823679b68add4a58004de00512a95b6c1c98a6dcac0ee5"
dependencies = [
"libc",
"pyo3-build-config",
]
[[package]]
name = "pyo3-macros"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd44cf207476c6a9760c4653559be4f206efafb924d3e4cbf2721475fc0d6cc5"
dependencies = [
"proc-macro2",
"pyo3-macros-backend",
"quote",
"syn 1.0.109",
]
[[package]]
name = "pyo3-macros-backend"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1f43d8e30460f36350d18631ccf85ded64c059829208fe680904c65bcd0a4c"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "quote"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags",
]
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89c2d1c76a26822187a1fbb5964e3fff108bc208f02e820ab9dac1234f6b388a"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "target-lexicon"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ae9980cab1db3fceee2f6c6f643d5d8de2997c58ee8d25fb0cc8a9e9e7348e5"
[[package]]
name = "unicode-ident"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4"
[[package]]
name = "unindent"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1766d682d402817b5ac4490b3c3002d91dfa0d22812f341609f97b08757359c"
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"

View File

@ -1,17 +0,0 @@
[package]
name = "pyglet_rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = 'pyglet_rs'
crate-type = ["cdylib"]
[profile.release]
codegen-units = 1
[dependencies.pyo3]
version = "0.18.1"
features = ["extension-module", "multiple-pymethods"]

View File

@ -1 +0,0 @@
cargo fmt;python3.8 .\setup.py build; python .\post_build.py

View File

@ -1,41 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
import os
import shutil
import warnings
import traceback
package_path = 'pyglet_rs'
lib_path = '../lib'
build_path = 'build'
if not os.path.exists(lib_path):
os.mkdir(lib_path)
builds = os.listdir(build_path)
print(os.path.abspath('.'))
try:
shutil.copy('src/__init__.py', os.path.join(lib_path, '__init__.py'))
except shutil.SameFileError:
traceback.print_exc()
for build_dir in builds:
if not os.path.exists(os.path.join(build_path, build_dir, package_path)):
warnings.warn(f'package not found at {build_path}/{build_dir}')
continue
for file in os.listdir(os.path.join(build_path, build_dir, package_path)):
# file_name = os.path.join(lib_path, file.replace(package_path, f'{package_path}.{DR_runtime.DR_Rust_version}'))
file_name = os.path.join(lib_path, file)
shutil.rmtree(file_name, ignore_errors=True)
try:
shutil.copy(os.path.join(build_path, build_dir, package_path, file), file_name)
except (shutil.SameFileError, PermissionError):
# print(os.path.exists(os.path))
print(os.listdir(lib_path))
traceback.print_exc()
continue
print(os.path.abspath(file_name))

View File

@ -1,39 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
import os
import sys
import rtoml
import shutil
from setuptools import setup
from setuptools_rust import Binding, RustExtension
sys.path.append('../../../')
sys.path.append(os.curdir)
package_path = 'pyglet_rs'
# 版本号从 cargo.toml 中读取
with open(f'Cargo.toml', 'r') as f:
cargo_toml = rtoml.load(f)
version = cargo_toml['package']['version']
setup(
name='pyglet_rs',
version=version,
author='shenjackyuanjie',
author_email='3695888@qq.com',
rust_extensions=[RustExtension(target="pyglet_rs.pyglet_rs",
binding=Binding.PyO3)],
zip_safe=False,
)
lib_path = '../lib'
build_path = 'build'
if 'clean' in sys.argv:
shutil.rmtree(build_path, ignore_errors=True)
shutil.rmtree(f'{package_path}.egg-info', ignore_errors=True)
sys.exit(0)

View File

@ -1,10 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
from typing import TYPE_CHECKING
if not TYPE_CHECKING:
from .pyglet_rs import *

View File

@ -1,30 +0,0 @@
/*
* -------------------------------
* Difficult Rocket
* Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
* All rights reserved
* -------------------------------
*/
mod math;
mod pymath;
mod sprite;
use pyo3::prelude::*;
#[pyfunction]
fn get_version_str() -> String {
return "0.1.0".to_string();
}
#[pymodule]
#[pyo3(name = "pyglet_rs")]
fn module_init(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(get_version_str, m)?)?;
m.add_class::<sprite::Sprite>()?;
// vector
m.add_class::<pymath::python_class::PyVector2>()?;
m.add_class::<pymath::python_class::PyVector3>()?;
m.add_class::<pymath::python_class::PyVector4>()?;
Ok(())
}

View File

@ -1,395 +0,0 @@
/*
* -------------------------------
* Difficult Rocket
* Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
* All rights reserved
* -------------------------------
*/
pub mod vector {
use std::ops::{Add, Div, Mul, Sub};
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Vector2 {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Vector3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Vector4 {
pub x: f64,
pub y: f64,
pub z: f64,
pub w: f64,
}
pub trait VectorTrait {
fn len(&self) -> i8; // use short int to save memory (even if its not going to save a lot)
fn floordiv(&self, other: &Self) -> Self;
fn abs(&self) -> f64;
fn neg(&self) -> Self;
fn dot(&self, other: &Self) -> f64;
fn round(&self, ndigits: Option<i64>) -> Self;
fn clamp(&self, min: f64, max: f64) -> Self;
fn distance(&self, other: &Self) -> f64;
fn normalize(&self) -> Self;
// from
fn from_same(len: f64) -> Self;
}
impl Add for Vector2 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::new(self.x + rhs.x, self.y + rhs.y)
}
}
impl Sub for Vector2 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self::new(self.x - rhs.x, self.y - rhs.y)
}
}
impl Mul for Vector2 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self::new(self.x * rhs.x, self.y * rhs.y)
}
}
impl Div for Vector2 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
Self::new(self.x / rhs.x, self.y / rhs.y)
}
}
impl Add for Vector3 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
}
}
impl Sub for Vector3 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
}
}
impl Mul for Vector3 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self::new(self.x * rhs.x, self.y * rhs.y, self.z * rhs.z)
}
}
impl Div for Vector3 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
Self::new(self.x / rhs.x, self.y / rhs.y, self.z / rhs.z)
}
}
impl Add for Vector4 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::new(
self.x + rhs.x,
self.y + rhs.y,
self.z + rhs.z,
self.w + rhs.w,
)
}
}
impl Sub for Vector4 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self::new(
self.x - rhs.x,
self.y - rhs.y,
self.z - rhs.z,
self.w - rhs.w,
)
}
}
impl Mul for Vector4 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self::new(
self.x * rhs.x,
self.y * rhs.y,
self.z * rhs.z,
self.w * rhs.w,
)
}
}
impl Div for Vector4 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
Self::new(
self.x / rhs.x,
self.y / rhs.y,
self.z / rhs.z,
self.w / rhs.w,
)
}
}
impl VectorTrait for Vector2 {
fn len(&self) -> i8 {
return 2;
}
fn floordiv(&self, other: &Self) -> Self {
// 手动模拟python的//运算符
Self::new((self.x / other.x).floor(), (self.y / other.y).floor())
}
fn abs(&self) -> f64 {
return (self.x.powi(2) + self.y.powi(2)).sqrt();
}
fn neg(&self) -> Self {
Self::new(-self.x, -self.y)
}
fn dot(&self, other: &Self) -> f64 {
self.x * other.x + self.y * other.y
}
fn round(&self, ndigits: Option<i64>) -> Self {
match ndigits {
Some(ndigits) => {
let ndigits = ndigits as i32;
Self::new(
self.x.round() * 10.0_f64.powi(ndigits),
self.y.round() * 10.0_f64.powi(ndigits),
)
}
None => Self::new(self.x.round(), self.y.round()),
}
}
fn clamp(&self, min: f64, max: f64) -> Self {
Self::new(self.x.clamp(min, max), self.y.clamp(min, max))
}
fn distance(&self, other: &Self) -> f64 {
(*self - *other).abs()
}
fn normalize(&self) -> Self {
let d = self.abs();
return if d != 0.0 {
Self::new(self.x / d, self.y / d)
} else {
self.clone()
};
}
fn from_same(len: f64) -> Self {
Self::new(len, len)
}
}
impl VectorTrait for Vector3 {
fn len(&self) -> i8 {
return 3;
}
fn floordiv(&self, other: &Self) -> Self {
// 手动模拟python的//运算符
Self::new(
(self.x / other.x).floor(),
(self.y / other.y).floor(),
(self.z / other.z).floor(),
)
}
fn abs(&self) -> f64 {
return (self.x.powi(2) + self.y.powi(2) + self.z.powi(2)).sqrt();
}
fn neg(&self) -> Self {
Self::new(-self.x, -self.y, -self.z)
}
fn dot(&self, other: &Self) -> f64 {
self.x * other.x + self.y * other.y + self.z * other.z
}
fn round(&self, ndigits: Option<i64>) -> Self {
match ndigits {
Some(ndigits) => {
let ndigits = ndigits as i32;
Self::new(
self.x.round() * 10.0_f64.powi(ndigits),
self.y.round() * 10.0_f64.powi(ndigits),
self.z.round() * 10.0_f64.powi(ndigits),
)
}
None => Self::new(self.x.round(), self.y.round(), self.z.round()),
}
}
fn clamp(&self, min: f64, max: f64) -> Self {
Self::new(
self.x.clamp(min, max),
self.y.clamp(min, max),
self.z.clamp(min, max),
)
}
fn distance(&self, other: &Self) -> f64 {
(*self - *other).abs()
}
fn normalize(&self) -> Self {
let d = self.abs();
return if d != 0.0 {
Self::new(self.x / d, self.y / d, self.z / d)
} else {
self.clone()
};
}
fn from_same(len: f64) -> Self {
Self::new(len, len, len)
}
}
impl VectorTrait for Vector4 {
fn len(&self) -> i8 {
return 4;
}
fn floordiv(&self, other: &Self) -> Self {
// 手动模拟python的//运算符
Self::new(
(self.x / other.x).floor(),
(self.y / other.y).floor(),
(self.z / other.z).floor(),
(self.w / other.w).floor(),
)
}
fn abs(&self) -> f64 {
return (self.x.powi(2) + self.y.powi(2) + self.z.powi(2) + self.w.powi(2)).sqrt();
}
fn neg(&self) -> Self {
Self::new(-self.x, -self.y, -self.z, -self.w)
}
fn dot(&self, other: &Self) -> f64 {
self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w
}
fn round(&self, ndigits: Option<i64>) -> Self {
match ndigits {
Some(ndigits) => {
let ndigits = ndigits as i32;
Self::new(
self.x.round() * 10.0_f64.powi(ndigits),
self.y.round() * 10.0_f64.powi(ndigits),
self.z.round() * 10.0_f64.powi(ndigits),
self.w.round() * 10.0_f64.powi(ndigits),
)
}
None => Self::new(
self.x.round(),
self.y.round(),
self.z.round(),
self.w.round(),
),
}
}
fn clamp(&self, min: f64, max: f64) -> Self {
Self::new(
self.x.clamp(min, max),
self.y.clamp(min, max),
self.z.clamp(min, max),
self.w.clamp(min, max),
)
}
fn distance(&self, other: &Self) -> f64 {
(*self - *other).abs()
}
fn normalize(&self) -> Self {
let d = self.abs();
return if d != 0.0 {
Self::new(self.x / d, self.y / d, self.z / d, self.w / d)
} else {
self.clone()
};
}
fn from_same(len: f64) -> Self {
Self::new(len, len, len, len)
}
}
impl Vector2 {
pub fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
}
impl Vector3 {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
}
impl Vector4 {
pub fn new(x: f64, y: f64, z: f64, w: f64) -> Self {
Self { x, y, z, w }
}
}
}
pub mod matrix {
use super::vector::{Vector3, Vector4};
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Matrix3 {
pub line1: Vector3,
pub line2: Vector3,
pub line3: Vector3,
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Matrix4 {
pub line1: Vector4,
pub line2: Vector4,
pub line3: Vector4,
pub line4: Vector4,
}
}

View File

@ -1,354 +0,0 @@
/*
* -------------------------------
* Difficult Rocket
* Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
* All rights reserved
* -------------------------------
*/
pub mod python_class {
use pyo3::class::basic::CompareOp;
use pyo3::prelude::*;
use pyo3::types::PySlice;
use crate::math::matrix::{Matrix3, Matrix4};
use crate::math::vector::{Vector2, Vector3, Vector4, VectorTrait};
#[derive(Clone)]
#[pyclass(name = "Vector2_rs")]
pub struct PyVector2 {
pub data: Vector2,
}
#[derive(Clone)]
#[pyclass(name = "Vector3_rs")]
pub struct PyVector3 {
pub data: Vector3,
}
#[derive(Clone)]
#[pyclass(name = "Vector4_rs")]
pub struct PyVector4 {
pub data: Vector4,
}
#[derive(Clone)]
#[pyclass(name = "Matrix3_rs")]
pub struct PyMatrix3 {
pub data: Matrix3,
}
#[derive(Clone)]
#[pyclass(name = "Matrix4_rs")]
pub struct PyMatrix4 {
pub data: Matrix4,
}
#[allow(unused)]
pub trait PyCalc {
fn __add__(&self, other: &Self) -> Self;
fn __sub__(&self, other: &Self) -> Self;
fn __mul__(&self, other: &Self) -> Self;
fn __truediv__(&self, other: &Self) -> Self;
fn __floordiv__(&self, other: &Self) -> Self;
fn __abs__(&self) -> f64;
fn __neg__(&self) -> Self;
fn __round__(&self, ndigits: Option<i64>) -> Self;
fn __radd__(&self, other: &PyAny) -> Self;
// fn rotate
}
/// 这是一个用来自动给 impl xxx for xxx 的块去掉 trait 部分的宏
/// 用于在为 pyclass 实现
#[pymethods]
impl PyVector2 {
#[new]
fn py_new(x: f64, y: f64) -> Self {
return Self {
data: Vector2::new(x, y),
};
}
fn __add__(&self, other: &Self) -> Self {
return Self {
data: self.data + other.data,
};
}
fn __radd__(&self, other: &PyAny) -> Self {
return if other.is_instance_of::<PyVector2>().unwrap() {
Self {
data: self.data + other.extract::<PyVector2>().unwrap().data,
}
} else {
// if other == 0
if other.is_none() {
self.clone()
} else {
Self {
data: self.data + Vector2::from_same(other.extract::<f64>().unwrap()),
}
}
};
}
fn __sub__(&self, other: &Self) -> Self {
return Self {
data: self.data - other.data,
};
}
fn __mul__(&self, other: &Self) -> Self {
return Self {
data: self.data * other.data,
};
}
fn __truediv__(&self, other: &Self) -> Self {
return Self {
data: self.data / other.data,
};
}
fn __floordiv__(&self, other: &Self) -> Self {
return Self {
data: self.data.floordiv(&other.data),
};
}
fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self.data < other.data),
CompareOp::Le => Ok(self.data <= other.data),
CompareOp::Eq => Ok(self.data == other.data),
CompareOp::Ne => Ok(self.data != other.data),
CompareOp::Gt => Ok(self.data > other.data),
CompareOp::Ge => Ok(self.data >= other.data),
}
}
fn __repr__(&self) -> String {
return format!("Vector2_rs({}, {})", self.data.x, self.data.y);
}
// fn __getitem__(&self, item: &PyAny) -> PyResult<&PyAny> {
// if item.is_instance_of::<PySlice>().unwrap() {
// let item = item.extract::<PySlice>().unwrap();
// let indices = item.indices().unwrap();
// }
// }
// getter and setter
#[getter]
fn get_x(&self) -> f64 {
return self.data.x;
}
#[getter]
fn get_y(&self) -> f64 {
return self.data.y;
}
#[setter]
fn set_x(&mut self, x: f64) {
self.data.x = x;
}
#[setter]
fn set_y(&mut self, y: f64) {
self.data.y = y;
}
}
#[pymethods]
impl PyVector3 {
#[new]
fn py_new(x: f64, y: f64, z: f64) -> Self {
return Self {
data: Vector3::new(x, y, z),
};
}
fn __add__(&self, other: &Self) -> Self {
return Self {
data: self.data + other.data,
};
}
fn __sub__(&self, other: &Self) -> Self {
return Self {
data: self.data - other.data,
};
}
fn __mul__(&self, other: &Self) -> Self {
return Self {
data: self.data * other.data,
};
}
fn __truediv__(&self, other: &Self) -> Self {
return Self {
data: self.data / other.data,
};
}
fn __floordiv__(&self, other: &Self) -> Self {
return Self {
data: self.data.floordiv(&other.data),
};
}
fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self.data < other.data),
CompareOp::Le => Ok(self.data <= other.data),
CompareOp::Eq => Ok(self.data == other.data),
CompareOp::Ne => Ok(self.data != other.data),
CompareOp::Gt => Ok(self.data > other.data),
CompareOp::Ge => Ok(self.data >= other.data),
}
}
fn __repr__(&self) -> String {
return format!(
"Vector3_rs({}, {}, {})",
self.data.x, self.data.y, self.data.z
);
}
// getter and setter
#[getter]
fn get_x(&self) -> f64 {
return self.data.x;
}
#[getter]
fn get_y(&self) -> f64 {
return self.data.y;
}
#[getter]
fn get_z(&self) -> f64 {
return self.data.z;
}
#[setter]
fn set_x(&mut self, x: f64) {
self.data.x = x;
}
#[setter]
fn set_y(&mut self, y: f64) {
self.data.y = y;
}
#[setter]
fn set_z(&mut self, z: f64) {
self.data.z = z;
}
}
#[pymethods]
impl PyVector4 {
#[new]
fn py_new(x: f64, y: f64, z: f64, w: f64) -> Self {
return Self {
data: Vector4::new(x, y, z, w),
};
}
fn __add__(&self, other: &Self) -> Self {
return Self {
data: self.data + other.data,
};
}
fn __sub__(&self, other: &Self) -> Self {
return Self {
data: self.data - other.data,
};
}
fn __mul__(&self, other: &Self) -> Self {
return Self {
data: self.data * other.data,
};
}
fn __truediv__(&self, other: &Self) -> Self {
return Self {
data: self.data / other.data,
};
}
fn __floordiv__(&self, other: &Self) -> Self {
return Self {
data: self.data.floordiv(&other.data),
};
}
fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self.data < other.data),
CompareOp::Le => Ok(self.data <= other.data),
CompareOp::Eq => Ok(self.data == other.data),
CompareOp::Ne => Ok(self.data != other.data),
CompareOp::Gt => Ok(self.data > other.data),
CompareOp::Ge => Ok(self.data >= other.data),
}
}
fn __repr__(&self) -> String {
return format!(
"Vector4_rs({}, {}, {}, {})",
self.data.x, self.data.y, self.data.z, self.data.w
);
}
// getter and setter
#[getter]
fn get_x(&self) -> f64 {
return self.data.x;
}
#[getter]
fn get_y(&self) -> f64 {
return self.data.y;
}
#[getter]
fn get_z(&self) -> f64 {
return self.data.z;
}
#[getter]
fn get_w(&self) -> f64 {
return self.data.w;
}
#[setter]
fn set_x(&mut self, x: f64) {
self.data.x = x;
}
#[setter]
fn set_y(&mut self, y: f64) {
self.data.y = y;
}
#[setter]
fn set_z(&mut self, z: f64) {
self.data.z = z;
}
#[setter]
fn set_w(&mut self, w: f64) {
self.data.w = w;
}
}
}

View File

@ -1,226 +0,0 @@
/*
* -------------------------------
* Difficult Rocket
* Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
* All rights reserved
* -------------------------------
*/
use pyo3::intern;
use pyo3::prelude::*;
// use pyo3::types::PyDict;
/// Instance of an on-screen image
/// See the module documentation for usage.
#[pyclass(name = "Sprite_rs", subclass)]
#[pyo3(text_signature = "(img, x=0.0, y=0.0, z=0.0, \
blend_src=770, blend_dest=771, \
batch=None, group=None, \
subpixel=False, program=None)")]
pub struct Sprite {
// render
pub subpixel: bool,
pub batch: Py<PyAny>,
pub group: Option<Py<PyAny>>,
pub user_group: Option<Py<PyAny>>,
pub group_class: Py<PyAny>,
// view
pub x: f64,
pub y: f64,
pub z: f64,
pub scale: f64,
pub scale_x: f64,
pub scale_y: f64,
pub visible: bool,
pub vertex_list: Option<Vec<()>>,
// frame
pub frame_index: u32,
pub next_dt: f64,
#[pyo3(get)]
pub program: Option<Py<PyAny>>,
pub animation: Option<Py<PyAny>>,
pub texture: Option<Py<PyAny>>,
pub paused: bool,
// other
pub rotation: f64,
pub rgba: (u8, u8, u8, u8),
}
#[pymethods]
impl Sprite {
/// python code:
/// 366:
/// if isinstance(img, image.Animation):
/// self._animation = img
/// self._texture = img.frames[0].image.get_texture()
/// self._next_dt = img.frames[0].duration
/// if self._next_dt:
/// clock.schedule_once(self._animate, self._next_dt)
/// else:
/// self._texture = img.get_texture()
/// 375:
/// if not program:
/// if isinstance(img, image.TextureArrayRegion):
/// self._program = get_default_array_shader()
/// else:
/// self._program = get_default_shader()
/// else:
/// self._program = program
/// 383:
/// self._batch = batch or graphics.get_default_batch()
/// self._user_group = group
/// self._group = self.group_class(self._texture, blend_src, blend_dest, self.program, group)
/// self._subpixel = subpixel
/// 387:
/// self._create_vertex_list()
#[new]
fn new(
py_: Python,
img: &PyAny,
x: f64,
y: f64,
z: f64,
blend_src: u32, // default 770 (GL_SRC_ALPHA)
blend_dest: u32, // default 771 (GL_ONE_MINUS_SRC_ALPHA)
batch_: &PyAny,
group: &PyAny,
subpixel: bool,
program_: &PyAny,
) -> Self {
let texture;
let batch;
let mut next_dt = 0.0;
let mut animation = None;
let mut program = program_;
let sprite_group_class = PyModule::import(py_, "pyglet.sprite")
.unwrap()
.getattr("SpriteGroup")
.unwrap();
// 366
let animation_class = PyModule::import(py_, "pyglet.image.Animation")
.unwrap()
.getattr("Animation")
.unwrap();
if img.is_instance(animation_class).unwrap() {
animation = Some(img.into());
texture = img
.getattr(intern!(img.py(), "frames"))
.unwrap()
.get_item(0)
.unwrap()
.getattr(intern!(img.py(), "image"))
.unwrap()
.call_method0(intern!(img.py(), "get_texture"))
.unwrap();
let _next_dt = img
.getattr(intern!(img.py(), "frames"))
.unwrap()
.get_item(0)
.unwrap()
.getattr(intern!(img.py(), "duration"));
next_dt = match _next_dt {
Ok(v) => v.extract().unwrap(),
Err(_) => 0.0,
}
// 372
} else {
texture = img.call_method0(intern!(img.py(), "get_texture")).unwrap();
}
// 375
if !program.is_true().unwrap() {
let texture_array_region_class =
PyModule::import(py_, "pyglet.image.TextureArrayRegion")
.unwrap()
.getattr("TextureArrayRegion")
.unwrap();
if img.is_instance(texture_array_region_class).unwrap() {
// self._program = get_default_array_shader()
let get_default_array_shader = PyModule::import(py_, "pyglet.sprite")
.unwrap()
.getattr("get_default_array_shader")
.unwrap();
program = get_default_array_shader.call0().unwrap();
} else {
// self._program = get_default_shader()
let get_default_shader = PyModule::import(py_, "pyglet.sprite")
.unwrap()
.getattr("get_default_shader")
.unwrap();
program = get_default_shader.call0().unwrap();
}
}
// 383
if !batch_.is_none() {
batch = PyModule::import(py_, "pyglet.graphics")
.unwrap()
.getattr("get_default_batch")
.unwrap()
.call0()
.unwrap();
} else {
batch = batch_;
}
// 385
let group = sprite_group_class
.call1((texture, blend_src, blend_dest, program, group))
.unwrap();
Sprite {
subpixel,
batch: batch.into(),
group: Some(group.into()),
user_group: Some(group.into()),
group_class: group.into(),
x,
y,
z,
scale: 1.0,
scale_x: 1.0,
scale_y: 1.0,
visible: true,
vertex_list: None,
frame_index: 0,
next_dt,
program: Some(program.into()),
animation: animation,
texture: Some(texture.into()),
paused: false,
rotation: 0.0,
rgba: (255, 255, 255, 255),
}
}
// python code:
// 390:
// def _create_vertex_list(self):
// texture = self._texture
// self._vertex_list = self.program.vertex_list(
// 1, GL_POINTS, self._batch, self._group,
// position=('f', (self._x, self._y, self._z)),
// size=('f', (texture.width, texture.height, 1, 1)),
// color=('Bn', self._rgba),
// texture_uv=('f', texture.uv),
// rotation=('f', (self._rotation,)))
// pub fn _create_vertex_list(&mut self) -> PyResult<()> {
// let texture = self.texture.as_ref()?;
// Python::with_gil(|py| -> PyResult<()> {
// let args = PyDict::new(py);
// args.set_item("position", (self.x, self.y, self.z))?;
// args.set_item(
// "size",
// (
// texture.getattr(py, "width")?,
// texture.getattr(py, "height")?,
// 1,
// 1,
// ),
// )?;
// args.set_item("color", ("Bn", self.rgba))?;
// args.set_item("texture_uv", texture.getattr(py, "uv")?)?;
// args.set_item("rotation", (self.rotation,))?;
// Ok(())
// })?;
// Ok(())
// }
}

View File

@ -1,71 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
import random
import unittest
from typing import Tuple
from libs.pyglet_rs import Vector2_rs, Vector3_rs, Vector4_rs
# 用于自动在测试运行前后输出测试信息的装饰器
def print_test_info(func):
def wrapper(*args, **kwargs):
print(f"{'=' * 20} {func.__name__} {'=' * 20}")
func(*args, **kwargs)
print(f"{'=' * 20} {func.__name__} {'=' * 20}")
return wrapper
def gen_random_vector() -> Tuple[Vector2_rs, Vector3_rs, Vector4_rs]:
vec2 = Vector2_rs(random.randint(1, 100), random.randint(1, 100))
vec3 = Vector3_rs(random.randint(1, 100), random.randint(1, 100), random.randint(1, 100))
vec4 = Vector4_rs(random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100))
return vec2, vec3, vec4
class TestVector(unittest.TestCase):
@print_test_info
def test1_create_print_vector(self):
vec2, vec3, vec4 = gen_random_vector()
print(f"{vec2=}")
print(f"{vec3=}")
print(f"{vec4=}")
@print_test_info
def test2_calculate_vector(self):
vec2, vec3, vec4 = gen_random_vector()
vec2_1, vec3_1, vec4_1 = gen_random_vector()
print('test add')
self.assertEqual(vec2 + vec2_1, Vector2_rs(vec2.x + vec2_1.x, vec2.y + vec2_1.y))
self.assertEqual(vec3 + vec3_1, Vector3_rs(vec3.x + vec3_1.x, vec3.y + vec3_1.y, vec3.z + vec3_1.z))
self.assertEqual(vec4 + vec4_1, Vector4_rs(vec4.x + vec4_1.x, vec4.y + vec4_1.y, vec4.z + vec4_1.z, vec4.w + vec4_1.w))
print('test sub')
self.assertEqual(vec2 - vec2_1, Vector2_rs(vec2.x - vec2_1.x, vec2.y - vec2_1.y))
self.assertEqual(vec3 - vec3_1, Vector3_rs(vec3.x - vec3_1.x, vec3.y - vec3_1.y, vec3.z - vec3_1.z))
self.assertEqual(vec4 - vec4_1, Vector4_rs(vec4.x - vec4_1.x, vec4.y - vec4_1.y, vec4.z - vec4_1.z, vec4.w - vec4_1.w))
print('test mul')
self.assertEqual(vec2 * vec2_1, Vector2_rs(vec2.x * vec2_1.x, vec2.y * vec2_1.y))
self.assertEqual(vec3 * vec3_1, Vector3_rs(vec3.x * vec3_1.x, vec3.y * vec3_1.y, vec3.z * vec3_1.z))
self.assertEqual(vec4 * vec4_1, Vector4_rs(vec4.x * vec4_1.x, vec4.y * vec4_1.y, vec4.z * vec4_1.z, vec4.w * vec4_1.w))
print('test true_div')
self.assertEqual(vec2 / vec2_1, Vector2_rs(vec2.x / vec2_1.x, vec2.y / vec2_1.y))
self.assertEqual(vec3 / vec3_1, Vector3_rs(vec3.x / vec3_1.x, vec3.y / vec3_1.y, vec3.z / vec3_1.z))
self.assertEqual(vec4 / vec4_1, Vector4_rs(vec4.x / vec4_1.x, vec4.y / vec4_1.y, vec4.z / vec4_1.z, vec4.w / vec4_1.w))
print('test floor_div')
self.assertEqual(vec2 // vec2_1, Vector2_rs(vec2.x // vec2_1.x, vec2.y // vec2_1.y))
self.assertEqual(vec3 // vec3_1, Vector3_rs(vec3.x // vec3_1.x, vec3.y // vec3_1.y, vec3.z // vec3_1.z))
self.assertEqual(vec4 // vec4_1, Vector4_rs(vec4.x // vec4_1.x, vec4.y // vec4_1.y, vec4.z // vec4_1.z, vec4.w // vec4_1.w))