forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.rs
More file actions
89 lines (77 loc) · 2.59 KB
/
Copy pathcomponent.rs
File metadata and controls
89 lines (77 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
use anyhow::Context;
use feather_ecs::Entity;
use feather_plugin_host_macros::host_function;
use quill_common::{component::ComponentVisitor, HostComponent};
use crate::context::{PluginContext, PluginPtr, PluginPtrMut};
struct GetComponentVisitor<'a> {
cx: &'a PluginContext,
entity: Entity,
}
impl<'a> ComponentVisitor<anyhow::Result<(PluginPtrMut<u8>, u32)>> for GetComponentVisitor<'a> {
fn visit<T: quill_common::Component>(self) -> anyhow::Result<(PluginPtrMut<u8>, u32)> {
let game = self.cx.game_mut();
let component = match game.ecs.get::<T>(self.entity) {
Ok(c) => c,
Err(_) => return Ok((unsafe { PluginPtrMut::null() }, 0)),
};
let bytes = component.to_cow_bytes();
let ptr = self.cx.bump_allocate_and_write_bytes(&bytes)?;
Ok((ptr, bytes.len() as u32))
}
}
#[host_function]
pub fn entity_get_component(
cx: &PluginContext,
entity: u64,
component: u32,
bytes_ptr_ptr: PluginPtrMut<PluginPtrMut<u8>>,
bytes_len_ptr: PluginPtrMut<u32>,
) -> anyhow::Result<()> {
let component = HostComponent::from_u32(component).context("invalid component")?;
let entity = Entity::from_bits(entity);
let visitor = GetComponentVisitor { cx, entity };
let (bytes_ptr, bytes_len) = component.visit(visitor)?;
cx.write_pod(bytes_ptr_ptr, bytes_ptr)?;
cx.write_pod(bytes_len_ptr, bytes_len)?;
Ok(())
}
struct SetComponentVisitor<'a> {
cx: &'a PluginContext,
entity: Entity,
bytes_ptr: PluginPtr<u8>,
bytes_len: u32,
}
impl<'a> ComponentVisitor<anyhow::Result<()>> for SetComponentVisitor<'a> {
fn visit<T: quill_common::Component>(self) -> anyhow::Result<()> {
let component = self
.cx
.read_component::<T>(self.bytes_ptr, self.bytes_len)?;
let mut game = self.cx.game_mut();
let existing_component = game.ecs.get_mut::<T>(self.entity);
if let Ok(mut existing_component) = existing_component {
*existing_component = component;
} else {
drop(existing_component);
let _ = game.ecs.insert(self.entity, component);
}
Ok(())
}
}
#[host_function]
pub fn entity_set_component(
cx: &PluginContext,
entity: u64,
component: u32,
bytes_ptr: PluginPtr<u8>,
bytes_len: u32,
) -> anyhow::Result<()> {
let entity = Entity::from_bits(entity);
let component = HostComponent::from_u32(component).context("invalid component")?;
let visitor = SetComponentVisitor {
cx,
entity,
bytes_ptr,
bytes_len,
};
component.visit(visitor)
}