2024-03-04 00:01:05 +00:00
|
|
|
//! This example illustrates how to transfer log events from the [`Layer`] to Bevy's ECS.
|
|
|
|
//!
|
|
|
|
//! The way we will do this is via a [`mpsc`] channel. [`mpsc`] channels allow 2 unrelated
|
|
|
|
//! parts of the program to communicate (in this case, [`Layer`]s and Bevy's ECS).
|
|
|
|
//!
|
2024-05-12 21:16:56 +00:00
|
|
|
//! Inside the `custom_layer` function we will create a [`mpsc::Sender`] and a [`mpsc::Receiver`] from a
|
2024-04-14 15:23:44 +00:00
|
|
|
//! [`mpsc::channel`]. The [`Sender`](mpsc::Sender) will go into the `AdvancedLayer` and the [`Receiver`](mpsc::Receiver) will
|
|
|
|
//! go into a non-send resource called `LogEvents` (It has to be non-send because [`Receiver`](mpsc::Receiver) is [`!Sync`](Sync)).
|
|
|
|
//! From there we will use `transfer_log_events` to transfer log events from `LogEvents` to an ECS event called `LogEvent`.
|
2024-03-04 00:01:05 +00:00
|
|
|
//!
|
2024-04-14 15:23:44 +00:00
|
|
|
//! Finally, after all that we can access the `LogEvent` event from our systems and use it.
|
2024-03-04 00:01:05 +00:00
|
|
|
//! In this example we build a simple log viewer.
|
|
|
|
|
|
|
|
use std::sync::mpsc;
|
|
|
|
|
|
|
|
use bevy::{
|
2024-09-24 11:42:59 +00:00
|
|
|
log::{
|
|
|
|
tracing_subscriber::{self, Layer},
|
2024-10-16 16:42:35 +00:00
|
|
|
BoxedLayer, Level,
|
2024-09-24 11:42:59 +00:00
|
|
|
},
|
2024-03-04 00:01:05 +00:00
|
|
|
prelude::*,
|
2024-10-16 16:42:35 +00:00
|
|
|
utils::tracing::{self, Subscriber},
|
2024-03-04 00:01:05 +00:00
|
|
|
};
|
|
|
|
|
2024-10-16 16:42:35 +00:00
|
|
|
fn main() {
|
|
|
|
App::new()
|
|
|
|
.add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
|
|
|
|
// Show logs all the way up to the trace level, but only for logs
|
|
|
|
// produced by this example.
|
|
|
|
level: Level::TRACE,
|
|
|
|
filter: "warn,log_layers_ecs=trace".to_string(),
|
|
|
|
custom_layer,
|
|
|
|
}))
|
|
|
|
.add_systems(Startup, (log_system, setup))
|
|
|
|
.add_systems(Update, print_logs)
|
|
|
|
.run();
|
|
|
|
}
|
|
|
|
|
2024-03-04 00:01:05 +00:00
|
|
|
/// A basic message. This is what we will be sending from the [`CaptureLayer`] to [`CapturedLogEvents`] non-send resource.
|
|
|
|
#[derive(Debug, Event)]
|
|
|
|
struct LogEvent {
|
|
|
|
message: String,
|
2024-10-16 16:42:35 +00:00
|
|
|
level: Level,
|
2024-03-04 00:01:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This non-send resource temporarily stores [`LogEvent`]s before they are
|
|
|
|
/// written to [`Events<LogEvent>`] by [`transfer_log_events`].
|
|
|
|
#[derive(Deref, DerefMut)]
|
|
|
|
struct CapturedLogEvents(mpsc::Receiver<LogEvent>);
|
|
|
|
|
2024-04-14 15:23:44 +00:00
|
|
|
/// Transfers information from the `LogEvents` resource to [`Events<LogEvent>`](LogEvent).
|
2024-03-04 00:01:05 +00:00
|
|
|
fn transfer_log_events(
|
2024-03-04 07:48:09 +00:00
|
|
|
receiver: NonSend<CapturedLogEvents>,
|
2024-03-04 00:01:05 +00:00
|
|
|
mut log_events: EventWriter<LogEvent>,
|
|
|
|
) {
|
|
|
|
// Make sure to use `try_iter()` and not `iter()` to prevent blocking.
|
2024-03-04 07:48:09 +00:00
|
|
|
log_events.send_batch(receiver.try_iter());
|
2024-03-04 00:01:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This is the [`Layer`] that we will use to capture log events and then send them to Bevy's
|
|
|
|
/// ECS via it's [`mpsc::Sender`].
|
|
|
|
struct CaptureLayer {
|
|
|
|
sender: mpsc::Sender<LogEvent>,
|
|
|
|
}
|
|
|
|
impl<S: Subscriber> Layer<S> for CaptureLayer {
|
|
|
|
fn on_event(
|
|
|
|
&self,
|
|
|
|
event: &tracing::Event<'_>,
|
|
|
|
_ctx: tracing_subscriber::layer::Context<'_, S>,
|
|
|
|
) {
|
|
|
|
// In order to obtain the log message, we have to create a struct that implements
|
|
|
|
// Visit and holds a reference to our string. Then we use the `record` method and
|
|
|
|
// the struct to modify the reference to hold the message string.
|
|
|
|
let mut message = None;
|
|
|
|
event.record(&mut CaptureLayerVisitor(&mut message));
|
|
|
|
if let Some(message) = message {
|
2024-10-16 16:42:35 +00:00
|
|
|
let metadata = event.metadata();
|
|
|
|
|
2024-03-04 00:01:05 +00:00
|
|
|
self.sender
|
2024-10-16 16:42:35 +00:00
|
|
|
.send(LogEvent {
|
|
|
|
message,
|
|
|
|
level: *metadata.level(),
|
|
|
|
})
|
2024-03-04 00:01:05 +00:00
|
|
|
.expect("LogEvents resource no longer exists!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-04 07:48:09 +00:00
|
|
|
/// A [`Visit`](tracing::field::Visit)or that records log messages that are transferred to [`CaptureLayer`].
|
2024-03-04 00:01:05 +00:00
|
|
|
struct CaptureLayerVisitor<'a>(&'a mut Option<String>);
|
|
|
|
impl tracing::field::Visit for CaptureLayerVisitor<'_> {
|
|
|
|
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
|
|
|
|
// This if statement filters out unneeded events sometimes show up
|
|
|
|
if field.name() == "message" {
|
|
|
|
*self.0 = Some(format!("{value:?}"));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-05-12 21:16:56 +00:00
|
|
|
fn custom_layer(app: &mut App) -> Option<BoxedLayer> {
|
2024-03-04 07:48:09 +00:00
|
|
|
let (sender, receiver) = mpsc::channel();
|
2024-03-04 00:01:05 +00:00
|
|
|
|
|
|
|
let layer = CaptureLayer { sender };
|
2024-03-04 07:48:09 +00:00
|
|
|
let resource = CapturedLogEvents(receiver);
|
2024-03-04 00:01:05 +00:00
|
|
|
|
|
|
|
app.insert_non_send_resource(resource);
|
|
|
|
app.add_event::<LogEvent>();
|
|
|
|
app.add_systems(Update, transfer_log_events);
|
|
|
|
|
2024-05-12 21:16:56 +00:00
|
|
|
Some(layer.boxed())
|
2024-03-04 00:01:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn log_system() {
|
2024-10-16 16:42:35 +00:00
|
|
|
// Here is how you write new logs at each "log level" (in "most important" to
|
2024-03-04 00:01:05 +00:00
|
|
|
// "least important" order)
|
2024-10-16 16:42:35 +00:00
|
|
|
error!("Something failed");
|
|
|
|
warn!("Something bad happened that isn't a failure, but thats worth calling out");
|
|
|
|
info!("Helpful information that is worth printing by default");
|
|
|
|
debug!("Helpful for debugging");
|
|
|
|
trace!("Very noisy");
|
2024-03-04 00:01:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Component)]
|
|
|
|
struct LogViewerRoot;
|
|
|
|
|
|
|
|
fn setup(mut commands: Commands) {
|
2024-10-05 01:59:52 +00:00
|
|
|
commands.spawn(Camera2d);
|
2024-03-04 00:01:05 +00:00
|
|
|
|
|
|
|
commands.spawn((
|
Merge Style properties into Node. Use ComputedNode for computed properties. (#15975)
# Objective
Continue improving the user experience of our UI Node API in the
direction specified by [Bevy's Next Generation Scene / UI
System](https://github.com/bevyengine/bevy/discussions/14437)
## Solution
As specified in the document above, merge `Style` fields into `Node`,
and move "computed Node fields" into `ComputedNode` (I chose this name
over something like `ComputedNodeLayout` because it currently contains
more than just layout info. If we want to break this up / rename these
concepts, lets do that in a separate PR). `Style` has been removed.
This accomplishes a number of goals:
## Ergonomics wins
Specifying both `Node` and `Style` is now no longer required for
non-default styles
Before:
```rust
commands.spawn((
Node::default(),
Style {
width: Val::Px(100.),
..default()
},
));
```
After:
```rust
commands.spawn(Node {
width: Val::Px(100.),
..default()
});
```
## Conceptual clarity
`Style` was never a comprehensive "style sheet". It only defined "core"
style properties that all `Nodes` shared. Any "styled property" that
couldn't fit that mold had to be in a separate component. A "real" style
system would style properties _across_ components (`Node`, `Button`,
etc). We have plans to build a true style system (see the doc linked
above).
By moving the `Style` fields to `Node`, we fully embrace `Node` as the
driving concept and remove the "style system" confusion.
## Next Steps
* Consider identifying and splitting out "style properties that aren't
core to Node". This should not happen for Bevy 0.15.
---
## Migration Guide
Move any fields set on `Style` into `Node` and replace all `Style`
component usage with `Node`.
Before:
```rust
commands.spawn((
Node::default(),
Style {
width: Val::Px(100.),
..default()
},
));
```
After:
```rust
commands.spawn(Node {
width: Val::Px(100.),
..default()
});
```
For any usage of the "computed node properties" that used to live on
`Node`, use `ComputedNode` instead:
Before:
```rust
fn system(nodes: Query<&Node>) {
for node in &nodes {
let computed_size = node.size();
}
}
```
After:
```rust
fn system(computed_nodes: Query<&ComputedNode>) {
for computed_node in &computed_nodes {
let computed_size = computed_node.size();
}
}
```
2024-10-18 22:25:33 +00:00
|
|
|
Node {
|
Migrate UI bundles to required components (#15898)
# Objective
- Migrate UI bundles to required components, fixes #15889
## Solution
- deprecate `NodeBundle` in favor of `Node`
- deprecate `ImageBundle` in favor of `UiImage`
- deprecate `ButtonBundle` in favor of `Button`
## Testing
CI.
## Migration Guide
- Replace all uses of `NodeBundle` with `Node`. e.g.
```diff
commands
- .spawn(NodeBundle {
- style: Style {
+ .spawn((
+ Node::default(),
+ Style {
width: Val::Percent(100.),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
- ..default()
- })
+ ))
```
- Replace all uses of `ButtonBundle` with `Button`. e.g.
```diff
.spawn((
- ButtonBundle {
- style: Style {
- width: Val::Px(w),
- height: Val::Px(h),
- // horizontally center child text
- justify_content: JustifyContent::Center,
- // vertically center child text
- align_items: AlignItems::Center,
- margin: UiRect::all(Val::Px(20.0)),
- ..default()
- },
- image: image.clone().into(),
+ Button,
+ Style {
+ width: Val::Px(w),
+ height: Val::Px(h),
+ // horizontally center child text
+ justify_content: JustifyContent::Center,
+ // vertically center child text
+ align_items: AlignItems::Center,
+ margin: UiRect::all(Val::Px(20.0)),
..default()
},
+ UiImage::from(image.clone()),
ImageScaleMode::Sliced(slicer.clone()),
))
```
- Replace all uses of `ImageBundle` with `UiImage`. e.g.
```diff
- commands.spawn(ImageBundle {
- image: UiImage {
+ commands.spawn((
+ UiImage {
texture: metering_mask,
..default()
},
- style: Style {
+ Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
..default()
},
- ..default()
- });
+ ));
```
---------
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-10-17 21:11:02 +00:00
|
|
|
width: Val::Vw(100.0),
|
|
|
|
height: Val::Vh(100.0),
|
|
|
|
flex_direction: FlexDirection::Column,
|
|
|
|
padding: UiRect::all(Val::Px(12.)),
|
2024-03-04 00:01:05 +00:00
|
|
|
..default()
|
|
|
|
},
|
|
|
|
LogViewerRoot,
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
// This is how we can read our LogEvents.
|
|
|
|
// In this example we are reading the LogEvents and inserting them as text into our log viewer.
|
|
|
|
fn print_logs(
|
|
|
|
mut events: EventReader<LogEvent>,
|
|
|
|
mut commands: Commands,
|
2024-10-13 20:32:06 +00:00
|
|
|
log_viewer_root: Single<Entity, With<LogViewerRoot>>,
|
2024-03-04 00:01:05 +00:00
|
|
|
) {
|
2024-10-13 20:32:06 +00:00
|
|
|
let root_entity = *log_viewer_root;
|
2024-03-04 00:01:05 +00:00
|
|
|
|
|
|
|
commands.entity(root_entity).with_children(|child| {
|
|
|
|
for event in events.read() {
|
2024-10-16 16:42:35 +00:00
|
|
|
child.spawn(Text::default()).with_children(|child| {
|
|
|
|
child.spawn((
|
|
|
|
TextSpan::new(format!("{:5} ", event.level)),
|
|
|
|
TextColor(level_color(&event.level)),
|
|
|
|
));
|
|
|
|
child.spawn(TextSpan::new(&event.message));
|
|
|
|
});
|
2024-03-04 00:01:05 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2024-10-16 16:42:35 +00:00
|
|
|
|
|
|
|
fn level_color(level: &Level) -> Color {
|
|
|
|
use bevy::color::palettes::tailwind::*;
|
|
|
|
Color::from(match *level {
|
|
|
|
Level::WARN => ORANGE_400,
|
|
|
|
Level::ERROR => RED_400,
|
|
|
|
Level::INFO => GREEN_400,
|
|
|
|
Level::TRACE => PURPLE_400,
|
|
|
|
Level::DEBUG => BLUE_400,
|
|
|
|
})
|
|
|
|
}
|