DR rs 0.3.3

This commit is contained in:
shenjack 2024-05-16 00:33:25 +08:00
parent ea76747998
commit a6f8a70895
Signed by: shenjack
GPG Key ID: 7B1134A979775551
12 changed files with 70 additions and 68 deletions

View File

@ -9,7 +9,7 @@ import argparse
# fmt: off
basic = {
"images": [
'pillow >= 10.2.0; (platform_python_implementation == "PyPy" and '
'pillow >= 10.3.0; (platform_python_implementation == "PyPy" and '
'python_version < "3.10") or platform_python_implementation == "CPython"',
],
"sys info": [
@ -24,17 +24,18 @@ basic = {
build = {
"compile": [
"nuitka >= 2.0.0",
"imageio >= 2.33.1",
"nuitka >= 2.2.2",
"imageio >= 2.34.1",
"setuptools >= 69",
"setuptools-rust >= 1.8.1"
"setuptools-rust >= 1.9.0",
"wheel >= 0.37.0",
]
}
dev = {
"debug": [
"objprint >= 0.2.3",
"viztracer >= 0.16.1; platform_python_implementation != \"PyPy\"",
"viztracer >= 0.16.3; platform_python_implementation != \"PyPy\"",
"vizplugins >= 0.1.3; platform_python_implementation != \"PyPy\""
]
}

View File

@ -9,12 +9,6 @@ from .lib import * # noqa: F403
from typing import TYPE_CHECKING, Dict, Tuple, Optional, List
if TYPE_CHECKING:
def test_call(py_obj) -> bool:
"""这里展示的代码实际上就是实际的等效实现"""
py_obj.draw()
return True
def get_version_str() -> str:
"""
获取版本号

View File

@ -20,6 +20,12 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
[[package]]
name = "anyhow"
version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3"
[[package]]
name = "approx"
version = "0.5.1"
@ -140,10 +146,10 @@ dependencies = [
[[package]]
name = "difficult_rocket_rs"
version = "0.3.2"
version = "0.3.3"
dependencies = [
"anyhow",
"dict_derive",
"fs-err",
"nalgebra",
"pyo3",
"quick-xml",
@ -163,15 +169,6 @@ version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2"
[[package]]
name = "fs-err"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41"
dependencies = [
"autocfg",
]
[[package]]
name = "hashbrown"
version = "0.14.5"

View File

@ -1,6 +1,6 @@
[package]
name = "difficult_rocket_rs"
version = "0.3.2"
version = "0.3.3"
edition = "2021"
license-file = '../../LICENSE'
authors = ["shenjackyuanjie <3695888@qq.com>"]
@ -22,7 +22,7 @@ panic = "abort"
opt-level = 2
[dependencies]
fs-err = "2.11.0"
anyhow = "1.0"
quick-xml = { version = "0.31.0", features = ["serialize"] }
serde = { version = "1.0", features = ["derive"] }

View File

@ -19,17 +19,10 @@ fn get_version_str() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[pyfunction]
fn test_call(py_obj: &PyAny) -> PyResult<bool> {
py_obj.call_method0("draw")?;
Ok(true)
}
#[pymodule]
#[pyo3(name = "Difficult_Rocket_rs")]
fn module_init(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(get_version_str, m)?)?;
m.add_function(wrap_pyfunction!(test_call, m)?)?;
m.add_function(wrap_pyfunction!(sr1_parse::part_list::read_part_list_py, m)?)?;
m.add_function(wrap_pyfunction!(sr1_parse::ship::py_raw_ship_from_file, m)?)?;
m.add_function(wrap_pyfunction!(python::data::load_and_save_test, m)?)?;

View File

@ -109,7 +109,13 @@ impl PySR1PartList {
#[new]
#[pyo3(text_signature = "(file_path = './assets/builtin/PartList.xml', list_name = 'NewPartList')")]
fn new(file_path: String, list_name: String) -> Self {
let raw_part_list: RawPartList = RawPartList::from_file(file_path).unwrap();
let raw_part_list: RawPartList = match RawPartList::from_file(file_path.clone()) {
Ok(raw_part_list) => raw_part_list,
Err(e) => {
println!("ERROR!\n{}\n----------", e);
panic!("Parse part list failed! {}\n{e}", file_path);
}
};
let data = raw_part_list.to_sr_part_list(Some(list_name));
Self { data }
}

View File

@ -6,7 +6,7 @@ use crate::dr_physics::math::{Edge, Shape};
use crate::dr_physics::math::{Point2D, Rotate};
use crate::sr1_parse::part_list::Damage as RawDamage;
use crate::sr1_parse::part_list::{AttachPoint, AttachPoints, Engine, Lander, Rcs, Shape as RawShape, Solar, Tank};
use crate::sr1_parse::part_list::{RawPartList, RawPartType, SR1PartTypeEnum, FuelType};
use crate::sr1_parse::part_list::{FuelType, RawPartList, RawPartType, SR1PartTypeEnum};
use crate::sr1_parse::ship::{
Activate as RawActivate, Connection, Connections, DisconnectedPart as RawDisconnectedPart,
DisconnectedParts as RawDisconnectedParts, Engine as RawEngine, Part as RawPartData, Parts as RawParts,
@ -19,7 +19,6 @@ use std::collections::HashMap;
use std::io::Cursor;
use std::ops::Deref;
use fs_err as fs;
use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::writer::Writer;
@ -174,7 +173,7 @@ impl SR1PartList {
}
pub fn from_file(file_name: String) -> Option<SR1PartList> {
if let Some(raw_list) = RawPartList::from_file(file_name) {
if let Ok(raw_list) = RawPartList::from_file(file_name) {
let sr_list = raw_list.to_sr_part_list(None);
return Some(sr_list);
}
@ -898,7 +897,7 @@ impl SR1Ship {
String::from_utf8(writer.into_inner().into_inner()).unwrap()
}
fs::write(file_name, write_data(self, save_status)).unwrap();
std::fs::write(file_name, write_data(self, save_status)).unwrap();
Some(())
}
}

View File

@ -1,7 +1,7 @@
use crate::sr1_parse::{SR1PartList, SR1PartType, SR1PartTypeAttr};
use crate::sr1_parse::{SR1PartListTrait, SR1PartTypeData};
use fs_err as fs;
use anyhow::Result;
use pyo3::prelude::*;
use quick_xml::de::from_str;
use serde::{Deserialize, Serialize};
@ -153,12 +153,16 @@ impl Damage {
pub enum FuelType {
/// 就是液体燃料
#[default]
#[serde(rename = "0")]
Common = 0,
/// RCS 推进剂
#[serde(rename = "1")]
Rcs = 1,
/// 电!!!!!
#[serde(rename = "2")]
Battery = 2,
/// 固推神教!
#[serde(rename = "3")]
Soild = 3,
}
@ -376,10 +380,10 @@ impl RawPartList {
RawPartList { part_types: parts }
}
pub fn from_file(file_name: String) -> Option<RawPartList> {
let part_list_file = fs::read_to_string(file_name).ok()?;
let part_list: RawPartList = from_str(part_list_file.as_str()).ok()?;
Some(part_list)
pub fn from_file(file_name: String) -> Result<Self> {
let part_list_file = std::fs::read_to_string(file_name)?;
let part_list: RawPartList = from_str(part_list_file.as_str())?;
Ok(part_list)
}
pub fn list_print(&self) {
@ -407,11 +411,12 @@ impl SR1PartListTrait for RawPartList {
#[pyo3(name = "part_list_read_test", signature = (file_name = "./assets/builtin/PartList.xml".to_string()))]
pub fn read_part_list_py(_py: Python, file_name: Option<String>) -> PyResult<()> {
let file_name = file_name.unwrap_or("./assets/builtin/PartList.xml".to_string());
let _parts = RawPartList::from_file(file_name);
if let Some(parts) = _parts {
// println!("{:?}", parts)
parts.list_print();
let _part_list = parts.to_sr_part_list(Some("Vanilla".to_string()));
}
// let _parts = RawPartList::from_file(file_name);
// if let Some(parts) = _parts {
// // println!("{:?}", parts)
// parts.list_print();
// let _part_list = parts.to_sr_part_list(Some("Vanilla".to_string()));
// }
println!("{:?}", RawPartList::from_file(file_name));
Ok(())
}

View File

@ -2,11 +2,10 @@ use crate::sr1_parse::{SR1PartData, SR1PartDataAttr, SR1Ship};
use crate::sr1_parse::{SR1PartDataTrait, SR1ShipTrait};
use crate::IdType;
use fs_err as fs;
use anyhow::Result;
use pyo3::prelude::*;
use quick_xml::de::from_str;
use quick_xml::se::to_string;
// use quick_xml::Error as XmlError;
use serde::{Deserialize, Serialize};
/// https://docs.rs/quick-xml/latest/quick_xml/de/index.html#basics
@ -240,7 +239,7 @@ impl SR1ShipTrait for RawShip {
impl RawShip {
pub fn from_file(path: String) -> Option<RawShip> {
let ship_file = fs::read_to_string(path); // for encoding error
let ship_file = std::fs::read_to_string(path); // for encoding error
if let Err(e) = ship_file {
println!("ERROR!\n{}\n----------", e);
return None;
@ -256,14 +255,10 @@ impl RawShip {
}
}
pub fn save(&self, file_name: String) -> Result<(), quick_xml::DeError> {
pub fn save(&self, file_name: String) -> Result<()> {
let part_list_file = to_string(self)?;
print!("{:?}", part_list_file);
match fs::write(file_name, part_list_file) {
Ok(()) => (),
Err(_) => return Err(quick_xml::DeError::Custom("Failed to save file!".to_string())),
}
std::fs::write(file_name, part_list_file)?;
Ok(())
}
}
@ -272,7 +267,7 @@ impl RawShip {
#[pyo3(name = "read_ship_test")]
#[pyo3(signature = (path = "./assets/builtin/dock1.xml".to_string()))]
pub fn py_raw_ship_from_file(path: String) -> PyResult<bool> {
let file = fs::read_to_string(path)?;
let file = std::fs::read_to_string(path)?;
let raw_ship = from_str::<RawShip>(&file);
match raw_ship {
Ok(ship) => {

View File

@ -16,7 +16,7 @@ from Difficult_Rocket.api.types import Options, Version
from lib_not_dr import loggers
DR_rust_version = Version("0.3.2") # DR_mod 的 Rust 编写部分的兼容版本
DR_rust_version = Version("0.3.3") # DR_mod 的 Rust 编写部分的兼容版本
logger = loggers.config.get_logger_from_old("client.dr_game", "client")
@ -40,7 +40,8 @@ class _DR_mod_runtime(Options): # NOQA
"larger" if self.DR_rust_version > self.DR_rust_version else "smaller"
)
logger.warn(
f"DR_rust builtin version is {self.DR_rust_version} but true version is {get_version_str()}.\n"
f"DR_rust builtin version is {self.DR_rust_version} "
f"but true version is {get_version_str()}.\n"
f"Builtin version {relationship} than true version",
tag="load_dll",
)

View File

@ -74,7 +74,7 @@ class SR1ShipRender(BaseScreen):
def __init__(self, main_window: ClientWindow):
super().__init__(main_window)
self.logger = logger
logger.info(sr_tr().mod.info.setup.start())
logger.info(sr_tr().mod.info.setup.start(), tag="setup")
load_start_time = time.time_ns()
# status
self.status = SR1ShipRenderStatus()
@ -150,7 +150,8 @@ class SR1ShipRender(BaseScreen):
logger.info(
sr_tr()
.mod.info.setup.use_time()
.format((load_end_time - load_start_time) / 1000000000)
.format((load_end_time - load_start_time) / 1000000000),
tag="setup",
)
@property
@ -171,20 +172,21 @@ class SR1ShipRender(BaseScreen):
"""
try:
start_time = time.time_ns()
logger.info(sr_tr().sr1.ship.xml.loading().format(file_path))
logger.info(sr_tr().sr1.ship.xml.loading().format(file_path), tag="load_xml")
self.ship_name = file_path.split("/")[-1].split(".")[0]
if DR_mod_runtime.use_DR_rust:
self.rust_ship = SR1Ship_rs(file_path, self.part_list_rs, "a_new_ship")
logger.info(sr_tr().sr1.ship.xml.load_done())
logger.info(sr_tr().sr1.ship.xml.load_done(), tag="load_xml")
logger.info(
sr_tr()
.sr1.ship.xml.load_time()
.format((time.time_ns() - start_time) / 1000000000)
.format((time.time_ns() - start_time) / 1000000000),
tag="load_xml",
)
return True
except Exception:
traceback.print_exc()
self.logger.error(traceback.format_exc())
self.logger.error(traceback.format_exc(), tag="load_xml")
return False
def gen_sprite(self, each_count: int = 100) -> Generator:
@ -349,7 +351,7 @@ class SR1ShipRender(BaseScreen):
渲染船
"""
self.status.draw_done = False
logger.info(sr_tr().sr1.ship.ship.load().format(self.ship_name))
logger.info(sr_tr().sr1.ship.ship.load().format(self.ship_name), tag="ship")
start_time = time.perf_counter_ns()
self.parts_sprite: Dict[int, Sprite] = {}
self.part_line_box = {}
@ -369,7 +371,8 @@ class SR1ShipRender(BaseScreen):
logger.info(
sr_tr()
.sr1.ship.ship.load_time()
.format((time.perf_counter_ns() - start_time) / 1000000000)
.format((time.perf_counter_ns() - start_time) / 1000000000),
tag="ship"
)
logger.info(
sr_tr()
@ -379,7 +382,8 @@ class SR1ShipRender(BaseScreen):
f"{full_mass}kg"
if DR_mod_runtime.use_DR_rust
else sr_tr().game.require_DR_rs(),
)
),
tag="ship",
)
def draw_batch(self, window: ClientWindow):
@ -430,6 +434,8 @@ class SR1ShipRender(BaseScreen):
return
self.render_d_line.x2 = width // 2
self.render_d_line.y2 = height // 2
self.width = width
self.height = height
def on_mouse_scroll(
self, x: int, y: int, scroll_x: int, scroll_y: int, window: ClientWindow

View File

@ -13,6 +13,11 @@ if __name__ == "__main__":
# 移动到项目根目录
os.chdir("./mods/dr_game/Difficult_Rocket_rs/src")
os.chdir("./src")
subprocess.run(["cargo", "fmt", "--all"])
os.chdir("../")
if not args.py:
if args.all: