/* 
-------------------------------------------------------------------------------
Author: Mihail Lupu
Description: Conform object. Best for retopology. Conforming low poly 
				mesh on to high poly mesh.
version: 1.0
How it works?
Select first the low poly mesh, then the highpoly mesh and evaluate the script
NOTE: the LP mesh MUST not intersect the HP mesh and have to cover outwards.
-------------------------------------------------------------------------------
 */

clearlistener()
(
	local source, target
	Fn getVertNormals vert = (
		local Faces = meshop.getPolysUsingVert source vert
		local vertNormal = point3 0 0 0
		for f = 1 to Faces.count do (
			if Faces[f] then (
				faceNormal = getFaceNormal source f
				vertNormal = vertNormal + faceNormal
				)
			)
		vertNormal = normalize vertNormal
		return vertNormal
	)
	Fn conformObj = (
		converttomesh source
		local numVerts = getNumVerts source
		local vertsList = #()
		for a = 1 to numVerts do (
			local v = getVertNormals a
			append vertsList v )
		for b = 1 to numVerts do (
			local vertPos = getVert source b 
			(
				local rays = ray vertPos -vertsList[b]
				local raysHit = intersectRay target rays
				if raysHit != undefined then meshop.setVert source b raysHit.pos 
			)
		)
		converttopoly source
		select source
	)
	if selection.count == 2 then (
		source = $[1] -- Conform mesh (LP)
		target = $[2] -- Target mesh (HP )
		if (SuperclassOf source == geometryClass and SuperclassOf target == geometryClass ) == true then (
		if (source.mesh.numFaces as string) <= (target.mesh.numFaces as string) then conformObj()
			else (messagebox "Select LP then the HP!" beep:false)
		)	else (messagebox "Works only with geometry!" beep:false)
	)		else (messagebox "Only 2 objects can be selected" beep:false)
)
