Debian Codegraph @

bin/term_plasma

raw symbols SCIP
1 #!/usr/bin/env ruby
2
3 require 'tins/go'
4 include Tins::GO
5 require 'term/ansicolor'
6 include Term::ANSIColor
7 Term::ANSIColor.true_coloring = ENV['COLORTERM'] =~ /\A(truecolor|24bit)\z/
8 include Math
9
10 # Generates a palette of 256 colors based on sine waves
11 #
12 # @return [Array<Array<Integer>>] An array of arrays, each containing
13 # three integers representing the RGB values of a color.
14 def generate_palette
15 (0..255).map { |i|
16 [
17 128 + 128 * sin(PI * i / 32.0),
18 128 + 128 * sin(PI * i / 64.0),
19 128 + 128 * sin(PI * i / 128.0),
20 ].map { _1.clamp(0, 255).round }
21 }
22 end
23
24 # Resets the terminal to its original state, and assigns width $w and height
25 # $h.
26 def full_reset
27 $w, $h = Tins::Terminal.cols, Tins::Terminal.lines
28 $h *= 2
29 print reset, clear_screen, move_home, hide_cursor
30 end
31
32 # Generates a screen based on a plasma.
33 #
34 # @param plasma [Array<Array<Integer>>] An array of arrays, each containing
35 # three integers representing the RGB values of a color.
36 # @return [String] The string representation of the screen, each character
37 # representing a pixel on the screen with the corresponding color.
38 def generate_screen(plasma)
39 screen = ''
40 0.step($h - 1, 2) do |y|
41 0.upto($w - 1) do |x|
42 screen << color(plasma[y][x]) + on_color(plasma[y + 1][x]) + ?▀
43 end
44 end
45 screen
46 end
47
48 # Generates a plasma generated based on sine waves
49 #
50 # @param now [Float] A value based on the current time in seconds
51 # @return [Array<Array<Integer>>] An array of arrays, each containing
52 # three integers representing the RGB values of a color.
53 def generate_plasma(now)
54 plasma = Array.new($h) { [ nil ] * $w }
55 0.upto($h - 1) do |y|
56 0.upto($w - 1) do |x|
57 x, y = x.to_f, y.to_f
58 color = (
59 128.0 + (128.0 * sin((x / 7.0) - 3.0 * cos(now / 2.0))) +
60 128.0 + (128.0 * sin((y / 13.0) - 2.0 * sin(now))) +
61 128.0 + (128.0 * sin(hypot((x - $w / 3.0), (y - $h / 2.0)) / 5.0)) +
62 128.0 + (128.0 * sin((hypot(x, y) / 5.0) - sin(now / 3.0)))
63 ) / 4.0
64 plasma[y][x] = $palette[(color + now).round % $palette.size]
65 end
66 end
67 plasma
68 end
69
70 $opts = go('n:')
71
72 $palette = generate_palette
73
74 begin
75 $full_reset = true
76 trap(:SIGWINCH) { $full_reset = true }
77
78 loop do
79 if $full_reset
80 $full_reset = false
81 full_reset
82 end
83
84 now = Time.now.to_f / ($opts[?n]&.to_f || 1)
85 plasma = generate_plasma(now)
86 print move_home, generate_screen(plasma), reset
87
88 if n = $opts[?n]&.to_f
89 sleep n
90 else
91 print move_to_column(1), erase_in_line, show_cursor
92 exit
93 end
94 end
95 rescue Interrupt
96 print reset, clear_screen, move_home, show_cursor
97 end