forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

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