import { v2_bearing_angle_towards } from "../../../../../../core/geom/vec2/v2_bearing_angle_towards.js";

/**
 * Depending on the direction in which shape winds, normals of the generated geometry faces might end up flipped,
 * so we pre-process the shape to avoid that here
 * @param {number[]|Float32Array} shape
 * @returns {Float32Array}
 */
export function fix_shape_normal_order(shape) {
    const shape_array_length = shape.length;

    if (shape_array_length <= 2) {
        // less than 2 points in the shape
        return shape;
    }

    // compute initial direction
    const x0 = shape[0];
    const y0 = shape[1];
    const x1 = shape[2];
    const y1 = shape[3];

    const angle = v2_bearing_angle_towards(x0, y0, x1, y1);

    if (angle > Math.PI) {
        // order is fine
        return shape;
    }

    // reverse order
    const reversed = new Float32Array(shape_array_length);

    const n = shape_array_length / 2;

    for (let i = 0; i < n; i++) {
        const i2 = i * 2;

        const j2 = (n - (i + 1)) * 2;

        reversed[i2] = shape[j2];
        reversed[i2 + 1] = shape[j2 + 1];
    }

    return reversed;
}
