/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   center_vertices.c                                  :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: gbrochar <gbrochar@student.42.fr>          +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/12/26 06:11:21 by gbrochar          #+#    #+#             */
/*   Updated: 2020/12/26 06:25:59 by gbrochar         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "scop.h"
#include "vec3.h"

void			center_vertices(t_buf_d *vertices)
{
	t_vec3		average;
	t_vec3		max = { .x = DBL_MIN, .y = DBL_MIN, .z = DBL_MIN };
	t_vec3		min = { .x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX };

	for (size_t i = 0; i < vertices->ptr; i++)
	{
		if (i % 3 == 0) {
			if (vertices->data[i] > max.x)
				max.x = vertices->data[i];
			if (vertices->data[i] < min.x)
				min.x = vertices->data[i];
			average.x += vertices->data[i];
		}
		else if (i % 3 == 1) {
			if (vertices->data[i] > max.y)
				max.y = vertices->data[i];
			if (vertices->data[i] < min.y)
				min.y = vertices->data[i];
			average.y += vertices->data[i];
		}
		else if (i % 3 == 2) {
			if (vertices->data[i] > max.z)
				max.z = vertices->data[i];
			if (vertices->data[i] < min.z)
				min.z = vertices->data[i];
			average.z += vertices->data[i];
		}
	}
	average.x /= (vertices->ptr / 3);
	average.y /= (vertices->ptr / 3);
	average.z /= (vertices->ptr / 3);
	double max_k = max.x - min.x;
	max_k = max_k > max.y - min.y ? max_k : max.y - min.y;
	max_k = max_k > max.z - min.z ? max_k : max.z - min.z;
	for (size_t i = 0; i < vertices->ptr; i++)
	{
		if (i % 3 == 0) {
			vertices->data[i] -= average.x;
			vertices->data[i] /= max_k;
		}
		else if (i % 3 == 1) {
			vertices->data[i] -= average.y;
			vertices->data[i] /= max_k;
		}
		else if (i % 3 == 2) {
			vertices->data[i] -= average.z;
			vertices->data[i] /= max_k;
		}
	}

}

