bevyengine / bevyengine/bevy

BSN: #[template(required)] attribute for for fields that aren't `FromTemplate`

Open
#24,739 3 comments 6 reactions 0 assignees View on GitHub
A-Scenes C-Feature D-Complex S-Needs-Design X-Contentious
Dominant language
Rust
Stars
48.2k
Forks
4.8k
Avg merge
3d 22h
Merged PRs (30d)
161

Description

## What problem does this solve or what need does it fill?

`#[derive(FromTemplate)]` currently requires all fields to implement `FromTemplate`. However, many user types do not have a meaningful `Default` and therefore `FromTemplate` implementation. To use the type in `bsn!` macros the user can do the following

1. wrap the `Component` with `template(move |_| Ok(MyComponent {}))`
2. implement a nonsense or sentinel `Default` value (e.g. `Entity::PLACEHOLDER`) that they need to override
3. hand write a companion `Template` / `FromTemplate` type (i.e. `MyComponentTemplate`)

None of these options are ideal, considering (1) is rather ugly, (2) can result in runtime logic errors, and (3) is boilerplate that could be handled by a macro (this proposal).

## What solution would you like?

An opt-in field attribute that re-uses the current `#[template(...)]` namespace.
```rs
#[derive(Component, Clone, FromTemplate)]
struct Weapon {
#[template(required)]
damage: DamageRange,
crit_chance: f32,
}
```

Which is then used like
```rs
bsn! {
Weapon {
damage: DamageRange {low: 10.0, high: 12.0 }
// crit_chance implements `FromTemplate`, so it is optional
}
}
```

This gives you the regular patching behaviour letting you leave off `Default` fields.

## What alternative(s) have you considered?

It's possible to hand write a companion type with `Option` wrapping non `FromTemplate` fields, and manually implement `Template`.

## Additional context
This is the largest issue I'm running into transitioning to `Scene` from `Bundle` for my UI work so far. The manual companion type implementations work fine but this would be more convenient, and may help for other things.

I think this should be a pretty small addition to add to the `bsn!` macro. Happy to work on it myself if this seems like something worth doing.

Contributor guide

Open the contributing guide

Research direction

Locate the bsn! macro and the FromTemplate derive implementation, then inspect how existing template field attributes are parsed and applied. Add coverage for a required field that lacks FromTemplate, and consider the change done when the shown Weapon example compiles and preserves regular patching behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
game-dev, tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.