pikopiko-runtime 0.1.0

no_std, heap-free runtime for pikopiko: synth trait, event-binary sequencer, effects and built-in synths (AY-3-8912, buzzer, sfx).
Documentation
//! 効果音のトラックを借りるチャンネルの割り当て([`SfxChannels`])と、割り込みを始められなかったときの理由([`SfxError`])。

use super::*;

/// 効果音のトラックを、BGM のどのチャンネルに割り当てるか。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SfxChannels {
    map: [u8; MAX_SFX_TRACKS],
}

impl SfxChannels {
    /// 割り当てない印。
    const NONE: u8 = u8::MAX;

    /// 後ろのチャンネルから順に割り当てる(3 チャンネルで 1 トラックの効果音なら 2 番 = C)。
    /// 効果音のトラック 0 が最後のチャンネル、トラック 1 がその前、…。
    pub const AUTO: SfxChannels = SfxChannels {
        map: [Self::NONE; MAX_SFX_TRACKS],
    };

    /// 効果音のトラック i をチャンネル `channels[i]` に割り当てる。
    /// 4 つより多い分は捨てる。
    pub fn new(channels: &[u8]) -> Self {
        let mut map = [Self::NONE; MAX_SFX_TRACKS];
        for (m, c) in map.iter_mut().zip(channels) {
            *m = *c;
        }
        SfxChannels { map }
    }

    /// 自動([`SfxChannels::AUTO`])か。
    pub fn is_auto(&self) -> bool {
        self.map[0] == Self::NONE
    }

    /// `tracks` 本のトラックを、`channels` 本の音源に割り当てた結果。
    /// 足りない・範囲外・重複なら `None`。
    pub fn resolve(&self, tracks: usize, channels: usize) -> Option<[u8; MAX_SFX_TRACKS]> {
        if tracks == 0 || tracks > MAX_SFX_TRACKS || tracks > channels {
            return None;
        }
        let mut out = [Self::NONE; MAX_SFX_TRACKS];
        for (t, o) in out.iter_mut().enumerate().take(tracks) {
            let ch = if self.is_auto() {
                (channels - 1 - t) as u8
            } else {
                self.map[t]
            };
            if ch == Self::NONE || ch as usize >= channels {
                return None;
            }
            *o = ch;
        }
        for i in 0..tracks {
            for j in i + 1..tracks {
                if out[i] == out[j] {
                    return None;
                }
            }
        }
        Some(out)
    }
}

impl Default for SfxChannels {
    fn default() -> Self {
        SfxChannels::AUTO
    }
}

/// 効果音を鳴らし始められなかった理由。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SfxError {
    /// 枠の番号が範囲外([`MAX_SFX`] 以上)。
    BadSlot,
    /// チャンネルの割り当てが正しくない(範囲外・重複・トラックが多すぎる)。
    BadChannels,
    /// 借りたいチャンネルを、優先度の高い効果音が使っている。
    Busy,
}

impl crate::text::Localized for SfxError {
    fn text_key(&self) -> &'static str {
        match self {
            SfxError::BadSlot => "err-sfx-bad-slot",
            SfxError::BadChannels => "err-sfx-bad-channels",
            SfxError::Busy => "err-sfx-busy",
        }
    }

    fn catalogs(&self) -> &'static [crate::text::Catalog] {
        crate::text::table::CATALOGS
    }
}

impl core::fmt::Display for SfxError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
    }
}