Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update hecs to upstream 0.7 #533

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 7 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion feather/ecs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition = "2018"
[dependencies]
ahash = "0.7"
anyhow = "1"
hecs = { git = "https://github.com/feather-rs/feather-hecs" }
hecs = "0.7.0"
log = "0.4"
thiserror = "1"
utils = { path = "../utils", package = "feather-utils" }
Expand Down
18 changes: 13 additions & 5 deletions feather/ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use hecs::{Component, DynamicBundle, Fetch, Query, World};

#[doc(inline)]
pub use hecs::{
BuiltEntity, ComponentError, DynamicQuery, DynamicQueryTypes, Entity, EntityBuilder,
MissingComponent, NoSuchEntity, QueryBorrow, Ref, RefMut,
Archetype, BuiltEntity, ComponentError, Entity, EntityBuilder, MissingComponent, NoSuchEntity,
QueryBorrow, Ref, RefMut,
};

mod system;
Expand Down Expand Up @@ -151,9 +151,17 @@ impl Ecs {
self.world.query()
}

/// Performs a dynamic query. Used for plugins.
pub fn query_dynamic<'q>(&'q self, types: DynamicQueryTypes<'q>) -> DynamicQuery<'q> {
self.world.query_dynamic(types)
pub fn archetypes(&self) -> impl Iterator<Item = &Archetype> {
self.world.archetypes()
}

///
/// # Safety
///
/// `id` must correspond to a currently live [`Entity`].
/// A despawned or never-allocated `id` will produce undefined behavior.
pub unsafe fn find_entity_from_id(&self, id: u32) -> Entity {
self.world.find_entity_from_id(id)
}

/// Sets the index of the currently executing system,
Expand Down
4 changes: 2 additions & 2 deletions feather/plugin-host/src/host_calls/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn entity_get_component(
bytes_len_ptr: PluginPtrMut<u32>,
) -> anyhow::Result<()> {
let component = HostComponent::from_u32(component).context("invalid component")?;
let entity = Entity::from_bits(entity);
let entity = Entity::from_bits(entity).context("invalid entity")?;
let visitor = GetComponentVisitor { cx, entity };
let (bytes_ptr, bytes_len) = component.visit(visitor)?;

Expand Down Expand Up @@ -87,7 +87,7 @@ pub fn entity_set_component(
bytes_ptr: PluginPtr<u8>,
bytes_len: u32,
) -> anyhow::Result<()> {
let entity = Entity::from_bits(entity);
let entity = Entity::from_bits(entity).context("invalid entity")?;
let component = HostComponent::from_u32(component).context("invalid component")?;
let visitor = InsertComponentVisitor {
cx,
Expand Down
12 changes: 9 additions & 3 deletions feather/plugin-host/src/host_calls/entity.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::Context;
use feather_base::Text;
use feather_common::chat::{ChatKind, ChatMessage};
use feather_ecs::Entity;
Expand All @@ -7,7 +8,12 @@ use crate::context::{PluginContext, PluginPtr};

#[host_function]
pub fn entity_exists(cx: &PluginContext, entity: u64) -> anyhow::Result<u32> {
Ok(cx.game_mut().ecs.entity(Entity::from_bits(entity)).is_ok()).map(|b| b as u32)
Ok(cx
.game_mut()
.ecs
.entity(Entity::from_bits(entity).context("invalid entity")?)
.is_ok())
.map(|b| b as u32)
}

#[host_function]
Expand All @@ -18,7 +24,7 @@ pub fn entity_send_message(
message_len: u32,
) -> anyhow::Result<()> {
let message = cx.read_json(message_ptr, message_len)?;
let entity = Entity::from_bits(entity);
let entity = Entity::from_bits(entity).context("invalid entity")?;
let _ = cx
.game_mut()
.send_message(entity, ChatMessage::new(ChatKind::System, message));
Expand All @@ -33,7 +39,7 @@ pub fn entity_send_title(
title_len: u32,
) -> anyhow::Result<()> {
let title = cx.read_json(title_ptr, title_len)?;
let entity = Entity::from_bits(entity);
let entity = Entity::from_bits(entity).context("invalid entity")?;
cx.game_mut().send_title(entity, title);
Ok(())
}
2 changes: 1 addition & 1 deletion feather/plugin-host/src/host_calls/entity_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,5 @@ pub fn entity_builder_finish(cx: &PluginContext, builder: u32) -> anyhow::Result
.context("invalid entity builder")?;

let entity = cx.game_mut().spawn_entity(builder);
Ok(entity.to_bits())
Ok(entity.to_bits().get())
}
2 changes: 1 addition & 1 deletion feather/plugin-host/src/host_calls/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn entity_add_event(
bytes_ptr: PluginPtr<u8>,
bytes_len: u32,
) -> anyhow::Result<()> {
let entity = Entity::from_bits(entity);
let entity = Entity::from_bits(entity).context("invalid entity")?;
let event = HostComponent::from_u32(event).context("invalid component")?;
let visitor = InsertComponentVisitor {
cx,
Expand Down
3 changes: 2 additions & 1 deletion feather/plugin-host/src/host_calls/plugin_message.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::Context;
use feather_common::events::PluginMessageEvent;
use feather_ecs::Entity;
use feather_plugin_host_macros::host_function;
Expand All @@ -16,7 +17,7 @@ pub fn plugin_message_send(
let channel = cx.read_string(channel_ptr, channel_len)?;
let data = cx.read_bytes(data_ptr, data_len)?;

let entity = Entity::from_bits(entity);
let entity = Entity::from_bits(entity).context("invalid entity")?;
let event = PluginMessageEvent { channel, data };
cx.game_mut().ecs.insert_entity_event(entity, event)?;

Expand Down
48 changes: 36 additions & 12 deletions feather/plugin-host/src/host_calls/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::{alloc::Layout, any::TypeId, mem::size_of, ptr};

use anyhow::Context;
use feather_ecs::{DynamicQuery, DynamicQueryTypes, Ecs};
use feather_ecs::{Archetype, Ecs};
use feather_plugin_host_macros::host_function;
use quill_common::{
component::{ComponentVisitor, SerializationMethod},
Expand Down Expand Up @@ -44,14 +44,16 @@ struct WrittenComponentData {
/// `ComponentVisitor` implementation used to write
/// component data to plugin memory.
struct WriteComponentsVisitor<'a> {
query: &'a DynamicQuery<'a>,
ecs: &'a Ecs,
types: &'a [HostComponent],
cx: &'a PluginContext,
num_entities: usize,
}

impl<'a> ComponentVisitor<anyhow::Result<WrittenComponentData>> for WriteComponentsVisitor<'a> {
fn visit<T: Component>(self) -> anyhow::Result<WrittenComponentData> {
let components = self.query.iter_component_slices(TypeId::of::<T>());
let components = matching_archetypes(self.ecs, self.types)
.map(|archetype| archetype.get::<T>().unwrap());

// Write each component.
// We use a different strategy depending
Expand All @@ -66,7 +68,7 @@ impl<'a> ComponentVisitor<anyhow::Result<WrittenComponentData>> for WriteCompone
// Copy the components into the buffer.
let mut byte_index = 0;
for component_slice in components {
for component in component_slice.as_slice::<T>() {
for component in component_slice.iter() {
let bytes = component.as_bytes();

unsafe {
Expand All @@ -87,7 +89,7 @@ impl<'a> ComponentVisitor<anyhow::Result<WrittenComponentData>> for WriteCompone

// Write components into the buffer.
for component_slice in components {
for component in component_slice.as_slice::<T>() {
for component in component_slice.iter() {
component.to_bytes(&mut bytes);
}
}
Expand All @@ -104,15 +106,28 @@ impl<'a> ComponentVisitor<anyhow::Result<WrittenComponentData>> for WriteCompone
}
}

fn matching_archetypes<'a>(
ecs: &'a Ecs,
types: &'a [HostComponent],
) -> impl Iterator<Item = &'a Archetype> + 'a {
struct Has<'a>(&'a Archetype);
impl ComponentVisitor<bool> for Has<'_> {
fn visit<T: Component>(self) -> bool {
self.0.has::<T>()
}
}
ecs.archetypes()
.filter(move |archetype| types.iter().all(|t| t.visit(Has(archetype))))
}

fn create_query_data(
cx: &PluginContext,
ecs: &Ecs,
types: &[HostComponent],
) -> anyhow::Result<QueryData> {
let query_types: Vec<TypeId> = types.iter().copied().map(HostComponent::type_id).collect();
let query = ecs.query_dynamic(DynamicQueryTypes::new(&query_types, &[]));

let num_entities = query.iter_entities().count();
let num_entities = matching_archetypes(ecs, types)
.map(|archetype| archetype.ids().len())
.sum();
if num_entities == 0 {
return Ok(QueryData {
num_entities: 0,
Expand All @@ -126,7 +141,8 @@ fn create_query_data(
let component_lens = cx.bump_allocate(Layout::array::<u32>(types.len())?)?;
for (i, &typ) in types.iter().enumerate() {
let data = typ.visit(WriteComponentsVisitor {
query: &query,
ecs,
types,
cx,
num_entities,
})?;
Expand All @@ -138,8 +154,16 @@ fn create_query_data(
}

let entities_ptr = cx.bump_allocate(Layout::array::<EntityId>(num_entities)?)?;
for (i, entity) in query.iter_entities().enumerate() {
let bits = entity.to_bits();
for (i, entity) in matching_archetypes(ecs, types)
.flat_map(|archetype| {
archetype
.ids()
.iter()
.map(|id| unsafe { ecs.find_entity_from_id(*id) })
})
.enumerate()
{
let bits = entity.to_bits().get();
unsafe {
cx.write_pod(entities_ptr.cast().add(i), bits)?;
}
Expand Down