
/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2006 Francisco Leon. C.C. 80087371.
email: projectileman@yahoo.com

 This library is free software; you can redistribute it and/or
 modify it under the terms of EITHER:
   (1) The GNU Lesser General Public License as published by the Free
       Software Foundation; either version 2.1 of the License, or (at
       your option) any later version. The text of the GNU Lesser
       General Public License is included with this library in the
       file GIMPACT-LICENSE-LGPL.TXT.
   (2) The BSD-style license that is included with this library in
       the file GIMPACT-LICENSE-BSD.TXT.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
 GIMPACT-LICENSE-LGPL.TXT and GIMPACT-LICENSE-BSD.TXT for more details.

-----------------------------------------------------------------------------
*/

#include "GIMPACT/gim_trimesh.h"

void _debug_print(int);

//#undef PSP_GIMPACT_OPT

int gim_triangle_sphere_collision(GIM_TRIANGLE_DATA *tri,vec3f center, GREAL radius,GIM_TRIANGLE_CONTACT_DATA * contact_data) {
	volatile int ret_val = 0;
    contact_data->m_point_count = 0;

#ifdef PSP_GIMPACT_OPT
	__asm__ volatile ("lv.s S001, %0\nlv.s S011, 4+%0\nlv.s S021, 8+%0\nvone.s S031\nvneg.s S031,S031\n"::"m"(center[0]));
	__asm__ volatile ("mtv %0, S200\n vneg.s S201, S200\n"::"r"(radius));
#endif

    //Find Face plane distance
#ifdef PSP_GIMPACT_OPT
    GREAL  dis;
	__asm__ volatile (
	"lv.q    R100, %0\n"
	"vdot.q   S203, R100, R001\n"
	"vabs.s   S400, S203\n"
	:: "m"(tri->m_planes.m_planes[0][0]));
	
	__asm__ volatile (
	".set push\n"
        ".set noreorder\n"
	"vcmp.s   GT, S400, S200\n"
	"bvt     0, return_block_\n"
	"vzero.s S202\n"  // max_dis
        ".set pop\n");
	__asm__ volatile ("sv.s   S203,%0\n"::"m"(contact_data->m_penetration_depth));
#else
    GREAL  dis = DISTANCE_PLANE_POINT(tri->m_planes.m_planes[0],center);
    if(dis>radius) return 0; //out
    if(dis<-radius) return 0;//Out of triangle
    contact_data->m_penetration_depth = dis;
#endif

    //Find the most edge
#ifdef PSP_GIMPACT_OPT
	register volatile int most_edge = 4;
	__asm__ volatile (
	"lv.q    R000, %1\n"
	"vdot.q   S000, R000, R001\n"
	".set push\n"
        ".set noreorder\n"
	"vcmp.s   GT, S000, S200\n"
	"bvt     0, return_block_\n"
	"vcmp.s   GT, S000, S202\n"
	"bvf     0, cont_block_1_\n"
	"nop\n"
	"vmov.s   S202, S000\n"
	"li    %0, 0\n"
	".set pop\n"
	:"=r"(most_edge): "m"(tri->m_planes.m_planes[1][0]));
	__asm__ volatile ("cont_block_1_:\n");
#else
    int most_edge = 4;
    GREAL max_dis = 0.0f;
    dis = DISTANCE_PLANE_POINT(tri->m_planes.m_planes[1],center);
    if(dis>radius) return 0;//Out of triangle
    if(dis>0.0f) {
        max_dis = dis;
        most_edge = 0;
    }
#endif

    //Find the most edge
#ifdef PSP_GIMPACT_OPT
	__asm__ volatile (
	"lv.q    R000, %1\n"
	"vdot.q   S000, R000, R001\n"
	".set push\n"
        ".set noreorder\n"
	"vcmp.s   GT, S000, S200\n"
	"bvt     0, return_block_\n"
	"vcmp.s   GT, S000, S202\n"
	"bvf     0, cont_block_2_\n"
	"nop\n"
	"vmov.s   S202, S000\n"
	"li    %0, 1\n"
	".set pop\n"
	:"=r"(most_edge): "m"(tri->m_planes.m_planes[2][0]));
	__asm__ volatile ("cont_block_2_:\n");
#else
    dis = DISTANCE_PLANE_POINT(tri->m_planes.m_planes[2],center);
    if(dis>radius) return 0;//Out of triangle
    if(dis>max_dis) {
        max_dis = dis;
        most_edge = 1;
    }
#endif

    //Find the most edge
#ifdef PSP_GIMPACT_OPT
	__asm__ volatile (
	"lv.q    R000, %1\n"
	"vdot.q   S000, R000, R001\n"
	".set push\n"
        ".set noreorder\n"
	"vcmp.s   GT, S000, S200\n"
	"bvt     0, return_block_\n"
	"vcmp.s   GT, S000, S202\n"
	"bvf     0, cont_block_3_\n"
	"nop\n"
	"vmov.s   S202, S000\n"
	"li     %0, 2\n"
	".set pop\n"
	: "=r"(most_edge) : "m"(tri->m_planes.m_planes[3][0]));
	__asm__ volatile ("cont_block_3_:\n");
#else
    dis = DISTANCE_PLANE_POINT(tri->m_planes.m_planes[3],center);
    if(dis>radius) return 0;//Out of triangle
    if(dis>max_dis) {
        max_dis = dis;
        most_edge = 2;
    }
#endif

    if(most_edge == 4) { //Box is into triangle
        //contact_data->m_penetration_depth = dis is set above
        //Find Face plane point
#ifdef PSP_GIMPACT_OPT
	__asm__ volatile (
	".set push\n"
        ".set noreorder\n"
	"vcmp.s   GE, S203, S203[0]\n"
	"bvf      0, cont_block_10_\n"
	"vscl.t   R101, R100, S200\n"   // else case
	"vscl.t   R101, R100, S201\n"  // if case
	"cont_block_10_:\n"
	
	"vsub.s   S203, S200, S203\n"
	"sv.s     S203, %0\n"
	".set  pop\n"
	:"=m"(contact_data->m_penetration_depth));

	__asm__ volatile (
	"vadd.t  R101, R101, R001\n"  // add center
	"sv.q    R101,%0\n"
	:"=m"(contact_data->m_points[0][0]));

	__asm__ volatile (
	"vneg.t  R102, R100\n"
	"sv.q    R102,%0\n"
	:"=m"(contact_data->m_separating_normal[0]));
#else
        VEC_COPY(contact_data->m_separating_normal,tri->m_planes.m_planes[0]);
        //Find point projection on plane
        if(contact_data->m_penetration_depth>=0.0f) {
            VEC_SCALE(contact_data->m_points[0],-radius,contact_data->m_separating_normal);
        }else{
            VEC_SCALE(contact_data->m_points[0],radius,contact_data->m_separating_normal);
        }
	contact_data->m_penetration_depth = radius - contact_data->m_penetration_depth;

	VEC_SUM(contact_data->m_points[0],contact_data->m_points[0],center);
        VEC_SCALE(contact_data->m_separating_normal,-1.0f,contact_data->m_separating_normal);
#endif
        //Scale normal for pointing to triangle
        contact_data->m_point_count = 1;
        return 1;
    }

#ifdef PSP_GIMPACT_OPT
	vec4f e1;
	__asm__ volatile (
	"lv.q    R200, %0\n"  // e1
	"lv.q    R201, %1\n"  // e2
	"vsub.t  R202, R201, R200\n"  // n
	"vsub.t  R203, R001, R200\n"  // cp
	"vdot.t  S003, R203, R202\n"  // _scalar
	"vdot.t  S013, R202, R202\n"  // div
	"vrcp.s  S013, S013\n"
	"vmul.s  S003, S003, S013\n"  // _scalar divided
	:: "m"(tri->m_vertices[most_edge][0]),"m"(tri->m_vertices[(most_edge+1)%3][0]));

	__asm__ volatile (
	".set push\n"
        ".set noreorder\n"
	"vcmp.s   LT,S003,S003[0]\n"
	"bvt      0, skip_block_20_\n"
	"vmov.t  R300, R200\n"
	"vcmp.s   GT,S003,S003[1]\n"
	"bvt      0, skip_block_20_\n"
	"vmov.t  R300, R200\n"
	"vscl.t    R300, R202, S003\n"
	"vadd.t    R300, R300, R200\n"
	"skip_block_20_:\n"
	".set pop\n");

	__asm__ volatile (
	"sv.q      R300, %0\n"
	"vsub.t    R301, R001, R300\n"
	"usv.q     R301, %1\n"
	"vdot.t    S033, R301, R301\n"
	"vsqrt.s   S033, S033\n"
	"mfv       %2, S033\n"
	:"=m"(contact_data->m_points[0][0]),"=m"(e1[0]),"=r"(dis));
#else
    //find the edge
    vec4f e1,e2;
    VEC_COPY(e1,tri->m_vertices[most_edge]);
    VEC_COPY(e2,tri->m_vertices[(most_edge+1)%3]);

    CLOSEST_POINT_ON_SEGMENT(contact_data->m_points[0],center,e1,e2);
    //find distance
    VEC_DIFF(e1,center,contact_data->m_points[0]);
    VEC_LENGTH(e1,dis);
#endif

	if(dis>radius) return 0;

	contact_data->m_penetration_depth = radius - dis;

	#ifdef PSP_GIMPACT_OPT
	    if(IS_ZERO(dis)){
		__asm__ volatile ("lv.q R200, %0\n"::"m"(tri->m_planes.m_planes[most_edge+1][0]));
	    }else{
		__asm__ volatile ("vrcp.s   S033, S033\n vscl.t  R200, R301, S033\n");
	    }
	    __asm__ volatile (
	    "mtv       %2, S433\n"
	    "vneg.s    S433, S433\n"
	    "vscl.t    R201, R200, S433\n"
	    "vadd.t    R201, R201, R001\n"
	    "vneg.t    R200, R200\n"
	    "sv.q      R201, %1\n"
	    "sv.q      R200, %0\n"
	    :"=m"(contact_data->m_separating_normal[0]),"=m"(contact_data->m_points[0]) :"r"(radius) );
	#else
	    if(IS_ZERO(dis)){
		VEC_COPY(contact_data->m_separating_normal,tri->m_planes.m_planes[most_edge+1]);
	    }else{
		VEC_SCALE(contact_data->m_separating_normal,1.0f/dis,e1);
	    }

	    VEC_SCALE(contact_data->m_points[0],-radius,contact_data->m_separating_normal);
	    VEC_SUM(contact_data->m_points[0],contact_data->m_points[0],center);
	    //Scale normal for pointing to triangle
	    VEC_SCALE(contact_data->m_separating_normal,-1.0f,contact_data->m_separating_normal);
	#endif

	    contact_data->m_point_count = 1;
	ret_val = 1;
	__asm__ volatile ("return_block_:\n");
	    return ret_val;
	
}

//! Trimesh Sphere Collisions
/*!
In each contact
<ul>
<li> m_handle1 points to trimesh.
<li> m_handle2 points to NULL.
<li> m_feature1 Is a triangle index of trimesh.
</ul>

\param trimesh
\param center
\param radius
\param contacts A GIM_CONTACT array. Must be initialized
*/
void gim_trimesh_sphere_collision(GIM_TRIMESH * trimesh,vec3f center,GREAL radius, GDYNAMIC_ARRAY * contacts) {
    contacts->m_size = 0;

    aabb3f test_aabb;
	test_aabb.minX = center[0]-radius;
	test_aabb.maxX = center[0]+radius;
	test_aabb.minY = center[1]-radius;
	test_aabb.maxY = center[1]+radius;
	test_aabb.minZ = center[2]-radius;
	test_aabb.maxZ = center[2]+radius;

	GDYNAMIC_ARRAY collision_result;
	GIM_CREATE_BOXQUERY_LIST(collision_result);

	gim_aabbset_box_collision(&test_aabb, &trimesh->m_aabbset , &collision_result);

	if(collision_result.m_size==0)
	{
	    GIM_DYNARRAY_DESTROY(collision_result);
	}

	//collide triangles
	//Locks trimesh
	gim_trimesh_locks_work_data(trimesh);
	 //dummy contacts
    GDYNAMIC_ARRAY dummycontacts;
    GIM_CREATE_CONTACT_LIST(dummycontacts);

	int cresult;
	unsigned int i;
	GUINT32 * boxesresult = GIM_DYNARRAY_POINTER(GUINT32,collision_result);
	GIM_TRIANGLE_CONTACT_DATA * tri_contact_data = (GIM_TRIANGLE_CONTACT_DATA*)GIM_ALLOCA16(sizeof(GIM_TRIANGLE_CONTACT_DATA));
	GIM_TRIANGLE_DATA * tri_data =  (GIM_TRIANGLE_DATA*)GIM_ALLOCA16(sizeof(GIM_TRIANGLE_DATA));

	for(i=0;i<collision_result.m_size;i++) {
		gim_trimesh_get_triangle_data(trimesh,boxesresult[i],tri_data);
		cresult = gim_triangle_sphere_collision(tri_data,center,radius,tri_contact_data);
		if(cresult!=0)  {
		    GIM_PUSH_CONTACT(dummycontacts, tri_contact_data->m_points[0],tri_contact_data->m_separating_normal ,tri_contact_data->m_penetration_depth,trimesh, 0, boxesresult[i],0);
		}
	}
	///unlocks
	gim_trimesh_unlocks_work_data(trimesh);
	///Destroy box result
	GIM_DYNARRAY_DESTROY(collision_result);

	 //merge contacts
    gim_merge_contacts(&dummycontacts,contacts);

    //Destroy dummy
    GIM_DYNARRAY_DESTROY(dummycontacts);
}

