This commit is contained in:
Lapin Raving 2023-08-23 13:13:53 +02:00
parent 4a87821c22
commit baf149ef8a
23 changed files with 1030 additions and 856 deletions

View File

@ -1,7 +1,6 @@
///
/// $ cargo run --example populate_redis
///
use redis::{
//RedisResult,
Client,
@ -14,7 +13,10 @@ fn do_something() -> redis::RedisResult<()> {
let mut con: Connection = client.get_connection()?;
let _ = con.set("/clientkey", "/pl/0/")?;
let _ = con.set("/EDH/0", "[[1.0, 0.0, 0.0],\n [ 0.0, 1.0, 0.0],\n [ 0.0, 0.0, 1.0]]")?;
let _ = con.set(
"/EDH/0",
"[[1.0, 0.0, 0.0],\n [ 0.0, 1.0, 0.0],\n [ 0.0, 0.0, 1.0]]",
)?;
let _ = con.set("/kpps/0", "5000")?;
let _ = con.set("/intensity/0", "255")?;
Ok(())

View File

@ -1,7 +1,6 @@
///
/// $ cargo run --example simple_client
///
use redis::{
//RedisResult,
Client,
@ -20,20 +19,16 @@ fn do_something() -> redis::RedisResult<()> {
let elapsed = start.elapsed();
let time = 60.0 * elapsed.as_millis() as f32 / 1000.0;
let mut v : Vec<(f32,f32,u32)> = vec![];
let mut v: Vec<(f32, f32, u32)> = vec![];
for i in 0..128 {
let a = (time + i as f32) / 128.0 * std::f32::consts::PI * 2.0;
let r = 1200.0 + (a*5.0).cos() * (500.0 * (time/5.0).cos());
let r = 1200.0 + (a * 5.0).cos() * (500.0 * (time / 5.0).cos());
let x = a.cos() * r;
let y = a.sin() * r;
let col = if i % 8 < 4 {
0x000000ff
} else {
0x00ff0000
};
v.push((x,y,col));
let col = if i % 8 < 4 { 0x000000ff } else { 0x00ff0000 };
v.push((x, y, col));
}
// println!("{:?}", v);
let _ = con.set("/pl/0/0", format!("{:?}", v))?;

View File

@ -1,7 +1,7 @@
use config::Config;
use serde::{Serialize,Deserialize};
use crate::errors::{LJError,LJResult};
use crate::errors::{LJError, LJResult};
use crate::transformer;
use config::Config;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Conf {
@ -10,7 +10,7 @@ pub struct Conf {
pub redis_url: String,
pub dac: DacFamily,
#[serde(default)]
pub transformers: Vec<TransformConf>
pub transformers: Vec<TransformConf>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@ -25,12 +25,12 @@ pub enum DacFamily {
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HeliosConf {
pub id: u8
pub id: u8,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EtherDreamConf {
pub ip: String
pub ip: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@ -48,24 +48,32 @@ pub enum TransformConf {
#[serde(rename = "grid")]
Grid(transformer::Grid),
#[serde(rename = "homography")]
Homography(transformer::Homography)
Homography(transformer::Homography),
#[serde(rename = "angle_correction")]
AngleOptimisation(transformer::AngleOptimisation),
}
impl Conf {
pub fn new(path: &str) -> LJResult<Conf> {
let settings = Config::builder()
.add_source(config::File::with_name(path))
.build()?;
let conf : Conf = settings.try_deserialize().map_err(LJError::Config)?;
dbg!("path:", path);
//println!("plop");
dbg!(settings.clone());
let conf: Conf = settings.try_deserialize().map_err(LJError::Config)?;
//println!("plum");
Ok(conf)
}
//println!("plop");
pub fn get_transformers(&self) -> Vec<Box<dyn transformer::Transformers>> {
let mut v = vec![];
for t in &self.transformers {
let t : Box<dyn transformer::Transformers> = match t {
let t: Box<dyn transformer::Transformers> = match t {
TransformConf::Translate(t) => Box::new(*t),
TransformConf::Replicate(r) => Box::new(*r),
TransformConf::Rotate(r) => Box::new(*r),
@ -73,6 +81,7 @@ impl Conf {
TransformConf::FlipV(r) => Box::new(*r),
TransformConf::Grid(r) => Box::new(*r),
TransformConf::Homography(r) => Box::new(*r),
TransformConf::AngleOptimisation(r) => Box::new(*r),
};
v.push(t);
}
@ -87,10 +96,12 @@ impl Conf {
redis_url: "redis://127.0.0.1:6379/".to_string(),
dac: DacFamily::Helios(HeliosConf { id: 0 }),
transformers: vec![
TransformConf::Translate(transformer::Translate { x: 2000.0,
y: 2000.0 } ),
TransformConf::Replicate(transformer::Replicate::Until(48))
]
TransformConf::Translate(transformer::Translate {
x: 2000.0,
y: 2000.0,
}),
TransformConf::Replicate(transformer::Replicate::Until(48)),
],
};
let s = toml::to_string(&conf).unwrap();
println!("{}", s);

View File

@ -1,15 +1,15 @@
mod helios;
mod dummy;
mod etherdream;
mod helios;
use std::fmt;
use crate::conf::{Conf, DacFamily /*EtherDreamConf, HeliosConf*/};
use crate::device::helios::HeliosDevice;
use crate::device::dummy::DummyDevice;
use crate::device::etherdream::EtherdreamDevice;
use crate::device::helios::HeliosDevice;
use crate::errors::LJResult;
use crate::point::Point;
use serde::Serialize;
use crate::device::etherdream::EtherdreamDevice;
use std::fmt;
/*
self.protocol_version,
@ -53,11 +53,7 @@ pub struct Status {
pub trait Device {
fn status(&mut self) -> Status;
fn draw(
&mut self,
frame: Vec<Point>,
speed: u32,
) -> LJResult<()>;
fn draw(&mut self, frame: Vec<Point>, speed: u32) -> LJResult<()>;
fn stop(&mut self) -> LJResult<()>;
fn grid(&mut self) -> Vec<Point>;
}
@ -65,8 +61,8 @@ pub trait Device {
pub fn device_factory(config: &Conf) -> LJResult<Box<dyn Device>> {
let device: Box<dyn Device> = match &config.dac {
DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?),
DacFamily::Etherdream( conf) => Box::new( EtherdreamDevice::new(conf)?),
DacFamily::Dummy => Box::new(DummyDevice::new()?)
DacFamily::Etherdream(conf) => Box::new(EtherdreamDevice::new(conf)?),
DacFamily::Dummy => Box::new(DummyDevice::new()?),
};
Ok(device)
}

View File

@ -1,15 +1,17 @@
use crate::device::{Device, Status, PlaybackState};
use crate::device::{Device, PlaybackState, Status};
use crate::errors::LJResult;
use crate::point::{Color, Point};
use log::debug;
pub struct DummyDevice {
state: PlaybackState
state: PlaybackState,
}
impl DummyDevice {
pub fn new() -> LJResult<Self> {
Ok(Self { state: PlaybackState::IDLE })
Ok(Self {
state: PlaybackState::IDLE,
})
}
}
@ -20,14 +22,11 @@ impl Device for DummyDevice {
properties: vec!["foo".to_string()],
playback_state: self.state,
capacity: 0,
lack: "lack".to_string()
lack: "lack".to_string(),
}
}
fn draw(&mut self,
line: Vec<Point>,
speed: u32,
) -> LJResult<()> {
fn draw(&mut self, line: Vec<Point>, speed: u32) -> LJResult<()> {
debug!("Draw Line at speed {speed} : {:?}", line);
Ok(())
}
@ -36,8 +35,10 @@ impl Device for DummyDevice {
Ok(())
}
fn grid(&mut self) -> Vec<Point> {
vec!(
Point{ x: 0 as f32, y: 0 as f32, color:Color{ r: 0, g: 0, b: 0 }}
)
vec![Point {
x: 0 as f32,
y: 0 as f32,
color: Color { r: 0, g: 0, b: 0 },
}]
}
}

View File

@ -1,10 +1,10 @@
use std::time;
use std::net::SocketAddr;
use ether_dream::dac::stream::connect;
use ether_dream::dac::Stream;
use std::net::SocketAddr;
use std::time;
use crate::conf::EtherDreamConf;
use crate::device::{Device, Status, PlaybackState};
use crate::device::{Device, PlaybackState, Status};
use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use ether_dream::protocol::{DacBroadcast, DacStatus};
@ -41,27 +41,27 @@ impl EtherdreamDevice {
dac_broadcast.set_timeout(Some(time::Duration::new(10, 0)))?;
info!("Attempting to get DAC broadcast...");
let broadcast = dac_broadcast
.filter_map(|result| {
match result {
.filter_map(|result| match result {
Err(err) => {
warn!( "Failed to find a valid DAC via broadcast. Error: {:?}", err);
info!( "Retrying...");
warn!("Failed to find a valid DAC via broadcast. Error: {:?}", err);
info!("Retrying...");
None
},
}
Ok((dac, source_addr)) => {
if source_addr.is_ipv6() { return None; }
if &source_addr.ip().to_string() != ip { return None; }
if source_addr.is_ipv6() {
return None;
}
if &source_addr.ip().to_string() != ip {
return None;
}
info!("Valid broadcast");
Some(Ok((dac, source_addr)))
}
}
})
.next()
.expect("Failed to receive broadcast.");
match broadcast {
Err(err) => {
Err(Box::new(LJError::EtherdreamConnectError(err)))
}
Err(err) => Err(Box::new(LJError::EtherdreamConnectError(err))),
Ok((dac, source_addr)) => {
let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?;
Ok((dac, source_addr, stream))
@ -90,7 +90,6 @@ impl EtherdreamDevice {
Ok(stream)
}
pub fn check_tcp_stream(&mut self) -> LJResult<()> {
// todo Reinit stream if needed
// self.stream = EtherdreamDevice::get_tcp_stream(&self.dac, &self.source_address)?
@ -112,7 +111,7 @@ impl Device for EtherdreamDevice {
DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE,
DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE,
DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING,
_ => PlaybackState::UNKNOWN
_ => PlaybackState::UNKNOWN,
};
Status {
@ -124,10 +123,7 @@ impl Device for EtherdreamDevice {
}
}
fn draw(&mut self,
line: Vec<Point>,
_speed: u32,
) -> LJResult<()> {
fn draw(&mut self, line: Vec<Point>, _speed: u32) -> LJResult<()> {
let n_points = self.points_to_generate();
self.stream
.queue_commands()
@ -146,8 +142,14 @@ impl Device for EtherdreamDevice {
}
fn grid(&mut self) -> Vec<Point> {
vec!(
Point { x: 0.0, y: 0.0, color: Color { r: 255, g: 255, b: 255 } }
)
vec![Point {
x: 0.0,
y: 0.0,
color: Color {
r: 255,
g: 255,
b: 255,
},
}]
}
}

View File

@ -1,8 +1,8 @@
///
/// Configure udev:
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
///
use helios_dac::{NativeHeliosDac, NativeHeliosDacController};
use crate::conf::HeliosConf;
use crate::device::{Device, PlaybackState, Status};
use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use chrono::Utc;
use helios_dac::{
// Coordinate,
// Color,
@ -10,11 +10,11 @@ use helios_dac::{
Frame,
// Point as HeliosPoint,
};
use crate::conf::HeliosConf;
use crate::device::{Device, Status, PlaybackState};
use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use chrono::Utc;
///
/// Configure udev:
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
///
use helios_dac::{NativeHeliosDac, NativeHeliosDacController};
pub struct HeliosDevice {
pub conf: HeliosConf,
@ -57,10 +57,7 @@ impl Device for HeliosDevice {
}
}
fn draw(&mut self,
line: Vec<Point>,
speed: u32,
) -> LJResult<()> {
fn draw(&mut self, line: Vec<Point>, speed: u32) -> LJResult<()> {
self.state = PlaybackState::IDLE;
while let Ok(DeviceStatus::NotReady) = self.dac.status() {}
self.state = PlaybackState::PLAYING;
@ -83,21 +80,73 @@ impl Device for HeliosDevice {
let dim_mid = 2047 as f32;
let dim_max = 4095 as f32;
let col_min = Color { r: 0, g: 0, b: 0 };
let col_max = Color { r: 255, g: 255, b: 255 };
let col_max = Color {
r: 255,
g: 255,
b: 255,
};
vec![
Point { x: dim_min, y: dim_max, color: col_min },
Point { x: dim_min, y: dim_max, color: col_max },
Point { x: dim_max, y: dim_max, color: col_max },
Point { x: dim_max, y: dim_min, color: col_max },
Point { x: dim_min, y: dim_min, color: col_max },
Point { x: dim_min, y: dim_min, color: col_min },
Point { x: dim_min, y: dim_mid, color: col_min },
Point { x: dim_min, y: dim_mid, color: col_max },
Point { x: dim_mid, y: dim_mid, color: col_max },
Point { x: dim_mid, y: dim_min, color: col_max },
Point { x: dim_min, y: dim_min, color: col_max },
Point { x: dim_min, y: dim_min, color: col_min },
Point {
x: dim_min,
y: dim_max,
color: col_min,
},
Point {
x: dim_min,
y: dim_max,
color: col_max,
},
Point {
x: dim_max,
y: dim_max,
color: col_max,
},
Point {
x: dim_max,
y: dim_min,
color: col_max,
},
Point {
x: dim_min,
y: dim_min,
color: col_max,
},
Point {
x: dim_min,
y: dim_min,
color: col_min,
},
Point {
x: dim_min,
y: dim_mid,
color: col_min,
},
Point {
x: dim_min,
y: dim_mid,
color: col_max,
},
Point {
x: dim_mid,
y: dim_mid,
color: col_max,
},
Point {
x: dim_mid,
y: dim_min,
color: col_max,
},
Point {
x: dim_min,
y: dim_min,
color: col_max,
},
Point {
x: dim_min,
y: dim_min,
color: col_min,
},
]
}
}

View File

@ -1,7 +1,7 @@
use config::ConfigError;
use redis::RedisError;
use std::error::Error;
use std::{fmt, io};
use redis::RedisError;
use config::ConfigError;
pub type LJResult<T> = Result<T, Box<dyn std::error::Error>>;
@ -44,7 +44,7 @@ impl Error for LJError {
match self {
RedisConnect(err) => Some(err),
_ => None
_ => None,
}
}
}

View File

@ -1,7 +1,7 @@
pub mod redis_ctrl;
pub mod conf;
pub mod errors;
pub mod device;
pub mod errors;
pub mod point;
pub mod redis_ctrl;
pub mod transformer;
pub mod worldstate;

View File

@ -1,25 +1,25 @@
mod conf;
mod device;
mod errors;
mod point;
///
/// Configure udev:
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
///
mod redis_ctrl;
mod conf;
mod errors;
mod point;
mod transformer;
mod device;
mod worldstate;
use conf::Conf;
use device::device_factory;
use env_logger::Builder;
use errors::LJResult;
use log::{/* warn, */ error, info, LevelFilter};
use point::{Color, Point};
use redis_ctrl::{Order, RedisCtrl};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use redis_ctrl::{RedisCtrl, Order};
use conf::Conf;
use errors::LJResult;
use point::{Point, Color};
use transformer::Transformers;
use log::{LevelFilter, info, /* warn, */ error};
use env_logger::Builder;
use worldstate::WorldState;
const DEFAULT_CONF_FILE: &str = "settings.toml";
@ -33,12 +33,11 @@ pub fn main() {
}
}
fn run_all() -> LJResult<()> {
// Setup configuration file and set up logs
let filename = std::env::args().nth(1).unwrap_or_else(|| {
DEFAULT_CONF_FILE.to_string()
});
let filename = std::env::args()
.nth(1)
.unwrap_or_else(|| DEFAULT_CONF_FILE.to_string());
let config = Conf::new(&filename);
init_logging(&config);
@ -52,6 +51,7 @@ fn run_all() -> LJResult<()> {
let mut world_state = rs.init_world_state().unwrap();
info!("WorldState: {:?}", world_state);
dbg!("worldstate.kpps: {}", world_state.kpps);
// Setup handler for interrupt Signals
let running = Arc::new(AtomicBool::new(true));
@ -76,7 +76,6 @@ fn run_all() -> LJResult<()> {
let order = rs.get_order(config.laser_id)?;
match order {
Order::Draw | Order::Black | Order::Grid => {
// 0 : Draw Normal point list
@ -84,19 +83,13 @@ fn run_all() -> LJResult<()> {
// 3 : Draw GRID point list
world_state.draw_black = order == Order::Black;
world_state.draw_grid = order == Order::Grid;
let frame = get_next_frame(
&config,
&transformers,
&mut rs,
&world_state,
)?;
let frame = get_next_frame(&config, &transformers, &mut rs, &world_state)?;
// For now, draw all the time
tracer.draw(frame, world_state.kpps)?;
}
Order::Intensity => {
// 6 : Max Intensity Change = reread redis key /intensity
world_state.intensity = rs.get_int("intensity")?
.try_into()?;
world_state.intensity = rs.get_int("intensity")?.try_into()?;
}
Order::Edh => {
// 1 : Get the new EDH = reread redis key /EDH/lasernumber
@ -105,10 +98,11 @@ fn run_all() -> LJResult<()> {
Order::Kpps => {
// 7 : kpps change = reread redis key /kpps
world_state.kpps = rs.get_int("kpps")?;
//dbg!(world_state.kpps);
}
Order::ClientKey => {
world_state.client_key = rs.get_client_key()?;
},
}
// Order::ColorBalance => {},
_ => {
// 4 : Resampler Change (longs and shorts lsteps)
@ -129,9 +123,7 @@ fn init_logging(config: &LJResult<Conf>) {
if let Ok(ref config) = config {
if config.debug {
let mut builder = Builder::from_default_env();
builder
.filter(None, LevelFilter::Info)
.init();
builder.filter(None, LevelFilter::Info).init();
info!("Debug mode enabled from configuration file");
return;
}
@ -146,9 +138,7 @@ fn get_next_frame(
rs: &mut RedisCtrl,
world_state: &WorldState,
) -> LJResult<Vec<Point>> {
let format_key = format!("{}{}",
world_state.client_key,
config.laser_id);
let format_key = format!("{}{}", world_state.client_key, config.laser_id);
// Handle the grid case
@ -156,9 +146,7 @@ fn get_next_frame(
world_state.grid.clone()
} else {
let redis_line = rs.get_line(&format_key)?;
redis_line.into_iter()
.map(|tpl| tpl.into())
.collect()
redis_line.into_iter().map(|tpl| tpl.into()).collect()
};
for transformer in transformers {
@ -169,7 +157,8 @@ fn get_next_frame(
info!("Draw Grid -> {}", world_state.draw_grid);
// LIMITER and BLACK
line = line.into_iter()
line = line
.into_iter()
.map(|p| {
let color = if world_state.draw_black {
Color { r: 0, g: 0, b: 0 }
@ -180,14 +169,10 @@ fn get_next_frame(
b: p.color.b.min(world_state.intensity),
}
};
Point {
color,
..p
}
Point { color, ..p }
})
.collect();
//info!("Line: {:?}", line);
Ok(line)
}

View File

@ -14,6 +14,30 @@ pub struct Color {
pub b: u8,
}
impl Point {
pub fn diff(p1: &Self, p2: &Self) -> Self {
Point {
x: p1.x - p2.x,
y: p1.y - p2.y,
color: Color { r: 0, g: 0, b: 0 },
}
}
pub fn normalize(&mut self) -> Self {
let length = (self.x * self.x + self.y * self.y).sqrt();
self.x = self.x / length;
self.y = self.y / length;
*self
}
pub fn cross(&self, pt: &Self) -> f32 {
self.x * pt.x + self.y * pt.y
}
}
// normalaize
// diff
impl From<Color> for u32 {
fn from(value: Color) -> Self {
let r = value.r as u32;
@ -28,7 +52,11 @@ impl From<(f32, f32, u32)> for Point {
let r = (color >> 16) as u8;
let g = ((color >> 8) & 255) as u8;
let b = (color & 255) as u8;
Point { x, y, color: Color { r, g, b } }
Point {
x,
y,
color: Color { r, g, b },
}
}
}

View File

@ -1,8 +1,8 @@
use redis::{Client, Commands, Connection};
use ron::de::from_str;
use crate::device::Status;
use crate::errors::{LJError, LJResult};
use crate::worldstate::{WorldState,EDH};
use crate::worldstate::{WorldState, EDH};
use redis::{Client, Commands, Connection};
use ron::de::from_str;
// use log::info;
#[repr(u8)]
@ -40,7 +40,7 @@ impl TryFrom<u8> for Order {
6 => Intensity,
7 => Kpps,
8 => ColorBalance,
_ => unreachable!()
_ => unreachable!(),
})
}
}
@ -55,11 +55,13 @@ pub struct RedisCtrl {
impl RedisCtrl {
pub fn new(url: &str, laser_id: &u8) -> LJResult<Self> {
let client = Client::open(url)
.map_err(LJError::RedisConnect)?;
let connection = client.get_connection()
.map_err(LJError::RedisConnect)?;
Ok(RedisCtrl { client, connection, laser_id: *laser_id })
let client = Client::open(url).map_err(LJError::RedisConnect)?;
let connection = client.get_connection().map_err(LJError::RedisConnect)?;
Ok(RedisCtrl {
client,
connection,
laser_id: *laser_id,
})
}
pub fn get_line(&mut self, key: &str) -> LJResult<Line> {
@ -99,7 +101,7 @@ impl RedisCtrl {
Ok(())
}
pub fn init_world_state( &mut self) -> LJResult<WorldState>{
pub fn init_world_state(&mut self) -> LJResult<WorldState> {
Ok(WorldState {
client_key: self.get_client_key().unwrap(),
edh: self.get_edh().unwrap(),
@ -109,24 +111,24 @@ impl RedisCtrl {
})
}
pub fn get_edh( &mut self ) -> LJResult<EDH> {
pub fn get_edh(&mut self) -> LJResult<EDH> {
// Get new EDH
let edh_key = format!("/EDH/{}", self.laser_id);
let edh : String = self.connection.get(edh_key)?;
let edh : Vec<Vec<f32>> = from_str(&edh)?;
let edh: String = self.connection.get(edh_key)?;
let edh: Vec<Vec<f32>> = from_str(&edh)?;
let edh = EDH::new(edh)?;
Ok(edh)
}
pub fn get_client_key( &mut self ) -> LJResult<String> {
let key : String = self.connection.get("/clientkey")?;
pub fn get_client_key(&mut self) -> LJResult<String> {
let key: String = self.connection.get("/clientkey")?;
Ok(key)
}
pub fn get_int(&mut self, key: &str ) -> LJResult<u32> {
pub fn get_int(&mut self, key: &str) -> LJResult<u32> {
// Get new Int
let fmt = format!("/{key}/{}", self.laser_id);
let val : u32 = self.connection.get(fmt)?;
let val: u32 = self.connection.get(fmt)?;
Ok(val)
}
}

View File

@ -1,28 +1,26 @@
//pub mod common;
mod translate;
mod replicate;
mod rotate;
mod angle_optimisation;
mod flip_horizontal;
mod flip_vertical;
mod grid;
mod homography;
mod replicate;
mod rotate;
mod translate;
use crate::point::Point;
use crate::worldstate::WorldState;
// re-export transformers to be abe to use it directly from transformer::
pub use translate::Translate;
pub use replicate::Replicate;
pub use rotate::Rotate;
pub use self::homography::Homography;
pub use angle_optimisation::AngleOptimisation;
pub use flip_horizontal::FlipHorizontal;
pub use flip_vertical::FlipVertical;
pub use grid::Grid;
pub use self::homography::Homography;
pub use replicate::Replicate;
pub use rotate::Rotate;
pub use translate::Translate;
pub trait Transformers {
fn apply(
&self,
point_list: &[Point],
world_state: &WorldState
) -> Vec<Point>;
fn apply(&self, point_list: &[Point], world_state: &WorldState) -> Vec<Point>;
}

View File

@ -0,0 +1,86 @@
use crate::point::{Color, Point};
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Deserialize, Serialize};
use std::f32::consts::PI;
/// Angle Optimisation
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct AngleOptimisation {
coef: f32,
}
fn color_not_zero(p1: &Point, p2: &Point, p3: &Point) -> bool {
let c0 = Color { r: 0, g: 0, b: 0 };
if p1.color == c0 || p2.color == c0 || p3.color == c0 {
false
} else {
true
}
}
fn pos_different(p1: &Point, p2: &Point) -> bool {
if p1.x == p2.x && p1.y == p2.y {
false
} else {
true
}
}
impl Transformers for AngleOptimisation {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
let c0 = Color { r: 0, g: 0, b: 0 };
let mut v = vec![];
//println!();
//println!("====================");
//println!("= next Frame =");
//println!("====================");
v.push(point_list[0]);
for i in 1..(point_list.len() - 1) {
let prev = point_list[i - 1];
let node = point_list[i];
let next = point_list[i + 1];
if color_not_zero(&prev, &node, &next)
&& pos_different(&prev, &node)
&& pos_different(&node, &next)
{
//println!("=========");
let mut d1 = Point::diff(&node, &prev);
let mut d2 = Point::diff(&next, &next);
//dbg!(d1);
//dbg!(d2);
d1.normalize();
d2.normalize();
let cross = d1.cross(&d2);
let angle = d1.cross(&d2).acos();
let deg = angle * 180. / PI;
//dbg!(prev);
//dbg!(node);
//dbg!(next);
//dbg!(d1);
//dbg!(d2);
//dbg!(cross);
//dbg!(angle);
//dbg!(deg);
//println!("deg: {deg}");
let nb_add = (self.coef * (1. - angle / PI)) as usize;
for _ in 0..nb_add {}
}
v.push(node); // push node
}
v.push(point_list[point_list.len() - 1]); // push last
v
}
}

View File

@ -1,24 +1,27 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize};
use serde::{Deserialize, Serialize};
/// Flip Horizontal
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct FlipHorizontal {
x: f32,
}
impl Transformers for FlipHorizontal {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter()
.map(| pt | {
point_list
.iter()
.map(|pt| {
let dx = pt.x - self.x;
Point { x: dx - 2. * dx,
Point {
x: dx - 2. * dx,
..*pt
}
}).collect()
})
.collect()
}
}

View File

@ -1,24 +1,27 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize};
use serde::{Deserialize, Serialize};
/// Flip Vertical
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct FlipVertical {
y: f32,
}
impl Transformers for FlipVertical {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter()
.map(| pt | {
point_list
.iter()
.map(|pt| {
let dy = pt.y - self.y;
Point { y: dy - 2. * dy,
Point {
y: dy - 2. * dy,
..*pt
}
}).collect()
})
.collect()
}
}

View File

@ -1,47 +1,38 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize};
use serde::{Deserialize, Serialize};
/// Translate
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Grid {
width: f32,
height: f32
height: f32,
}
fn square_box(size: f32, color: u32) -> Vec<(f32, f32, u32)> {
vec![
(-size, -size, 0),
(-size, -size, color),
(0.0, -size, color),
(0.0, -size, color),
(size, -size, color),
(size, -size, color),
(size, 0.0, color),
(size, 0.0, color),
(size, size, color),
(size, size, color),
(0.0, size, color),
(0.0, size, color),
(-size, size, color),
(-size, size, color),
(-size, 0.0, color),
(-size, 0.0, color),
(-size, -size, color),
(-size, -size, color),
(-size, -size, 0)
(-size, -size, 0),
]
}
@ -51,8 +42,7 @@ impl Transformers for Grid {
let mut line = square_box(2000.0, 255);
line.append(&mut sq1);
let line: Vec<Point> = line.into_iter()
.map(|tpl| tpl.into()).collect();
let line: Vec<Point> = line.into_iter().map(|tpl| tpl.into()).collect();
line
}
}

View File

@ -1,20 +1,18 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::worldstate::{WorldState,EDH};
use serde::{Serialize,Deserialize};
use crate::transformer::Transformers;
use crate::worldstate::{WorldState, EDH};
use serde::{Deserialize, Serialize};
/// Homography
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Homography {}
impl Transformers for Homography {
fn apply(&self, point_list: &[Point], ws: &WorldState) -> Vec<Point> {
let edh : &EDH = &ws.edh;
let edh: &EDH = &ws.edh;
point_list.iter()
.map(| point | edh.apply(point))
.collect()
point_list.iter().map(|point| edh.apply(point)).collect()
}
}
@ -24,41 +22,67 @@ mod tests {
#[test]
fn identity_matrix_let_point_unchanged() {
let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() };
let p0 = Point {
x: -1500.0,
y: 1500.0,
..Point::default()
};
let edh = EDH::new(vec![
vec![ 1.0, 0.0, 0.0 ],
vec![ 0.0, 1.0, 0.0 ],
vec![ 0.0, 0.0, 1.0 ]
]).unwrap();
vec![1.0, 0.0, 0.0],
vec![0.0, 1.0, 0.0],
vec![0.0, 0.0, 1.0],
])
.unwrap();
let ws = WorldState { edh : edh, ..WorldState::default() };
let ws = WorldState {
edh: edh,
..WorldState::default()
};
let homography = Homography{};
let homography = Homography {};
let result = homography.apply(&[p0], &ws);
assert_eq!(result, vec![Point { x: -1500.0,
assert_eq!(
result,
vec![Point {
x: -1500.0,
y: 1500.0,
..Point::default() }]);
..Point::default()
}]
);
}
#[test]
fn rotation_matrix_rotate_the_point() {
let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() };
let p0 = Point {
x: -1500.0,
y: 1500.0,
..Point::default()
};
let edh = EDH::new(vec![
vec![ 1.24107321e-03, 1.00500127e-03, 7.15439347e-01],
vec![-9.93223912e-04, 1.22652939e-03,-6.98671238e-01],
vec![ 1.06017142e-17,-4.69459541e-17, 3.32700590e-05]
]).unwrap();
vec![1.24107321e-03, 1.00500127e-03, 7.15439347e-01],
vec![-9.93223912e-04, 1.22652939e-03, -6.98671238e-01],
vec![1.06017142e-17, -4.69459541e-17, 3.32700590e-05],
])
.unwrap();
let ws = WorldState { edh : edh, ..WorldState::default() };
let ws = WorldState {
edh: edh,
..WorldState::default()
};
let homography = Homography{};
let homography = Homography {};
let result = homography.apply(&[p0], &ws);
assert_eq!(result, vec![Point { x: 10860.557,
assert_eq!(
result,
vec![Point {
x: 10860.557,
y: 79078.87,
..Point::default() }]);
..Point::default()
}]
);
}
}

View File

@ -1,16 +1,16 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize};
use serde::{Deserialize, Serialize};
/// Replicate
#[allow(dead_code)]
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum Replicate {
Until(usize),
Times(usize)
Times(usize),
}
impl Transformers for Replicate {
@ -21,7 +21,7 @@ impl Transformers for Replicate {
while point_list2.len() < *n {
point_list2.append(&mut point_list.to_vec());
}
},
}
Replicate::Times(n) => {
for _ in 0..*n {
point_list2.append(&mut point_list.to_vec());
@ -31,4 +31,3 @@ impl Transformers for Replicate {
point_list2
}
}

View File

@ -1,35 +1,32 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize};
use serde::{Deserialize, Serialize};
//use std::f32::consts::PI;
/// Rotate
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Rotate {
cx: f32,
cy: f32,
angle: f32,
}
impl Transformers for Rotate {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter()
.map(| pt | {
point_list
.iter()
.map(|pt| {
let dx = pt.x - self.cx;
let dy = pt.y - self.cy;
let cos = self.angle.cos();
let sin = self.angle.sin();
let x = (dx * cos - dy * sin) + self.cx;
let y = (dx * sin + dy * cos) + self.cy;
Point { x,
y,
..*pt
}
}).collect()
Point { x, y, ..*pt }
})
.collect()
}
}

View File

@ -1,24 +1,25 @@
use crate::transformer::Transformers;
use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize};
use serde::{Deserialize, Serialize};
/// Translate
#[derive(Serialize,Deserialize,Debug,Clone,Copy)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Translate {
pub x: f32,
pub y: f32
pub y: f32,
}
impl Transformers for Translate {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter()
.map(| pt | {
Point { x: pt.x + self.x,
point_list
.iter()
.map(|pt| Point {
x: pt.x + self.x,
y: pt.y + self.y,
..*pt
}
}).collect()
})
.collect()
}
}

View File

@ -1,7 +1,7 @@
use crate::point::{Point, Color};
use nalgebra::base::{Matrix3, Matrix1x3};
use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use log::debug;
use nalgebra::base::{Matrix1x3, Matrix3};
#[derive(Debug, Default)]
pub struct EDH {
@ -10,17 +10,15 @@ pub struct EDH {
impl EDH {
pub fn new(vec: Vec<Vec<f32>>) -> LJResult<EDH> {
if vec.len() != 3 ||
vec[0].len() != 3 ||
vec[1].len() != 3 ||
vec[2].len() != 3 {
if vec.len() != 3 || vec[0].len() != 3 || vec[1].len() != 3 || vec[2].len() != 3 {
return Err(Box::new(LJError::BadEDH));
}
// this is the matrix already transposed.
let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0],
vec[0][1], vec[1][1], vec[2][1],
vec[0][2], vec[1][2], vec[2][2]);
let matrix = Matrix3::new(
vec[0][0], vec[1][0], vec[2][0], vec[0][1], vec[1][1], vec[2][1], vec[0][2], vec[1][2],
vec[2][2],
);
Ok(EDH { matrix })
}
@ -28,7 +26,11 @@ impl EDH {
pub fn apply(&self, point: &Point) -> Point {
let p = Matrix1x3::new(point.x, point.y, 1.0);
let p = p * self.matrix;
let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point };
let new_p = Point {
x: p[0] / p[2],
y: p[1] / p[2],
..*point
};
debug!("{:?} => {:?}", point, new_p);

View File

@ -1,4 +1,4 @@
use lj_rust::conf::{Conf, DacFamily, HeliosConf, EtherDreamConf};
use lj_rust::conf::{Conf, DacFamily, EtherDreamConf, HeliosConf};
#[test]
fn it_loads_a_valid_conf() {