You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
466 lines
14 KiB
466 lines
14 KiB
//
|
|
// This is an abstraction over a drawing environment.
|
|
// Future note: z-Buffer is described here:
|
|
// https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/perspective-correct-interpolation-vertex-attributes
|
|
//
|
|
// Georg Hopp <georg@steffers.org>
|
|
//
|
|
// Copyright © 2019 Georg Hopp
|
|
//
|
|
// This program is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// This program is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
//
|
|
use std::cmp;
|
|
use std::fmt::{Formatter, Debug, Display, Result};
|
|
use std::ops::{Add, Sub, Div};
|
|
use std::sync::mpsc;
|
|
|
|
pub trait Easel {
|
|
//fn canvas(&mut self, width :u16, height :u16) -> Option<&dyn Canvas>;
|
|
}
|
|
|
|
pub trait Canvas<T> {
|
|
fn init_events(&self);
|
|
fn start_events(&self, tx :mpsc::Sender<i32>);
|
|
|
|
fn width(&self) -> u16;
|
|
fn height(&self) -> u16;
|
|
|
|
fn clear(&mut self);
|
|
fn draw(&mut self, c :&dyn Drawable<T>, ofs :Coordinate<T>, color :u32);
|
|
fn put_text(&self, ofs :Coordinate<T>, s :&str);
|
|
fn show(&self);
|
|
}
|
|
|
|
pub trait Drawable<T> {
|
|
fn plot(&self) -> Coordinates<T>;
|
|
}
|
|
|
|
pub trait Fillable<T> {
|
|
fn fill(&self) -> Coordinates<T>;
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub struct Coordinate<T>(pub i32, pub i32, pub T);
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Coordinates<T>(pub Vec<Coordinate<T>>);
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct LineIterator<T> where T: Debug {
|
|
a :Option<Coordinate<T>>
|
|
, b :Coordinate<T>
|
|
, dx :i32
|
|
, dy :i32
|
|
, dz :T
|
|
, sx :i32
|
|
, sy :i32
|
|
, err :i32
|
|
, only_edges :bool
|
|
}
|
|
|
|
impl<T> Iterator for LineIterator<T>
|
|
where T: Add<Output = T> + Debug + Copy + From<i32> {
|
|
type Item = Coordinate<T>;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
match self.a {
|
|
None => None,
|
|
Some(a) => {
|
|
let Coordinate(ax, ay, az) = a;
|
|
let Coordinate(bx, by, _) = self.b;
|
|
|
|
if ax != bx || ay != by {
|
|
match (2 * self.err >= self.dy, 2 * self.err <= self.dx ) {
|
|
(true, false) => {
|
|
let r = self.a;
|
|
self.a = Some(Coordinate( ax + self.sx
|
|
, ay
|
|
, az + self.dz ));
|
|
self.err = self.err + self.dy;
|
|
if self.only_edges { self.next() } else { r }
|
|
},
|
|
(false, true) => {
|
|
let r = self.a;
|
|
self.a = Some(Coordinate( ax
|
|
, ay + self.sy
|
|
, az + self.dz ));
|
|
self.err = self.err + self.dx;
|
|
r
|
|
},
|
|
_ => {
|
|
let r = self.a;
|
|
self.a = Some(Coordinate( ax + self.sx
|
|
, ay + self.sy
|
|
, az + self.dz ));
|
|
self.err = self.err + self.dx + self.dy;
|
|
r
|
|
},
|
|
}
|
|
} else {
|
|
self.a = None;
|
|
Some(self.b)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<T> Coordinate<T>
|
|
where T: Add<Output = T> + Sub<Output = T> + Div<Output = T>
|
|
+ Debug + Clone + Copy + From<i32> {
|
|
fn iter(self, b :&Self, only_edges :bool) -> LineIterator<T> {
|
|
let Coordinate(ax, ay, az) = self;
|
|
let Coordinate(bx, by, bz) = *b;
|
|
|
|
let dx = (bx - ax).abs();
|
|
let dy = -(by - ay).abs();
|
|
|
|
LineIterator { a: Some(self)
|
|
, b: *b
|
|
, dx: dx
|
|
, dy: dy
|
|
, dz: (bz - az) / cmp::max(dx, -dy).into()
|
|
, sx: if ax < bx { 1 } else { -1 }
|
|
, sy: if ay < by { 1 } else { -1 }
|
|
, err: dx + dy
|
|
, only_edges: only_edges
|
|
}
|
|
}
|
|
|
|
fn line_iter(self, b :&Self) -> LineIterator<T> {
|
|
self.iter(b, false)
|
|
}
|
|
|
|
fn line(self, b :&Self) -> Vec<Self> {
|
|
self.line_iter(b).collect()
|
|
}
|
|
|
|
fn edge_iter(self, b :&Self) -> LineIterator<T> {
|
|
self.iter(b, true)
|
|
}
|
|
|
|
fn edge(self, b :&Self) -> Vec<Self> {
|
|
self.edge_iter(b).collect()
|
|
}
|
|
}
|
|
|
|
impl<T> Display for Coordinate<T> {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
|
write!(f, "<{},{}>", self.0, self.1)
|
|
}
|
|
}
|
|
|
|
impl<T> Display for Coordinates<T> where T: Copy {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
|
let Coordinates(is) = self;
|
|
|
|
let c = match is[..] {
|
|
[] => String::from(""),
|
|
[a] => format!("{}", a),
|
|
_ => {
|
|
let mut a = format!("{}", is[0]);
|
|
for i in is[1..].iter() {
|
|
a = a + &format!(",{}", i);
|
|
}
|
|
a
|
|
}
|
|
};
|
|
|
|
write!(f, "Coordinates[{}]", c)
|
|
}
|
|
}
|
|
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub struct Point<T>(pub Coordinate<T>);
|
|
|
|
impl<T> Drawable<T> for Point<T> where T: Copy {
|
|
fn plot(&self) -> Coordinates<T> {
|
|
let Point(c) = *self;
|
|
Coordinates(vec!(c))
|
|
}
|
|
}
|
|
|
|
impl<T> Display for Point<T> {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
|
let Point(p) = self;
|
|
write!(f, "Point[{}]", p)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub struct Line<T>(pub Coordinate<T>, pub Coordinate<T>);
|
|
|
|
impl<T> Drawable<T> for Line<T>
|
|
where T: Add<Output = T> + Sub<Output = T> + Div<Output = T>
|
|
+ Debug + Clone + Copy + From<i32> {
|
|
fn plot(&self) -> Coordinates<T> {
|
|
let Line(a, b) = *self;
|
|
Coordinates(a.line(&b))
|
|
}
|
|
}
|
|
|
|
impl<T> Display for Line<T> {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
|
let Line(a, b) = self;
|
|
write!(f, "Line[{},{}]", a, b)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Polyline<T>(pub Coordinates<T>);
|
|
|
|
impl<T> Drawable<T> for Polyline<T>
|
|
where T: Add<Output = T> + Sub<Output = T> + Div<Output = T>
|
|
+ Debug + Clone + Copy + From<i32> {
|
|
fn plot(&self) -> Coordinates<T> {
|
|
let Polyline(Coordinates(cs)) = self;
|
|
|
|
match cs[..] {
|
|
[] => Coordinates(Vec::<Coordinate<T>>::new()),
|
|
[a] => Coordinates(vec!(a)),
|
|
[a, b] => Coordinates(a.line(&b)),
|
|
_ => {
|
|
let (a, b) = (cs[0], cs[1]);
|
|
let mut r = a.line(&b);
|
|
let mut i = b;
|
|
for j in cs[2..].iter() {
|
|
r.append(&mut i.line(j)[1..].to_vec());
|
|
i = *j;
|
|
}
|
|
Coordinates(r)
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<T> Display for Polyline<T> where T: Copy {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
|
let Polyline(a) = self;
|
|
write!(f, "PLine[{}]", a)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
enum Direction { Left, Right }
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Polygon<T>(pub Coordinates<T>);
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct VertexIterator<'a,T> where T: Debug {
|
|
p :&'a Polygon<T>,
|
|
top :usize,
|
|
current :Option<usize>,
|
|
inner :Option<LineIterator<T>>,
|
|
direction :Direction,
|
|
}
|
|
|
|
impl<'a,T> Iterator for VertexIterator<'a,T>
|
|
where T: Add<Output = T> + Sub<Output = T> + Div<Output = T>
|
|
+ Debug + Copy + From<i32> {
|
|
type Item = Coordinate<T>;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
let inner = match self.inner {
|
|
Some(i) => i,
|
|
None => {
|
|
let current = self.current?;
|
|
let next = self.p.next_y(current, self.direction)?;
|
|
self.p.vertex(current).edge_iter(&self.p.vertex(next))
|
|
},
|
|
}
|
|
|
|
match self.current {
|
|
None => None,
|
|
Some(c) => {
|
|
let r = self.p.vertex(c);
|
|
self.current = self.p.next_y(c, self.direction);
|
|
Some(r)
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<T> Polygon<T> where T: Copy + Debug {
|
|
fn vert_min<'a>(&'a self) -> usize {
|
|
let Polygon(Coordinates(cs)) = self;
|
|
|
|
type ICoord<'a,T> = (usize, &'a Coordinate<T>);
|
|
|
|
let fold = | acc :Option<ICoord<'a,T>>, x :ICoord<'a,T> |
|
|
match acc {
|
|
None => Some(x),
|
|
Some(a) => {
|
|
let Coordinate(_, ay, _) = a.1;
|
|
let Coordinate(_, xy, _) = x.1;
|
|
if xy < ay {Some(x)} else {Some(a)}
|
|
},
|
|
};
|
|
|
|
cs.iter().enumerate().fold(None, fold).unwrap().0
|
|
}
|
|
|
|
fn left_vertices(&self) -> VertexIterator<T> {
|
|
VertexIterator { p: &self
|
|
, top: self.vert_min()
|
|
, current: Some(self.vert_min())
|
|
, inner: None
|
|
, direction: Direction::Left }
|
|
}
|
|
|
|
fn left(&self, v :usize) -> usize {
|
|
let Polygon(Coordinates(cs)) = self;
|
|
|
|
match v {
|
|
0 => cs.len() - 1,
|
|
_ => v - 1,
|
|
}
|
|
}
|
|
|
|
fn right(&self, v :usize) -> usize {
|
|
let Polygon(Coordinates(cs)) = self;
|
|
|
|
(v + 1) % cs.len()
|
|
}
|
|
|
|
fn step(&self, v :usize, d :Direction) -> usize {
|
|
match d {
|
|
Direction::Left => self.left(v),
|
|
Direction::Right => self.right(v),
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn vertex(&self, v :usize) -> Coordinate<T> {
|
|
let Polygon(Coordinates(cs)) = self;
|
|
cs[v]
|
|
}
|
|
|
|
fn next_y(&self, c :usize, d :Direction) -> Option<usize> {
|
|
fn inner<T>( p :&Polygon<T>
|
|
, c :usize
|
|
, n :usize
|
|
, d :Direction) -> Option<usize>
|
|
where T: Copy + Debug {
|
|
if c == n {
|
|
None
|
|
} else {
|
|
let Coordinate(_, cy, _) = p.vertex(c);
|
|
let Coordinate(_, ny, _) = p.vertex(n);
|
|
|
|
match ny.cmp(&cy) {
|
|
cmp::Ordering::Less => None,
|
|
cmp::Ordering::Equal => inner(p, c, p.step(n, d), d),
|
|
cmp::Ordering::Greater => Some(n),
|
|
}
|
|
}
|
|
}
|
|
|
|
inner(self, c, self.step(c, d), d)
|
|
}
|
|
}
|
|
|
|
impl<T> Drawable<T> for Polygon<T>
|
|
where T: Add<Output = T> + Sub<Output = T> + Div<Output = T>
|
|
+ Debug + Clone + Copy + From<i32> {
|
|
fn plot(&self) -> Coordinates<T> {
|
|
let Polygon(Coordinates(cs)) = self;
|
|
|
|
match cs[..] {
|
|
[] => Coordinates(Vec::<Coordinate<T>>::new()),
|
|
[a] => Coordinates(vec!(a)),
|
|
[a, b] => Coordinates(a.line(&b)),
|
|
_ => {
|
|
let (a, b) = (cs[0], cs[1]);
|
|
let mut r = a.line(&b);
|
|
let mut i = b;
|
|
for j in cs[2..].iter() {
|
|
r.append(&mut i.line(j)[1..].to_vec());
|
|
i = *j;
|
|
}
|
|
let mut j = a.line(&i);
|
|
let l = j.len();
|
|
if l > 1 {
|
|
r.append(&mut j[1..l-1].to_vec());
|
|
}
|
|
Coordinates(r)
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<T> Fillable<T> for Polygon<T>
|
|
where T: Add<Output = T> + Sub<Output = T> + Div<Output = T>
|
|
+ Debug + Clone + Copy + From<i32> {
|
|
fn fill(&self) -> Coordinates<T> {
|
|
let Polygon(Coordinates(cs)) = self;
|
|
|
|
let vert_min = self.vert_min();
|
|
|
|
println!("== vert_min: [{}] {:?}", vert_min, cs[vert_min]);
|
|
|
|
let mut r = (vert_min, self.next_y(vert_min, Direction::Right));
|
|
let mut l = (vert_min, self.next_y(vert_min, Direction::Left));
|
|
|
|
let mut l_edge :Vec<Coordinate<T>> = Vec::new();
|
|
let mut r_edge :Vec<Coordinate<T>> = Vec::new();
|
|
|
|
let append_edge = | v :&mut Vec<Coordinate<T>>
|
|
, e :(usize, Option<usize>)
|
|
, f :Direction | {
|
|
match e {
|
|
(_, None) => e,
|
|
(a, Some(b)) => {
|
|
let mut edge = cs[a].edge(&cs[b]);
|
|
v.append(&mut edge);
|
|
(b, self.next_y(b, f))
|
|
},
|
|
}
|
|
};
|
|
|
|
let print_current = |s :&str, e :(usize, Option<usize>)| {
|
|
match e.1 {
|
|
None => println!( "== {}: [{:?}] - {:?}"
|
|
, s, e.1, "None"),
|
|
Some(e) => println!( "== {}: [{:?}] - {:?}"
|
|
, s, e, cs[e]),
|
|
}
|
|
};
|
|
|
|
while l.1 != None || r.1 != None {
|
|
print_current("l", l);
|
|
l = append_edge(&mut l_edge, l, Direction::Left);
|
|
print_current("r", r);
|
|
r = append_edge(&mut r_edge, r, Direction::Right);
|
|
}
|
|
|
|
println!("== [{}] {:?}", l_edge.len(), l_edge);
|
|
println!("== [{}] {:?}", r_edge.len(), r_edge);
|
|
|
|
// TODO we always miss the last scanline…
|
|
// TODO check what happend with at least 2 vertices with same y and
|
|
// different x…
|
|
// loop though edges…
|
|
|
|
Coordinates(Vec::<Coordinate<T>>::new())
|
|
}
|
|
}
|
|
|
|
impl<T> Display for Polygon<T> where T: Copy {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
|
let Polygon(a) = self;
|
|
write!(f, "Poly[{}]", a)
|
|
}
|
|
}
|