@@ -10,7 +10,7 @@ use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, mask_terms};
1010use lightcraft_pipeline:: geometry:: SampleMode ;
1111use lightcraft_pipeline:: local:: plane_at;
1212use lightcraft_pipeline:: masks:: { AlphaCache , AlphaKeys , alpha_key} ;
13- use lightcraft_pipeline:: { Plan , RenderRequest , Rendered , SourceInfo , local} ;
13+ use lightcraft_pipeline:: { Overlay , PixelWindow , Plan , RenderRequest , Rendered , SourceInfo , local} ;
1414use lightcraft_raster:: resample:: Filter ;
1515use lightcraft_raster:: { Histogram , Plane , Rgb32f , Rgba8 } ;
1616
@@ -21,6 +21,7 @@ use crate::params::{Present, finish_block};
2121/// (as its extension). Holds the last two output sizes, like the CPU cache.
2222#[ derive( Default ) ]
2323pub struct GpuStages {
24+ airlight : lightcraft_pipeline:: airlight:: AirlightCache ,
2425 entries : Mutex < Vec < Entry > > ,
2526 /// The uploaded source (a view renders one photo at several sizes).
2627 source : Mutex < Option < ( Arc < Rgb32f > , Arc < Buf > ) > > ,
@@ -122,6 +123,7 @@ impl GpuStages {
122123 /// Drop everything (e.g. when memory is needed).
123124 pub fn clear ( & self ) {
124125 self . lock ( ) . clear ( ) ;
126+ self . airlight . clear ( ) ;
125127 * self . source . lock ( ) . unwrap_or_else ( |e| e. into_inner ( ) ) = None ;
126128 }
127129
@@ -272,10 +274,15 @@ pub(crate) fn gaussian(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, nc: usize
272274/// Resample taps of `lightcraft_raster::resample::resize`, packed for the `resize_*` kernels.
273275fn taps ( src : usize , dst : usize , filter : Filter ) -> Vec < u32 > {
274276 let w = lightcraft_raster:: resample:: weights ( src, dst, filter) ;
277+ pack_taps ( & w)
278+ }
279+
280+ fn pack_taps ( w : & [ ( usize , Vec < f32 > ) ] ) -> Vec < u32 > {
281+ let dst = w. len ( ) ;
275282 let mut t = Vec :: with_capacity ( dst * 3 ) ;
276283 let mut weights = Vec :: new ( ) ;
277284 let base = dst * 3 ;
278- for ( lo, ws) in & w {
285+ for ( lo, ws) in w {
279286 t. extend_from_slice ( & [ * lo as u32 , ws. len ( ) as u32 , ( base + weights. len ( ) ) as u32 ] ) ;
280287 weights. extend ( ws. iter ( ) . map ( |v| v. to_bits ( ) ) ) ;
281288 }
@@ -298,6 +305,19 @@ pub(crate) fn resize(cx: &mut Cx<'_>, src: &Buf, (sw, sh): (usize, usize), (dw,
298305 out
299306}
300307
308+ /// Windowed resampling uses exactly the CPU's full-frame coefficient grid.
309+ fn resize_window ( cx : & mut Cx < ' _ > , src : & Buf , ( sw, sh) : ( usize , usize ) , nc : usize , taps : & local:: ResampleTaps ) -> Buf {
310+ let [ wx, wy] = taps;
311+ let ( dw, dh) = ( wx. len ( ) , wy. len ( ) ) ;
312+ let tx = cx. gpu . upload ( & pack_taps ( wx) ) ;
313+ let tmp = cx. gpu . buffer ( dw * sh * nc) ;
314+ cx. run ( "resize_h" , & [ sw as u32 , sh as u32 , dw as u32 , nc as u32 ] , & [ Some ( src) , Some ( & tx) , Some ( & tmp) ] , groups2 ( dw, sh, [ 16 , 16 ] ) ) ;
315+ let ty = cx. gpu . upload ( & pack_taps ( wy) ) ;
316+ let out = cx. gpu . buffer ( dw * dh * nc) ;
317+ cx. run ( "resize_v" , & [ dw as u32 , sh as u32 , dh as u32 , nc as u32 ] , & [ Some ( & tmp) , Some ( & ty) , Some ( & out) ] , groups2 ( dw, dh, [ 16 , 16 ] ) ) ;
318+ out
319+ }
320+
301321/// An element-wise kernel of the `map` module over `n` items.
302322pub ( crate ) fn map ( cx : & mut Cx < ' _ > , k : & str , n : usize , extra : & [ u32 ] , ins : [ Option < & Buf > ; 3 ] , out : & Buf ) {
303323 let mut p = vec ! [ n as u32 ] ;
@@ -338,24 +358,32 @@ fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf {
338358}
339359
340360/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no median).
341- fn tone_base ( cx : & mut Cx < ' _ > , l : & Buf , w : usize , h : usize , sigma : f32 , detail : usize ) -> Buf {
361+ fn tone_base ( cx : & mut Cx < ' _ > , l : & Buf , plan : & Plan < ' _ > , sigma : f32 , detail : usize ) -> Buf {
342362 if detail == 0 {
343- return guided_fast ( cx, l, w , h , sigma, local:: BASE_EPS ) ;
363+ return guided_fast ( cx, l, plan , sigma, local:: BASE_EPS ) ;
344364 }
345- let m = median_hv ( cx, l, w, h, detail) ;
346- guided_fast ( cx, & m, w , h , sigma, local:: BASE_EPS )
365+ let m = median_hv ( cx, l, plan . w , plan . h , detail) ;
366+ guided_fast ( cx, & m, plan , sigma, local:: BASE_EPS )
347367}
348368
349369/// Fast guided filter (`local::guided_fast`): coefficients on a subsampled grid.
350- fn guided_fast ( cx : & mut Cx < ' _ > , p : & Buf , w : usize , h : usize , sigma : f32 , eps : f32 ) -> Buf {
370+ fn guided_fast ( cx : & mut Cx < ' _ > , p : & Buf , plan : & Plan < ' _ > , sigma : f32 , eps : f32 ) -> Buf {
371+ let ( w, h) = ( plan. w , plan. h ) ;
351372 let s = local:: guided_fast_step ( sigma) ;
352373 if s <= 1 {
353374 return guided ( cx, p, w, h, sigma, eps) ;
354375 }
355- let ( lw, lh) = ( w. div_ceil ( s) . max ( 1 ) , h. div_ceil ( s) . max ( 1 ) ) ;
356- let lo = resize ( cx, p, ( w, h) , ( lw, lh) , 1 , Filter :: Box ) ;
357- let ab = guided_coeffs ( cx, & lo, lw, lh, sigma / s as f32 , eps) ;
358- let up = resize ( cx, & ab, ( lw, lh) , ( w, h) , 2 , Filter :: Bilinear ) ;
376+ let up = if let Some ( grid) = local:: GuidedGrid :: for_window ( w, h, s, plan. frame . view ) {
377+ let ( lw, lh) = ( grid. down [ 0 ] . len ( ) , grid. down [ 1 ] . len ( ) ) ;
378+ let lo = resize_window ( cx, p, ( w, h) , 1 , & grid. down ) ;
379+ let ab = guided_coeffs ( cx, & lo, lw, lh, sigma / s as f32 , eps) ;
380+ resize_window ( cx, & ab, ( lw, lh) , 2 , & grid. up )
381+ } else {
382+ let ( lw, lh) = ( w. div_ceil ( s) . max ( 1 ) , h. div_ceil ( s) . max ( 1 ) ) ;
383+ let lo = resize ( cx, p, ( w, h) , ( lw, lh) , 1 , Filter :: Box ) ;
384+ let ab = guided_coeffs ( cx, & lo, lw, lh, sigma / s as f32 , eps) ;
385+ resize ( cx, & ab, ( lw, lh) , ( w, h) , 2 , Filter :: Bilinear )
386+ } ;
359387 let q = cx. gpu . buffer ( w * h) ;
360388 map ( cx, "guided_apply" , w * h, & [ ] , [ Some ( p) , Some ( & up) , None ] , & q) ;
361389 q
@@ -617,6 +645,15 @@ pub fn render(
617645 ) ;
618646 return None ;
619647 }
648+ let full = plan. needs_airlight . then ( || lightcraft_pipeline:: plan ( src, info, s, & RenderRequest { window : None , ..* req } ) ) ;
649+ // Finish the full statistic before allocating the window's device buffers.
650+ let fixed_air = full. as_ref ( ) . filter ( |full| full. lin_key != plan. lin_key ) . map ( |full| {
651+ let compute = || frame_airlight ( gpu, src, info, full) ;
652+ match stages {
653+ Some ( stages) => stages. airlight . get_or_compute ( src, full. lin_key , compute) ,
654+ None => compute ( ) ,
655+ }
656+ } ) ;
620657 let s = & * plan. settings ;
621658 let cached = stages. and_then ( |c| c. get ( src, plan. geo ) ) ;
622659 let mut host = Host :: default ( ) ;
@@ -662,7 +699,13 @@ pub fn render(
662699 } ;
663700 let mut prep = prepare ( & mut cx, & lin, & plan, req, & mut planes) ;
664701 // a window dehazes with the whole frame's airlight
665- if let Some ( a) = plan. fixed_air {
702+ if let Some ( stages) = stages
703+ && ( req. window . is_none ( ) || full. as_ref ( ) . is_some_and ( |p| p. lin_key == plan. lin_key ) )
704+ && prep. dark . is_some ( )
705+ {
706+ stages. airlight . remember ( src, plan. lin_key , prep. air ) ;
707+ }
708+ if let Some ( a) = fixed_air {
666709 prep. air = a;
667710 }
668711 lap ( "planes" , & mut t, & mut cx) ;
@@ -685,19 +728,23 @@ pub fn render(
685728 dark : prep. dark . is_some ( ) ,
686729 chroma : masks. is_some ( ) && prep. chroma . is_some ( ) ,
687730 } ;
688- let ( p, aux) = finish_block ( & fp, & terms, & present) ;
731+ let finish_keep = plan. keep . filter ( |_| req. overlay == Overlay :: None ) ;
732+ let crop = plan. keep . filter ( |_| finish_keep. is_none ( ) ) ;
733+ let output = finish_keep. unwrap_or ( PixelWindow { x : 0 , y : 0 , w, h } ) ;
734+ let out_n = output. w * output. h ;
735+ let ( p, aux) = finish_block ( & fp, & terms, & present, output) ;
689736 let aux = gpu. upload ( & aux) ;
690737 // cleared, so that work which never ran cannot pass for an image (see the check below)
691- let out = cx. zeroed ( n ) ;
738+ let out = cx. zeroed ( out_n ) ;
692739 if fault == Some ( crate :: Fault :: Validation ) {
693740 // a dispatch the device rejects (too many workgroups)
694741 cx. run ( "box_h" , & [ 0 ; 5 ] , & [ Some ( & aux) , Some ( & out) ] , [ gpu. device . limits ( ) . max_compute_workgroups_per_dimension + 1 , 1 , 1 ] ) ;
695742 }
696743 // in bands of rows: each dispatch (and submission) stays short on a slow GPU
697- let rows = ( BAND_PIXELS / w. max ( 1 ) / 16 * 16 ) . max ( 16 ) ; // whole workgroups: bands never overlap
744+ let rows = ( BAND_PIXELS / output . w . max ( 1 ) / 16 * 16 ) . max ( 16 ) ; // whole workgroups: bands never overlap
698745 let y0_at = crate :: params:: index ( "Y0" ) . unwrap_or ( 0 ) ;
699746 let mut p = p;
700- for y0 in ( 0 ..h) . step_by ( rows) . filter ( |_| fault != Some ( crate :: Fault :: DropWork ) ) {
747+ for y0 in ( 0 ..output . h ) . step_by ( rows) . filter ( |_| fault != Some ( crate :: Fault :: DropWork ) ) {
701748 p[ y0_at] = y0 as u32 ;
702749 cx. run (
703750 "main" ,
@@ -713,7 +760,7 @@ pub fn render(
713760 Some ( & aux) ,
714761 Some ( & out) ,
715762 ] ,
716- groups2 ( w, rows. min ( h - y0) , [ 16 , 16 ] ) ,
763+ groups2 ( output . w , rows. min ( output . h - y0) , [ 16 , 16 ] ) ,
717764 ) ;
718765 }
719766 // the alpha a mask overlay shows: copied out before the readback below submits
@@ -745,8 +792,8 @@ pub fn render(
745792 } else {
746793 None
747794 } ;
748- let data: Vec < [ u8 ; 4 ] > = cx. read ( & out, n ) ;
749- let image = Rgba8 { width : w, height : h, data } ;
795+ let data: Vec < [ u8 ; 4 ] > = cx. read ( & out, out_n ) ;
796+ let image = Rgba8 { width : output . w , height : output . h , data } ;
750797 lap ( "finish + readback" , & mut t, & mut cx) ;
751798 if crate :: ctx:: failed ( ) {
752799 return None ;
@@ -756,10 +803,10 @@ pub fn render(
756803 // without reporting it — issue #78's all-black exports).
757804 let unwritten = unwritten ( & image. data ) ;
758805 if unwritten > 0 {
759- fail ( FailKind :: Fatal , format ! ( "the GPU returned an incomplete image ({unwritten} of {n } pixels unwritten)" ) ) ;
806+ fail ( FailKind :: Fatal , format ! ( "the GPU returned an incomplete image ({unwritten} of {out_n } pixels unwritten)" ) ) ;
760807 return None ;
761808 }
762- let histogram = match plan . keep {
809+ let histogram = match crop {
763810 Some ( k) => Histogram :: of_srgb8 ( & image. crop ( k. x , k. y , k. w , k. h ) ) ,
764811 None => Histogram :: of_srgb8 ( & image) ,
765812 } ;
@@ -782,7 +829,7 @@ pub fn render(
782829 } ) ;
783830 lightcraft_pipeline:: visualize:: apply ( & mut image, req. overlay , & plan, overlay_mask. as_ref ( ) , all_overlay_alphas. as_deref ( ) ) ;
784831 // spots grew the window the render worked on: cut it back to the request
785- if let Some ( k) = plan . keep {
832+ if let Some ( k) = crop {
786833 image = image. crop ( k. x , k. y , k. w , k. h ) ;
787834 }
788835 Some ( Rendered { image, histogram, deep : None } )
@@ -862,6 +909,35 @@ struct Prep {
862909 air : f32 ,
863910}
864911
912+ /// Use the same geometry, linear stages, dark-channel kernel and sample selection as a
913+ /// full GPU render. If that frame exceeds device limits, its reference is the CPU fallback.
914+ fn frame_airlight ( gpu : & Gpu , src : & Arc < Rgb32f > , info : & SourceInfo , full : & Plan < ' _ > ) -> f32 {
915+ let ( w, h) = ( full. w , full. h ) ;
916+ let n = w * h;
917+ if !gpu. fits ( n * 3 ) {
918+ return lightcraft_pipeline:: airlight:: compute ( src, info, full) ;
919+ }
920+ let mut cx = Cx :: new ( gpu) ;
921+ let mut host = Host :: default ( ) ;
922+ let sampled = if gpu. fits ( src. data . len ( ) * 3 ) && !full. frame . warp . as_ref ( ) . is_some_and ( |w| w. needs_f64 ( ) ) {
923+ sample ( & mut cx, src, Arc :: new ( gpu. upload ( rgb_words ( src) ) ) , full)
924+ } else {
925+ let img = full. frame . sample ( src, w, h) ;
926+ let b = Arc :: new ( gpu. upload ( rgb_words ( & img) ) ) ;
927+ host. sampled = Some ( img) ;
928+ b
929+ } ;
930+ let lin = linear ( & mut cx, & sampled, info, full, & mut host) ;
931+ drop ( sampled) ;
932+ let d0 = cx. gpu . buffer ( n) ;
933+ map ( & mut cx, "dark_k" , n, & [ ] , [ Some ( & lin) , None , None ] , & d0) ;
934+ let dark = gaussian ( & mut cx, & d0, w, h, 1 , ( 0.02 * full. px_per_long as f32 ) . max ( 1.0 ) ) ;
935+ let m = n. div_ceil ( local:: AIRLIGHT_STEP ) ;
936+ let sub = cx. gpu . buffer ( m) ;
937+ map ( & mut cx, "subsample" , m, & [ local:: AIRLIGHT_STEP as u32 ] , [ Some ( & dark) , None , None ] , & sub) ;
938+ local:: airlight_of ( cx. read ( & sub, m) )
939+ }
940+
865941/// The spatial planes (`local::prepare`), reusing those in `planes`.
866942fn prepare ( cx : & mut Cx < ' _ > , lin : & Buf , plan : & Plan < ' _ > , req : & RenderRequest , planes : & mut Planes ) -> Prep {
867943 let ( w, h) = ( plan. w , plan. h ) ;
@@ -880,11 +956,11 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla
880956 let base = match sig. base {
881957 Some ( sg) => {
882958 let key = local:: base_key ( & plan. settings , sg, sig. base_detail ) ;
883- plane_at ( & mut planes. base , key, || tone_base ( cx, & log_l, w , h , sg, sig. base_detail ) )
959+ plane_at ( & mut planes. base , key, || tone_base ( cx, & log_l, plan , sg, sig. base_detail ) )
884960 }
885961 None => log_l. clone ( ) ,
886962 } ;
887- let clarity = sig. clarity . map ( |sg| plane_at ( & mut planes. clarity , sg. to_bits ( ) , || guided_fast ( cx, & log_l, w , h , sg, local:: CLARITY_EPS ) ) ) ;
963+ let clarity = sig. clarity . map ( |sg| plane_at ( & mut planes. clarity , sg. to_bits ( ) , || guided_fast ( cx, & log_l, plan , sg, local:: CLARITY_EPS ) ) ) ;
888964 let texture = sig. texture . map ( |sg| plane_at ( & mut planes. texture , sg. to_bits ( ) , || gaussian ( cx, & log_l, w, h, 1 , sg) ) ) ;
889965 let ( dark, air) = match sig. dark {
890966 None => ( None , 1.0 ) ,
0 commit comments