-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathlib.rs
More file actions
1526 lines (1423 loc) · 51.3 KB
/
lib.rs
File metadata and controls
1526 lines (1423 loc) · 51.3 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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! An implementation of the Bevy Remote Protocol, to allow for remote control of a Bevy app.
//!
//! Adding the [`RemotePlugin`] to your [`App`] will setup everything needed without
//! starting any transports. To start accepting remote connections you will need to
//! add a second plugin like the [`RemoteHttpPlugin`](http::RemoteHttpPlugin) to enable communication
//! over HTTP. These *remote clients* can inspect and alter the state of the
//! entity-component system.
//!
//! The Bevy Remote Protocol is based on the JSON-RPC 2.0 protocol.
//!
//! ## Request objects
//!
//! A typical client request might look like this:
//!
//! ```json
//! {
//! "method": "world.get_components",
//! "id": 0,
//! "params": {
//! "entity": 4294967298,
//! "components": [
//! "bevy_transform::components::transform::Transform"
//! ]
//! }
//! }
//! ```
//!
//! The `id` and `method` fields are required. The `params` field may be omitted
//! for certain methods:
//!
//! * `id` is arbitrary JSON data. The server completely ignores its contents,
//! and the client may use it for any purpose. It will be copied via
//! serialization and deserialization (so object property order, etc. can't be
//! relied upon to be identical) and sent back to the client as part of the
//! response.
//!
//! * `method` is a string that specifies one of the possible [`BrpRequest`]
//! variants: `world.query`, `world.get_components`, `world.insert_components`, etc. It's case-sensitive.
//!
//! * `params` is parameter data specific to the request.
//!
//! For more information, see the documentation for [`BrpRequest`].
//! [`BrpRequest`] is serialized to JSON via `serde`, so [the `serde`
//! documentation] may be useful to clarify the correspondence between the Rust
//! structure and the JSON format.
//!
//! ## Response objects
//!
//! A response from the server to the client might look like this:
//!
//! ```json
//! {
//! "jsonrpc": "2.0",
//! "id": 0,
//! "result": {
//! "bevy_transform::components::transform::Transform": {
//! "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 },
//! "scale": { "x": 1.0, "y": 1.0, "z": 1.0 },
//! "translation": { "x": 0.0, "y": 0.5, "z": 0.0 }
//! }
//! }
//! }
//! ```
//!
//! The `id` field will always be present. The `result` field will be present if the
//! request was successful. Otherwise, an `error` field will replace it.
//!
//! * `id` is the arbitrary JSON data that was sent as part of the request. It
//! will be identical to the `id` data sent during the request, modulo
//! serialization and deserialization. If there's an error reading the `id` field,
//! it will be `null`.
//!
//! * `result` will be present if the request succeeded and will contain the response
//! specific to the request.
//!
//! * `error` will be present if the request failed and will contain an error object
//! with more information about the cause of failure.
//!
//! ## Error objects
//!
//! An error object might look like this:
//!
//! ```json
//! {
//! "code": -32602,
//! "message": "Missing \"entity\" field"
//! }
//! ```
//!
//! The `code` and `message` fields will always be present. There may also be a `data` field.
//!
//! * `code` is an integer representing the kind of an error that happened. Error codes documented
//! in the [`error_codes`] module.
//!
//! * `message` is a short, one-sentence human-readable description of the error.
//!
//! * `data` is an optional field of arbitrary type containing additional information about the error.
//!
//! ## Built-in methods
//!
//! The Bevy Remote Protocol includes a number of built-in methods for accessing and modifying data
//! in the ECS.
//!
//! ### `world.get_components`
//!
//! Retrieve the values of one or more components from an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components will be fetched.
//! - `components`: An array of [fully-qualified type names] of components to fetch.
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the
//! components is not present or can not be reflected. Defaults to false.
//!
//! If `strict` is false:
//!
//! `result`:
//! - `components`: A map associating each type name to its value on the requested entity.
//! - `errors`: A map associating each type name with an error if it was not on the entity
//! or could not be reflected.
//!
//! If `strict` is true:
//!
//! `result`: A map associating each type name to its value on the requested entity.
//!
//! ### `world.query`
//!
//! Perform a query over components in the ECS, returning all matching entities and their associated
//! component values.
//!
//! All of the arrays that comprise this request are optional, and when they are not provided, they
//! will be treated as if they were empty.
//!
//! `params`:
//! - `data`:
//! - `components` (optional): An array of [fully-qualified type names] of components to fetch,
//! see _below_ example for a query to list all the type names in **your** project.
//! - `option` (optional): An array of fully-qualified type names of components to fetch optionally.
//! to fetch all reflectable components, you can pass in the string `"all"`.
//! - `has` (optional): An array of fully-qualified type names of components whose presence will be
//! reported as boolean values.
//! - `filter` (optional):
//! - `with` (optional): An array of fully-qualified type names of components that must be present
//! on entities in order for them to be included in results.
//! - `without` (optional): An array of fully-qualified type names of components that must *not* be
//! present on entities in order for them to be included in results.
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the components
//! is not present or can not be reflected. Defaults to false.
//!
//! `result`: An array, each of which is an object containing:
//! - `entity`: The ID of a query-matching entity.
//! - `components`: A map associating each type name from `components`/`option` to its value on the matching
//! entity if the component is present.
//! - `has`: A map associating each type name from `has` to a boolean value indicating whether or not the
//! entity has that component. If `has` was empty or omitted, this key will be omitted in the response.
//!
//! #### Example
//! To use the query API and retrieve Transform data for all entities that have a Transform
//! use this query:
//!
//! ```json
//! {
//! "jsonrpc": "2.0",
//! "method": "world.query",
//! "id": 0,
//! "params": {
//! "data": {
//! "components": ["bevy_transform::components::transform::Transform"]
//! "option": [],
//! "has": []
//! },
//! "filter": {
//! "with": [],
//! "without": []
//! },
//! "strict": false
//! }
//! }
//! ```
//!
//!
//! To query all entities and all of their Reflectable components (and retrieve their values), you can pass in "all" for the option field:
//! ```json
//! {
//! "jsonrpc": "2.0",
//! "method": "world.query",
//! "id": 0,
//! "params": {
//! "data": {
//! "components": []
//! "option": "all",
//! "has": []
//! },
//! "filter": {
//! "with": [],
//! "without": []
//! },
//! "strict": false
//! }
//! }
//! ```
//!
//! This should return you something like the below (in a larger list):
//! ```json
//! {
//! "components": {
//! "bevy_camera::Camera3d": {
//! "depth_load_op": {
//! "Clear": 0.0
//! },
//! "depth_texture_usages": 16,
//! },
//! "bevy_core_pipeline::tonemapping::DebandDither": "Enabled",
//! "bevy_core_pipeline::tonemapping::Tonemapping": "TonyMcMapface",
//! "bevy_light::cluster::ClusterConfig": {
//! "FixedZ": {
//! "dynamic_resizing": true,
//! "total": 4096,
//! "z_config": {
//! "far_z_mode": "MaxClusterableObjectRange",
//! "first_slice_depth": 5.0
//! },
//! "z_slices": 24
//! }
//! },
//! "bevy_camera::Camera": {
//! "clear_color": "Default",
//! "is_active": true,
//! "msaa_writeback": true,
//! "order": 0,
//! "sub_camera_view": null,
//! "target": {
//! "Window": "Primary"
//! },
//! "viewport": null
//! },
//! "bevy_camera::Projection": {
//! "Perspective": {
//! "aspect_ratio": 1.7777777910232544,
//! "far": 1000.0,
//! "fov": 0.7853981852531433,
//! "near": 0.10000000149011612
//! }
//! },
//! "bevy_camera::primitives::Frustum": {},
//! "bevy_render::sync_world::RenderEntity": 4294967291,
//! "bevy_render::sync_world::SyncToRenderWorld": {},
//! "bevy_render::view::Msaa": "Sample4",
//! "bevy_camera::visibility::InheritedVisibility": true,
//! "bevy_camera::visibility::ViewVisibility": false,
//! "bevy_camera::visibility::Visibility": "Inherited",
//! "bevy_camera::visibility::VisibleEntities": {},
//! "bevy_transform::components::global_transform::GlobalTransform": [
//! 0.9635179042816162,
//! -3.725290298461914e-9,
//! 0.26764383912086487,
//! 0.11616238951683044,
//! 0.9009039402008056,
//! -0.4181846082210541,
//! -0.24112138152122495,
//! 0.4340185225009918,
//! 0.8680371046066284,
//! -2.5,
//! 4.5,
//! 9.0
//! ],
//! "bevy_transform::components::transform::Transform": {
//! "rotation": [
//! -0.22055435180664065,
//! -0.13167093694210052,
//! -0.03006339818239212,
//! 0.9659786224365234
//! ],
//! "scale": [
//! 1.0,
//! 1.0,
//! 1.0
//! ],
//! "translation": [
//! -2.5,
//! 4.5,
//! 9.0
//! ]
//! },
//! "bevy_transform::components::transform::TransformTreeChanged": null
//! },
//! "entity": 4294967261
//!},
//! ```
//!
//! ### `world.spawn_entity`
//!
//! Create a new entity with the provided components and return the resulting entity ID.
//!
//! `params`:
//! - `components`: A map associating each component's [fully-qualified type name] with its value.
//!
//! `result`:
//! - `entity`: The ID of the newly spawned entity.
//!
//! ### `world.despawn_entity`
//!
//! Despawn the entity with the given ID.
//!
//! `params`:
//! - `entity`: The ID of the entity to be despawned.
//!
//! `result`: null.
//!
//! ### `world.remove_components`
//!
//! Delete one or more components from an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components should be removed.
//! - `components`: An array of [fully-qualified type names] of components to be removed.
//!
//! `result`: null.
//!
//! ### `world.insert_components`
//!
//! Insert one or more components into an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity to insert components into.
//! - `components`: A map associating each component's fully-qualified type name with its value.
//!
//! `result`: null.
//!
//! ### `world.mutate_components`
//!
//! Mutate a field in a component.
//!
//! `params`:
//! - `entity`: The ID of the entity with the component to mutate.
//! - `component`: The component's [fully-qualified type name].
//! - `path`: The path of the field within the component. See
//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.
//! - `value`: The value to insert at `path`.
//!
//! `result`: null.
//!
//! ### `world.reparent_entities`
//!
//! Assign a new parent to one or more entities.
//!
//! `params`:
//! - `entities`: An array of entity IDs of entities that will be made children of the `parent`.
//! - `parent` (optional): The entity ID of the parent to which the child entities will be assigned.
//! If excluded, the given entities will be removed from their parents.
//!
//! `result`: null.
//!
//! ### `world.list_components`
//!
//! List all registered components or all components present on an entity.
//!
//! When `params` is not provided, this lists all registered components. If `params` is provided,
//! this lists only those components present on the provided entity.
//!
//! `params` (optional):
//! - `entity`: The ID of the entity whose components will be listed.
//!
//! `result`: An array of fully-qualified type names of components.
//!
//! ### `world.get_components+watch`
//!
//! Watch the values of one or more components from an entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components will be fetched.
//! - `components`: An array of [fully-qualified type names] of components to fetch.
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the
//! components is not present or can not be reflected. Defaults to false.
//!
//! If `strict` is false:
//!
//! `result`:
//! - `components`: A map of components added or changed in the last tick associating each type
//! name to its value on the requested entity.
//! - `removed`: An array of fully-qualified type names of components removed from the entity
//! in the last tick.
//! - `errors`: A map associating each type name with an error if it was not on the entity
//! or could not be reflected.
//!
//! If `strict` is true:
//!
//! `result`:
//! - `components`: A map of components added or changed in the last tick associating each type
//! name to its value on the requested entity.
//! - `removed`: An array of fully-qualified type names of components removed from the entity
//! in the last tick.
//!
//! ### `world.list_components+watch`
//!
//! Watch all components present on an entity.
//!
//! When `params` is not provided, this lists all registered components. If `params` is provided,
//! this lists only those components present on the provided entity.
//!
//! `params`:
//! - `entity`: The ID of the entity whose components will be listed.
//!
//! `result`:
//! - `added`: An array of fully-qualified type names of components added to the entity in the
//! last tick.
//! - `removed`: An array of fully-qualified type names of components removed from the entity
//! in the last tick.
//!
//! ### `world.get_resources`
//!
//! Extract the value of a given resource from the world.
//!
//! `params`:
//! - `resource`: The [fully-qualified type name] of the resource to get.
//!
//! `result`:
//! - `value`: The value of the resource in the world.
//!
//! ### `world.insert_resources`
//!
//! Insert the given resource into the world with the given value.
//!
//! `params`:
//! - `resource`: The [fully-qualified type name] of the resource to insert.
//! - `value`: The value of the resource to be inserted.
//!
//! `result`: null.
//!
//! ### `world.remove_resources`
//!
//! Remove the given resource from the world.
//!
//! `params`
//! - `resource`: The [fully-qualified type name] of the resource to remove.
//!
//! `result`: null.
//!
//! ### `world.mutate_resources`
//!
//! Mutate a field in a resource.
//!
//! `params`:
//! - `resource`: The [fully-qualified type name] of the resource to mutate.
//! - `path`: The path of the field within the resource. See
//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.
//! - `value`: The value to be inserted at `path`.
//!
//! `result`: null.
//!
//! ### `world.list_resources`
//!
//! List all reflectable registered resource types. This method has no parameters.
//!
//! `result`: An array of [fully-qualified type names] of registered resource types.
//!
//! ### `world.trigger_event`
//!
//! Triggers an event.
//!
//! `params`:
//! - `event`: The [fully-qualified type name] of the event to trigger.
//! - `value`: The value of the event to trigger.
//!
//! `result`: null.
//!
//! ### `registry.schema`
//!
//! Retrieve schema information about registered types in the Bevy app's type registry.
//!
//! `params` (optional):
//! - `with_crates`: An array of crate names to include in the results. When empty or omitted, types from all crates will be included.
//! - `without_crates`: An array of crate names to exclude from the results. When empty or omitted, no crates will be excluded.
//! - `type_limit`: Additional type constraints:
//! - `with`: An array of [fully-qualified type names] that must be present for a type to be included
//! - `without`: An array of [fully-qualified type names] that must not be present for a type to be excluded
//!
//! `result`: A map associating each type's [fully-qualified type name] to a [`JsonSchemaBevyType`](crate::schemas::json_schema::JsonSchemaBevyType).
//! This contains schema information about that type, including field definitions, type information, reflect type information, and other metadata
//! helpful for understanding the structure of the type.
//!
//! ### `rpc.discover`
//!
//! Discover available remote methods and server information. This follows the [`OpenRPC` specification for service discovery](https://spec.open-rpc.org/#service-discovery-method).
//!
//! This method takes no parameters.
//!
//! `result`: An `OpenRPC` document containing:
//! - Information about all available remote methods
//! - Server connection information (when using HTTP transport)
//! - `OpenRPC` specification version
//!
//! ## Custom methods
//!
//! In addition to the provided methods, the Bevy Remote Protocol can be extended to include custom
//! methods. This is primarily done during the initialization of [`RemotePlugin`], although the
//! methods may also be extended at runtime using the [`RemoteMethods`] resource.
//!
//! ### Example
//! ```ignore
//! fn main() {
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_plugins(
//! // `default` adds all of the built-in methods, while `with_method` extends them
//! RemotePlugin::default()
//! .with_method("super_user/cool_method", path::to::my::cool::handler)
//! // ... more methods can be added by chaining `with_method`
//! )
//! .add_systems(
//! // ... standard application setup
//! )
//! .run();
//! }
//! ```
//!
//! The handler is expected to be a system-convertible function which takes optional JSON parameters
//! as input and returns a [`BrpResult`]. This means that it should have a type signature which looks
//! something like this:
//! ```
//! # use serde_json::Value;
//! # use bevy_ecs::prelude::{In, World};
//! # use bevy_remote::BrpResult;
//! fn handler(In(params): In<Option<Value>>, world: &mut World) -> BrpResult {
//! todo!()
//! }
//! ```
//!
//! Arbitrary system parameters can be used in conjunction with the optional `Value` input. The
//! handler system will always run with exclusive `World` access.
//!
//! [the `serde` documentation]: https://serde.rs/
//! [fully-qualified type names]: bevy_reflect::TypePath::type_path
//! [fully-qualified type name]: bevy_reflect::TypePath::type_path
extern crate alloc;
use async_channel::{Receiver, Sender};
use bevy_app::{prelude::*, MainScheduleOrder};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
entity::Entity,
observer::On,
resource::Resource,
schedule::{
InternedScheduleLabel, IntoScheduleConfigs, ScheduleBuildMetadata, ScheduleBuilt,
ScheduleLabel, SystemSet,
},
system::{Commands, In, IntoSystem, ResMut, System, SystemId},
world::World,
};
use bevy_platform::collections::HashMap;
#[cfg(feature = "bevy_render")]
use bevy_render::{Render, RenderApp, RenderScheduleOrder, RenderStartup};
use bevy_utils::prelude::default;
use serde::{ser::SerializeMap, Deserialize, Serialize};
use serde_json::Value;
use std::sync::RwLock;
pub mod builtin_methods;
#[cfg(feature = "http")]
pub mod http;
pub mod schemas;
const CHANNEL_SIZE: usize = 16;
/// Add this plugin to your [`App`] to allow remote connections to inspect and modify entities.
///
/// This the main plugin for `bevy_remote`. See the [crate-level documentation] for details on
/// the available protocols and its default methods.
///
/// [crate-level documentation]: crate
pub struct RemotePlugin {
/// The verbs that the server will recognize and respond to for the main app.
methods: RwLock<Vec<(String, RemoteMethodHandler)>>,
/// The verbs that the server will recognize and respond to for the render subapp.
render_methods: RwLock<Vec<(String, RemoteMethodHandler)>>,
}
impl RemotePlugin {
/// Create a [`RemotePlugin`] with the default address and port but without
/// any associated methods.
fn empty() -> Self {
Self {
methods: RwLock::new(vec![]),
render_methods: RwLock::new(vec![]),
}
}
/// Add a remote method to the plugin using the given `name` and `handler` to main app.
#[inline]
pub fn with_method_main<M>(
self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,
) -> Self {
self.with_method(name, handler, true)
}
/// Add a remote method to the plugin using the given `name` and `handler` to render app.
#[inline]
pub fn with_method_render<M>(
self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,
) -> Self {
self.with_method(name, handler, false)
}
/// Add a remote method to the plugin using the given `name` and `handler` to given app.
#[must_use]
fn with_method<M>(
mut self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,
to_main: bool,
) -> Self {
(if to_main {
self.methods.get_mut()
} else {
self.render_methods.get_mut()
})
.unwrap()
.push((
name.into(),
RemoteMethodHandler::Instant(Box::new(IntoSystem::into_system(handler))),
));
self
}
/// Add a remote method with a watching handler to the plugin using the given `name` to main app.
#[inline]
pub fn with_watching_method_main<M>(
self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,
) -> Self {
self.with_watching_method(name, handler, true)
}
/// Add a remote method with a watching handler to the plugin using the given `name` to render app.
#[inline]
pub fn with_watching_method_render<M>(
self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,
) -> Self {
self.with_watching_method(name, handler, false)
}
/// Add a remote method with a watching handler to the plugin using the given `name` to given app.
#[must_use]
fn with_watching_method<M>(
mut self,
name: impl Into<String>,
handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,
to_main: bool,
) -> Self {
(if to_main {
self.methods.get_mut()
} else {
self.render_methods.get_mut()
})
.unwrap()
.push((
name.into(),
RemoteMethodHandler::Watching(Box::new(IntoSystem::into_system(handler))),
));
self
}
/// Create the default list of BRP methods
fn add_default_methods(self, to_main: bool) -> Self {
self.with_method(
builtin_methods::BRP_GET_COMPONENTS_METHOD,
builtin_methods::process_remote_get_components_request,
to_main,
)
.with_method(
builtin_methods::BRP_QUERY_METHOD,
builtin_methods::process_remote_query_request,
to_main,
)
.with_method(
builtin_methods::BRP_SPAWN_ENTITY_METHOD,
builtin_methods::process_remote_spawn_entity_request,
to_main,
)
.with_method(
builtin_methods::BRP_INSERT_COMPONENTS_METHOD,
builtin_methods::process_remote_insert_components_request,
to_main,
)
.with_method(
builtin_methods::BRP_REMOVE_COMPONENTS_METHOD,
builtin_methods::process_remote_remove_components_request,
to_main,
)
.with_method(
builtin_methods::BRP_DESPAWN_COMPONENTS_METHOD,
builtin_methods::process_remote_despawn_entity_request,
to_main,
)
.with_method(
builtin_methods::BRP_REPARENT_ENTITIES_METHOD,
builtin_methods::process_remote_reparent_entities_request,
to_main,
)
.with_method(
builtin_methods::BRP_LIST_COMPONENTS_METHOD,
builtin_methods::process_remote_list_components_request,
to_main,
)
.with_method(
builtin_methods::BRP_MUTATE_COMPONENTS_METHOD,
builtin_methods::process_remote_mutate_components_request,
to_main,
)
.with_method(
builtin_methods::RPC_DISCOVER_METHOD,
builtin_methods::process_remote_list_methods_request,
to_main,
)
.with_watching_method(
builtin_methods::BRP_GET_COMPONENTS_AND_WATCH_METHOD,
builtin_methods::process_remote_get_components_watching_request,
to_main,
)
.with_watching_method(
builtin_methods::BRP_LIST_COMPONENTS_AND_WATCH_METHOD,
builtin_methods::process_remote_list_components_watching_request,
to_main,
)
.with_method(
builtin_methods::BRP_GET_RESOURCE_METHOD,
builtin_methods::process_remote_get_resources_request,
to_main,
)
.with_method(
builtin_methods::BRP_INSERT_RESOURCE_METHOD,
builtin_methods::process_remote_insert_resources_request,
to_main,
)
.with_method(
builtin_methods::BRP_REMOVE_RESOURCE_METHOD,
builtin_methods::process_remote_remove_resources_request,
to_main,
)
.with_method(
builtin_methods::BRP_MUTATE_RESOURCE_METHOD,
builtin_methods::process_remote_mutate_resources_request,
to_main,
)
.with_method(
builtin_methods::BRP_LIST_RESOURCES_METHOD,
builtin_methods::process_remote_list_resources_request,
to_main,
)
.with_method(
builtin_methods::BRP_TRIGGER_EVENT_METHOD,
builtin_methods::process_remote_trigger_event_request,
to_main,
)
.with_method(
builtin_methods::BRP_WRITE_MESSAGE_METHOD,
builtin_methods::process_remote_write_message_request,
to_main,
)
.with_watching_method(
builtin_methods::BRP_OBSERVE_METHOD,
builtin_methods::process_remote_observe_watching_request,
to_main,
)
.with_method(
builtin_methods::BRP_REGISTRY_SCHEMA_METHOD,
builtin_methods::export_registry_types,
to_main,
)
.with_method(
builtin_methods::BRP_SCHEDULE_LIST,
builtin_methods::schedule_list,
to_main,
)
.with_method(
builtin_methods::BRP_SCHEDULE_GRAPH,
builtin_methods::schedule_graph,
to_main,
)
}
}
impl Default for RemotePlugin {
fn default() -> Self {
let mut t = Self::empty();
t = t.add_default_methods(true);
#[cfg(feature = "bevy_render")]
{
t = t.add_default_methods(false);
}
t
}
}
impl Plugin for RemotePlugin {
fn build(&self, app: &mut App) {
let mut remote_methods = RemoteMethods::new();
let plugin_methods = &mut *self.methods.write().unwrap();
for (name, handler) in plugin_methods.drain(..) {
remote_methods.insert(
name.clone(),
match handler {
RemoteMethodHandler::Instant(system) => RemoteMethodSystemId::Instant(
app.main_mut().world_mut().register_boxed_system(system),
),
RemoteMethodHandler::Watching(system) => RemoteMethodSystemId::Watching(
app.main_mut().world_mut().register_boxed_system(system),
),
},
);
}
if remote_methods
.0
.contains_key(builtin_methods::BRP_SCHEDULE_GRAPH)
{
app.init_resource::<PreviousScheduleBuildMetadata>()
.add_observer(cache_schedule_build_metadata);
}
app.init_schedule(RemoteLast)
.world_mut()
.resource_mut::<MainScheduleOrder>()
.insert_after(Last, RemoteLast);
app.insert_resource(remote_methods)
.init_resource::<schemas::SchemaTypesMetadata>()
.init_resource::<RemoteWatchingRequests>()
.init_resource::<builtin_methods::BrpEventObservers>()
.add_systems(PreStartup, setup_mailbox_channel)
.configure_sets(
RemoteLast,
(RemoteSystems::ProcessRequests, RemoteSystems::Cleanup).chain(),
)
.add_systems(
RemoteLast,
(
(process_remote_requests, process_ongoing_watching_requests)
.chain()
.in_set(RemoteSystems::ProcessRequests),
remove_closed_watching_requests.in_set(RemoteSystems::Cleanup),
),
);
#[cfg(feature = "bevy_render")]
{
use bevy_ecs::schedule::common_conditions::run_once;
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
let mut render_remote_methods = RemoteMethods::new();
let render_plugin_methods = &mut *self.render_methods.write().unwrap();
for (name, handler) in render_plugin_methods.drain(..) {
render_remote_methods.insert(
name,
match handler {
RemoteMethodHandler::Instant(system) => RemoteMethodSystemId::Instant(
render_app.world_mut().register_boxed_system(system),
),
RemoteMethodHandler::Watching(system) => RemoteMethodSystemId::Watching(
render_app.world_mut().register_boxed_system(system),
),
},
);
}
render_app
.init_schedule(RemoteLast)
.world_mut()
.resource_mut::<RenderScheduleOrder>()
.insert_after(Render, RemoteLast);
render_app
.insert_resource(render_remote_methods)
.init_resource::<schemas::SchemaTypesMetadata>()
.init_resource::<RemoteWatchingRequests>()
.add_systems(RenderStartup, setup_mailbox_channel.run_if(run_once))
.configure_sets(
RemoteLast,
(RemoteSystems::ProcessRequests, RemoteSystems::Cleanup).chain(),
)
.add_systems(
RemoteLast,
(
(process_remote_requests, process_ongoing_watching_requests)
.chain()
.in_set(RemoteSystems::ProcessRequests),
remove_closed_watching_requests.in_set(RemoteSystems::Cleanup),
),
);
}
}
}
/// Schedule that contains all systems to process Bevy Remote Protocol requests
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct RemoteLast;
/// The systems sets of the [`RemoteLast`] schedule.
///
/// These can be useful for ordering.
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum RemoteSystems {
/// Processing of remote requests.
ProcessRequests,
/// Cleanup (remove closed watchers etc)
Cleanup,
}
/// A type to hold the allowed types of systems to be used as method handlers.
#[derive(Debug)]
pub enum RemoteMethodHandler {
/// A handler that only runs once and returns one response.
Instant(Box<dyn System<In = In<Option<Value>>, Out = BrpResult>>),
/// A handler that watches for changes and response when a change is detected.
Watching(Box<dyn System<In = In<Option<Value>>, Out = BrpResult<Option<Value>>>>),
}
/// The [`SystemId`] of a function that implements a remote instant method (`world.get_components`, `world.query`, etc.)
///
/// The first parameter is the JSON value of the `params`. Typically, an
/// implementation will deserialize these as the first thing they do.
///
/// The returned JSON value will be returned as the response. Bevy will
/// automatically populate the `id` field before sending.
pub type RemoteInstantMethodSystemId = SystemId<In<Option<Value>>, BrpResult>;
/// The [`SystemId`] of a function that implements a remote watching method (`world.get_components+watch`, `world.list_components+watch`, etc.)
///
/// The first parameter is the JSON value of the `params`. Typically, an
/// implementation will deserialize these as the first thing they do.
///
/// The optional returned JSON value will be sent as a response. If no
/// changes were detected this should be [`None`]. Re-running of this
/// handler is done in the [`RemotePlugin`].
pub type RemoteWatchingMethodSystemId = SystemId<In<Option<Value>>, BrpResult<Option<Value>>>;
/// The [`SystemId`] of a function that can be used as a remote method.
#[derive(Debug, Clone, Copy)]
pub enum RemoteMethodSystemId {
/// A handler that only runs once and returns one response.
Instant(RemoteInstantMethodSystemId),
/// A handler that watches for changes and response when a change is detected.
Watching(RemoteWatchingMethodSystemId),
}
/// Holds all implementations of methods known to the server.
///
/// Custom methods can be added to this list using [`RemoteMethods::insert`].
#[derive(Debug, Resource, Default)]
pub struct RemoteMethods(HashMap<String, RemoteMethodSystemId>);
impl RemoteMethods {
/// Creates a new [`RemoteMethods`] resource with no methods registered in it.
pub fn new() -> Self {
default()
}
/// Adds a new method, replacing any existing method with that name.
///
/// If there was an existing method with that name, returns its handler.
pub fn insert(
&mut self,
method_name: impl Into<String>,
handler: RemoteMethodSystemId,
) -> Option<RemoteMethodSystemId> {
self.0.insert(method_name.into(), handler)
}
/// Get a [`RemoteMethodSystemId`] with its method name.
pub fn get(&self, method: &str) -> Option<&RemoteMethodSystemId> {
self.0.get(method)
}
/// Get a [`Vec<String>`] with method names.
pub fn methods(&self) -> Vec<String> {
self.0.keys().cloned().collect()
}
}
/// Holds the [`BrpMessage`]'s of all ongoing watching requests along with their handlers.
#[derive(Debug, Resource, Default)]
pub struct RemoteWatchingRequests(Vec<(BrpMessage, RemoteWatchingMethodSystemId)>);
/// A single request from a Bevy Remote Protocol client to the server,
/// serialized in JSON.