bevy_ecs/world/
filtered_resource.rs

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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use std::sync::OnceLock;

use crate::{
    change_detection::{Mut, MutUntyped, Ref, Ticks, TicksMut},
    component::{ComponentId, Tick},
    query::Access,
    system::Resource,
    world::{unsafe_world_cell::UnsafeWorldCell, World},
};
use bevy_ptr::Ptr;
#[cfg(feature = "track_change_detection")]
use bevy_ptr::UnsafeCellDeref;

/// Provides read-only access to a set of [`Resource`]s defined by the contained [`Access`].
///
/// Use [`FilteredResourcesMut`] if you need mutable access to some resources.
///
/// To be useful as a [`SystemParam`](crate::system::SystemParam),
/// this must be configured using a [`FilteredResourcesParamBuilder`](crate::system::FilteredResourcesParamBuilder)
/// to build the system using a [`SystemParamBuilder`](crate::prelude::SystemParamBuilder).
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # #[derive(Default, Resource)]
/// # struct C;
/// #
/// # let mut world = World::new();
/// // Use `FilteredResourcesParamBuilder` to declare access to resources.
/// let system = (FilteredResourcesParamBuilder::new(|builder| {
///     builder.add_read::<B>().add_read::<C>();
/// }),)
///     .build_state(&mut world)
///     .build_system(resource_system);
///
/// world.init_resource::<A>();
/// world.init_resource::<C>();
///
/// fn resource_system(res: FilteredResources) {
///     // The resource exists, but we have no access, so we can't read it.
///     assert!(res.get::<A>().is_none());
///     // The resource doesn't exist, so we can't read it.
///     assert!(res.get::<B>().is_none());
///     // The resource exists and we have access, so we can read it.
///     let c = res.get::<C>().unwrap();
///     // The type parameter can be left out if it can be determined from use.
///     let c: Ref<C> = res.get().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// This can be used alongside ordinary [`Res`](crate::system::Res) and [`ResMut`](crate::system::ResMut) parameters if they do not conflict.
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// # world.init_resource::<B>();
/// #
/// let system = (
///     FilteredResourcesParamBuilder::new(|builder| {
///         builder.add_read::<A>();
///     }),
///     ParamBuilder,
///     ParamBuilder,
/// )
///     .build_state(&mut world)
///     .build_system(resource_system);
///
/// // Read access to A does not conflict with read access to A or write access to B.
/// fn resource_system(filtered: FilteredResources, res_a: Res<A>, res_mut_b: ResMut<B>) {
///     let res_a_2: Ref<A> = filtered.get::<A>().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// But it will conflict if it tries to read the same resource that another parameter writes.
///
/// ```should_panic
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// #
/// let system = (
///     FilteredResourcesParamBuilder::new(|builder| {
///         builder.add_read::<A>();
///     }),
///     ParamBuilder,
/// )
///     .build_state(&mut world)
///     .build_system(invalid_resource_system);
///
/// // Read access to A conflicts with write access to A.
/// fn invalid_resource_system(filtered: FilteredResources, res_mut_a: ResMut<A>) { }
/// #
/// # world.run_system_once(system);
/// ```
#[derive(Clone, Copy)]
pub struct FilteredResources<'w, 's> {
    world: UnsafeWorldCell<'w>,
    access: &'s Access<ComponentId>,
    last_run: Tick,
    this_run: Tick,
}

impl<'w, 's> FilteredResources<'w, 's> {
    /// Creates a new [`FilteredResources`].
    /// # Safety
    /// It is the callers responsibility to ensure that nothing else may access the any resources in the `world` in a way that conflicts with `access`.
    pub(crate) unsafe fn new(
        world: UnsafeWorldCell<'w>,
        access: &'s Access<ComponentId>,
        last_run: Tick,
        this_run: Tick,
    ) -> Self {
        Self {
            world,
            access,
            last_run,
            this_run,
        }
    }

    /// Returns a reference to the underlying [`Access`].
    pub fn access(&self) -> &Access<ComponentId> {
        self.access
    }

    /// Returns `true` if the `FilteredResources` has access to the given resource.
    /// Note that [`Self::get()`] may still return `None` if the resource does not exist.
    pub fn has_read<R: Resource>(&self) -> bool {
        let component_id = self.world.components().resource_id::<R>();
        component_id.is_some_and(|component_id| self.access.has_resource_read(component_id))
    }

    /// Gets a reference to the resource of the given type if it exists and the `FilteredResources` has access to it.
    pub fn get<R: Resource>(&self) -> Option<Ref<'w, R>> {
        let component_id = self.world.components().resource_id::<R>()?;
        if !self.access.has_resource_read(component_id) {
            return None;
        }
        // SAFETY: We have read access to this resource
        unsafe { self.world.get_resource_with_ticks(component_id) }.map(
            |(value, ticks, _caller)| Ref {
                // SAFETY: `component_id` was obtained from the type ID of `R`.
                value: unsafe { value.deref() },
                // SAFETY: We have read access to the resource, so no mutable reference can exist.
                ticks: unsafe { Ticks::from_tick_cells(ticks, self.last_run, self.this_run) },
                #[cfg(feature = "track_change_detection")]
                // SAFETY: We have read access to the resource, so no mutable reference can exist.
                changed_by: unsafe { _caller.deref() },
            },
        )
    }

    /// Gets a pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
        if !self.access.has_resource_read(component_id) {
            return None;
        }
        // SAFETY: We have read access to this resource
        unsafe { self.world.get_resource_by_id(component_id) }
    }
}

impl<'w, 's> From<FilteredResourcesMut<'w, 's>> for FilteredResources<'w, 's> {
    fn from(resources: FilteredResourcesMut<'w, 's>) -> Self {
        // SAFETY:
        // - `FilteredResourcesMut` guarantees exclusive access to all resources in the new `FilteredResources`.
        unsafe {
            FilteredResources::new(
                resources.world,
                resources.access,
                resources.last_run,
                resources.this_run,
            )
        }
    }
}

impl<'w, 's> From<&'w FilteredResourcesMut<'_, 's>> for FilteredResources<'w, 's> {
    fn from(resources: &'w FilteredResourcesMut<'_, 's>) -> Self {
        // SAFETY:
        // - `FilteredResourcesMut` guarantees exclusive access to all components in the new `FilteredResources`.
        unsafe {
            FilteredResources::new(
                resources.world,
                resources.access,
                resources.last_run,
                resources.this_run,
            )
        }
    }
}

impl<'w> From<&'w World> for FilteredResources<'w, 'static> {
    fn from(value: &'w World) -> Self {
        static READ_ALL_RESOURCES: OnceLock<Access<ComponentId>> = OnceLock::new();
        let access = READ_ALL_RESOURCES.get_or_init(|| {
            let mut access = Access::new();
            access.read_all_resources();
            access
        });

        let last_run = value.last_change_tick();
        let this_run = value.read_change_tick();
        // SAFETY: We have a reference to the entire world, so nothing else can alias with read access to all resources.
        unsafe {
            Self::new(
                value.as_unsafe_world_cell_readonly(),
                access,
                last_run,
                this_run,
            )
        }
    }
}

impl<'w> From<&'w mut World> for FilteredResources<'w, 'static> {
    fn from(value: &'w mut World) -> Self {
        Self::from(&*value)
    }
}

/// Provides mutable access to a set of [`Resource`]s defined by the contained [`Access`].
///
/// Use [`FilteredResources`] if you only need read-only access to resources.
///
/// To be useful as a [`SystemParam`](crate::system::SystemParam),
/// this must be configured using a [`FilteredResourcesMutParamBuilder`](crate::system::FilteredResourcesMutParamBuilder)
/// to build the system using a [`SystemParamBuilder`](crate::prelude::SystemParamBuilder).
///
/// # Examples
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # #[derive(Default, Resource)]
/// # struct C;
/// #
/// # #[derive(Default, Resource)]
/// # struct D;
/// #
/// # let mut world = World::new();
/// // Use `FilteredResourcesMutParamBuilder` to declare access to resources.
/// let system = (FilteredResourcesMutParamBuilder::new(|builder| {
///     builder.add_write::<B>().add_read::<C>().add_write::<D>();
/// }),)
///     .build_state(&mut world)
///     .build_system(resource_system);
///
/// world.init_resource::<A>();
/// world.init_resource::<C>();
/// world.init_resource::<D>();
///
/// fn resource_system(mut res: FilteredResourcesMut) {
///     // The resource exists, but we have no access, so we can't read it or write it.
///     assert!(res.get::<A>().is_none());
///     assert!(res.get_mut::<A>().is_none());
///     // The resource doesn't exist, so we can't read it or write it.
///     assert!(res.get::<B>().is_none());
///     assert!(res.get_mut::<B>().is_none());
///     // The resource exists and we have read access, so we can read it but not write it.
///     let c = res.get::<C>().unwrap();
///     assert!(res.get_mut::<C>().is_none());
///     // The resource exists and we have write access, so we can read it or write it.
///     let d = res.get::<D>().unwrap();
///     let d = res.get_mut::<D>().unwrap();
///     // The type parameter can be left out if it can be determined from use.
///     let c: Ref<C> = res.get().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// This can be used alongside ordinary [`Res`](crate::system::ResMut) and [`ResMut`](crate::system::ResMut) parameters if they do not conflict.
///
/// ```
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # #[derive(Default, Resource)]
/// # struct B;
/// #
/// # #[derive(Default, Resource)]
/// # struct C;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// # world.init_resource::<B>();
/// # world.init_resource::<C>();
/// #
/// let system = (
///     FilteredResourcesMutParamBuilder::new(|builder| {
///         builder.add_read::<A>().add_write::<B>();
///     }),
///     ParamBuilder,
///     ParamBuilder,
/// )
///     .build_state(&mut world)
///     .build_system(resource_system);
///
/// // Read access to A does not conflict with read access to A or write access to C.
/// // Write access to B does not conflict with access to A or C.
/// fn resource_system(mut filtered: FilteredResourcesMut, res_a: Res<A>, res_mut_c: ResMut<C>) {
///     let res_a_2: Ref<A> = filtered.get::<A>().unwrap();
///     let res_mut_b: Mut<B> = filtered.get_mut::<B>().unwrap();
/// }
/// #
/// # world.run_system_once(system);
/// ```
///
/// But it will conflict if it tries to read the same resource that another parameter writes,
/// or write the same resource that another parameter reads.
///
/// ```should_panic
/// # use bevy_ecs::{prelude::*, system::*};
/// #
/// # #[derive(Default, Resource)]
/// # struct A;
/// #
/// # let mut world = World::new();
/// # world.init_resource::<A>();
/// #
/// let system = (
///     FilteredResourcesMutParamBuilder::new(|builder| {
///         builder.add_write::<A>();
///     }),
///     ParamBuilder,
/// )
///     .build_state(&mut world)
///     .build_system(invalid_resource_system);
///
/// // Read access to A conflicts with write access to A.
/// fn invalid_resource_system(filtered: FilteredResourcesMut, res_a: Res<A>) { }
/// #
/// # world.run_system_once(system);
/// ```
pub struct FilteredResourcesMut<'w, 's> {
    world: UnsafeWorldCell<'w>,
    access: &'s Access<ComponentId>,
    last_run: Tick,
    this_run: Tick,
}

impl<'w, 's> FilteredResourcesMut<'w, 's> {
    /// Creates a new [`FilteredResources`].
    /// # Safety
    /// It is the callers responsibility to ensure that nothing else may access the any resources in the `world` in a way that conflicts with `access`.
    pub(crate) unsafe fn new(
        world: UnsafeWorldCell<'w>,
        access: &'s Access<ComponentId>,
        last_run: Tick,
        this_run: Tick,
    ) -> Self {
        Self {
            world,
            access,
            last_run,
            this_run,
        }
    }

    /// Gets read-only access to all of the resources this `FilteredResourcesMut` can access.
    pub fn as_readonly(&self) -> FilteredResources<'_, 's> {
        FilteredResources::from(self)
    }

    /// Returns a new instance with a shorter lifetime.
    /// This is useful if you have `&mut FilteredResourcesMut`, but you need `FilteredResourcesMut`.
    pub fn reborrow(&mut self) -> FilteredResourcesMut<'_, 's> {
        // SAFETY: We have exclusive access to this access for the duration of `'_`, so there cannot be anything else that conflicts.
        unsafe { Self::new(self.world, self.access, self.last_run, self.this_run) }
    }

    /// Returns a reference to the underlying [`Access`].
    pub fn access(&self) -> &Access<ComponentId> {
        self.access
    }

    /// Returns `true` if the `FilteredResources` has read access to the given resource.
    /// Note that [`Self::get()`] may still return `None` if the resource does not exist.
    pub fn has_read<R: Resource>(&self) -> bool {
        let component_id = self.world.components().resource_id::<R>();
        component_id.is_some_and(|component_id| self.access.has_resource_read(component_id))
    }

    /// Returns `true` if the `FilteredResources` has write access to the given resource.
    /// Note that [`Self::get_mut()`] may still return `None` if the resource does not exist.
    pub fn has_write<R: Resource>(&self) -> bool {
        let component_id = self.world.components().resource_id::<R>();
        component_id.is_some_and(|component_id| self.access.has_resource_write(component_id))
    }

    /// Gets a reference to the resource of the given type if it exists and the `FilteredResources` has access to it.
    pub fn get<R: Resource>(&self) -> Option<Ref<'_, R>> {
        self.as_readonly().get()
    }

    /// Gets a pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
        self.as_readonly().get_by_id(component_id)
    }

    /// Gets a mutable reference to the resource of the given type if it exists and the `FilteredResources` has access to it.
    pub fn get_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
        // SAFETY: We have exclusive access to the resources in `access` for `'_`, and we shorten the returned lifetime to that.
        unsafe { self.get_mut_unchecked() }
    }

    /// Gets a mutable pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
    pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
        // SAFETY: We have exclusive access to the resources in `access` for `'_`, and we shorten the returned lifetime to that.
        unsafe { self.get_mut_by_id_unchecked(component_id) }
    }

    /// Consumes self and gets mutable access to resource of the given type with the world `'w` lifetime if it exists and the `FilteredResources` has access to it.
    pub fn into_mut<R: Resource>(mut self) -> Option<Mut<'w, R>> {
        // SAFETY: This consumes self, so we have exclusive access to the resources in `access` for the entirety of `'w`.
        unsafe { self.get_mut_unchecked() }
    }

    /// Consumes self and gets mutable access to resource with the given [`ComponentId`] with the world `'w` lifetime if it exists and the `FilteredResources` has access to it.
    pub fn into_mut_by_id(mut self, component_id: ComponentId) -> Option<MutUntyped<'w>> {
        // SAFETY: This consumes self, so we have exclusive access to the resources in `access` for the entirety of `'w`.
        unsafe { self.get_mut_by_id_unchecked(component_id) }
    }

    /// Gets a mutable pointer to the resource of the given type if it exists and the `FilteredResources` has access to it.
    /// # Safety
    /// It is the callers responsibility to ensure that there are no conflicting borrows of anything in `access` for the duration of the returned value.
    unsafe fn get_mut_unchecked<R: Resource>(&mut self) -> Option<Mut<'w, R>> {
        let component_id = self.world.components().resource_id::<R>()?;
        // SAFETY: THe caller ensures that there are no conflicting borrows.
        unsafe { self.get_mut_by_id_unchecked(component_id) }
            // SAFETY: The underlying type of the resource is `R`.
            .map(|ptr| unsafe { ptr.with_type::<R>() })
    }

    /// Gets a mutable pointer to the resource with the given [`ComponentId`] if it exists and the `FilteredResources` has access to it.
    /// # Safety
    /// It is the callers responsibility to ensure that there are no conflicting borrows of anything in `access` for the duration of the returned value.
    unsafe fn get_mut_by_id_unchecked(
        &mut self,
        component_id: ComponentId,
    ) -> Option<MutUntyped<'w>> {
        if !self.access.has_resource_write(component_id) {
            return None;
        }
        // SAFETY: We have access to this resource in `access`, and the caller ensures that there are no conflicting borrows for the duration of the returned value.
        unsafe { self.world.get_resource_with_ticks(component_id) }.map(
            |(value, ticks, _caller)| MutUntyped {
                // SAFETY: We have exclusive access to the underlying storage.
                value: unsafe { value.assert_unique() },
                // SAFETY: We have exclusive access to the underlying storage.
                ticks: unsafe { TicksMut::from_tick_cells(ticks, self.last_run, self.this_run) },
                #[cfg(feature = "track_change_detection")]
                // SAFETY: We have exclusive access to the underlying storage.
                changed_by: unsafe { _caller.deref_mut() },
            },
        )
    }
}

impl<'w> From<&'w mut World> for FilteredResourcesMut<'w, 'static> {
    fn from(value: &'w mut World) -> Self {
        static WRITE_ALL_RESOURCES: OnceLock<Access<ComponentId>> = OnceLock::new();
        let access = WRITE_ALL_RESOURCES.get_or_init(|| {
            let mut access = Access::new();
            access.write_all_resources();
            access
        });

        let last_run = value.last_change_tick();
        let this_run = value.change_tick();
        // SAFETY: We have a mutable reference to the entire world, so nothing else can alias with mutable access to all resources.
        unsafe {
            Self::new(
                value.as_unsafe_world_cell_readonly(),
                access,
                last_run,
                this_run,
            )
        }
    }
}

/// Builder struct to define the access for a [`FilteredResources`].
///
/// This is passed to a callback in [`FilteredResourcesParamBuilder`](crate::system::FilteredResourcesParamBuilder).
pub struct FilteredResourcesBuilder<'w> {
    world: &'w mut World,
    access: Access<ComponentId>,
}

impl<'w> FilteredResourcesBuilder<'w> {
    /// Creates a new builder with no access.
    pub fn new(world: &'w mut World) -> Self {
        Self {
            world,
            access: Access::new(),
        }
    }

    /// Returns a reference to the underlying [`Access`].
    pub fn access(&self) -> &Access<ComponentId> {
        &self.access
    }

    /// Add accesses required to read all resources.
    pub fn add_read_all(&mut self) -> &mut Self {
        self.access.read_all_resources();
        self
    }

    /// Add accesses required to read the resource of the given type.
    pub fn add_read<R: Resource>(&mut self) -> &mut Self {
        let component_id = self.world.components.register_resource::<R>();
        self.add_read_by_id(component_id)
    }

    /// Add accesses required to read the resource with the given [`ComponentId`].
    pub fn add_read_by_id(&mut self, component_id: ComponentId) -> &mut Self {
        self.access.add_resource_read(component_id);
        self
    }

    /// Create an [`Access`] that represents the accesses of the builder.
    pub fn build(self) -> Access<ComponentId> {
        self.access
    }
}

/// Builder struct to define the access for a [`FilteredResourcesMut`].
///
/// This is passed to a callback in [`FilteredResourcesMutParamBuilder`](crate::system::FilteredResourcesMutParamBuilder).
pub struct FilteredResourcesMutBuilder<'w> {
    world: &'w mut World,
    access: Access<ComponentId>,
}

impl<'w> FilteredResourcesMutBuilder<'w> {
    /// Creates a new builder with no access.
    pub fn new(world: &'w mut World) -> Self {
        Self {
            world,
            access: Access::new(),
        }
    }

    /// Returns a reference to the underlying [`Access`].
    pub fn access(&self) -> &Access<ComponentId> {
        &self.access
    }

    /// Add accesses required to read all resources.
    pub fn add_read_all(&mut self) -> &mut Self {
        self.access.read_all_resources();
        self
    }

    /// Add accesses required to read the resource of the given type.
    pub fn add_read<R: Resource>(&mut self) -> &mut Self {
        let component_id = self.world.components.register_resource::<R>();
        self.add_read_by_id(component_id)
    }

    /// Add accesses required to read the resource with the given [`ComponentId`].
    pub fn add_read_by_id(&mut self, component_id: ComponentId) -> &mut Self {
        self.access.add_resource_read(component_id);
        self
    }

    /// Add accesses required to get mutable access to all resources.
    pub fn add_write_all(&mut self) -> &mut Self {
        self.access.write_all_resources();
        self
    }

    /// Add accesses required to get mutable access to the resource of the given type.
    pub fn add_write<R: Resource>(&mut self) -> &mut Self {
        let component_id = self.world.components.register_resource::<R>();
        self.add_write_by_id(component_id)
    }

    /// Add accesses required to get mutable access to the resource with the given [`ComponentId`].
    pub fn add_write_by_id(&mut self, component_id: ComponentId) -> &mut Self {
        self.access.add_resource_write(component_id);
        self
    }

    /// Create an [`Access`] that represents the accesses of the builder.
    pub fn build(self) -> Access<ComponentId> {
        self.access
    }
}