'/// AvarageNormals 1.0 for XSI 3.5+
'/// By Homam Bahnassi - In|Framez 2003
'--------------------------------------

set oSelection = SIFilter( GetValue( "SelectionList" ), "polygon_mesh" )
AverageNormals oSelection

function AverageNormals(oInObjectsCollection)
	AverageNormals = false
	
	'--- Checking input collection
	if typename(oInObjectsCollection) <> "Object" then
		logmessage "AvarageNormals: Objects required..."
		exit function
	end if
	
	for each oObj in oInObjectsCollection
		if oObj.type <> "polymsh" then
			logmessage "AvarageNormals: " & oObj & " is not a polygonal mesh object..."
			exit function
		end if
	next
	
	for each oObj in oInObjectsCollection
		set oGeo = oObj.ActivePrimitive.Geometry
		set oNormalCluster = oGeo.AddCluster("sample", "NormalCls")
		set oNormalProp = oNormalCluster.AddProperty("User Normal Property")

		aNormalArray = oNormalProp.Elements.Array
		iNormalArrayCount = oNormalProp.Elements.Count

		set oNor = CreateObject("Sumatra\Scripting\Math\SIVector3")
		set o0DGeometry = oObj.Obj.Geometry0D

		set oPoints = oGeo.Points
		for iPI=0 to oPoints.Count-1
			oIndicesArray = Array(iPI)
			o0DGeometry.AverageNormal oIndicesArray, oNor
			set oSamples = oPoints(iPI).Samples
			for each iSample in oSamples
				iSI = iSample.index
				aNormalArray(0,iSI) = oNor.x
				aNormalArray(1,iSI) = oNor.y
				aNormalArray(2,iSI) = oNor.z
			next
		next

		'--- Write the normals
		oNormalProp.elements.array = aNormalArray
	Next
	AverageNormals = true
end function
