'/// AddRandomAnim 1.0 for XSI 4.0+
'/// By Homam Bahnassi - In|Framez 2004
'--------------------------------------
replacemats

function replacemats()

replacemats = false
set oPickMat = PickElement( siShaderFilter, "Select Original Material", _ 
"Select New Material", oPNewMat , button ) 
if button = 1 then 
	set oOriMat = GetValue(oPNewMat)
elseif button = 2 then 
	set oNewMat = GetValue(oPNewMat)
else
	logmessage "ReplaceMats: Canceled by user..."
	exit function
end if

if typename(oOriMat) = "Material" then
	set oPickMat = PickElement( siShaderFilter, "Select New Material", _ 
	"Select New Material", oPNewMat , button ) 
	if button = 0 then 
		logmessage "ReplaceMats: Cancelled by user..."
		exit function
	end if
	set oNewMat = GetValue(oPNewMat)
else
	set oPickMat = PickElement( siShaderFilter, "Select Original Material", _ 
	"Select Original Material", oPNewMat , button ) 
	if button = 0 then 
		logmessage "ReplaceMats: Cancelled by user..."
		exit function
	end if
	set oOriMat = GetValue(oPNewMat)
end if

clsChk = msgbox("Consider Materials on Clusters?",vbYesNo,"ReplaceMats")

set oSceneRoot = Application.ActiveSceneRoot

set oSceneObjs = oSceneRoot.FindChildren("*",siPolyMeshType) '// only polymesh???

if clsChk = 6 then '-- Users choose Yes for clusters...
	for each oObj in oSceneObjs
		'Replace mat
		set oMat = oObj.Material
		if oMat.name = oOriMat.name then
			AssignMaterial oMat.parent & "," & oNewMat
		end if

		set oClusters = oObj.activeprimitive.geometry.Clusters 
		for each oCluster in oClusters
			if oCluster.type = "poly" then
				'Replace mat
				set oMat = oCluster.Material
				if oMat.name = oOriMat.name then
					AssignMaterial oMat.parent & "," & oNewMat
				end if
			end if
		next
	next

else '-- User choose No!
	for each oObj in oSceneObjs
		'Replace mat
		set oMat = oObj.Material
		if oMat.name = oOriMat.name then
			AssignMaterial oMat.parent & "," & oNewMat
		end if
	next
end if

logmessage "Done..."
replacemats = true
end function
