just like mess

This commit is contained in:
shenjack 2023-04-05 01:27:34 +08:00
parent dcd490b1c7
commit 767fd4877d
7 changed files with 74 additions and 184 deletions

View File

@ -5,6 +5,7 @@
# -------------------------------
import time
import logging
import contextlib
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
@ -13,7 +14,6 @@ from typing import List, TYPE_CHECKING, Union, Dict, Optional, Generator
# third party package
from defusedxml.ElementTree import parse
import pyglet.graphics
# pyglet
from pyglet.math import Vec4
from pyglet.text import Label
@ -23,6 +23,7 @@ from pyglet.graphics import Batch, Group
# Difficult Rocket
from Difficult_Rocket import DR_option
from Difficult_Rocket.utils.translate import tr
from Difficult_Rocket.api.types import Fonts, Options
from Difficult_Rocket.command.line import CommandText
from Difficult_Rocket.client.screen import BaseScreen
@ -32,7 +33,10 @@ if TYPE_CHECKING:
from Difficult_Rocket.client import ClientWindow
if DR_option.use_DR_rust:
from libs.Difficult_Rocket_rs import PartDatas, CenterCamera_rs
from libs.Difficult_Rocket_rs import CenterCamera_rs, SR1PartData
logger = logging.getLogger('client')
def get_sr1_part(part_xml: Element) -> Optional[SR1PartData]:
@ -121,6 +125,7 @@ class SR1ShipRender(BaseScreen):
self.camera_rs = CenterCamera_rs(main_window,
min_zoom=(1 / 2) ** 10, max_zoom=10)
self.rust_parts = None
self.part_list_rs =
def load_xml(self, file_path: str) -> bool:
try:
@ -182,7 +187,6 @@ class SR1ShipRender(BaseScreen):
for part_xml in parts:
if part_xml.tag != 'Part':
continue # 如果不是部件,则跳过
# print(f"tag: {part.tag} attrib: {part.attrib}")
part = get_sr1_part(part_xml)
if part.id in self.part_data:
print(f'hey! warning! id{part.id}')
@ -194,11 +198,6 @@ class SR1ShipRender(BaseScreen):
except GeneratorExit:
self.drawing = False
self.need_draw = False
if DR_option.use_DR_rust:
print(type(self.part_data))
self.rust_parts = PartDatas(self.part_data)
# print(self.rust_parts.get_rust_pointer())
print(len(self.part_data))
print(time.perf_counter_ns() - start_time)
self.rendered = True
@ -322,7 +321,7 @@ class SR1ShipRender(BaseScreen):
elif command.re_match('get_buf'):
def screenshot(window):
from libs.pyglet.gl import GLubyte, GLint, GL_RGBA, GL_UNSIGNED_BYTE, \
from libs.pyglet.gl import GLubyte, GL_RGBA, GL_UNSIGNED_BYTE, \
glReadPixels
import pyglet

View File

@ -31,21 +31,6 @@ if TYPE_CHECKING:
def part_list_read_test(file_name: Optional[str] = "./configs/PartList.xml") -> None: ...
class PartDatas:
""" 用于在 PyObj 里塞一个浓眉大眼的 HashMap<uszie, SR1PartData>"""
def __new__(cls, py_part_data: Dict[int, SR1PartData]) -> "PartDatas": ...
def get_rust_pointer(self) -> int: ...
def better_update_parts(render: SR1ShipRender,
option: SR1ShipRender_Option,
window: BaseScreen,
parts: PartDatas,
sr1_xml_scale: int) -> bool: ...
class Camera_rs:
""" 用于闲的没事 用 rust 写一个 camera """

View File

@ -6,10 +6,10 @@
* -------------------------------
*/
mod render;
mod simulator;
mod sr1_data;
mod sr1_render;
mod render;
mod logger;
mod types;
use pyo3::prelude::*;
@ -33,10 +33,8 @@ fn test_call(py_obj: &PyAny) -> PyResult<bool> {
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_render::better_update_parts, m)?)?;
m.add_function(wrap_pyfunction!(simulator::simluation, m)?)?;
m.add_function(wrap_pyfunction!(sr1_data::part_list::read_part_list_py, m)?)?;
m.add_class::<sr1_render::types::PartDatas>()?;
m.add_class::<render::camera::CameraRs>()?;
m.add_class::<render::camera::CenterCameraRs>()?;
m.add_class::<render::screen::PartFrame>()?;

View File

@ -0,0 +1,8 @@
/*
* -------------------------------
* Difficult Rocket
* Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
* All rights reserved
* -------------------------------
*/

View File

@ -14,7 +14,7 @@ pub mod part_list {
// use quick_xml::de::from_str;
use serde_xml_rs::from_str;
use crate::types::sr1::{SR1PartAttr, SR1PartList, SR1PartType};
use crate::types::sr1::{SR1PartList, SR1PartType, SR1PartTypeAttr};
use crate::types::sr1::{SR1PartListTrait, SR1PartTypeData};
#[derive(Debug, Serialize, Deserialize, Clone)]
@ -236,10 +236,10 @@ pub mod part_list {
impl SR1PartTypeData for RawPartType {
fn to_sr_part_type(&self) -> SR1PartType {
let part_attr: Option<SR1PartAttr> = match self.r#type {
let part_attr: Option<SR1PartTypeAttr> = match self.r#type {
SR1PartTypeEnum::tank => {
let tank = self.tank.unwrap();
Some(SR1PartAttr::Tank {
Some(SR1PartTypeAttr::Tank {
fuel: tank.fuel,
dry_mass: tank.dry_mass,
fuel_type: tank.fuel_type.unwrap_or(0),
@ -247,7 +247,7 @@ pub mod part_list {
}
SR1PartTypeEnum::engine => {
let engine = self.engine.unwrap();
Some(SR1PartAttr::Engine {
Some(SR1PartTypeAttr::Engine {
power: engine.power,
consumption: engine.consumption,
size: engine.size,
@ -258,7 +258,7 @@ pub mod part_list {
}
SR1PartTypeEnum::rcs => {
let rcs = self.rcs.unwrap();
Some(SR1PartAttr::Rcs {
Some(SR1PartTypeAttr::Rcs {
power: rcs.power,
consumption: rcs.consumption,
size: rcs.size,
@ -266,13 +266,13 @@ pub mod part_list {
}
SR1PartTypeEnum::solar => {
let solar = self.solar.unwrap();
Some(SR1PartAttr::Solar {
Some(SR1PartTypeAttr::Solar {
charge_rate: solar.charge_rate,
})
}
SR1PartTypeEnum::lander => {
let lander = self.lander.unwrap();
Some(SR1PartAttr::Lander {
Some(SR1PartTypeAttr::Lander {
max_angle: lander.max_angle,
min_length: lander.min_length,
max_length: lander.max_length,
@ -335,18 +335,6 @@ pub mod part_list {
println!("{:?}\n", part_data);
}
}
pub fn to_sr_part_list(&self, name: Option<String>) -> SR1PartList {
let mut part_list = Vec::new();
for part_data in self.part_types.iter() {
println!("{}", part_data.id.to_string());
part_list.push(part_data.to_sr_part_type());
}
SR1PartList {
types: part_list,
name: name.unwrap_or("NewPartList".to_string()),
}
}
}
impl SR1PartListTrait for RawPartList {
@ -402,7 +390,7 @@ pub mod ship {
use serde_xml_rs::from_str;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Ship {
pub struct RawShip {
#[serde(rename = "Parts")]
pub parts: Parts,
#[serde(rename = "Connections")]
@ -476,12 +464,12 @@ pub mod ship {
#[serde(rename = "Staging")]
pub stages: Vec<Staging>,
pub name: String,
pub throttle: i8,
pub throttle: f64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Tank {
pub fuel: i64,
pub fuel: f64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@ -536,4 +524,8 @@ pub mod ship {
#[serde(rename = "childPart")]
pub child_part: i64,
}
// pub fn read_ship_from_file(file_name: String) -> Result<RawShip, String> {
// }
}

View File

@ -1,122 +0,0 @@
/*
* -------------------------------
* Difficult Rocket
* Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
* All rights reserved
* -------------------------------
*/
use crate::types::sr1::SR1PartData;
use pyo3::intern;
use pyo3::prelude::*;
use std::collections::HashMap;
use std::time;
#[allow(dead_code)]
pub mod types {
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use std::collections::HashMap;
use crate::types::sr1::SR1PartData;
pub struct Point {
pub x: f64,
pub y: f64,
pub id: usize,
pub type_: String,
}
#[pyclass(name = "PartDatas")]
pub struct PartDatas {
pub part_structs: HashMap<i64, SR1PartData>,
}
impl PartDatas {
fn get_rust_data(&self) -> &HashMap<i64, SR1PartData> {
return &self.part_structs;
}
}
#[pymethods]
impl PartDatas {
#[new]
fn py_new(py_part_data: &PyDict) -> PyResult<Self> {
let datas: HashMap<i64, SR1PartData> = part_data_tp_SR1PartDatas(py_part_data)?;
return Ok(PartDatas {
part_structs: datas,
});
}
}
#[allow(non_snake_case)]
pub fn part_data_to_SR1PartData(input: &PyAny) -> PyResult<SR1PartData> {
let connections = match input.getattr(intern!(input.py(), "connections")) {
Ok(ok) => ok.extract()?,
_ => None,
};
return Ok(SR1PartData {
x: input.getattr(intern!(input.py(), "x"))?.extract()?,
y: input.getattr(intern!(input.py(), "y"))?.extract()?,
id: input.getattr(intern!(input.py(), "id"))?.extract()?,
p_type: input.getattr(intern!(input.py(), "p_type"))?.extract()?,
active: input.getattr(intern!(input.py(), "active"))?.extract()?,
angle: input.getattr(intern!(input.py(), "angle"))?.extract()?,
angle_v: input.getattr(intern!(input.py(), "angle_v"))?.extract()?,
editor_angle: input
.getattr(intern!(input.py(), "editor_angle"))?
.extract()?,
flip_x: input.getattr(intern!(input.py(), "flip_x"))?.extract()?,
flip_y: input.getattr(intern!(input.py(), "flip_y"))?.extract()?,
explode: input.getattr(intern!(input.py(), "explode"))?.extract()?,
textures: input.getattr(intern!(input.py(), "textures"))?.extract()?,
connections, // connections: input.getattr(intern!(input.py(), "connections"))?.extract()?,
});
}
#[allow(non_snake_case)]
pub fn part_data_tp_SR1PartDatas(input: &PyDict) -> PyResult<HashMap<i64, SR1PartData>> {
let mut result: HashMap<i64, SR1PartData> = HashMap::with_capacity(input.len());
for key in input.iter() {
result.insert(key.0.extract()?, part_data_to_SR1PartData(key.1)?);
}
return Ok(result);
}
}
#[pyfunction]
#[allow(unused_variables)]
pub fn better_update_parts(
render: &PyAny,
option: &PyAny,
window: &PyAny,
parts: &types::PartDatas,
sr1_xml_scale: i32,
) -> PyResult<bool> {
if !render
.getattr(intern!(render.py(), "rendered"))?
.is_true()?
{
return Ok(false);
}
let start_time = time::Instant::now();
let x_center: f32 = window.getattr(intern!(window.py(), "width"))?.extract()?;
let y_center: f32 = window.getattr(intern!(window.py(), "height"))?.extract()?;
let x_center: f32 = x_center / 2.0;
let y_center: f32 = y_center / 2.0;
let datas: &HashMap<i64, SR1PartData> = &parts.part_structs;
let part_sprites = render.getattr(intern!(render.py(), "parts_sprite"))?;
let get_stuf_time = start_time.elapsed();
for keys in datas {
let sprite = part_sprites.get_item(keys.0)?;
let new_x: f64 = keys.1.x * sr1_xml_scale as f64 + x_center as f64;
let new_y: f64 = keys.1.y * sr1_xml_scale as f64 + y_center as f64;
sprite.setattr(intern!(sprite.py(), "x"), new_x)?;
sprite.setattr(intern!(sprite.py(), "y"), new_y)?;
}
let run_time = start_time.elapsed();
Ok(true)
}

View File

@ -51,23 +51,36 @@ pub mod sr1 {
#[derive(Debug, Clone)]
pub struct SR1PartData {
// 单独的属性
pub attr: Option<SR1PartDataAttr>,
// 基本状态属性
pub x: f64,
pub y: f64,
pub id: i64,
pub p_type: String,
pub active: bool,
pub angle: f64, // 弧度制
pub angle_v: f64,
pub editor_angle: usize,
// 状态属性
pub part_type: String,
pub active: bool,
pub editor_angle: i32,
pub flip_x: bool,
pub flip_y: bool,
// 降落伞属性
pub chute_x: f64,
pub chute_y: f64,
pub chute_angle: f64,
pub chute_height: f64,
pub inflate: bool,
pub inflation: bool,
pub deployed: bool,
// 太阳能板属性
pub extension: f64,
pub explode: bool,
pub textures: String,
pub connections: Option<Vec<((usize, usize), (isize, isize))>>,
}
#[derive(Debug, Copy, Clone)]
pub enum SR1PartAttr {
pub enum SR1PartTypeAttr {
Tank {
fuel: f64,
dry_mass: f64,
@ -103,6 +116,22 @@ pub mod sr1 {
},
}
#[derive(Debug, Clone)]
pub enum SR1PartDataAttr {
Tank {
fuel: f64,
},
Engine {
fuel: f64,
},
Pod {
name: String,
throttle: f64,
current_stage: u32,
steps: Vec<(i64, bool)>,
},
}
#[derive(Debug, Copy, Clone)]
pub struct Damage {
pub disconnect: i32,
@ -171,7 +200,7 @@ pub mod sr1 {
// 部件碰撞箱
pub attach_points: Option<Vec<AttachPoint>>,
// 部件连接点
pub attr: Option<SR1PartAttr>, // 部件特殊属性
pub attr: Option<SR1PartTypeAttr>, // 部件特殊属性
}
#[derive(Debug, Clone)]
@ -243,7 +272,7 @@ pub mod sr1 {
fn to_raw_part_type(&self) -> RawPartType {
let tank: Option<Tank> = match &self.attr {
Some(attr) => match attr {
SR1PartAttr::Tank {
SR1PartTypeAttr::Tank {
fuel,
dry_mass,
fuel_type,
@ -258,7 +287,7 @@ pub mod sr1 {
};
let engine: Option<Engine> = match &self.attr {
Some(attr) => match attr {
SR1PartAttr::Engine {
SR1PartTypeAttr::Engine {
power,
consumption,
size,
@ -279,7 +308,7 @@ pub mod sr1 {
};
let rcs: Option<Rcs> = match &self.attr {
Some(attr) => match attr {
SR1PartAttr::Rcs {
SR1PartTypeAttr::Rcs {
power,
consumption,
size,
@ -294,7 +323,7 @@ pub mod sr1 {
};
let solar: Option<Solar> = match &self.attr {
Some(attr) => match attr {
SR1PartAttr::Solar { charge_rate } => Some(Solar {
SR1PartTypeAttr::Solar { charge_rate } => Some(Solar {
charge_rate: *charge_rate,
}),
_ => None,
@ -303,7 +332,7 @@ pub mod sr1 {
};
let lander: Option<Lander> = match &self.attr {
Some(attr) => match attr {
SR1PartAttr::Lander {
SR1PartTypeAttr::Lander {
max_angle,
min_length,
max_length,
@ -366,6 +395,7 @@ pub mod sr1 {
pub struct SR1Ship {
pub name: String,
pub description: String,
pub parts: Vec<SR1PartData>,
pub connections: Vec<String>,
pub lift_off: bool,
pub touch_ground: bool,