Struct pixel_engine_draw::graphics::Sprite
source · pub struct Sprite { /* private fields */ }
Expand description
Represent a Sprite
Implementations§
source§impl Sprite
impl Sprite
sourcepub fn size(&self) -> &Vu2d
pub fn size(&self) -> &Vu2d
Examples found in repository?
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
fn get_pixel(&self, pos: Vi2d) -> Option<Color> {
if pos.x < 0 || pos.y < 0 || pos.x as u32 >= self.size().x || pos.y as u32 >= self.size().y
{
return None;
}
let (raw, lock) = self.get_read_lock();
let mut col = Color::BLANK;
let pos = pos.cast_u32();
col.r = raw[(pos.y * self.width() + pos.x) as usize * 4];
col.g = raw[(pos.y * self.width() + pos.x) as usize * 4 + 1];
col.b = raw[(pos.y * self.width() + pos.x) as usize * 4 + 2];
col.a = raw[(pos.y * self.width() + pos.x) as usize * 4 + 3];
drop(lock);
Some(col)
}
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
if pos.x < 0 || pos.y < 0 {
return;
};
self.set_pixel(pos.x as u32, pos.y as u32, col);
}
fn size(&self) -> Vu2d {
*self.size()
}
sourcepub fn width(&self) -> u32
pub fn width(&self) -> u32
Examples found in repository?
More examples
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
pub unsafe fn create_sub_sprite_unchecked(
&self,
pos: Vu2d,
size: Vu2d,
index: usize,
) -> SpriteMutRef<'_> {
SpriteMutRef {
spr: self,
size,
pos,
spr_width: self.width(),
index,
write_lock: self.read_lock.clone(),
}
}
/// This is used when using [`create_sub_sprite_unchecked`()](Sprite::create_sub_sprite_unchecked)
///
/// # Safety
///
/// Editing this could lead to overlapping subsprite so be careful when handling the list
/// (slab) of areas.
pub unsafe fn get_areas(&self) -> &Mutex<slab::Slab<Area>> {
&self.areas
}
/// Load an image from bytes, will clone the slice
///
/// # Errors
///
/// If the slice isn't an valid image format handled by the image crate, returns an error
pub fn load_image_bytes(bytes: &[u8]) -> Result<Self, String> {
let img = image::load_from_memory(bytes)
.map_err(|err| err.to_string())?
.to_rgba8();
Ok(Sprite {
size: Vu2d {
x: (&img).width(),
y: (&img).height(),
},
raw: Self::image_to_boxedslice(img),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
})
}
///Load a image file and return a Sprite object representing that image
/// # Errors
///
/// If the file isn't an valid image format handled by the image crate or if the file IO failed, returns an error
pub fn load_from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Sprite, String> {
let img = image::open(path).map_err(|err| err.to_string())?.to_rgba8();
Ok(Sprite {
size: Vu2d {
x: img.width(),
y: img.height(),
},
raw: Self::image_to_boxedslice(img),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
})
}
/// Create [Sprite] with a size of 1x1
#[must_use]
pub fn new_blank() -> Sprite {
Sprite {
size: Vu2d { x: 1, y: 1 },
raw: Self::boxed_slice_to_cell(vec![0x00; 4].into_boxed_slice()),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
}
}
/// Create [Sprite] with given size and [Color]
#[must_use]
pub fn new_with_color(w: u32, h: u32, col: Color) -> Self {
Sprite {
size: Vu2d { x: w, y: h },
raw: Self::boxed_slice_to_cell(
vec![col.r, col.g, col.b, col.a]
.repeat(w as usize * h as usize)
.into_boxed_slice(),
),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
//image::ImageBuffer::from_raw(w, h, raw) /*; (w * h) as usize]) */
//.unwrap(), // as image::RgbaImage,
}
}
/// Create a blank [Sprite] with given size
#[must_use]
pub fn new(w: u32, h: u32) -> Sprite {
Sprite {
size: Vu2d { x: w, y: h },
raw: Self::boxed_slice_to_cell(
vec![0x00; w as usize * h as usize * 4].into_boxed_slice(),
),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
}
}
/// Set pixel's [Color] on a [Sprite]
pub fn set_pixel(&mut self, x: u32, y: u32, col: Color) {
let width = self.width();
if y >= self.height() || x >= width {
return;
}
self.raw.get_mut()[(y * width + x) as usize * 4] = col.r;
self.raw.get_mut()[(y * width + x) as usize * 4 + 1] = col.g;
self.raw.get_mut()[(y * width + x) as usize * 4 + 2] = col.b;
self.raw.get_mut()[(y * width + x) as usize * 4 + 3] = col.a;
}
/// Return the [Color] of the pixel at given coordinates, if it exist
pub fn get_pixel(&self, x: u32, y: u32) -> Color {
let mut col = Color::BLANK;
if x >= self.width() || y >= self.height() {
return col;
}
let (raw, lock) = self.get_read_lock();
col.r = raw[(y * self.width() + x) as usize * 4];
col.g = raw[(y * self.width() + x) as usize * 4 + 1];
col.b = raw[(y * self.width() + x) as usize * 4 + 2];
col.a = raw[(y * self.width() + x) as usize * 4 + 3];
drop(lock);
col
}
/// Return the [Color] of the pixel at given sample
/// This sampling will take only the fractional part of the given sample coordinates, so it is
/// effictivly from [O; 1)
pub fn get_sample(&self, x: f64, y: f64) -> Color {
let x = x.fract();
let y = y.fract();
let sample_x = ((x * f64::from(self.width())) as u32).min(self.width() - 1);
let sample_y = ((y * f64::from(self.height())) as u32).min(self.height() - 1);
self.get_pixel(sample_x, sample_y)
}
}
impl<'spr> SpriteMutRef<'spr> {
fn get_nth_ptr(&self, row: u32) -> *mut u8 {
unsafe {
let base_offset = (self.pos.y * self.spr_width + self.pos.x) as usize * 4;
let base_ptr = self.spr.raw.get().cast::<u8>().add(base_offset);
base_ptr.add((self.spr_width * row * 4) as usize)
}
}
fn get_nth_slice(&self, row: u32) -> &'spr [u8] {
unsafe {
std::slice::from_raw_parts(self.get_nth_ptr(row) as *const u8, self.size.x as usize * 4)
}
}
fn get_nth_slice_mut(&mut self, row: u32) -> &'spr mut [u8] {
unsafe { std::slice::from_raw_parts_mut(self.get_nth_ptr(row), self.size.x as usize * 4) }
}
pub fn get_pixel(&self, p: impl Into<Vu2d>) -> Option<Color> {
let pos = p.into();
if pos.x >= self.size.x || pos.y >= self.size.y {
return None;
}
let slice = self.get_nth_slice(pos.y);
Some(
[
slice[pos.x as usize * 4],
slice[pos.x as usize * 4 + 1],
slice[pos.x as usize * 4 + 2],
slice[pos.x as usize * 4 + 3],
]
.into(),
)
}
pub fn set_pixel(&mut self, p: impl Into<Vu2d>, col: impl Into<Color>) {
let pos = p.into();
let col = col.into();
if pos.x >= self.size.x || pos.y >= self.size.y {
return;
}
let slice = self.get_nth_slice_mut(pos.y);
let lock = self.write_lock.read();
slice[pos.x as usize * 4] = col.r;
slice[pos.x as usize * 4 + 1] = col.g;
slice[pos.x as usize * 4 + 2] = col.b;
slice[pos.x as usize * 4 + 3] = col.a;
drop(lock); // I like to explicitly drop the lock
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
/// Represent a [Color] in a RGBA format
pub struct Color {
/// Red part of the color
pub r: u8,
/// Green part of the color
pub g: u8,
/// Blue part of the color
pub b: u8,
/// Alpha part of the color
pub a: u8,
}
impl Color {
/// Return a [Color] with alpha set at 255
#[must_use]
pub const fn new(r: u8, g: u8, b: u8) -> Color {
Color { r, g, b, a: 255 }
}
/// Return a [Color] where alpha is also a argument
#[must_use]
pub const fn new_with_alpha(r: u8, g: u8, b: u8, a: u8) -> Color {
Color { r, g, b, a }
}
/// White [Color]
pub const WHITE: Color = Color::new(255, 255, 255);
/// Gray [Color]
pub const GREY: Color = Color::new(192, 192, 192);
/// Dark Grey [Color]
pub const DARK_GREY: Color = Color::new(128, 128, 128);
/// Very Dark Grey [Color]
pub const VERY_DARK_GREY: Color = Color::new(64, 64, 64);
/// Red [Color]
pub const RED: Color = Color::new(255, 0, 0);
/// Dark Red [Color]
pub const DARK_RED: Color = Color::new(128, 0, 0);
/// Very Dark Red [Color]
pub const VERY_DARK_RED: Color = Color::new(64, 0, 0);
/// Yellow [Color]
pub const YELLOW: Color = Color::new(255, 255, 0);
/// Dark Yellow [Color]
pub const DARK_YELLOW: Color = Color::new(128, 128, 0);
/// Very Dark Yellow [Color]
pub const VERY_DARK_YELLOW: Color = Color::new(64, 64, 0);
/// Green [Color]
pub const GREEN: Color = Color::new(0, 255, 0);
/// Dark Green [Color]
pub const DARK_GREEN: Color = Color::new(0, 128, 0);
/// Very Dark Green [Color]
pub const VERY_DARK_GREEN: Color = Color::new(0, 64, 0);
/// Cyan [Color]
pub const CYAN: Color = Color::new(0, 255, 255);
/// Dark Cyan [Color]
pub const DARK_CYAN: Color = Color::new(0, 128, 128);
/// Very Dark Cyan [Color]
pub const VERY_DARK_CYAN: Color = Color::new(0, 64, 64);
/// Blue [Color]
pub const BLUE: Color = Color::new(0, 0, 255);
/// Dark Blue [Color]
pub const DARK_BLUE: Color = Color::new(0, 0, 128);
/// Very Dark Blue [Color]
pub const VERY_DARK_BLUE: Color = Color::new(0, 0, 64);
/// Magenta [Color]
pub const MAGENTA: Color = Color::new(255, 0, 255);
/// Dark Magenta [Color]
pub const DARK_MAGENTA: Color = Color::new(128, 0, 128);
/// Very Dark Magenta [Color]
pub const VERY_DARK_MAGENTA: Color = Color::new(64, 0, 64);
/// Black [Color]
pub const BLACK: Color = Color::new(0, 0, 0);
/// Blank [Color]
pub const BLANK: Color = Color::new_with_alpha(0, 0, 0, 0);
}
#[derive(Debug, Clone)]
struct DrawData {
pixel_mode: PixelMode,
blend_factor: f32,
}
#[derive(Clone, Debug)]
pub struct DrawingSprite<S: DrawSpriteTrait> {
draw_data: DrawData,
sprite: S,
}
impl<S: DrawSpriteTrait> DrawSpriteTrait for DrawingSprite<S> {
fn size(&self) -> Vu2d {
self.sprite.size()
}
fn get_pixel(&self, pos: Vi2d) -> Option<Color> {
self.sprite.get_pixel(pos)
}
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
self.sprite.set_pixel(pos, col);
}
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color {
self.sprite.get_pixel_unchecked(pos)
}
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color) {
self.sprite.set_pixel_unchecked(pos, col);
}
}
impl<S: DrawSpriteTrait> crate::traits::SmartDrawingTrait for DrawingSprite<S> {
fn get_size(&self) -> Vu2d {
self.sprite.size()
}
fn get_pixel<P: Into<Vi2d>>(&self, pos: P) -> Option<Color> {
let pos = pos.into();
self.sprite.get_pixel(pos)
}
fn draw<P: Into<Vi2d>>(&mut self, pos: P, col: Color) {
let pixel_mode = self.get_pixel_mode();
let blend_factor = self.get_blend_factor();
let pos @ Vi2d { x, y } = pos.into();
if x >= self.sprite.size().x.try_into().unwrap()
|| y >= self.sprite.size().y.try_into().unwrap()
|| x < 0
|| y < 0
{
return;
}
match pixel_mode {
PixelMode::Normal => unsafe {
self.sprite.set_pixel_unchecked(pos.cast_u32(), col);
},
PixelMode::Mask => {
if col.a == 255 {
unsafe {
self.sprite.set_pixel_unchecked(pos.cast_u32(), col);
}
}
}
PixelMode::Alpha => {
let current_color: Color =
unsafe { self.sprite.get_pixel_unchecked(pos.cast_u32()) };
let alpha: f32 = (f32::from(col.a) / 255.0f32) * blend_factor;
let inverse_alpha: f32 = 1.0 - alpha;
let red: f32 =
alpha * f32::from(col.r) + inverse_alpha * f32::from(current_color.r);
let green: f32 =
alpha * f32::from(col.g) + inverse_alpha * f32::from(current_color.g);
let blue: f32 =
alpha * f32::from(col.b) + inverse_alpha * f32::from(current_color.b);
unsafe {
self.sprite
.set_pixel_unchecked(pos.cast_u32(), [red, green, blue].into());
}
}
}
}
fn get_textsheet(&self) -> &'static Sprite {
create_text()
}
fn clear(&mut self, col: Color) {
let size = self.sprite.size();
for y in 0..size.y {
for x in 0..size.x {
unsafe {
self.sprite.set_pixel_unchecked(Vu2d { x, y }, col);
}
}
}
}
fn get_pixel_mode(&self) -> PixelMode {
self.draw_data.pixel_mode
}
fn get_blend_factor(&self) -> f32 {
self.draw_data.blend_factor
}
fn set_pixel_mode(&mut self, mode: PixelMode) {
self.draw_data.pixel_mode = mode;
}
fn set_blend_factor(&mut self, f: f32) {
self.draw_data.blend_factor = f;
}
}
pub trait DrawSpriteTrait {
fn get_pixel(&self, pos: Vi2d) -> Option<Color>;
fn set_pixel(&mut self, pos: Vi2d, col: Color);
fn size(&self) -> Vu2d;
/// Get the pixel at the given location, but bypassing any bounds check
///
/// # Safety
/// You must ensure that the pos in bounds
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color;
/// Set the pixel at the given location, but bypassing any bounds check
///
/// # Safety
/// You must ensure that the pos in bounds
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color);
}
impl DrawSpriteTrait for Sprite {
fn get_pixel(&self, pos: Vi2d) -> Option<Color> {
if pos.x < 0 || pos.y < 0 || pos.x as u32 >= self.size().x || pos.y as u32 >= self.size().y
{
return None;
}
let (raw, lock) = self.get_read_lock();
let mut col = Color::BLANK;
let pos = pos.cast_u32();
col.r = raw[(pos.y * self.width() + pos.x) as usize * 4];
col.g = raw[(pos.y * self.width() + pos.x) as usize * 4 + 1];
col.b = raw[(pos.y * self.width() + pos.x) as usize * 4 + 2];
col.a = raw[(pos.y * self.width() + pos.x) as usize * 4 + 3];
drop(lock);
Some(col)
}
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
if pos.x < 0 || pos.y < 0 {
return;
};
self.set_pixel(pos.x as u32, pos.y as u32, col);
}
fn size(&self) -> Vu2d {
*self.size()
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color {
let (raw, _lock) = self.get_read_lock();
let mut col = Color::BLANK;
col.r = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4);
col.g = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 1);
col.b = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 2);
col.a = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 3);
col
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color) {
let Vu2d { x, y } = pos;
let width = self.width();
// SAFETY: Its up to the caller to make sure that the bounds are correct to not write oob
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4) = col.r;
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4 + 1) = col.g;
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4 + 2) = col.b;
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4 + 3) = col.a;
}
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
fn draw_sprite<P: Into<Vi2d>>(
&mut self,
pos: P,
scale: u32,
sprite: &Sprite,
flip: (bool, bool),
) {
#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let Vi2d { x, y } = pos.into();
let (mut fxs, mut fxm) = (0i32, 1i32);
let (mut fys, mut fym) = (0i32, 1i32);
let mut fx: i32;
let mut fy: i32;
if flip.0 {
fxs = sprite.width() as i32 - 1;
fxm = -1;
}
if flip.1 {
fys = sprite.height() as i32 - 1;
fym = -1;
}
if scale > 1 {
fx = fxs;
for i in 0..(sprite.width() as i32) {
fy = fys;
for j in 0..(sprite.height() as i32) {
for is in 0..(scale as i32) {
for js in 0..(scale as i32) {
self.draw(
(x + i * (scale as i32) + is, y + j * (scale as i32) + js),
sprite.get_pixel(fx as u32, fy as u32),
);
}
}
fy += fym;
}
fx += fxm;
}
} else {
fx = fxs;
for i in 0..(sprite.width() as i32) {
fy = fys;
for j in 0..(sprite.height() as i32) {
self.draw((x + i, y + j), sprite.get_pixel(fx as u32, fy as u32));
fy += fym;
}
fx += fxm;
}
}
}
sourcepub fn height(&self) -> u32
pub fn height(&self) -> u32
Examples found in repository?
More examples
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
pub fn set_pixel(&mut self, x: u32, y: u32, col: Color) {
let width = self.width();
if y >= self.height() || x >= width {
return;
}
self.raw.get_mut()[(y * width + x) as usize * 4] = col.r;
self.raw.get_mut()[(y * width + x) as usize * 4 + 1] = col.g;
self.raw.get_mut()[(y * width + x) as usize * 4 + 2] = col.b;
self.raw.get_mut()[(y * width + x) as usize * 4 + 3] = col.a;
}
/// Return the [Color] of the pixel at given coordinates, if it exist
pub fn get_pixel(&self, x: u32, y: u32) -> Color {
let mut col = Color::BLANK;
if x >= self.width() || y >= self.height() {
return col;
}
let (raw, lock) = self.get_read_lock();
col.r = raw[(y * self.width() + x) as usize * 4];
col.g = raw[(y * self.width() + x) as usize * 4 + 1];
col.b = raw[(y * self.width() + x) as usize * 4 + 2];
col.a = raw[(y * self.width() + x) as usize * 4 + 3];
drop(lock);
col
}
/// Return the [Color] of the pixel at given sample
/// This sampling will take only the fractional part of the given sample coordinates, so it is
/// effictivly from [O; 1)
pub fn get_sample(&self, x: f64, y: f64) -> Color {
let x = x.fract();
let y = y.fract();
let sample_x = ((x * f64::from(self.width())) as u32).min(self.width() - 1);
let sample_y = ((y * f64::from(self.height())) as u32).min(self.height() - 1);
self.get_pixel(sample_x, sample_y)
}
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
fn draw_sprite<P: Into<Vi2d>>(
&mut self,
pos: P,
scale: u32,
sprite: &Sprite,
flip: (bool, bool),
) {
#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let Vi2d { x, y } = pos.into();
let (mut fxs, mut fxm) = (0i32, 1i32);
let (mut fys, mut fym) = (0i32, 1i32);
let mut fx: i32;
let mut fy: i32;
if flip.0 {
fxs = sprite.width() as i32 - 1;
fxm = -1;
}
if flip.1 {
fys = sprite.height() as i32 - 1;
fym = -1;
}
if scale > 1 {
fx = fxs;
for i in 0..(sprite.width() as i32) {
fy = fys;
for j in 0..(sprite.height() as i32) {
for is in 0..(scale as i32) {
for js in 0..(scale as i32) {
self.draw(
(x + i * (scale as i32) + is, y + j * (scale as i32) + js),
sprite.get_pixel(fx as u32, fy as u32),
);
}
}
fy += fym;
}
fx += fxm;
}
} else {
fx = fxs;
for i in 0..(sprite.width() as i32) {
fy = fys;
for j in 0..(sprite.height() as i32) {
self.draw((x + i, y + j), sprite.get_pixel(fx as u32, fy as u32));
fy += fym;
}
fx += fxm;
}
}
}
sourcepub fn get_read_lock(&self) -> (&mut [u8], RwLockWriteGuard<'_, ()>)
pub fn get_read_lock(&self) -> (&mut [u8], RwLockWriteGuard<'_, ()>)
Examples found in repository?
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
fn clone(&self) -> Self {
let raw = Self::boxed_slice_to_cell(self.get_read_lock().0.to_vec().into_boxed_slice());
Self {
size: self.size,
raw,
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Area {
pub pos: Vu2d,
pub size: Vu2d,
}
impl Area {
fn overlap(&self, other: &Self) -> bool {
(self.pos.x < other.pos.x && other.pos.x < self.pos.x + self.size.x)
|| (self.pos.y < other.pos.y && other.pos.y < self.pos.y + self.size.y)
|| (other.pos.x < self.pos.x && self.pos.x < other.pos.x + other.size.x)
|| (other.pos.y < self.pos.y && self.pos.y < other.pos.y + other.size.y)
}
}
#[derive(Debug)]
pub struct SpriteMutRef<'spr> {
/// A reference to the base sprite;
spr: &'spr Sprite,
/// Top left of the subsprite (in pixels)
pos: Vu2d,
/// Size fot the left subsprite (in pixels)
size: Vu2d,
/// To do pointer math
/// this is the with (in pixel) of the sprite.
spr_width: u32,
/// Signal that a write/read is happening
/// The contract is that when a subsprite is writing or reading, it will take a ReadGuard and
/// when then sprite want to read from its data, it lock with an exclusive access so it is the
/// only one accessing the data.
write_lock: Arc<RwLock<()>>,
/// The area index inside the sprite's areas field.
index: usize,
}
unsafe impl Send for Sprite {}
unsafe impl<'spr> Send for SpriteMutRef<'spr> {}
impl<'spr> Drop for SpriteMutRef<'spr> {
fn drop(&mut self) {
self.spr.areas.lock().remove(self.index);
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct OverlappingError;
impl std::fmt::Display for OverlappingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Tried to create overlapping subsprite")
}
}
impl std::error::Error for OverlappingError {}
impl Sprite {
pub fn size(&self) -> &Vu2d {
&self.size
}
pub fn width(&self) -> u32 {
self.size.x
}
pub fn height(&self) -> u32 {
self.size.y
}
pub fn get_read_lock(&self) -> (&mut [u8], RwLockWriteGuard<'_, ()>) {
let lock = self.read_lock.write();
// SAFETY: We have exclusive access as the contract is everyone that wishese to write to
// the sprite gets a ReadGuard, and when you want to read from the whole sprite you get a
// WriteGuard (so it is exclusive) to the data behind self.raw
// We also return the lock so we keep the exclusive access.
//
(unsafe { &mut *self.raw.get() }, lock)
}
fn image_to_boxedslice(img: image::RgbaImage) -> Box<UnsafeCell<[u8]>> {
Self::boxed_slice_to_cell(img.into_raw().into_boxed_slice())
}
/// Transmute a owned slice to an owned `UnsafeCell` wrapped slice
pub(crate) fn boxed_slice_to_cell(slice: Box<[u8]>) -> Box<UnsafeCell<[u8]>> {
// This is because we can't have the slice on the stack to create a Boxed slice and there
// is no .map for a Box.
// Transmuting the Box<[u8]> is fine because UnsafeCell is #[repr(transparent)]
unsafe { transmute(slice) }
}
/// Load an rgba slice as an Sprite, will clone the slice
/// the dimentions are in pixel
///
/// # Errors
///
/// if the slice isn't an rgba slice it will return an `Err`
/// this means that `slice.len() % 4 = 0` and that `slice.len() = width * height * 4`
pub fn load_rgba(rgba: &[u8], width: usize, height: usize) -> Result<Self, String> {
if rgba.len() % 4 != 0 || rgba.len() != width * height * 4 {
Err("Wrong Image len".to_string())
} else {
Ok(Self {
size: Vu2d {
x: width.try_into().expect("Image too large"),
y: height.try_into().expect("Image too large"),
},
raw: Self::boxed_slice_to_cell(rgba.to_vec().into_boxed_slice()),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
})
}
}
/// Creates a subsprite on a given parent sprite
/// The real position will be clamped to the sprite dimentions, so if the `pos` has some
/// negative parts, it will be clipped, only showing the positive part.
/// Same with if the `size + pos` goes outside of the sprite.
///
/// # Errors
///
/// This will return an error if an subsprite already exists and that it overlaps
#[allow(clippy::cast_sign_loss)]
pub fn create_sub_sprite(
&self,
pos: Vi2d,
mut size: Vu2d,
) -> Result<SpriteMutRef<'_>, OverlappingError> {
let real_pos = Vu2d {
x: if pos.x < 0 {
size.x -= (-pos.x) as u32;
0
} else {
(pos.x as u32).min(self.size.x)
},
y: if pos.y < 0 {
size.y -= (-pos.y) as u32;
0
} else {
(pos.y as u32).min(self.size.y)
},
};
size.x = size.x.min(self.size.x - real_pos.x);
size.y = size.y.min(self.size.y - real_pos.y);
let area = Area {
pos: real_pos,
size,
};
let mut lock = self.areas.lock();
let overlap = lock.iter().any(|(_, a)| a.overlap(&area));
if overlap {
return Err(OverlappingError);
};
let index = lock.insert(area);
// SAFETY:
// We checked that the subsprite is inside the main sprite
// We checked that there is no overlap$
// We added the area to the list
unsafe { Ok(self.create_sub_sprite_unchecked(real_pos, size, index)) }
}
/// Creates a subsprite without any checks
///
/// # Safety
///
/// - You need to make sure there is no overlap with another subsprite
/// - You need to make sure that the size is correct and fit inside the base sprites
/// - You need to make sure that the area has been inserted in the area list and that the given
/// index is the one pointing to the subsprite's area;
pub unsafe fn create_sub_sprite_unchecked(
&self,
pos: Vu2d,
size: Vu2d,
index: usize,
) -> SpriteMutRef<'_> {
SpriteMutRef {
spr: self,
size,
pos,
spr_width: self.width(),
index,
write_lock: self.read_lock.clone(),
}
}
/// This is used when using [`create_sub_sprite_unchecked`()](Sprite::create_sub_sprite_unchecked)
///
/// # Safety
///
/// Editing this could lead to overlapping subsprite so be careful when handling the list
/// (slab) of areas.
pub unsafe fn get_areas(&self) -> &Mutex<slab::Slab<Area>> {
&self.areas
}
/// Load an image from bytes, will clone the slice
///
/// # Errors
///
/// If the slice isn't an valid image format handled by the image crate, returns an error
pub fn load_image_bytes(bytes: &[u8]) -> Result<Self, String> {
let img = image::load_from_memory(bytes)
.map_err(|err| err.to_string())?
.to_rgba8();
Ok(Sprite {
size: Vu2d {
x: (&img).width(),
y: (&img).height(),
},
raw: Self::image_to_boxedslice(img),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
})
}
///Load a image file and return a Sprite object representing that image
/// # Errors
///
/// If the file isn't an valid image format handled by the image crate or if the file IO failed, returns an error
pub fn load_from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Sprite, String> {
let img = image::open(path).map_err(|err| err.to_string())?.to_rgba8();
Ok(Sprite {
size: Vu2d {
x: img.width(),
y: img.height(),
},
raw: Self::image_to_boxedslice(img),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
})
}
/// Create [Sprite] with a size of 1x1
#[must_use]
pub fn new_blank() -> Sprite {
Sprite {
size: Vu2d { x: 1, y: 1 },
raw: Self::boxed_slice_to_cell(vec![0x00; 4].into_boxed_slice()),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
}
}
/// Create [Sprite] with given size and [Color]
#[must_use]
pub fn new_with_color(w: u32, h: u32, col: Color) -> Self {
Sprite {
size: Vu2d { x: w, y: h },
raw: Self::boxed_slice_to_cell(
vec![col.r, col.g, col.b, col.a]
.repeat(w as usize * h as usize)
.into_boxed_slice(),
),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
//image::ImageBuffer::from_raw(w, h, raw) /*; (w * h) as usize]) */
//.unwrap(), // as image::RgbaImage,
}
}
/// Create a blank [Sprite] with given size
#[must_use]
pub fn new(w: u32, h: u32) -> Sprite {
Sprite {
size: Vu2d { x: w, y: h },
raw: Self::boxed_slice_to_cell(
vec![0x00; w as usize * h as usize * 4].into_boxed_slice(),
),
areas: Mutex::new(slab::Slab::new()),
read_lock: Arc::new(RwLock::new(())),
}
}
/// Set pixel's [Color] on a [Sprite]
pub fn set_pixel(&mut self, x: u32, y: u32, col: Color) {
let width = self.width();
if y >= self.height() || x >= width {
return;
}
self.raw.get_mut()[(y * width + x) as usize * 4] = col.r;
self.raw.get_mut()[(y * width + x) as usize * 4 + 1] = col.g;
self.raw.get_mut()[(y * width + x) as usize * 4 + 2] = col.b;
self.raw.get_mut()[(y * width + x) as usize * 4 + 3] = col.a;
}
/// Return the [Color] of the pixel at given coordinates, if it exist
pub fn get_pixel(&self, x: u32, y: u32) -> Color {
let mut col = Color::BLANK;
if x >= self.width() || y >= self.height() {
return col;
}
let (raw, lock) = self.get_read_lock();
col.r = raw[(y * self.width() + x) as usize * 4];
col.g = raw[(y * self.width() + x) as usize * 4 + 1];
col.b = raw[(y * self.width() + x) as usize * 4 + 2];
col.a = raw[(y * self.width() + x) as usize * 4 + 3];
drop(lock);
col
}
/// Return the [Color] of the pixel at given sample
/// This sampling will take only the fractional part of the given sample coordinates, so it is
/// effictivly from [O; 1)
pub fn get_sample(&self, x: f64, y: f64) -> Color {
let x = x.fract();
let y = y.fract();
let sample_x = ((x * f64::from(self.width())) as u32).min(self.width() - 1);
let sample_y = ((y * f64::from(self.height())) as u32).min(self.height() - 1);
self.get_pixel(sample_x, sample_y)
}
}
impl<'spr> SpriteMutRef<'spr> {
fn get_nth_ptr(&self, row: u32) -> *mut u8 {
unsafe {
let base_offset = (self.pos.y * self.spr_width + self.pos.x) as usize * 4;
let base_ptr = self.spr.raw.get().cast::<u8>().add(base_offset);
base_ptr.add((self.spr_width * row * 4) as usize)
}
}
fn get_nth_slice(&self, row: u32) -> &'spr [u8] {
unsafe {
std::slice::from_raw_parts(self.get_nth_ptr(row) as *const u8, self.size.x as usize * 4)
}
}
fn get_nth_slice_mut(&mut self, row: u32) -> &'spr mut [u8] {
unsafe { std::slice::from_raw_parts_mut(self.get_nth_ptr(row), self.size.x as usize * 4) }
}
pub fn get_pixel(&self, p: impl Into<Vu2d>) -> Option<Color> {
let pos = p.into();
if pos.x >= self.size.x || pos.y >= self.size.y {
return None;
}
let slice = self.get_nth_slice(pos.y);
Some(
[
slice[pos.x as usize * 4],
slice[pos.x as usize * 4 + 1],
slice[pos.x as usize * 4 + 2],
slice[pos.x as usize * 4 + 3],
]
.into(),
)
}
pub fn set_pixel(&mut self, p: impl Into<Vu2d>, col: impl Into<Color>) {
let pos = p.into();
let col = col.into();
if pos.x >= self.size.x || pos.y >= self.size.y {
return;
}
let slice = self.get_nth_slice_mut(pos.y);
let lock = self.write_lock.read();
slice[pos.x as usize * 4] = col.r;
slice[pos.x as usize * 4 + 1] = col.g;
slice[pos.x as usize * 4 + 2] = col.b;
slice[pos.x as usize * 4 + 3] = col.a;
drop(lock); // I like to explicitly drop the lock
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
/// Represent a [Color] in a RGBA format
pub struct Color {
/// Red part of the color
pub r: u8,
/// Green part of the color
pub g: u8,
/// Blue part of the color
pub b: u8,
/// Alpha part of the color
pub a: u8,
}
impl Color {
/// Return a [Color] with alpha set at 255
#[must_use]
pub const fn new(r: u8, g: u8, b: u8) -> Color {
Color { r, g, b, a: 255 }
}
/// Return a [Color] where alpha is also a argument
#[must_use]
pub const fn new_with_alpha(r: u8, g: u8, b: u8, a: u8) -> Color {
Color { r, g, b, a }
}
/// White [Color]
pub const WHITE: Color = Color::new(255, 255, 255);
/// Gray [Color]
pub const GREY: Color = Color::new(192, 192, 192);
/// Dark Grey [Color]
pub const DARK_GREY: Color = Color::new(128, 128, 128);
/// Very Dark Grey [Color]
pub const VERY_DARK_GREY: Color = Color::new(64, 64, 64);
/// Red [Color]
pub const RED: Color = Color::new(255, 0, 0);
/// Dark Red [Color]
pub const DARK_RED: Color = Color::new(128, 0, 0);
/// Very Dark Red [Color]
pub const VERY_DARK_RED: Color = Color::new(64, 0, 0);
/// Yellow [Color]
pub const YELLOW: Color = Color::new(255, 255, 0);
/// Dark Yellow [Color]
pub const DARK_YELLOW: Color = Color::new(128, 128, 0);
/// Very Dark Yellow [Color]
pub const VERY_DARK_YELLOW: Color = Color::new(64, 64, 0);
/// Green [Color]
pub const GREEN: Color = Color::new(0, 255, 0);
/// Dark Green [Color]
pub const DARK_GREEN: Color = Color::new(0, 128, 0);
/// Very Dark Green [Color]
pub const VERY_DARK_GREEN: Color = Color::new(0, 64, 0);
/// Cyan [Color]
pub const CYAN: Color = Color::new(0, 255, 255);
/// Dark Cyan [Color]
pub const DARK_CYAN: Color = Color::new(0, 128, 128);
/// Very Dark Cyan [Color]
pub const VERY_DARK_CYAN: Color = Color::new(0, 64, 64);
/// Blue [Color]
pub const BLUE: Color = Color::new(0, 0, 255);
/// Dark Blue [Color]
pub const DARK_BLUE: Color = Color::new(0, 0, 128);
/// Very Dark Blue [Color]
pub const VERY_DARK_BLUE: Color = Color::new(0, 0, 64);
/// Magenta [Color]
pub const MAGENTA: Color = Color::new(255, 0, 255);
/// Dark Magenta [Color]
pub const DARK_MAGENTA: Color = Color::new(128, 0, 128);
/// Very Dark Magenta [Color]
pub const VERY_DARK_MAGENTA: Color = Color::new(64, 0, 64);
/// Black [Color]
pub const BLACK: Color = Color::new(0, 0, 0);
/// Blank [Color]
pub const BLANK: Color = Color::new_with_alpha(0, 0, 0, 0);
}
#[derive(Debug, Clone)]
struct DrawData {
pixel_mode: PixelMode,
blend_factor: f32,
}
#[derive(Clone, Debug)]
pub struct DrawingSprite<S: DrawSpriteTrait> {
draw_data: DrawData,
sprite: S,
}
impl<S: DrawSpriteTrait> DrawSpriteTrait for DrawingSprite<S> {
fn size(&self) -> Vu2d {
self.sprite.size()
}
fn get_pixel(&self, pos: Vi2d) -> Option<Color> {
self.sprite.get_pixel(pos)
}
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
self.sprite.set_pixel(pos, col);
}
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color {
self.sprite.get_pixel_unchecked(pos)
}
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color) {
self.sprite.set_pixel_unchecked(pos, col);
}
}
impl<S: DrawSpriteTrait> crate::traits::SmartDrawingTrait for DrawingSprite<S> {
fn get_size(&self) -> Vu2d {
self.sprite.size()
}
fn get_pixel<P: Into<Vi2d>>(&self, pos: P) -> Option<Color> {
let pos = pos.into();
self.sprite.get_pixel(pos)
}
fn draw<P: Into<Vi2d>>(&mut self, pos: P, col: Color) {
let pixel_mode = self.get_pixel_mode();
let blend_factor = self.get_blend_factor();
let pos @ Vi2d { x, y } = pos.into();
if x >= self.sprite.size().x.try_into().unwrap()
|| y >= self.sprite.size().y.try_into().unwrap()
|| x < 0
|| y < 0
{
return;
}
match pixel_mode {
PixelMode::Normal => unsafe {
self.sprite.set_pixel_unchecked(pos.cast_u32(), col);
},
PixelMode::Mask => {
if col.a == 255 {
unsafe {
self.sprite.set_pixel_unchecked(pos.cast_u32(), col);
}
}
}
PixelMode::Alpha => {
let current_color: Color =
unsafe { self.sprite.get_pixel_unchecked(pos.cast_u32()) };
let alpha: f32 = (f32::from(col.a) / 255.0f32) * blend_factor;
let inverse_alpha: f32 = 1.0 - alpha;
let red: f32 =
alpha * f32::from(col.r) + inverse_alpha * f32::from(current_color.r);
let green: f32 =
alpha * f32::from(col.g) + inverse_alpha * f32::from(current_color.g);
let blue: f32 =
alpha * f32::from(col.b) + inverse_alpha * f32::from(current_color.b);
unsafe {
self.sprite
.set_pixel_unchecked(pos.cast_u32(), [red, green, blue].into());
}
}
}
}
fn get_textsheet(&self) -> &'static Sprite {
create_text()
}
fn clear(&mut self, col: Color) {
let size = self.sprite.size();
for y in 0..size.y {
for x in 0..size.x {
unsafe {
self.sprite.set_pixel_unchecked(Vu2d { x, y }, col);
}
}
}
}
fn get_pixel_mode(&self) -> PixelMode {
self.draw_data.pixel_mode
}
fn get_blend_factor(&self) -> f32 {
self.draw_data.blend_factor
}
fn set_pixel_mode(&mut self, mode: PixelMode) {
self.draw_data.pixel_mode = mode;
}
fn set_blend_factor(&mut self, f: f32) {
self.draw_data.blend_factor = f;
}
}
pub trait DrawSpriteTrait {
fn get_pixel(&self, pos: Vi2d) -> Option<Color>;
fn set_pixel(&mut self, pos: Vi2d, col: Color);
fn size(&self) -> Vu2d;
/// Get the pixel at the given location, but bypassing any bounds check
///
/// # Safety
/// You must ensure that the pos in bounds
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color;
/// Set the pixel at the given location, but bypassing any bounds check
///
/// # Safety
/// You must ensure that the pos in bounds
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color);
}
impl DrawSpriteTrait for Sprite {
fn get_pixel(&self, pos: Vi2d) -> Option<Color> {
if pos.x < 0 || pos.y < 0 || pos.x as u32 >= self.size().x || pos.y as u32 >= self.size().y
{
return None;
}
let (raw, lock) = self.get_read_lock();
let mut col = Color::BLANK;
let pos = pos.cast_u32();
col.r = raw[(pos.y * self.width() + pos.x) as usize * 4];
col.g = raw[(pos.y * self.width() + pos.x) as usize * 4 + 1];
col.b = raw[(pos.y * self.width() + pos.x) as usize * 4 + 2];
col.a = raw[(pos.y * self.width() + pos.x) as usize * 4 + 3];
drop(lock);
Some(col)
}
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
if pos.x < 0 || pos.y < 0 {
return;
};
self.set_pixel(pos.x as u32, pos.y as u32, col);
}
fn size(&self) -> Vu2d {
*self.size()
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color {
let (raw, _lock) = self.get_read_lock();
let mut col = Color::BLANK;
col.r = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4);
col.g = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 1);
col.b = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 2);
col.a = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 3);
col
}
sourcepub fn load_rgba(rgba: &[u8], width: usize, height: usize) -> Result<Self, String>
pub fn load_rgba(rgba: &[u8], width: usize, height: usize) -> Result<Self, String>
Load an rgba slice as an Sprite, will clone the slice the dimentions are in pixel
Errors
if the slice isn’t an rgba slice it will return an Err
this means that slice.len() % 4 = 0
and that slice.len() = width * height * 4
sourcepub fn create_sub_sprite(
&self,
pos: Vi2d,
size: Vu2d
) -> Result<SpriteMutRef<'_>, OverlappingError>
pub fn create_sub_sprite(
&self,
pos: Vi2d,
size: Vu2d
) -> Result<SpriteMutRef<'_>, OverlappingError>
Creates a subsprite on a given parent sprite
The real position will be clamped to the sprite dimentions, so if the pos
has some
negative parts, it will be clipped, only showing the positive part.
Same with if the size + pos
goes outside of the sprite.
Errors
This will return an error if an subsprite already exists and that it overlaps
Examples found in repository?
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
fn main() {
let spr = Sprite::new_with_color(20, 20, Color::GREEN);
let sub1 = spr.create_sub_sprite((0, 0).into(), (10, 10).into());
let sub2 = spr.create_sub_sprite((0, 10).into(), (10, 10).into());
let sub3 = spr.create_sub_sprite((10, 0).into(), (10, 10).into());
let sub4 = spr.create_sub_sprite((10, 10).into(), (10, 10).into());
let subs = [
(sub1, Color::BLUE),
(sub2, Color::YELLOW),
(sub3, Color::WHITE),
(sub4, Color::BLACK),
];
for (sub, col) in subs {
let mut sub = sub.unwrap();
for y in 0..10u32 {
for x in 0..10u32 {
sub.set_pixel(Vu2d { x, y }, col);
}
}
}
print_sprite(&spr);
}
sourcepub unsafe fn create_sub_sprite_unchecked(
&self,
pos: Vu2d,
size: Vu2d,
index: usize
) -> SpriteMutRef<'_>
pub unsafe fn create_sub_sprite_unchecked(
&self,
pos: Vu2d,
size: Vu2d,
index: usize
) -> SpriteMutRef<'_>
Creates a subsprite without any checks
Safety
- You need to make sure there is no overlap with another subsprite
- You need to make sure that the size is correct and fit inside the base sprites
- You need to make sure that the area has been inserted in the area list and that the given index is the one pointing to the subsprite’s area;
Examples found in repository?
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
pub fn create_sub_sprite(
&self,
pos: Vi2d,
mut size: Vu2d,
) -> Result<SpriteMutRef<'_>, OverlappingError> {
let real_pos = Vu2d {
x: if pos.x < 0 {
size.x -= (-pos.x) as u32;
0
} else {
(pos.x as u32).min(self.size.x)
},
y: if pos.y < 0 {
size.y -= (-pos.y) as u32;
0
} else {
(pos.y as u32).min(self.size.y)
},
};
size.x = size.x.min(self.size.x - real_pos.x);
size.y = size.y.min(self.size.y - real_pos.y);
let area = Area {
pos: real_pos,
size,
};
let mut lock = self.areas.lock();
let overlap = lock.iter().any(|(_, a)| a.overlap(&area));
if overlap {
return Err(OverlappingError);
};
let index = lock.insert(area);
// SAFETY:
// We checked that the subsprite is inside the main sprite
// We checked that there is no overlap$
// We added the area to the list
unsafe { Ok(self.create_sub_sprite_unchecked(real_pos, size, index)) }
}
sourcepub unsafe fn get_areas(&self) -> &Mutex<Slab<Area>>
pub unsafe fn get_areas(&self) -> &Mutex<Slab<Area>>
This is used when using create_sub_sprite_unchecked
()
Safety
Editing this could lead to overlapping subsprite so be careful when handling the list (slab) of areas.
sourcepub fn load_image_bytes(bytes: &[u8]) -> Result<Self, String>
pub fn load_image_bytes(bytes: &[u8]) -> Result<Self, String>
Load an image from bytes, will clone the slice
Errors
If the slice isn’t an valid image format handled by the image crate, returns an error
sourcepub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Sprite, String>
pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Sprite, String>
Load a image file and return a Sprite object representing that image
Errors
If the file isn’t an valid image format handled by the image crate or if the file IO failed, returns an error
sourcepub fn new_with_color(w: u32, h: u32, col: Color) -> Self
pub fn new_with_color(w: u32, h: u32, col: Color) -> Self
Examples found in repository?
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
fn main() {
let spr = Sprite::new_with_color(20, 20, Color::GREEN);
let sub1 = spr.create_sub_sprite((0, 0).into(), (10, 10).into());
let sub2 = spr.create_sub_sprite((0, 10).into(), (10, 10).into());
let sub3 = spr.create_sub_sprite((10, 0).into(), (10, 10).into());
let sub4 = spr.create_sub_sprite((10, 10).into(), (10, 10).into());
let subs = [
(sub1, Color::BLUE),
(sub2, Color::YELLOW),
(sub3, Color::WHITE),
(sub4, Color::BLACK),
];
for (sub, col) in subs {
let mut sub = sub.unwrap();
for y in 0..10u32 {
for x in 0..10u32 {
sub.set_pixel(Vu2d { x, y }, col);
}
}
}
print_sprite(&spr);
}
sourcepub fn new(w: u32, h: u32) -> Sprite
pub fn new(w: u32, h: u32) -> Sprite
Create a blank Sprite with given size
Examples found in repository?
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
fn create_text() -> &'static Sprite {
struct ForceSendSync<T>(T);
unsafe impl<T> Send for ForceSendSync<T> {}
unsafe impl<T> Sync for ForceSendSync<T> {}
static TEXT_FONT: &[u8] = b"?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?0000000070<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A00000H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@00000000000P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020";
static SPRITE_TEXTSHEET: OnceCell<ForceSendSync<Sprite>> = OnceCell::new();
&SPRITE_TEXTSHEET
.get_or_init(|| {
let mut sheet = Sprite::new(128, 48);
let mut px = 0;
let mut py = 0;
let chars = TEXT_FONT;
for b in (0..1024).step_by(4) {
let sym1 = u32::from(chars[b]) - 48;
let sym2 = u32::from(chars[b + 1]) - 48;
let sym3 = u32::from(chars[b + 2]) - 48;
let sym4 = u32::from(chars[b + 3]) - 48;
let r: u32 = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4;
for i in 0..24 {
let k = if (r & (1 << i)) == 0 { 0 } else { 255 };
sheet.set_pixel(px, py, [k, k, k, k].into());
py += 1;
if py == 48 {
px += 1;
py = 0;
}
}
}
ForceSendSync(sheet)
})
.0
}
sourcepub fn set_pixel(&mut self, x: u32, y: u32, col: Color)
pub fn set_pixel(&mut self, x: u32, y: u32, col: Color)
Examples found in repository?
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
if pos.x < 0 || pos.y < 0 {
return;
};
self.set_pixel(pos.x as u32, pos.y as u32, col);
}
fn size(&self) -> Vu2d {
*self.size()
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color {
let (raw, _lock) = self.get_read_lock();
let mut col = Color::BLANK;
col.r = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4);
col.g = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 1);
col.b = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 2);
col.a = *raw.get_unchecked((pos.y * self.width() + pos.x) as usize * 4 + 3);
col
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color) {
let Vu2d { x, y } = pos;
let width = self.width();
// SAFETY: Its up to the caller to make sure that the bounds are correct to not write oob
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4) = col.r;
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4 + 1) = col.g;
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4 + 2) = col.b;
*self
.raw
.get_mut()
.get_unchecked_mut((y * width + x) as usize * 4 + 3) = col.a;
}
}
impl<'spr> DrawSpriteTrait for SpriteMutRef<'spr> {
fn get_pixel(&self, pos: Vi2d) -> Option<Color> {
if pos.x < 0 || pos.y < 0 {
return None;
};
self.get_pixel(pos.cast_u32())
}
fn set_pixel(&mut self, pos: Vi2d, col: Color) {
if pos.x < 0 || pos.y < 0 {
return;
};
self.set_pixel(pos.cast_u32(), col);
}
fn size(&self) -> Vu2d {
self.size
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color {
let slice = self.get_nth_slice(pos.y);
[
*slice.get_unchecked(pos.x as usize * 4),
*slice.get_unchecked(pos.x as usize * 4 + 1),
*slice.get_unchecked(pos.x as usize * 4 + 2),
*slice.get_unchecked(pos.x as usize * 4 + 3),
]
.into()
}
/// # Safety
/// its up to the caller to make sure that the given position is in bounds
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color) {
let slice = self.get_nth_slice_mut(pos.y);
let lock = self.write_lock.read();
*slice.get_unchecked_mut(pos.x as usize * 4) = col.r;
*slice.get_unchecked_mut(pos.x as usize * 4 + 1) = col.g;
*slice.get_unchecked_mut(pos.x as usize * 4 + 2) = col.b;
*slice.get_unchecked_mut(pos.x as usize * 4 + 3) = col.a;
drop(lock); // I like to explicitly drop the lock
}
}
impl<S: DrawSpriteTrait> DrawingSprite<S> {
pub fn new(spr: S) -> Self {
DrawingSprite {
draw_data: DrawData::new(),
sprite: spr,
}
}
pub fn into_inner(self) -> S {
self.sprite
}
pub fn get_ref(&self) -> &S {
&self.sprite
}
pub fn get_mut(&mut self) -> &S {
&mut self.sprite
}
}
impl DrawData {
pub(crate) fn new() -> DrawData {
Self {
pixel_mode: PixelMode::Normal,
blend_factor: 1.0f32,
}
}
}
fn create_text() -> &'static Sprite {
struct ForceSendSync<T>(T);
unsafe impl<T> Send for ForceSendSync<T> {}
unsafe impl<T> Sync for ForceSendSync<T> {}
static TEXT_FONT: &[u8] = b"?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?0000000070<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A00000H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@00000000000P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020";
static SPRITE_TEXTSHEET: OnceCell<ForceSendSync<Sprite>> = OnceCell::new();
&SPRITE_TEXTSHEET
.get_or_init(|| {
let mut sheet = Sprite::new(128, 48);
let mut px = 0;
let mut py = 0;
let chars = TEXT_FONT;
for b in (0..1024).step_by(4) {
let sym1 = u32::from(chars[b]) - 48;
let sym2 = u32::from(chars[b + 1]) - 48;
let sym3 = u32::from(chars[b + 2]) - 48;
let sym4 = u32::from(chars[b + 3]) - 48;
let r: u32 = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4;
for i in 0..24 {
let k = if (r & (1 << i)) == 0 { 0 } else { 255 };
sheet.set_pixel(px, py, [k, k, k, k].into());
py += 1;
if py == 48 {
px += 1;
py = 0;
}
}
}
ForceSendSync(sheet)
})
.0
}
sourcepub fn get_pixel(&self, x: u32, y: u32) -> Color
pub fn get_pixel(&self, x: u32, y: u32) -> Color
Return the Color of the pixel at given coordinates, if it exist
Examples found in repository?
More examples
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
fn draw_text<P: Into<Vi2d>>(&mut self, pos: P, scale: u32, col: Color, text: &str) {
#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let Vi2d { x, y } = pos.into();
let scale: i32 = scale.try_into().unwrap();
let mut sx = 0;
let mut sy = 0;
for chr in text.chars() {
if chr == '\n' {
sx = 0;
sy += 8 * scale;
} else {
if !chr.is_ascii() {
continue;
}
let ox: i32 = ((chr as u32 - 32) % 16) as i32;
let oy: i32 = ((chr as u32 - 32) / 16) as i32;
if scale > 1 {
for i in 0..8i32 {
for j in 0..8i32 {
if self
.get_textsheet()
.get_pixel((i + ox * 8) as u32, (j + oy * 8) as u32)
.r
> 0
{
for is in 0..=(scale as i32) {
for js in 0..=(scale as i32) {
self.draw(
(x + sx + (i * scale) + is, y + sy + (j * scale) + js),
col,
);
}
}
}
}
}
} else {
for i in 0..8i32 {
for j in 0..8i32 {
if self
.get_textsheet()
.get_pixel((i + ox * 8) as u32, (j + oy * 8) as u32)
.r
> 0
{
self.draw((x + sx + i, y + sy + j), col);
}
}
}
}
}
sx += 8 * scale;
}
}
/// Draw a line between two points,
/// You don't need to do anything with the points for it to work, it will swap them it needed.
fn draw_line<P: Into<Vi2d>>(&mut self, p1: P, p2: P, col: Color) {
/* OLD Implementation by me
* let (p1, p2) = if p1.x < p2.x { (p1, p2) } else { (p2, p1) };
if p1.x == p2.x {
let iter = if p1.y < p2.y {
p1.y..=(p2.y)
} else {
p2.y..=(p1.y)
};
for y in iter {
self.draw(p1.x, y, col);
}
} else {
let a = (p1.y as f32 - p2.y as f32) / (p1.x as f32 - p2.x as f32);
let b = p1.y as f32 - (a * p1.x as f32);
/*println!(
"START {:?} || END: {:?} || a = {:.2} = {:.2}/{:.2} || b = {:.2}",
p1,
p2,
a,
(p1.y as f32 - p2.y as f32),
(p1.x as f32 - p2.x as f32),
b
);*/
if -1.x <= a && a <= 1.x {
for x in p1.x..=(p2.x) {
let y = a * x as f32 + b;
self.draw(x, y.round() as u32, col);
}
} else if a > 1.x || a < -1.x {
let iter = if p1.y < p2.y {
p1.y..=p2.y
} else {
p2.y..=p1.y
};
for y in iter {
let x = ((y as f32 - b) / a).round() as u32;
self.draw(x, y, col);
}
}
}*/
let p1: Vi2d = p1.into();
let p2: Vi2d = p2.into();
if p1.x == p2.x {
// VERTICAL LINE
for y in if p2.y > p1.y {
p1.y..=p2.y
} else {
p2.y..=p1.y
} {
self.draw((p1.x, y), col);
}
} else if p1.y == p2.y {
// HORIZONTAL LINE
for x in if p2.x > p1.x {
p1.x..=p2.x
} else {
p2.x..=p1.x
} {
self.draw((x, p1.y), col);
}
} else {
let (mut x0, mut y0) = (p1.x as i32, p1.y as i32);
let (mut x1, mut y1) = (p2.x as i32, p2.y as i32);
if (y1 - y0).abs() < (x1 - x0).abs() {
if x0 > x1 {
std::mem::swap(&mut x0, &mut x1);
std::mem::swap(&mut y0, &mut y1);
}
let dx = x1 - x0;
let mut dy = y1 - y0;
let mut yi = 1;
if dy < 0 {
yi = -1;
dy = -dy;
}
let mut d = 2 * dy - dx;
let mut y = y0;
for x in x0..x1 {
if x >= 0 && y >= 0 {
self.draw((x, y), col);
}
if d > 0 {
y += yi;
d -= 2 * dx;
}
d += 2 * dy;
}
} else {
if y0 > y1 {
std::mem::swap(&mut x0, &mut x1);
std::mem::swap(&mut y0, &mut y1);
}
let mut dx = x1 - x0;
let dy = y1 - y0;
let mut xi = 1;
if dx < 0 {
xi = -1;
dx = -dx;
}
let mut d = 2 * dx - dy;
let mut x = x0;
for y in y0..=y1 {
if x >= 0 && y >= 0 {
self.draw((x, y), col);
}
if d > 0 {
x += xi;
d -= 2 * dy;
}
d += 2 * dx;
}
}
}
}
/// Draw a rectangle with the top left corner at `(x, y)`
/// and the bottom right corner at `(x + w, y + h)` (both inclusive)
fn draw_rect<P: Into<Vi2d>>(&mut self, pos: P, size: P, col: Color) {
let Vi2d { x, y } = pos.into();
let Vi2d { x: w, y: h } = size.into() - Vi2d { x: 1, y: 1 };
self.draw_line((x, y), (x + w, y), col);
self.draw_line((x + w, y), (x + w, y + h), col);
self.draw_line((x + w, y + h), (x, y + h), col);
self.draw_line((x, y + h), (x, y), col);
}
/// Fill a rectangle with the top left corner at `(x, y)`
/// and the bottom right corner at `(x + w, y + h)` (both inclusive)
fn fill_rect<P: Into<Vi2d>>(&mut self, pos: P, size: P, col: Color) {
let Vi2d { x, y } = pos.into();
let Vi2d { x: w, y: h } = size.into();
for nx in x..(x + w) {
self.draw_line((nx, y), (nx, y + h), col);
}
}
/// Draw a circle with center `(x, y)` and raduis `r`
fn draw_circle<P: Into<Vi2d>>(&mut self, pos: P, r: u32, col: Color) {
let Vi2d { x, y } = pos.into();
let r_i32: i32 = r.try_into().unwrap();
let x = x as i32;
let y = y as i32;
let mut x0: i32 = 0;
let mut y0: i32 = r_i32;
let mut d: i32 = 3i32 - 2i32 * r_i32;
if r == 0 {
return;
}
while y0 >= x0 {
self.draw(((x + x0), (y - y0)), col);
self.draw(((x + y0), (y - x0)), col);
self.draw(((x + y0), (y + x0)), col);
self.draw(((x + x0), (y + y0)), col);
self.draw(((x - x0), (y + y0)), col);
self.draw(((x - y0), (y + x0)), col);
self.draw(((x - y0), (y - x0)), col);
self.draw(((x - x0), (y - y0)), col);
x0 += 1;
if d < 0 {
d += 4 * x0 + 6;
} else {
y0 -= 1;
d += 4 * (x0 - y0) + 10;
}
}
}
/// Fill a circle with center `(x, y)` and raduis `r`
fn fill_circle<P: Into<Vi2d>>(&mut self, pos: P, r: u32, col: Color) {
let Vi2d { x, y } = pos.into();
let r_i32: i32 = r.try_into().unwrap();
let x = x as i32;
let y = y as i32;
let mut x0: i32 = 0;
let mut y0: i32 = r_i32;
let mut d: i32 = 3 - 2 * r_i32;
if r == 0 {
return;
}
while y0 >= x0 {
self.draw_line((x - x0, y - y0), (x + x0, y - y0), col);
self.draw_line((x - y0, y - x0), (x + y0, y - x0), col);
self.draw_line((x - x0, y + y0), (x + x0, y + y0), col);
self.draw_line((x - y0, y + x0), (x + y0, y + x0), col);
x0 += 1;
if d < 0 {
d += 4 * x0 + 6;
} else {
y0 -= 1;
d += 4 * (x0 - y0) + 10;
}
}
}
/// Draw the edges of a triangle between the three points
fn draw_triangle<P: Into<Vi2d>>(&mut self, pts1: P, pts2: P, pts3: P, col: Color) {
let pts1: Vi2d = pts1.into();
let pts2: Vi2d = pts2.into();
let pts3: Vi2d = pts3.into();
self.draw_line(pts1, pts2, col);
self.draw_line(pts1, pts3, col);
self.draw_line(pts2, pts3, col);
}
/// Fill the given triangle
fn fill_triangle<P: Into<Vi2d>>(&mut self, pts1: P, pts2: P, pts3: P, col: Color) {
#![allow(clippy::cast_precision_loss)]
use std::cmp::{max, min};
let pts1: Vi2d = pts1.into();
let pts2: Vi2d = pts2.into();
let pts3: Vi2d = pts3.into();
self.draw_triangle(pts1, pts2, pts3, col);
let pts1 = (pts1.x as i32, pts1.y as i32);
let pts2 = (pts2.x as i32, pts2.y as i32);
let pts3 = (pts3.x as i32, pts3.y as i32);
let centroid = (
((pts1.0 + pts2.0 + pts3.0) as f32 / 3f32),
((pts1.1 + pts2.1 + pts3.1) as f32 / 3f32),
);
let lines = (
(
pts1.1 - pts2.1,
pts2.0 - pts1.0,
(pts1.1 - pts2.1) * pts2.0 + (pts2.0 - pts1.0) * pts2.1,
),
(
pts3.1 - pts1.1,
pts1.0 - pts3.0,
(pts3.1 - pts1.1) * pts1.0 + (pts1.0 - pts3.0) * pts1.1,
),
(
pts2.1 - pts3.1,
pts3.0 - pts2.0,
(pts2.1 - pts3.1) * pts3.0 + (pts3.0 - pts2.0) * pts3.1,
),
);
//dbg!(&lines);
let iterx = {
let x1 = min(min(pts1.0, pts2.0), pts3.0);
let x2 = max(max(pts1.0, pts2.0), pts3.0);
if x1 > x2 {
x2..=x1
} else {
x1..=x2
}
};
let itery = {
let y1 = min(min(pts1.1, pts2.1), pts3.1);
let y2 = max(max(pts1.1, pts2.1), pts3.1);
if y1 > y2 {
y2..=y1
} else {
y1..=y2
}
};
let l_mul = (
if (lines.0).0 as f32 * centroid.0 + (lines.0).1 as f32 * centroid.1
- (lines.0).2 as f32
>= 0f32
{
1
} else {
-1
},
if (lines.1).0 as f32 * centroid.0 + (lines.1).1 as f32 * centroid.1
- (lines.1).2 as f32
>= 0f32
{
1
} else {
-1
},
if (lines.2).0 as f32 * centroid.0 + (lines.2).1 as f32 * centroid.1
- (lines.2).2 as f32
>= 0f32
{
1
} else {
-1
},
);
for x in iterx {
for y in itery.clone() {
if ((lines.0).0 * x + (lines.0).1 * y - (lines.0).2) * l_mul.0 >= 0
&& ((lines.1).0 * x + (lines.1).1 * y - (lines.1).2) * l_mul.1 >= 0
&& ((lines.2).0 * x + (lines.2).1 * y - (lines.2).2) * l_mul.2 >= 0
{
self.draw((x, y), col);
}
}
}
}
}
/// A trait that will handle the drawing of Sprite onto the Target
pub trait SpriteTrait: SmartDrawingTrait {
/// Draw a Sprite with the top left corner at `(x, y)`
/// the flip arguement will allow fliping of the axis
/// flip: (horizontal, vertical)
/// scale is the scale of the result (must be >= 1)
fn draw_sprite<P: Into<Vi2d>>(
&mut self,
pos: P,
scale: u32,
sprite: &Sprite,
flip: (bool, bool),
) {
#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let Vi2d { x, y } = pos.into();
let (mut fxs, mut fxm) = (0i32, 1i32);
let (mut fys, mut fym) = (0i32, 1i32);
let mut fx: i32;
let mut fy: i32;
if flip.0 {
fxs = sprite.width() as i32 - 1;
fxm = -1;
}
if flip.1 {
fys = sprite.height() as i32 - 1;
fym = -1;
}
if scale > 1 {
fx = fxs;
for i in 0..(sprite.width() as i32) {
fy = fys;
for j in 0..(sprite.height() as i32) {
for is in 0..(scale as i32) {
for js in 0..(scale as i32) {
self.draw(
(x + i * (scale as i32) + is, y + j * (scale as i32) + js),
sprite.get_pixel(fx as u32, fy as u32),
);
}
}
fy += fym;
}
fx += fxm;
}
} else {
fx = fxs;
for i in 0..(sprite.width() as i32) {
fy = fys;
for j in 0..(sprite.height() as i32) {
self.draw((x + i, y + j), sprite.get_pixel(fx as u32, fy as u32));
fy += fym;
}
fx += fxm;
}
}
}
/// Draw a chunk of the given [`Sprite`] onto the Target
/// `coords` is the top left corner of the Target
/// `o` is the Top left corner of the Sprite Chunk
/// and `size` is the `(width, height)` of the chunk
/// `flip` and `scale` is the same as [`SpriteTrait::draw_sprite()`]
fn draw_partial_sprite<P: Into<Vi2d>>(
&mut self,
coords: P,
sprite: &Sprite,
o: P,
size: P,
scale: u32,
flip: (bool, bool),
) {
#![allow(
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let Vi2d { x, y } = coords.into();
let Vi2d { x: ox, y: oy } = o.into();
let Vi2d { x: w, y: h } = size.into();
let (mut fxs, mut fxm) = (0i32, 1i32);
let (mut fys, mut fym) = (0i32, 1i32);
let mut fx: i32;
let mut fy: i32;
if flip.0 {
fxs = w as i32 - 1;
fxm = -1;
}
if flip.1 {
fys = h as i32 - 1;
fym = -1;
}
if scale > 1 {
fx = fxs;
for i in 0..w {
fy = fys;
for j in 0..h {
for is in 0..(scale as i32) {
for js in 0..(scale as i32) {
self.draw(
(x + i * (scale as i32) + is, y + j * (scale as i32) + js),
sprite.get_pixel((fx + ox) as u32, (fy + oy) as u32),
);
}
}
fy += fym;
fx += fxm;
}
}
} else {
fx = fxs;
for i in 0..w {
fy = fys;
for j in 0..h {
self.draw(
(x + i, y + j),
sprite.get_pixel(fx as u32 + ox as u32, fy as u32 + oy as u32),
);
fy += fym;
}
fx += fxm;
}
}
}
Trait Implementations§
source§impl DrawSpriteTrait for Sprite
impl DrawSpriteTrait for Sprite
source§unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color
unsafe fn get_pixel_unchecked(&self, pos: Vu2d) -> Color
Safety
its up to the caller to make sure that the given position is in bounds
source§unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color)
unsafe fn set_pixel_unchecked(&mut self, pos: Vu2d, col: Color)
Safety
its up to the caller to make sure that the given position is in bounds