khora_data/ecs/components/audio/source.rs
1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Defines the `AudioSource` component for emitting sound.
16
17use crate::assets::SoundData;
18use bincode::{Decode, Encode};
19use khora_core::asset::AssetHandle;
20use khora_macros::Component;
21use serde::{Deserialize, Serialize};
22
23/// The internal playback state of an active sound.
24/// This will be managed by the `AudioMixingLane`.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode)]
26pub struct PlaybackState {
27 /// The current position in the sample data, in samples.
28 pub cursor: f32,
29}
30
31/// An ECS component that makes an entity an emitter of sound.
32#[derive(Debug, Clone, Component)]
33#[component(domain = Audio)]
34pub struct AudioSource {
35 /// A handle to the sound data to be played.
36 #[component(skip)]
37 pub handle: AssetHandle<SoundData>,
38 /// The volume of the sound, where 1.0 is normal volume.
39 pub volume: f32,
40 /// Whether the sound should loop back to the beginning when it finishes.
41 pub looping: bool,
42 /// Whether the sound should start playing automatically when this component is added.
43 pub autoplay: bool,
44 /// The internal playback state. This should be treated as read-only
45 /// by most systems outside of the audio engine itself.
46 #[component(skip)]
47 pub state: Option<PlaybackState>,
48}
49
50impl Default for AudioSource {
51 fn default() -> Self {
52 Self {
53 handle: AssetHandle::dangling(),
54 volume: 1.0,
55 looping: false,
56 autoplay: false,
57 state: None,
58 }
59 }
60}
61
62impl AudioSource {
63 /// Creates a new `AudioSource`.
64 pub fn new(handle: AssetHandle<SoundData>) -> Self {
65 Self {
66 handle,
67 volume: 1.0,
68 looping: false,
69 autoplay: true,
70 state: None,
71 }
72 }
73}