forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB055a94dIvan Molodetskikh1 year ago2247 commits

shader_element.rs543 lines, 19.2 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::ffi::CString;
3use std::rc::Rc;
4
5use glam::{Mat3, Vec2};
6use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
7use smithay::backend::renderer::gles::{
8 ffi, link_program, Capability, GlesError, GlesFrame, GlesRenderer, GlesTexture, Uniform,
9 UniformDesc, UniformName,
10};
11use smithay::backend::renderer::utils::{CommitCounter, OpaqueRegions};
12use smithay::backend::renderer::DebugFlags;
13use smithay::utils::{Buffer, Logical, Physical, Point, Rectangle, Scale, Size};
14
15use super::renderer::AsGlesFrame;
16use super::resources::Resources;
17use super::shaders::{ProgramType, Shaders};
18use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
19
20/// Renders a shader with optional texture input, on the primary GPU.
21#[derive(Debug, Clone)]
22pub struct ShaderRenderElement {
23 program: ProgramType,
24 id: Id,
25 commit_counter: CommitCounter,
26 area: Rectangle<f64, Logical>,
27 opaque_regions: Vec<Rectangle<f64, Logical>>,
28 // Should only be used for visual improvements, i.e. corner radius anti-aliasing.
29 scale: f32,
30 alpha: f32,
31 additional_uniforms: Vec<Uniform<'static>>,
32 textures: HashMap<String, GlesTexture>,
33 kind: Kind,
34}
35
36#[derive(Debug, Clone)]
37pub struct ShaderProgram(Rc<ShaderProgramInner>);
38
39#[derive(Debug)]
40struct ShaderProgramInner {
41 normal: ShaderProgramInternal,
42 debug: ShaderProgramInternal,
43 uniform_tint: ffi::types::GLint,
44}
45
46#[derive(Debug)]
47struct ShaderProgramInternal {
48 program: ffi::types::GLuint,
49 uniform_tex_matrix: ffi::types::GLint,
50 uniform_matrix: ffi::types::GLint,
51 uniform_size: ffi::types::GLint,
52 uniform_scale: ffi::types::GLint,
53 uniform_alpha: ffi::types::GLint,
54 attrib_vert: ffi::types::GLint,
55 attrib_vert_position: ffi::types::GLint,
56 additional_uniforms: HashMap<String, UniformDesc>,
57 texture_uniforms: HashMap<String, ffi::types::GLint>,
58}
59
60impl PartialEq for ShaderProgram {
61 fn eq(&self, other: &Self) -> bool {
62 Rc::ptr_eq(&self.0, &other.0)
63 }
64}
65
66unsafe fn compile_program(
67 gl: &ffi::Gles2,
68 src: &str,
69 additional_uniforms: &[UniformName<'_>],
70 texture_uniforms: &[&str],
71 // destruction_callback_sender: Sender<CleanupResource>,
72) -> Result<ShaderProgram, GlesError> {
73 let shader = format!("#version 100\n{src}");
74 let program = unsafe { link_program(gl, include_str!("shaders/texture.vert"), &shader)? };
75 let debug_shader = format!("#version 100\n#define DEBUG_FLAGS\n{src}");
76 let debug_program =
77 unsafe { link_program(gl, include_str!("shaders/texture.vert"), &debug_shader)? };
78
79 let vert = c"vert";
80 let vert_position = c"vert_position";
81 let matrix = c"matrix";
82 let tex_matrix = c"tex_matrix";
83 let size = c"niri_size";
84 let scale = c"niri_scale";
85 let alpha = c"niri_alpha";
86 let tint = c"niri_tint";
87
88 Ok(ShaderProgram(Rc::new(ShaderProgramInner {
89 normal: ShaderProgramInternal {
90 program,
91 uniform_matrix: gl.GetUniformLocation(program, matrix.as_ptr()),
92 uniform_tex_matrix: gl.GetUniformLocation(program, tex_matrix.as_ptr()),
93 uniform_size: gl.GetUniformLocation(program, size.as_ptr()),
94 uniform_scale: gl.GetUniformLocation(program, scale.as_ptr()),
95 uniform_alpha: gl.GetUniformLocation(program, alpha.as_ptr()),
96 attrib_vert: gl.GetAttribLocation(program, vert.as_ptr()),
97 attrib_vert_position: gl.GetAttribLocation(program, vert_position.as_ptr()),
98 additional_uniforms: additional_uniforms
99 .iter()
100 .map(|uniform| {
101 let name =
102 CString::new(uniform.name.as_bytes()).expect("Interior null in name");
103 let location = gl.GetUniformLocation(program, name.as_ptr());
104 (
105 uniform.name.clone().into_owned(),
106 UniformDesc {
107 location,
108 type_: uniform.type_,
109 },
110 )
111 })
112 .collect(),
113 texture_uniforms: texture_uniforms
114 .iter()
115 .map(|name_| {
116 let name = CString::new(name_.as_bytes()).expect("Interior null in name");
117 let location = gl.GetUniformLocation(program, name.as_ptr());
118 (name_.to_string(), location)
119 })
120 .collect(),
121 },
122 debug: ShaderProgramInternal {
123 program: debug_program,
124 uniform_matrix: gl.GetUniformLocation(debug_program, matrix.as_ptr()),
125 uniform_tex_matrix: gl.GetUniformLocation(debug_program, tex_matrix.as_ptr()),
126 uniform_size: gl.GetUniformLocation(debug_program, size.as_ptr()),
127 uniform_scale: gl.GetUniformLocation(debug_program, scale.as_ptr()),
128 uniform_alpha: gl.GetUniformLocation(debug_program, alpha.as_ptr()),
129 attrib_vert: gl.GetAttribLocation(debug_program, vert.as_ptr()),
130 attrib_vert_position: gl.GetAttribLocation(debug_program, vert_position.as_ptr()),
131 additional_uniforms: additional_uniforms
132 .iter()
133 .map(|uniform| {
134 let name =
135 CString::new(uniform.name.as_bytes()).expect("Interior null in name");
136 let location = gl.GetUniformLocation(debug_program, name.as_ptr());
137 (
138 uniform.name.clone().into_owned(),
139 UniformDesc {
140 location,
141 type_: uniform.type_,
142 },
143 )
144 })
145 .collect(),
146 texture_uniforms: texture_uniforms
147 .iter()
148 .map(|name_| {
149 let name = CString::new(name_.as_bytes()).expect("Interior null in name");
150 let location = gl.GetUniformLocation(debug_program, name.as_ptr());
151 (name_.to_string(), location)
152 })
153 .collect(),
154 },
155 uniform_tint: gl.GetUniformLocation(debug_program, tint.as_ptr()),
156 })))
157}
158
159impl ShaderProgram {
160 pub fn compile(
161 renderer: &mut GlesRenderer,
162 src: &str,
163 additional_uniforms: &[UniformName<'_>],
164 texture_uniforms: &[&str],
165 ) -> Result<Self, GlesError> {
166 renderer.with_context(move |gl| unsafe {
167 compile_program(gl, src, additional_uniforms, texture_uniforms)
168 })?
169 }
170
171 pub fn destroy(self, renderer: &mut GlesRenderer) -> Result<(), GlesError> {
172 renderer.with_context(move |gl| unsafe {
173 gl.DeleteProgram(self.0.normal.program);
174 gl.DeleteProgram(self.0.debug.program);
175 })
176 }
177}
178
179impl ShaderRenderElement {
180 #[allow(clippy::too_many_arguments)]
181 pub fn new(
182 program: ProgramType,
183 size: Size<f64, Logical>,
184 opaque_regions: Option<Vec<Rectangle<f64, Logical>>>,
185 // Should only be used for visual improvements, i.e. corner radius anti-aliasing.
186 scale: f32,
187 alpha: f32,
188 additional_uniforms: Vec<Uniform<'static>>,
189 textures: HashMap<String, GlesTexture>,
190 kind: Kind,
191 ) -> Self {
192 Self {
193 program,
194 id: Id::new(),
195 commit_counter: CommitCounter::default(),
196 area: Rectangle::from_size(size),
197 opaque_regions: opaque_regions.unwrap_or_default(),
198 scale,
199 alpha,
200 additional_uniforms,
201 textures,
202 kind,
203 }
204 }
205
206 pub fn empty(program: ProgramType, kind: Kind) -> Self {
207 Self {
208 program,
209 id: Id::new(),
210 commit_counter: CommitCounter::default(),
211 area: Rectangle::default(),
212 opaque_regions: vec![],
213 scale: 1.,
214 alpha: 1.,
215 additional_uniforms: vec![],
216 textures: HashMap::new(),
217 kind,
218 }
219 }
220
221 pub fn damage_all(&mut self) {
222 self.commit_counter.increment();
223 }
224
225 pub fn update(
226 &mut self,
227 size: Size<f64, Logical>,
228 opaque_regions: Option<Vec<Rectangle<f64, Logical>>>,
229 scale: f32,
230 alpha: f32,
231 uniforms: Vec<Uniform<'static>>,
232 textures: HashMap<String, GlesTexture>,
233 ) {
234 self.area.size = size;
235 self.opaque_regions = opaque_regions.unwrap_or_default();
236 self.scale = scale;
237 self.alpha = alpha;
238 self.additional_uniforms = uniforms;
239 self.textures = textures;
240
241 self.commit_counter.increment();
242 }
243
244 pub fn with_location(mut self, location: Point<f64, Logical>) -> Self {
245 self.area.loc = location;
246 self
247 }
248
249 pub fn with_alpha(mut self, alpha: f32) -> Self {
250 self.alpha = alpha;
251 self
252 }
253}
254
255impl Element for ShaderRenderElement {
256 fn id(&self) -> &Id {
257 &self.id
258 }
259
260 fn current_commit(&self) -> CommitCounter {
261 self.commit_counter
262 }
263
264 fn src(&self) -> Rectangle<f64, Buffer> {
265 Rectangle::from_size(Size::from((1., 1.)))
266 }
267
268 fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
269 self.area.to_physical_precise_round(scale)
270 }
271
272 fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
273 self.opaque_regions
274 .iter()
275 .map(|region| region.to_physical_precise_down(scale))
276 .collect()
277 }
278
279 fn alpha(&self) -> f32 {
280 self.alpha
281 }
282
283 fn kind(&self) -> Kind {
284 self.kind
285 }
286}
287
288impl RenderElement<GlesRenderer> for ShaderRenderElement {
289 fn draw(
290 &self,
291 frame: &mut GlesFrame<'_, '_>,
292 src: Rectangle<f64, Buffer>,
293 dest: Rectangle<i32, Physical>,
294 damage: &[Rectangle<i32, Physical>],
295 _opaque_regions: &[Rectangle<i32, Physical>],
296 ) -> Result<(), GlesError> {
297 let frame = frame.as_gles_frame();
298
299 let Some(shader) = Shaders::get_from_frame(frame).program(self.program) else {
300 return Ok(());
301 };
302
303 let Some(resources) = Resources::get(frame) else {
304 return Ok(());
305 };
306 let mut resources = resources.borrow_mut();
307
308 let supports_instancing = frame.capabilities().contains(&Capability::Instancing);
309
310 // prepare the vertices
311 resources.vertices.clear();
312 if supports_instancing {
313 resources.vertices.extend(damage.iter().flat_map(|rect| {
314 let dest_size = dest.size;
315
316 let rect_constrained_loc = rect
317 .loc
318 .constrain(Rectangle::from_extremities((0, 0), dest_size.to_point()));
319 let rect_clamped_size = rect.size.clamp(
320 (0, 0),
321 (dest_size.to_point() - rect_constrained_loc).to_size(),
322 );
323
324 let rect = Rectangle::new(rect_constrained_loc, rect_clamped_size);
325 [
326 rect.loc.x as f32,
327 rect.loc.y as f32,
328 rect.size.w as f32,
329 rect.size.h as f32,
330 ]
331 }));
332 } else {
333 resources.vertices.extend(damage.iter().flat_map(|rect| {
334 let dest_size = dest.size;
335
336 let rect_constrained_loc = rect
337 .loc
338 .constrain(Rectangle::from_extremities((0, 0), dest_size.to_point()));
339 let rect_clamped_size = rect.size.clamp(
340 (0, 0),
341 (dest_size.to_point() - rect_constrained_loc).to_size(),
342 );
343
344 let rect = Rectangle::new(rect_constrained_loc, rect_clamped_size);
345 // Add the 4 f32s per damage rectangle for each of the 6 vertices.
346 (0..6).flat_map(move |_| {
347 [
348 rect.loc.x as f32,
349 rect.loc.y as f32,
350 rect.size.w as f32,
351 rect.size.h as f32,
352 ]
353 })
354 }));
355 }
356
357 if resources.vertices.is_empty() {
358 return Ok(());
359 }
360
361 // dest position and scale
362 let mut matrix = Mat3::from_translation(Vec2::new(dest.loc.x as f32, dest.loc.y as f32));
363
364 let scale = src.size.to_f64() / dest.size.to_f64();
365 let tex_matrix = Mat3::from_scale(Vec2::new(scale.x as f32, scale.y as f32));
366 let tex_matrix =
367 Mat3::from_translation(Vec2::new(src.loc.x as f32, src.loc.y as f32)) * tex_matrix;
368
369 //apply output transformation
370 matrix = Mat3::from_cols_array(frame.projection()) * matrix;
371
372 let has_debug = !frame.debug_flags().is_empty();
373 let has_tint = frame.debug_flags().contains(DebugFlags::TINT);
374
375 // render
376 frame.with_context(move |gl| -> Result<(), GlesError> {
377 let program = if has_debug {
378 &shader.0.debug
379 } else {
380 &shader.0.normal
381 };
382
383 unsafe {
384 for (i, texture) in self.textures.values().enumerate() {
385 gl.ActiveTexture(ffi::TEXTURE0 + i as u32);
386 gl.BindTexture(ffi::TEXTURE_2D, texture.tex_id());
387 gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MIN_FILTER, ffi::LINEAR as i32);
388 gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MAG_FILTER, ffi::LINEAR as i32);
389 gl.TexParameteri(
390 ffi::TEXTURE_2D,
391 ffi::TEXTURE_WRAP_S,
392 ffi::CLAMP_TO_BORDER as i32,
393 );
394 gl.TexParameteri(
395 ffi::TEXTURE_2D,
396 ffi::TEXTURE_WRAP_T,
397 ffi::CLAMP_TO_BORDER as i32,
398 );
399 }
400
401 gl.UseProgram(program.program);
402
403 for (i, name) in self.textures.keys().enumerate() {
404 gl.Uniform1i(program.texture_uniforms[name], i as i32);
405 }
406
407 gl.UniformMatrix3fv(
408 program.uniform_matrix,
409 1,
410 ffi::FALSE,
411 matrix.as_ref().as_ptr(),
412 );
413 gl.UniformMatrix3fv(
414 program.uniform_tex_matrix,
415 1,
416 ffi::FALSE,
417 tex_matrix.as_ref().as_ptr(),
418 );
419 gl.Uniform2f(program.uniform_size, dest.size.w as f32, dest.size.h as f32);
420 gl.Uniform1f(program.uniform_scale, self.scale);
421 gl.Uniform1f(program.uniform_alpha, self.alpha);
422
423 let tint = if has_tint { 1.0f32 } else { 0.0f32 };
424 if has_debug {
425 gl.Uniform1f(shader.0.uniform_tint, tint);
426 }
427
428 for uniform in &self.additional_uniforms {
429 let desc =
430 program
431 .additional_uniforms
432 .get(&*uniform.name)
433 .ok_or_else(|| {
434 GlesError::UnknownUniform(uniform.name.clone().into_owned())
435 })?;
436 uniform.value.set(gl, desc)?;
437 }
438
439 gl.EnableVertexAttribArray(program.attrib_vert as u32);
440 gl.BindBuffer(ffi::ARRAY_BUFFER, resources.vbos[0]);
441 gl.VertexAttribPointer(
442 program.attrib_vert as u32,
443 2,
444 ffi::FLOAT,
445 ffi::FALSE,
446 0,
447 std::ptr::null(),
448 );
449
450 // vert_position
451 gl.EnableVertexAttribArray(program.attrib_vert_position as u32);
452 gl.BindBuffer(ffi::ARRAY_BUFFER, resources.vbos[1]);
453 gl.BufferData(
454 ffi::ARRAY_BUFFER,
455 (std::mem::size_of::<ffi::types::GLfloat>() * resources.vertices.len())
456 as isize,
457 resources.vertices.as_ptr() as *const _,
458 ffi::STREAM_DRAW,
459 );
460
461 gl.VertexAttribPointer(
462 program.attrib_vert_position as u32,
463 4,
464 ffi::FLOAT,
465 ffi::FALSE,
466 0,
467 std::ptr::null(),
468 );
469
470 let damage_len = damage.len() as i32;
471 if supports_instancing {
472 gl.VertexAttribDivisor(program.attrib_vert as u32, 0);
473 gl.VertexAttribDivisor(program.attrib_vert_position as u32, 1);
474 gl.DrawArraysInstanced(ffi::TRIANGLE_STRIP, 0, 4, damage_len);
475 } else {
476 // When we have more than 10 rectangles, draw them in batches of 10.
477 for i in 0..(damage_len - 1) / 10 {
478 gl.DrawArrays(ffi::TRIANGLES, 0, 6);
479
480 // Set damage pointer to the next 10 rectangles.
481 let offset =
482 (i + 1) as usize * 6 * 4 * std::mem::size_of::<ffi::types::GLfloat>();
483 gl.VertexAttribPointer(
484 program.attrib_vert_position as u32,
485 4,
486 ffi::FLOAT,
487 ffi::FALSE,
488 0,
489 offset as *const _,
490 );
491 }
492
493 // Draw the up to 10 remaining rectangles.
494 let count = ((damage_len - 1) % 10 + 1) * 6;
495 gl.DrawArrays(ffi::TRIANGLES, 0, count);
496 }
497
498 gl.BindBuffer(ffi::ARRAY_BUFFER, 0);
499 gl.BindTexture(ffi::TEXTURE_2D, 0);
500 gl.ActiveTexture(ffi::TEXTURE0);
501 gl.BindTexture(ffi::TEXTURE_2D, 0);
502 gl.DisableVertexAttribArray(program.attrib_vert as u32);
503 gl.DisableVertexAttribArray(program.attrib_vert_position as u32);
504 }
505
506 Ok(())
507 })??;
508
509 Ok(())
510 }
511
512 fn underlying_storage(&self, _renderer: &mut GlesRenderer) -> Option<UnderlyingStorage> {
513 // If scanout for things other than Wayland buffers is implemented, this will need to take
514 // the target GPU into account.
515 None
516 }
517}
518
519impl<'render> RenderElement<TtyRenderer<'render>> for ShaderRenderElement {
520 fn draw(
521 &self,
522 frame: &mut TtyFrame<'_, '_, '_>,
523 src: Rectangle<f64, Buffer>,
524 dst: Rectangle<i32, Physical>,
525 damage: &[Rectangle<i32, Physical>],
526 opaque_regions: &[Rectangle<i32, Physical>],
527 ) -> Result<(), TtyRendererError<'render>> {
528 let frame = frame.as_gles_frame();
529
530 RenderElement::<GlesRenderer>::draw(self, frame, src, dst, damage, opaque_regions)?;
531
532 Ok(())
533 }
534
535 fn underlying_storage(
536 &self,
537 _renderer: &mut TtyRenderer<'render>,
538 ) -> Option<UnderlyingStorage> {
539 // If scanout for things other than Wayland buffers is implemented, this will need to take
540 // the target GPU into account.
541 None
542 }
543}