-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathpirates_bevy_sky.rs
More file actions
517 lines (470 loc) · 14.5 KB
/
Copy pathpirates_bevy_sky.rs
File metadata and controls
517 lines (470 loc) · 14.5 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
//! Showcases dynamic ocean material + dynamic Sun/Atmosphere.
//! Most of the daylight cycle code taken from the examples of `bevy_atmosphere`.
#[cfg(feature = "depth_prepass")]
use bevy::core_pipeline::prepass::DepthPrepass;
use bevy::camera_controller::free_camera::{FreeCamera, FreeCameraPlugin};
#[cfg(feature = "debug")]
use bevy::color::palettes::css::*;
use bevy::mesh::*;
use bevy::pbr::wireframe::{Wireframe, WireframePlugin};
use bevy::{
anti_alias::fxaa::Fxaa,
app::AppExit,
camera::{Exposure, Hdr},
core_pipeline::tonemapping::Tonemapping,
input::keyboard::KeyCode,
light::{
light_consts::lux, Atmosphere, AtmosphereEnvironmentMapLight, CascadeShadowConfigBuilder,
FogVolume, VolumetricFog, VolumetricLight,
},
pbr::{AtmosphereMode, AtmosphereSettings, ScreenSpaceReflections},
post_process::bloom::Bloom,
prelude::*,
render::render_resource::TextureFormat,
world_serialization::WorldAssetRoot,
};
use bevy::light::atmosphere::ScatteringMedium;
use std::f32::consts::PI;
use bevy_water::*;
pub const WATER_HEIGHT: f32 = 1.0;
#[derive(Resource, Default)]
struct GameState {
paused: bool,
}
pub fn pirates_app(title: &str) -> App {
let mut app = App::new();
app
// Tell the asset server to watch for asset changes on disk:
.add_plugins(
DefaultPlugins
.set(WindowPlugin {
primary_window: Some(Window {
title: title.to_string(),
resolution: (1200, 600).into(),
..Default::default()
}),
..default()
})
.set(AssetPlugin::default()),
)
.add_plugins(FreeCameraPlugin);
#[cfg(feature = "inspector")]
app.add_plugins((
bevy_inspector_egui::bevy_egui::EguiPlugin::default(),
bevy_inspector_egui::quick::WorldInspectorPlugin::new(),
));
app
.insert_resource(ClearColor(Color::BLACK))
.insert_resource(GameState::default())
.insert_resource(GlobalAmbientLight::NONE)
//.insert_resource(bevy::light::DirectionalLightShadowMap { size: 4 * 1024 })
// Water
.insert_resource(WaterSettings {
height: WATER_HEIGHT,
clarity: 0.9,
amplitude: 1.5,
..default()
})
.add_plugins((WaterPlugin, ImageUtilsPlugin))
// Ship Physics.
.add_systems(Update, update_ships)
// Wireframe
.add_plugins(WireframePlugin::default())
.add_systems(Update, toggle_wireframe)
.add_systems(Startup, print_controls)
.add_systems(Update, (dynamic_scene, controls));
app
}
fn print_controls() {
println!("Atmosphere Example Controls:");
println!(" 1 - Switch to lookup texture rendering method");
println!(" 2 - Switch to raymarched rendering method");
println!(" Enter - Pause/Resume sun motion");
println!(" Up/Down - Increase/Decrease exposure");
}
fn controls(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut exit: MessageWriter<AppExit>,
mut atmosphere_settings: Query<&mut AtmosphereSettings>,
mut game_state: ResMut<GameState>,
mut camera_exposure: Query<&mut Exposure, With<Camera3d>>,
time: Res<Time>,
) {
if keyboard_input.just_pressed(KeyCode::Digit1) {
for mut settings in &mut atmosphere_settings {
settings.rendering_method = AtmosphereMode::LookupTexture;
println!("Switched to lookup texture rendering method");
}
}
if keyboard_input.just_pressed(KeyCode::Digit2) {
for mut settings in &mut atmosphere_settings {
settings.rendering_method = AtmosphereMode::Raymarched;
println!("Switched to raymarched rendering method");
}
}
if keyboard_input.just_pressed(KeyCode::Enter) {
game_state.paused = !game_state.paused;
}
if keyboard_input.pressed(KeyCode::ArrowUp) {
for mut exposure in &mut camera_exposure {
exposure.ev100 -= time.delta_secs() * 2.0;
}
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
for mut exposure in &mut camera_exposure {
exposure.ev100 += time.delta_secs() * 2.0;
}
}
if keyboard_input.pressed(KeyCode::Escape) {
exit.write(AppExit::Success);
}
}
fn dynamic_scene(
mut suns: Query<&mut Transform, With<Sun>>,
time: Res<Time>,
sun_motion_state: Res<GameState>,
) {
// Only rotate the sun if motion is not paused
if !sun_motion_state.paused {
suns
.iter_mut()
.for_each(|mut tf| tf.rotate_x(-time.delta_secs() * PI / 10.0));
}
}
#[allow(dead_code)]
pub fn main() {
let mut app = pirates_app("Pirates");
// Setup
app.add_systems(Startup, (setup_ocean, setup_orb, setup_camera, setup_ships));
app.run();
}
pub fn toggle_wireframe(
input: Res<ButtonInput<KeyCode>>,
query: Query<Entity, With<Mesh3d>>,
mut commands: Commands,
mut show_wireframe: Local<bool>,
) {
if input.just_pressed(KeyCode::KeyR) {
for entity in query.iter() {
let mut entity = commands.entity(entity);
if *show_wireframe {
entity.insert(Wireframe);
} else {
entity.remove::<Wireframe>();
}
}
// Update flag.
*show_wireframe = !*show_wireframe;
}
}
// Marker for updating the position of the light, not needed unless we have multiple lights
#[derive(Component)]
pub struct Sun;
#[derive(Component, Default, Clone)]
#[require(Transform, Visibility)]
pub struct Ship {
water_line: f32,
front: Vec3,
back_left: Vec3,
back_right: Vec3,
}
impl Ship {
pub fn new(water_line: f32, front: f32, back: f32, left: f32, right: f32) -> Self {
Self {
water_line,
front: Vec3::new(0.0, 0.0, front),
back_left: Vec3::new(left, 0.0, back),
back_right: Vec3::new(right, 0.0, back),
}
}
fn update(
&self,
water: &WaterParam,
pos: Vec3,
transform: &mut Transform,
#[cfg(feature = "debug")] gizmos: &mut Gizmos,
) {
let (yaw, _pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
let global = Transform::from_translation(pos).with_rotation(Quat::from_rotation_y(yaw));
// Get the wave position at the front, back_left and back_right.
let mut front = water.wave_point(global.transform_point(self.front));
let left = water.wave_point(global.transform_point(self.back_left));
let right = water.wave_point(global.transform_point(self.back_right));
let normal = (left - front).cross(right - front).normalize();
// Debug lines.
#[cfg(feature = "debug")]
{
gizmos.line(front, front + normal, WHITE);
gizmos.line(front, right, RED);
gizmos.line(right, left, WHITE);
gizmos.line(left, front, GREEN);
gizmos.line(transform.translation, transform.translation + normal, WHITE);
}
front.y += self.water_line - 0.2;
transform.look_at(front, normal);
transform.translation.y = ((front.y + left.y + right.y) / 3.0) + self.water_line;
}
}
pub fn update_ships(
water: WaterParam,
mut ships: Query<(&Ship, &mut Transform, &GlobalTransform)>,
#[cfg(feature = "debug")] mut gizmos: Gizmos,
) {
for (ship, mut transform, global) in ships.iter_mut() {
let pos = global.translation();
#[cfg(not(feature = "debug"))]
ship.update(&water, pos, &mut transform);
#[cfg(feature = "debug")]
ship.update(&water, pos, &mut transform, &mut gizmos);
}
}
pub fn scale_uvs(mesh: &mut Mesh, scale: f32) {
match mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0) {
Some(VertexAttributeValues::Float32x2(uvs)) => {
for [x, y] in uvs.iter_mut() {
*x *= scale;
*y *= scale;
}
}
Some(_) => {
panic!("Unexpected UV format");
}
_ => {
panic!("Mesh doesn't have UVS");
}
}
}
/// set up a simple ocean scene.
pub fn setup_ocean(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Configure a properly scaled cascade shadow map for this scene (defaults are too large, mesh units are in km)
let cascade_shadow_config = CascadeShadowConfigBuilder {
first_cascade_far_bound: 0.3,
maximum_distance: 15.0,
..default()
}
.build();
// Sun
commands.spawn((
Sun,
DirectionalLight {
shadow_maps_enabled: true,
// lux::RAW_SUNLIGHT is recommended for use with this feature, since
// other values approximate sunlight *post-scattering* in various
// conditions. RAW_SUNLIGHT in comparison is the illuminance of the
// sun unfiltered by the atmosphere, so it is the proper input for
// sunlight to be filtered by the atmosphere.
illuminance: lux::RAW_SUNLIGHT,
..default()
},
Transform::from_xyz(1.0, 0.4, 0.0).looking_at(Vec3::ZERO, Vec3::Y),
VolumetricLight,
cascade_shadow_config,
));
// spawn the fog volume
commands.spawn((
FogVolume::default(),
Transform::from_scale(Vec3::new(10.0, 1.0, 10.0)).with_translation(Vec3::Y * 0.5),
));
let sphere_mesh = meshes.add(Mesh::from(Sphere { radius: 1.0 }));
// light probe spheres
commands.spawn((
Mesh3d(sphere_mesh.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::WHITE,
metallic: 1.0,
perceptual_roughness: 0.0,
..default()
})),
Transform::from_xyz(-1.0, 1.0, -1.0),
));
commands.spawn((
Mesh3d(sphere_mesh.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::WHITE,
metallic: 0.0,
perceptual_roughness: 1.0,
..default()
})),
Transform::from_xyz(-1.0, 1.0, 1.0),
));
// Prepare textures.
let base_color_texture = Some(asset_server.load("textures/coast_sand_01_1k/diff.jpg"));
let metallic_roughness_texture = Some(ImageReformat::reformat(
&mut commands,
&asset_server,
"textures/coast_sand_01_1k/rough.jpg",
TextureFormat::Rgba8Unorm,
));
let normal_map_texture = Some(ImageReformat::reformat(
&mut commands,
&asset_server,
"textures/coast_sand_01_1k/normal.jpg",
TextureFormat::Rgba8Unorm,
));
ImageReformat::uv_repeat(
&mut commands,
&asset_server,
"textures/coast_sand_01_1k/diff.jpg",
);
ImageReformat::uv_repeat(
&mut commands,
&asset_server,
"textures/coast_sand_01_1k/rough.jpg",
);
ImageReformat::uv_repeat(
&mut commands,
&asset_server,
"textures/coast_sand_01_1k/normal.jpg",
);
// Coast sand material.
let sandy = MeshMaterial3d(materials.add(StandardMaterial {
perceptual_roughness: 1.0,
metallic: 0.0,
reflectance: 0.5,
base_color_texture,
metallic_roughness_texture,
normal_map_texture,
cull_mode: None,
double_sided: true,
..default()
}));
let floor_mesh = Mesh3d({
let mut mesh = PlaneMeshBuilder::from_length(256.0 * 6.0)
.subdivisions(25)
.build();
mesh.generate_tangents().expect("tangents");
scale_uvs(&mut mesh, 50.0);
meshes.add(mesh)
});
commands.spawn((
Name::new(format!("Sea floor")),
floor_mesh.clone(),
sandy.clone(),
Transform::from_xyz(0.0, -5.0, 0.0),
));
let island_mesh = Mesh3d({
let mut mesh = Sphere::new(2.0)
.mesh()
.kind(SphereKind::Uv {
sectors: 90,
stacks: 60,
})
.build();
mesh.generate_tangents().expect("tangents");
scale_uvs(&mut mesh, 20.0);
meshes.add(mesh)
});
commands.spawn((
Name::new(format!("Sandy island")),
island_mesh.clone(),
sandy.clone(),
Transform::from_xyz(-30.0, -10.0, -30.0).with_scale(Vec3::new(30.0, 6.5, 30.0)),
));
}
/// Create a simple Orb.
pub fn setup_orb(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let orb_mesh = Mesh3d({
let mut mesh = Sphere::new(1.0)
.mesh()
.kind(SphereKind::Uv {
sectors: 90,
stacks: 60,
})
.build();
mesh.generate_tangents().expect("tangents");
meshes.add(mesh)
});
commands.spawn((
Name::new(format!("Orb")),
orb_mesh.clone(),
MeshMaterial3d(materials.add(Color::srgba(0.1, 0.2, 0.4, 1.0))),
Transform::from_xyz(-30.0, 10.0, -30.0),
));
}
/// Create a simple 3D camera
pub fn make_camera<'a>(
commands: &'a mut Commands,
mediums: &mut Assets<ScatteringMedium>,
_asset_server: &AssetServer,
) -> EntityCommands<'a> {
// camera
let mut cam = commands.spawn((
Camera3d::default(),
Hdr,
Transform::from_xyz(-1.2, 5.15, 0.0).looking_at(Vec3::Y * 5.0, Vec3::Y),
// Earthlike atmosphere
Atmosphere::earth(mediums.add(ScatteringMedium::earth(256, 256))),
// Can be adjusted to change the scene scale and rendering quality
AtmosphereSettings::default(),
// The directional light illuminance used in this scene
// (the one recommended for use with this feature) is
// quite bright, so raising the exposure compensation helps
// bring the scene to a nicer brightness range.
Exposure { ev100: 13.0 },
// Tonemapper chosen just because it looked good with the scene, any
// tonemapper would be fine :)
Tonemapping::AcesFitted,
// Bloom gives the sun a much more natural look.
Bloom::NATURAL,
// Enables the atmosphere to drive reflections and ambient lighting (IBL) for this view
AtmosphereEnvironmentMapLight::default(),
FreeCamera::default(),
VolumetricFog {
ambient_intensity: 0.0,
..default()
},
Msaa::Off,
Fxaa::default(),
ScreenSpaceReflections::default(),
));
#[cfg(feature = "depth_prepass")]
{
// This will write the depth buffer to a texture that you can use in the main pass
cam.insert(DepthPrepass);
}
// This is just to keep the compiler happy when not using `depth_prepass` feature.
cam.insert(Name::new("Camera"));
cam
}
/// set up a simple 3D camera
pub fn setup_camera(
mut commands: Commands,
mut mediums: ResMut<Assets<ScatteringMedium>>,
asset_server: Res<AssetServer>,
) {
make_camera(&mut commands, &mut mediums, &asset_server);
}
/// Spawn some dutch ships.
pub fn setup_ships(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn ships.
let scene = asset_server.load("models/dutch_ship_medium_1k/dutch_ship_medium_1k.gltf#Scene0");
let ship = Ship::new(-0.400, -8.0, 9.0, -2.0, 2.0);
// "Randomly" place the ships.
for x in 1..10 {
let f = (x as f32) * 2.40;
let f2 = ((x % 6) as f32) * -20.90;
commands
.spawn((
ship.clone(),
Name::new(format!("Dutch Ship {x}")),
Transform::from_xyz(-10.0 + (f * 7.8), 0.0, 30.0 + f2)
.with_rotation(Quat::from_rotation_y(f)),
))
.with_children(|parent| {
parent.spawn((
WorldAssetRoot(scene.clone()),
// Rotate ship model to line up with rotation axis.
Transform::from_rotation(Quat::from_rotation_y(std::f32::consts::FRAC_PI_2)),
));
});
}
}