module Cura::Termbox::ColorMapper

A cached map comparing a color’s rgb values with the 256 terminal color codes.

Constants

CACHE
COLOR_CODES

Public Class Methods

code(color, _number_of_colors=256) click to toggle source

Find the closest terminal color code from the given RGB values.

@param [#to_i] number_of_colors The number of colors in the code list to search. 9 is Termbox without 256 colors enabled I.E. 3-bit. @return [Integer]

# File lib/cura/termbox/color_mapper.rb, line 339
def code(color, _number_of_colors=256)
  code = CACHE[color.hex]

  if code.nil?
    # code = find_closest_code(rgb, number_of_colors)

    distances = COLOR_CODES.map { |code| code - color }
    code = distances.each_with_index.min[1]

    CACHE[color.hex] = code
  end

  code
end

Protected Class Methods

compare_rgb_array(a1, a2) click to toggle source
# File lib/cura/termbox/color_mapper.rb, line 367
def compare_rgb_array(a1, a2)
  Math.sqrt(
    (a1[0] - a2[0]).abs ^ 2 +
    (a1[1] - a2[1]).abs ^ 2 +
    (a1[2] - a2[2]).abs ^ 2
  )
end
find_closest_code(rgb, number_of_colors=256) click to toggle source
# File lib/cura/termbox/color_mapper.rb, line 356
def find_closest_code(rgb, number_of_colors=256)
  last = nil
  COLOR_CODES.first(number_of_colors).each_with_index do |color, code|
    difference = compare_rgb_array(rgb, color)

    last = { difference: difference, code: code } if last.nil? || difference < last[:difference]
  end

  last.nil? ? nil : last[:code]
end