/// @file render/frame_buffer.h /// @brief The pixel buffer the software renderer draws into, and what can be /// done with one: hash it, save it as an image. #pragma once #include #include "core/types.h" namespace kumo { /// @brief A color packed as 0xAARRGGBB. using Color = uint32_t; /// @brief Packs 8-bit channels into a Color. constexpr Color make_color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) { return (static_cast(a) << 24) | (static_cast(r) << 16) | (static_cast(g) << 8) | (static_cast(b)); } /// @brief A grid of pixels stored row by row, top row first. struct FrameBuffer { int width; int height; std::vector pixels; ///< width * height colors; (0, 0) is top left. /// @brief Creates a buffer with every pixel set to @p fill. FrameBuffer(int width, int height, Color fill = 0) : width(width), height(height), pixels(static_cast(width) * static_cast(height), fill) { } /// @brief Tells whether (x, y) lies inside the buffer. bool contains(int x, int y) const { return x >= 0 && y >= 0 && x < width && y < height; } /// @brief The pixel at (x, y), which must be inside the buffer. Color& at(int x, int y) { return pixels[static_cast(y) * static_cast(width) + static_cast(x)]; } /// @copydoc at(int, int) Color at(int x, int y) const { return pixels[static_cast(y) * static_cast(width) + static_cast(x)]; } }; /// @brief Hashes the size and the pixels of a buffer with 64-bit FNV-1a. /// /// The bytes are fed to the hash in a fixed order, not the order they have in /// memory, so the result is the same on every platform. Two renders are /// identical if and only if (in practice) their hashes are equal. /// /// @param framebuffer The buffer to hash. /// @return The hash. uint64_t hash_pixels(const FrameBuffer& framebuffer); /// @brief Saves a buffer as an uncompressed 32-bit TGA image. /// /// TGA is chosen because it is a few lines to write and macOS Preview opens /// it directly. /// /// @param framebuffer The buffer to save; both sides must be 1 to 65535. /// @param path File to create or overwrite. /// @return `true` on success. bool write_tga(const FrameBuffer& framebuffer, const char* path); } // namespace kumo