wasm4fun-graphics 0.1.0

Graphics primitives and subsystems for WASM-4 fantasy console
Documentation
// Copyright Claudio Mattera 2022.
//
// Distributed under the MIT License or the Apache 2.0 License at your option.
// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
// online at
// https://opensource.org/licenses/MIT
// https://opensource.org/licenses/Apache-2.0

use wasm4fun_core::{text, SCREEN_SIZE};

use crate::assets::FONT4_SPRITE;

/// Draw text using the current colours
pub fn draw_text<T>(s: T, x: i32, y: i32)
where
    T: AsRef<str>,
{
    text(s, x, y)
}

/// Draw centered text using the current colours
pub fn draw_centered_text<T>(s: T, y: i32)
where
    T: AsRef<str>,
{
    let s = s.as_ref();
    let x = ((SCREEN_SIZE - s.len() as u32 * 8) / 2) as i32;
    text(s, x, y)
}

/// Draw text with 4×4 font using the current colours
pub fn draw_4x4_text(s: impl AsRef<str>, x: i32, y: i32) {
    let s = s.as_ref();

    const FONT_WIDTH: u32 = 4;
    const FONT_HEIGHT: u32 = 4;

    for (i, c) in s.chars().enumerate() {
        if c.is_ascii() {
            let u = c as u32;
            let index = u - 32;
            let row = index / 32;
            let column = index % 32;

            let x = x + (FONT_WIDTH as i32) * (i as i32);
            let src_x = (FONT_WIDTH as u32) * column;
            let src_y = (FONT_WIDTH as u32) * row;
            FONT4_SPRITE
                .clip(src_x, src_y, FONT_WIDTH, FONT_HEIGHT)
                .blit(x, y);
        }
    }
}

/// Draw centered text with 4×4 font using the current colours
pub fn draw_centered_4x4_text<T>(s: T, y: i32)
where
    T: AsRef<str>,
{
    let s = s.as_ref();
    let x = ((SCREEN_SIZE - s.len() as u32 * 8) / 2) as i32;
    draw_4x4_text(s, x, y)
}