forked from processing/processing4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
284 lines (248 loc) · 9.07 KB
/
lib.rs
File metadata and controls
284 lines (248 loc) · 9.07 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
pub mod error;
use crate::error::Result;
use bevy::app::{App, AppExit};
use bevy::log::tracing_subscriber;
use bevy::prelude::*;
use bevy::window::{RawHandleWrapper, Window, WindowRef, WindowResolution, WindowWrapper};
use raw_window_handle::{
DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
RawWindowHandle, WindowHandle,
};
use std::cell::RefCell;
use std::num::NonZero;
use std::sync::atomic::AtomicU32;
use std::sync::OnceLock;
use bevy::camera::RenderTarget;
use bevy::camera::visibility::RenderLayers;
use tracing::debug;
static IS_INIT: OnceLock<()> = OnceLock::new();
static WINDOW_COUNT: AtomicU32 = AtomicU32::new(0);
thread_local! {
static APP: OnceLock<RefCell<App>> = OnceLock::default();
}
fn app<T>(cb: impl FnOnce(&App) -> Result<T>) -> Result<T> {
let res = APP.with(|app_lock| {
let app = app_lock
.get()
.ok_or_else(|| error::ProcessingError::AppAccess)?
.borrow();
cb(&app)
})?;
Ok(res)
}
fn app_mut<T>(cb: impl FnOnce(&mut App) -> Result<T>) -> Result<T> {
let res = APP.with(|app_lock| {
let mut app = app_lock
.get()
.ok_or_else(|| error::ProcessingError::AppAccess)?
.borrow_mut();
cb(&mut app)
})?;
Ok(res)
}
struct GlfwWindow {
window_handle: RawWindowHandle,
display_handle: RawDisplayHandle,
}
// SAFETY:
// - RawWindowHandle and RawDisplayHandle are just pointers
// - The actual window is managed by Java and outlives this struct
// - GLFW is thread-safe-ish, see https://www.glfw.org/faq#29---is-glfw-thread-safe
//
// Note: we enforce that all calls to init/update/exit happen on the main thread, so
// there should be no concurrent access to the window from multiple threads anyway.
unsafe impl Send for GlfwWindow {}
unsafe impl Sync for GlfwWindow {}
impl HasWindowHandle for GlfwWindow {
fn window_handle(&self) -> core::result::Result<WindowHandle<'_>, HandleError> {
// SAFETY:
// - Handles passed from Java are valid
Ok(unsafe { WindowHandle::borrow_raw(self.window_handle) })
}
}
impl HasDisplayHandle for GlfwWindow {
fn display_handle(&self) -> core::result::Result<DisplayHandle<'_>, HandleError> {
// SAFETY:
// - Handles passed from Java are valid
Ok(unsafe { DisplayHandle::borrow_raw(self.display_handle) })
}
}
/// Create a WebGPU surface from a native window handle.
///
/// Currently, this just creates a bevy window with the given parameters and
/// stores the raw window handle for later use by the renderer, which will
/// actually create the surface.
pub fn create_surface(
window_handle: u64,
width: u32,
height: u32,
scale_factor: f32,
) -> Result<u64> {
#[cfg(target_os = "macos")]
let (raw_window_handle, raw_display_handle) = {
use raw_window_handle::{AppKitDisplayHandle, AppKitWindowHandle};
// GLFW gives us NSWindow*, but AppKitWindowHandle needs NSView*
// so we have to do some objc magic to grab the right pointer
let ns_view_ptr = {
use objc2::rc::Retained;
use objc2_app_kit::{NSView, NSWindow};
// SAFETY:
// - window_handle is a valid NSWindow pointer from the GLFW window
let ns_window = window_handle as *mut NSWindow;
if ns_window.is_null() {
return Err(error::ProcessingError::InvalidWindowHandle);
}
// SAFETY:
// - The contentView is owned by NSWindow and remains valid as long as the window exists
let ns_window_ref = unsafe { &*ns_window };
let content_view: Option<Retained<NSView>> = ns_window_ref.contentView();
match content_view {
Some(view) => {
let view_ptr = Retained::as_ptr(&view) as *mut std::ffi::c_void;
view_ptr
}
None => {
return Err(error::ProcessingError::InvalidWindowHandle);
}
}
};
let window = AppKitWindowHandle::new(std::ptr::NonNull::new(ns_view_ptr).unwrap());
let display = AppKitDisplayHandle::new();
(
RawWindowHandle::AppKit(window),
RawDisplayHandle::AppKit(display),
)
};
#[cfg(target_os = "windows")]
let (raw_window_handle, raw_display_handle) =
{ todo!("implemnt windows raw window handle conversion") };
#[cfg(target_os = "linux")]
let (raw_window_handle, raw_display_handle) =
{ todo!("implement linux raw window handle conversion") };
let glfw_window = GlfwWindow {
window_handle: raw_window_handle,
display_handle: raw_display_handle,
};
let window_wrapper = WindowWrapper::new(glfw_window);
let handle_wrapper = RawHandleWrapper::new(&window_wrapper)?;
let entity_id = app_mut(|app| {
let mut window = app
.world_mut()
.spawn((
Window {
resolution: WindowResolution::new(width, height)
.with_scale_factor_override(scale_factor),
..default()
},
handle_wrapper,
));
let count = WINDOW_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let render_layer = RenderLayers::none().with(count as usize);
let window_entity = window.id();
window.with_children(|parent| {
parent.spawn((
Camera3d::default(),
Camera {
target: RenderTarget::Window(WindowRef::Entity(window_entity)),
..default()
},
Projection::Orthographic(OrthographicProjection::default_3d()),
render_layer,
));
});
Ok(window_entity.to_bits())
})?;
Ok(entity_id)
}
pub fn destroy_surface(window_entity: Entity) -> Result<()>{
app_mut(|app| {
if app.world_mut().get::<Window>(window_entity).is_some() {
app.world_mut().despawn(window_entity);
WINDOW_COUNT.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
Ok(())
})
}
/// Update window size when resized.
pub fn resize_surface(window_entity: Entity, width: u32, height: u32) -> Result<()> {
app_mut(|app| {
if let Some(mut window) = app.world_mut().get_mut::<Window>(window_entity) {
window.resolution.set_physical_resolution(width, height);
Ok(())
} else {
Err(error::ProcessingError::WindowNotFound)
}
})
}
/// Initialize the app, if not already initialized. Must be called from the main thread and cannot
/// be called concurrently from multiple threads.
pub fn init() -> Result<()> {
setup_tracing()?;
let is_init = IS_INIT.get().is_some();
let thread_has_app = APP.with(|app_lock| app_lock.get().is_some());
if is_init && !thread_has_app {
return Err(error::ProcessingError::AppAccess);
}
if is_init && thread_has_app {
debug!("App already initialized");
return Ok(());
}
APP.with(|app_lock| {
app_lock.get_or_init(|| {
IS_INIT.get_or_init(|| ());
let mut app = App::new();
app.add_plugins(
DefaultPlugins
.build()
.disable::<bevy::log::LogPlugin>()
.disable::<bevy::winit::WinitPlugin>()
.disable::<bevy::render::pipelined_rendering::PipelinedRenderingPlugin>()
.set(WindowPlugin {
primary_window: None,
exit_condition: bevy::window::ExitCondition::DontExit,
..default()
}),
);
// this does not mean, as one might imagine, that the app is "done", but rather is part
// of bevy's plugin lifecycle prior to "starting" the app. we are manually driving the app
// so we don't need to call `app.run()`
app.finish();
app.cleanup();
RefCell::new(app)
});
});
Ok(())
}
pub fn update() -> Result<()> {
app_mut(|app| {
app.update();
Ok(())
})
}
pub fn exit(exit_code: u8) -> Result<()> {
app_mut(|app| {
app.world_mut().write_message(match exit_code {
0 => AppExit::Success,
_ => AppExit::Error(NonZero::new(exit_code).unwrap()),
});
// one final update to process the exit message
app.update();
Ok(())
})
}
pub fn background_color(window_entity: Entity, color: Color) -> Result<()> {
app_mut(|app| {
let mut camera_query = app.world_mut().query::<(&mut Camera, &ChildOf)>();
for (mut camera, parent) in camera_query.iter_mut(&mut app.world_mut()) {
if parent.parent() == window_entity {
camera.clear_color = ClearColorConfig::Custom(color);
}
}
Ok(())
})
}
fn setup_tracing() -> Result<()> {
let subscriber = tracing_subscriber::FmtSubscriber::new();
tracing::subscriber::set_global_default(subscriber)?;
Ok(())
}