#pragma once
#include "vecmath.h"
#include "scenefile.h"

#define QUAD_VALID 1
#define QUAD_IN_USE 2
#define QUAD_CLEARCACHE 4
#define QUAD_TILECACHED 8
#define QUAD_BG_PIN 16
#define QUAD_BG_AR11 32
#define QUAD_BG_TILE 64
#define UV_PER_METER (1.0f/0.256f)

typedef uint32_t yrColor;

struct _yrtag_yrQuad;
typedef struct _yrtag_yrQuad yrQuad;
struct _yrtag_yrQuad_ext;
typedef struct _yrtag_yrQuad_ext yrQuad_ext;

struct _yrtag_yrQuad
{
	vec4i v[3];
	vec4f normal;
	yrQuad_ext* ext;
	float uv_back[2][2];
	float uv_draw[2];
	float width;
	float height;
	yrColor color;
	uint8_t tile_width;
	uint8_t texture_bg;
	uint16_t _padding0;
	uint32_t id;
	uint32_t flags;
	uint64_t _padding1;
};

struct _yrtag_yrQuad_ext
{
	mat4f invtransform;
	uint32_t tile_max_idx;
	uint32_t tiles[64];//TODO: consider saving the tiles separately, most of them will be invalid anyway...
	uint32_t cached_tileidx[64];
};

yrQuad* yrQuadStore_add(yrQuad* q);
void yrQuadStore_remove(yrQuad* q);
void yrQuadStore_update(yrQuad* q);
void yrQuadStore_editlock(yrQuad* q);
int yrQuadStore_editlocked(void);

typedef void* yrQuad_iter;
yrQuad_iter yrQuad_iter_top(void);
yrQuad*		yrQuad_iter_next(yrQuad_iter* i, float* metric);

struct _yrtag_yrQuad_cold_iter;
typedef struct _yrtag_yrQuad_cold_iter yrQuad_cold_iter;
yrQuad_cold_iter*	yrQuad_cold_iter_init(yrSceneFile* sf, size_t* quadcount);
int					yrQuad_cold_iter_next(yrQuad_cold_iter* i, yrQuad* out, uint32_t* bg_out, uint32_t tiles_out[64]);
void				yrQuad_cold_iter_end(yrQuad_cold_iter* i);

int	yrQuadStore_cold_insert(yrSceneFile* sf, size_t icount, yrQuad* q, uint32_t* bg, uint32_t* tilecount, uint32_t** tiles, int add_offset);