#ifndef physics_hpp
#define physics_hpp

#include "asset.hpp"
#include "maths.hpp"

#include <tuple>

struct Arena;
struct Line_Renderer;
struct World;

struct Manifold {
	static constexpr int max_contacts = 16;
	v3f contacts[max_contacts];
	int contact_count;
	v3f normal;
};

struct Int_Collider;
struct Physics_Debughook {
	virtual void shrinkwrap(
		const Int_Collider* col,
		int axis,
		const v2f* points,
		int count
	);
	virtual void projection(
		const Int_Collider* col,
		const v3f& n,
		int axis,
		const v2f* points,
		int count
	);
};

struct Rigidbody;
struct Int_Collider {
	Rigidbody* rb;
	Int_Collider* next;
	int vert_count;
	int face_count;
	v3f* verts;
	v3f* faces;

	bool collide(
		Physics_Debughook* hook,
		Arena* a,
		const Int_Collider& other
	) const;

	struct Projection {
		const Int_Collider* col;
		v3f r, u;

		struct Iter {
			const Projection* p;
			int vert;

			bool equals(const Iter& other) const {
				return vert == other.vert;
			}
			bool operator==(const Iter& other) const {
				return equals(other);
			}
			bool operator!=(const Iter& other) const {
				return !equals(other);
			}
			Iter operator++() {
				vert++;
				return *this;
			}
			v2f operator*();
		};

		Iter begin() {
			return { this, 0 };
		}

		Iter end() {
			return { this, col->vert_count };
		}
	};

	Projection project(const v3f& axis) const;
};

struct Collider : Asset {
	struct Face {
		v3f normal;
		int vert_count;
		uint16_t* verts;
	};
	int face_count;
	int vert_count;
	Face* faces;
	v3f* verts;
	m3f moment;

	void debug_render(
		Line_Renderer& lr,
		const m4f& t,
		const v3f& c
	);
	Int_Collider* transform(const m4f& m, Arena* a) const;
};

struct Rigidbody {
	v3f prev_pos, pos;
	v3f vel, avel;
	v3f force;
	v3f torque;
	v4f prev_rot, rot;
	float inv_mass;
	Collider* col;
	int colliding;

	void init(Collider* c, const v3f& p, const v4f& r, float mass);
	void set_pos(const v3f& p);
	void set_rot(const v4f& r);
	void set_mass(float m);
	void add_force(const v3f& f);
	void add_force(const v3f& f, const v3f& p);
	void add_impulse(const v3f& f);
	void add_impulse(const v3f& f, const v3f& p);
	void add_torque(const v3f& t);
};

Collider* make_box(Arena* a, const v3f& size);

void physics_update(
	World& w,
	Arena* a,
	float ts,
	Physics_Debughook* hook
);
void physics_debug(World& w, Line_Renderer& lr);

#endif