/**
 * VBE.C -- interface into VESA BIOS extensions from DJGPP-compiled
 * MS-DOS programs.
 *
 * Copyright (c) 2025 Paper
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
**/

#include <stdint.h>

enum {
	VBE_BLIT_UNINITIALIZED = 0,
	VBE_BLIT_FRAMEBUFFER,
	VBE_BLIT_BANKS,
};

struct vbe {
	/* ---- PUBLIC MEMBERS ---- */

	uint16_t width, height, pitch;
	uint8_t bpp; /* BYTES per pixel */

	/* (width * height * bpp) */
	uint32_t size;

	uint8_t r_size;
	uint8_t r_pos;
	uint8_t g_size;
	uint8_t g_pos;
	uint8_t b_size;
	uint8_t b_pos;

	/* --- INTERNAL MEMBERS --- */

	int blit_type;
	union {
		struct {
			uint32_t address;
			int selector;
		} fb;
		struct {
			uint32_t size;
			uint32_t granularity;
		} banks;
	} blit;
};

#ifdef __GNUC__
# define VBE_INLINE static inline __attribute__((__always_inline__))
#else
# define VBE_INLINE static inline
#endif

/* VBE has a theoretical maximum resolution of 65535x65535. */
int vbe_init(struct vbe *vbe, uint16_t width, uint16_t height);
void vbe_blit(struct vbe *vbe, const void *ptr);
void vbe_quit(struct vbe *vbe);

/* this is a convenience macro for converting 8-bit RGB values into
 * a full RGB value for use in a framebuffer. */
#define VBE_RGB(/* struct vbe */vbe, /*uint8_t */r, /*uint8_t */g, /*uint8_t */b) \
	( \
		((((uint32_t)(r) & 0xFF) << (vbe).r_size >> 8) << (vbe).r_pos) \
		| ((((uint32_t)(g) & 0xFF) << (vbe).g_size >> 8) << (vbe).g_pos) \
		| ((((uint32_t)(b) & 0xFF) << (vbe).b_size >> 8) << (vbe).b_pos) \
	) \

/* function variation of the above. */
VBE_INLINE uint32_t vbe_rgb(struct vbe *vbe, uint8_t r, uint8_t g, uint8_t b)
{
	return VBE_RGB(*vbe, r, g, b);
}
