1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15
16 #include <math.h>
17 #include <stdint.h>
18
19 #include <cinttypes>
20 #include <cstdint>
21
22 namespace pw::display {
23
24 /// Base type for pixels in RGBA8888 format.
25 using ColorRgba8888 = uint32_t;
26
27 /// Base type for pixels in RGB565 format.
28 using ColorRgb565 = uint16_t;
29
30 /// @defgroup pw_display_color
31 /// Color conversion functions used by the pw_display draw library and
32 /// tests.
33 /// @{
34
35 /// Encode an RGB565 value from individual red, green, blue and alpha
36 /// values.
37 ///
38 /// This will introduce some loss in color as values are mapped from 8
39 /// bits per color down to 5 for red, 6 for green, and 5 for blue.
EncodeRgb565(uint8_t r,uint8_t g,uint8_t b)40 constexpr ColorRgb565 EncodeRgb565(uint8_t r, uint8_t g, uint8_t b) {
41 return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xF8) >> 3);
42 }
43
44 /// Encode an RGBA8888 value into RGB565.
EncodeRgb565(ColorRgba8888 rgba8888)45 constexpr ColorRgb565 EncodeRgb565(ColorRgba8888 rgba8888) {
46 uint8_t r = (rgba8888 & 0xFF);
47 uint8_t g = (rgba8888 & 0xFF00) >> 8;
48 uint8_t b = (rgba8888 & 0xFF0000) >> 16;
49 // Alpha is ignored for RGB565.
50 return EncodeRgb565(r, g, b);
51 }
52
53 /// Encode an RGBA8888 value from individual red, green, blue and
54 /// alpha values.
EncodeRgba8888(uint8_t r,uint8_t g,uint8_t b,uint8_t a)55 constexpr ColorRgba8888 EncodeRgba8888(uint8_t r,
56 uint8_t g,
57 uint8_t b,
58 uint8_t a) {
59 return (a << 24) | (b << 16) | (g << 8) | r;
60 }
61
62 /// Encode an RGBA8888 value from RGB565.
63 ///
64 /// This will scale each color up to 8 bits per pixel. Red and blue
65 /// are scaled from 5 bits to 8 bits. Green from 6 bits to 8
66 /// bits. There is no alpha channel in the RGB565 format so alpha is
67 /// set to 255 representing 100% opaque.
EncodeRgba8888(ColorRgb565 rgb565)68 constexpr ColorRgba8888 EncodeRgba8888(ColorRgb565 rgb565) {
69 uint8_t r = 255 * ((rgb565 & 0xF800) >> 11) / 31;
70 uint8_t g = 255 * ((rgb565 & 0x7E0) >> 5) / 63;
71 uint8_t b = 255 * (rgb565 & 0x1F) / 31;
72 uint8_t a = 255;
73 return EncodeRgba8888(r, g, b, a);
74 }
75
76 /// @}
77
78 } // namespace pw::display
79