#include "stt_class.h"

int SttGenerator::InTriangleTopoSet(QuadTreeNode* node, const ControlTopo& in_topo, ControlTopo& out_topo){
	//没有插入的地形 直接返回否
	if (in_topo.vert.empty()){
        out_topo.vert.clear();
        out_topo.topo.clear();
		return 0;
	}
	else{
        out_topo.vert.clear();
        out_topo.topo.clear();
        out_topo.max_depth = in_topo.max_depth;
        out_topo.minimal_resolution = in_topo.minimal_resolution;
        out_topo.physic_group = in_topo.physic_group;

		int count;
		Cpoint tri_nor;
		Cpoint cross_point;

		Triangle temp_tri;
		for (int j = 0; j < 3; j++){
			temp_tri.ids[j] = node->tri.ids[j];
		}

		tri_nor = CrossProduct(array_stt_vert_[temp_tri.ids[1]].posic - array_stt_vert_[temp_tri.ids[0]].posic,
		 array_stt_vert_[temp_tri.ids[2]].posic - array_stt_vert_[temp_tri.ids[0]].posic);

        // 这一步可能会非常耗时
		for (int i = 0; i < in_topo.vert.size(); i++){
			// 控制点和三角形的法线方向相同（在同一个半球）
			if (DotProduct(tri_nor, in_topo.vert[i].posic) > 0){
				count = 0;
				for (int j = 0; j < 3; j++){
					cross_point = LineCrossPlane(array_stt_vert_[temp_tri.ids[j]].posic, tri_nor, in_topo.vert[i].posic);
					if (DotProduct(tri_nor,
						CrossProduct(array_stt_vert_[temp_tri.ids[(j+1)%3]].posic - array_stt_vert_[temp_tri.ids[j]].posic,
						 cross_point - array_stt_vert_[temp_tri.ids[j]].posic)) > 0){
						count++;
					}
				}

                // 满足条件则 穿透点在三角形内
				if (count == 3){
                    out_topo.vert.push_back(in_topo.vert[i]);
                    out_topo.topo.push_back(in_topo.topo[i]);
				}
			}
		}
		return 0;
	}
}