1
+ use std:: f64:: consts:: PI ;
2
+ use std:: time:: Instant ;
3
+ use rayon:: prelude:: * ;
4
+ use softbuffer:: GraphicsContext ;
5
+ use winit:: event:: { Event , WindowEvent } ;
6
+ use winit:: event_loop:: { ControlFlow , EventLoop } ;
7
+ use winit:: window:: WindowBuilder ;
8
+
9
+ fn main ( ) {
10
+ let event_loop = EventLoop :: new ( ) ;
11
+ let window = WindowBuilder :: new ( ) . build ( & event_loop) . unwrap ( ) ;
12
+ let mut graphics_context = unsafe { GraphicsContext :: new ( window) } . unwrap ( ) ;
13
+
14
+ let mut old_size = ( 0 , 0 ) ;
15
+ let mut frames = pre_render_frames ( 0 , 0 ) ;
16
+
17
+ let start = Instant :: now ( ) ;
18
+ event_loop. run ( move |event, _, control_flow| {
19
+ * control_flow = ControlFlow :: Poll ;
20
+
21
+ match event {
22
+ Event :: RedrawRequested ( window_id) if window_id == graphics_context. window ( ) . id ( ) => {
23
+ let elapsed = start. elapsed ( ) . as_secs_f64 ( ) % 1.0 ;
24
+ let ( width, height) = {
25
+ let size = graphics_context. window ( ) . inner_size ( ) ;
26
+ ( size. width , size. height )
27
+ } ;
28
+
29
+ if ( width, height) != old_size{
30
+ old_size = ( width, height) ;
31
+ frames = pre_render_frames ( width as usize , height as usize ) ;
32
+ } ;
33
+
34
+ let buffer = & frames[ ( ( elapsed* 60.0 ) . round ( ) as usize ) . clamp ( 0 , 59 ) ] ;
35
+ graphics_context. set_buffer ( buffer. as_slice ( ) , width as u16 , height as u16 ) ;
36
+ }
37
+ Event :: MainEventsCleared => {
38
+ graphics_context. window ( ) . request_redraw ( ) ;
39
+ }
40
+ Event :: WindowEvent {
41
+ event : WindowEvent :: CloseRequested ,
42
+ window_id,
43
+ } if window_id == graphics_context. window ( ) . id ( ) => {
44
+ * control_flow = ControlFlow :: Exit ;
45
+ }
46
+ _ => { }
47
+ }
48
+ } ) ;
49
+ }
50
+
51
+ fn pre_render_frames ( width : usize , height : usize ) -> Vec < Vec < u32 > > {
52
+ ( 0 ..60 ) . into_par_iter ( ) . map ( |frame_id|{
53
+ let elapsed = ( ( frame_id as f64 ) /( 60.0 ) ) * 2.0 * PI ;
54
+ let buffer = ( 0 ..( ( width * height) as usize ) )
55
+ . map ( |index| {
56
+ let y = ( ( index / ( width as usize ) ) as f64 ) /( height as f64 ) ;
57
+ let x = ( ( index % ( width as usize ) ) as f64 ) /( width as f64 ) ;
58
+ let red = ( ( ( ( y + elapsed) . sin ( ) * 0.5 +0.5 ) * 255.0 ) . round ( ) as u32 ) . clamp ( 0 , 255 ) ;
59
+ let green = ( ( ( ( x + elapsed) . sin ( ) * 0.5 +0.5 ) * 255.0 ) . round ( ) as u32 ) . clamp ( 0 , 255 ) ;
60
+ let blue = ( ( ( ( y - elapsed) . cos ( ) * 0.5 +0.5 ) * 255.0 ) . round ( ) as u32 ) . clamp ( 0 , 255 ) ;
61
+
62
+ let color = blue | ( green << 8 ) | ( red << 16 ) ;
63
+
64
+ color
65
+ } )
66
+ . collect :: < Vec < _ > > ( ) ;
67
+
68
+ buffer
69
+ } ) . collect ( )
70
+ }
0 commit comments