macroScript PsSTAGESETUP
	category: "TurboSquid" 
	buttonText: "PixelSquid Studio v3.25" 
	tooltip: "PixelSquid Studio v3.25" 
	autoUndoEnabled: false
(
	
-- *************************************************************************
--  returns the script Name
-- *************************************************************************
	fn TS_VERSION =
	(
		local retVal = "v3.25"
		retval
	)
	
-- *************************************************************************
--  returns the script Name
-- *************************************************************************
	fn TS_SCRIPT_NAME =
	(
		retVal = "PixelSquid Studio"
		retVal
	)

-- *************************************************************************
--  returns the scripts fullname ( name and version )
-- *************************************************************************
	fn TS_SCRIPT_FULLNAME = 
	(
		local retVal = ( TS_SCRIPT_NAME() ) + " " +  TS_VERSION()
		retVal
	)
		
global PSOutputFolder
	
-- global saved values. saved with max scene and retrieved.
-- also will persist when the window is closed

persistent global useVray
persistent global g_stageversion
persistent global g_lightlevel
persistent global d_lightlevel
persistent global c_distancelevel
persistent global cam_mm
persistent global rig_sel
persistent global outrig
persistent global eye_h
persistent global camZoom
persistent global SpinType
persistent global CamFOV
	
persistent global RendDialStatus
persistent global g_vray_version
	
callbacks.addscript #systemPostReset "persistent global useVray=false" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global useVray=false" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "useVray=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if useVray==undefined do (persistent global useVray=false)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global g_stageversion='PixelSquid Studio v3.25'" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global g_stageversion='PixelSquid Studiov v3.25'" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "g_stageversion=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if g_stageversion==undefined do (persistent global g_stageversion='PixelSquid Studio v3.25')" id:#PsSTAGESETUP
	
callbacks.addscript #systemPostReset "persistent global g_lightlevel=1.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global g_lightlevel=1.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "g_lightlevel=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if g_lightlevel==undefined do (persistent global g_lightlevel=1.0)" id:#PsSTAGESETUP	

callbacks.addscript #systemPostReset "persistent global d_lightlevel=1.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global d_lightlevel=1.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "d_lightlevel=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if d_lightlevel==undefined do (persistent global d_lightlevel=1.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global c_distancelevel=0.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global c_distancelevel=0.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "c_distancelevel=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if c_distancelevel==undefined do (persistent global c_distancelevel=0.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global cam_mm=6.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global cam_mm=6.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "cam_mm=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if cam_mm==undefined do (persistent global cam_mm=6.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global rig_sel=1.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global rig_sel=1.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "rig_sel=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if rig_sel==undefined do (persistent global rig_sel=1.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global outrig=1.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global outrig=1.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "outrig=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if outrig==undefined do (persistent global outrig=1.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global eye_h=92.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global eye_h=92.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "eye_h=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if eye_h==undefined do (persistent global eye_h=92.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global camZoom=0.0" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global camZoom=0.0" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "camZoom=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if camZoom==undefined do (persistent global camZoom=0.0)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global RendDialStatus=false" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global RendDialStatus=false" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "RendDialStatus=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if RendDialStatus==undefined do (persistent global RendDialStatus=false)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global SpinType=1" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global SpinType=1" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "SpinType=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if SpinType==undefined do (persistent global SpinType=1)" id:#PsSTAGESETUP

callbacks.addscript #systemPostReset "persistent global CamFOV=39.60" id:#PsSTAGESETUP
callbacks.addscript #systemPostNew "persistent global CamFOV=39.60" id:#PsSTAGESETUP
callbacks.addscript #filePreOpen "CamFOV=undefined" id:#PsSTAGESETUP
callbacks.addscript #filePostOpen "if CamFOV==undefined do (persistent global CamFOV=39.60)" id:#PsSTAGESETUP

-- ----------------------------------------------------------------------------------------
-- variables
-- ----------------------------------------------------------------------------------------
global cameraObj
global spherePos = [0,0,0]
global sphereRadius = 25.0
global NUMBER_OF_LATITUDE_POINTS = 16
global EQUATOR = 8
global NUMBER_OF_LONGITUDE_POINTS = 16

global g_SetupRollout 
global g_SpinnerCameraRollout
global g_ShotCameraRig

function registerRollout i_Rollout RolloutName:#unkown =
(
	case RolloutName of
	(
		#SetupRollout:
		(
			g_SetupRollout = i_Rollout
		)
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout = i_Rollout
		)
		default:
		(
			throw ( "Attempt to register unknown kind of Rollout" )
		)
	)
)

function lockRegisteredRollout RolloutName:#unkown =
(
	case RolloutName of 	
	(
		#SetupRollout:
		(
			g_SetupRollout.lockRollout()
		)
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout.lockRollout()
		)
		default:
		(
			throw ( "Attempt to lock unknown Rollout" )
		)
	)
)

function unlockRegisteredRollout RolloutName:#unkown =
(
	case RolloutName of 	
	(
		#SetupRollout:
		(
			g_SetupRollout.unlockRollout()
		)
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout.unlockRollout()
		)
		default:
		(
			throw ( "Attempt to unlock unknown Rollout" )
		)
	)
)

function lockRegisteredCameraControls RolloutName:#unkown =
(
	case RolloutName of 	
	(
		#SetupRollout:
		(
			g_SetupRollout.lockCameraControls()
		)
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout.lockCameraControls()
		)
		default:
		(
			throw ( "Attempt to lock unknown Camera Controls" )
		)
	)
)

function unlockRegisteredCameraControls RolloutName:#unkown =
(
	case RolloutName of 	
	(
		#SetupRollout:
		(
			g_SetupRollout.unlockCameraControls()
		)
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout.unlockCameraControls()
		)
		default:
		(
			throw ( "Attempt to lock unknown Camera Controls" )
		)
	)
)

function enableRegisteredCreateRigButton RolloutName:#unkown =
(
	case RolloutName of 	
	(
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout.enableCreateRigButton()
		)
		default:
		(
			throw ( "Attempt to enable unknown CreatRigButton" )
		)
	)
)

function disableRegisteredCreateRigButton RolloutName:#unkown =
(
	case RolloutName of 	
	(
		#SpinnerCameraRollout:
		(
			g_SpinnerCameraRollout.disableCreateRigButton()
		)
		default:
		(
			throw ( "Attempt to disable unknown CreatRigButton" )
		)
	)
)

function validateSceneForRigGeneration = 
(
	if not isValidObj $HeroObjectGroup then
	(
		g_SpinnerCameraRollout.lockRollout()
		messageBox "HeroObjectGroup is missing. You need to prepare the scene again for the rig to work."
		false
	)
	else
	(
		true
	)
)

-- ----------------------------------------------------------------------------------------
-- Functions
-- ----------------------------------------------------------------------------------------

-- is material a default studiop script material ?
fn IsDefaultStudioMaterialTexture  textureName: =
(
	local studioTextures = #( "TSHero_HDRI_v10.exr",  
										"HDRISky_Morning_001.exr",  "glowCard_MorningSun.png",
										"HDRISky_midDay_001.exr",  "glowCard_MidDaySun.png",  
										"HDRISky_Sunset_001.exr", 	"glowCard_SunSetSun.png", 
										"TSHero_CarClassic_002.exr",  "TSHero_CarTech_002.exr",
										"lightglow_card.png", 
										"10k_lightBox_002.exr",
										"StemCell_Studio_001.exr",
										
										-- obsolete studio textures
										"10k_lightBox_001.hdr",
										"TSHero_CarClassic_001.exr", 
										"TSHero_HDRI_v8.exr",  "TSHero_HDRI_v8_Spec.exr",   
										"TSHero_HDRI_v9.exr", 	"TSHero_HDRI_v9_Spec.exr"
										 )
	local index = findItem studioTextures textureName
	local retVal = ( index > 0 )
	retVal
)

global g_TS_StudioTextureFiles = 
	#( #(#HDRISKY_MORNING, "HDRISky_Morning_001.exr"),
		#(#HDRISUN_MORNING, "glowCard_MorningSun.png"),
		#(#HDRISKY_MIDDAY, "HDRISky_midDay_001.exr"),
		#(#HDRISUN_MIDDAY, "glowCard_MidDaySun.png"),
		#(#HDRISKY_SUNSET, "HDRISky_Sunset_001.exr"),
		#(#HDRISUN_SUNSET, "glowCard_SunSetSun.png"),
		#(#TSHERO_CARCLASSIC, "TSHero_CarClassic_002.exr"),
		#(#TSHERO_CARTECH, "TSHero_CarTech_002.exr"),
		#(#TSHERO_HDRI, "TSHero_HDRI_v10.exr"),			
		#(#LIGHTGLOW_CARD, "lightglow_card.png"),
		#(#LIGHTBOX_10K, "10k_lightBox_002.exr"),
		#(#STEMCELL_HDRI, "StemCell_Studio_001.exr")
	)

-- single place to update current texture files used in env
fn getTextureFileAndPath texFile: nopath:false =
(
	if unsupplied == texFile then
	(
		throw ( "getTextureFileAndPath unspecified texFile " )
	)
	
	local retVal
	local fileName
	local found = false
	for each in g_TS_StudioTextureFiles while false == found do
	(
		if 	each[1] == texFile then
		(
			fileName = each[2]
			found = true
		)
	)
	if false == found then
	(
		throw ( "getTextureFileAndPath unknown texFile[" + ( texFile as string ) + "]" )
	)
	
	if noPath then 
	(
		retVal = fileName
	)
	else
	(
		retVal = ( getdir #MaxRoot ) + "turbosquid\\hdri\\" + fileName
	)
	retVal
)

function isCamera obj = 
(
	(isKindOf obj Camera) or (isKindOf obj TargetObject)
)

function validCameraFound=
(
	local retVal = ( isValidObj $ShotCamera or isValidObj $SpinnerCamera  )
	retVal
)

function sceneHasBeenPrepped=
(
	local retVal = validCameraFound() or ( ( isValidObj  $ShadowPlane ) and ( IsValidObj $HeroObjectGroup ) )
	retVal
)

function isHeroObject obj = 
(
	(findString "Hero" obj.name) == 1
)

function isLight obj = 
(
	(isKindOf obj Light)
)

function isVrayLight obj = 
(
	(isKindOf obj VrayLight)
)

function deleteLights =
(
	local objectsToProcess = objects as array
	for obj in objectsToProcess where (not isHeroObject(obj) and isLight(obj)) do 
	(
		delete obj
	)
	
	if $FoodCard != undefined then
	(
		delete $FoodCard
	)

	if $RigControlGroup != undefined then
	(
		delete $RigControlGroup
	)
)

function showShadowPlaneSpinnerCamera bShow = 
(
	local shadowPlane = $ShadowPlane
	
	if shadowPlane != undefined do
	(
		shadowPlane.visibility = bShow
	)
)

function get_vray_version =
(
	g_vray_version
)

function set_vray_version version =
(
	g_vray_version = version
	g_vray_version
)

-- *************************************************************************
-- returns version of vray installed or , #( 0.0,  0.0, 0.0 ) if not installed
-- if currentVersion: == true then returns if the current renderer is vray and its version
-- *************************************************************************
fn  getInstalledVRayVersion currentVersion: =
(
	local retVal = #(0.0, 0.0, 0.0 )
	
	local vrayInstalledVersions = #()
	if currentVersion == unsupplied or currentVersion == false then
	(
		vrayInstalledVersions = ( for x in RendererClass.classes where ( matchPattern ( x as string ) pattern:"*V_Ray_Adv_*" ) collect x )
		if  ( vrayInstalledVersions.count == 0 ) then
			vrayInstalledVersions = ( for x in RendererClass.classes where ( matchPattern ( x as string ) pattern:"*V_Ray_Next*" ) collect x )	
	)
	else
	(
		append vrayInstalledVersions ( classof renderers.current as string )
	)

	if ( vrayInstalledVersions.count > 0 ) then
	(
		-- valid versions of vray the studio script works with
		local TS_VrayVersions = #(	#( "V_Ray_Adv_2_3", 2.3 ), 
						#( "V_Ray_Adv_2_4", 2.4 ), 
						#( "V_Ray_Adv_2_5", 2.5 ), 
						#( "V_Ray_Adv_3_0", 3.0 ), 
						#( "V_Ray_Adv_3_1", 3.1 ), 
						#( "V_Ray_Adv_3_2", 3.2 ), 
						#( "V_Ray_Adv_3_3", 3.3 ), 			
						#( "V_Ray_Adv_3_4", 3.4 ),
						#( "V_Ray_Adv_3_5", 3.5 ),                        
						#( "V_Ray_Adv_3_6", 3.6 ),
						#( "V_Ray_Next__update_1", 4.1 ),
						#( "V_Ray_Next__update_2", 4.2 ),
						#( "V_Ray_Next__update_3", 4.3 ),
						#( "V_Ray_Next ",  4.0 ) 
			)
								
		local found = false												
		for each in TS_VrayVersions while false == found do
		(
			if 	matchPattern ( vrayInstalledVersions[1] as string ) pattern:(each[1] + "*") then
			(
				retVal[1] = each[2]
				retVal[2] = ( substring ( vrayInstalledVersions[1] as string ) 16 2 ) as integer 
				if (retVal[2] == undefined) then
					retVal[2]  = 0
				retVal[3] = vrayInstalledVersions[1]	
				found = true
			)
		)
	)
	
	set_vray_version( retVal[1] )	
	retVal 
)

function notExistsRenderElement rem classname = 
(
	local n =  rem.NumRenderElements()-1
	for i = 0 to n do 
	(
		local re = rem.GetRenderElement i
		local cn = (getclassname re)
		if cn == classname then
		(
			return false
		)
	)
	return true
)

function freezeObj i_obj =
(
	if isValidObj i_obj then	
	(
		freeze i_obj
	)
)

function getLayerName name: = 
(
	local layer = LayerManager.getLayerFromName name
	if layer == undefined then
	(
		layer = LayerManager.newLayerFromName name
	)
	layer
)

function addtoLayer layer: obj: =
(
	layer.addNode obj
	freezeObj obj
)

function getCameraTarget targetName: targetPos: displayBylayer: renderByLayer: =
(
	local targetObj = getnodebyname targetName
	if not isValidObj targetObj then 
	(
		targetObj = TargetObject pos:spherePos name:targetName
	) 
	else 
	(
		targetObj.pos = targetPos
	)
	targetObj.displayByLayer = displayBylayer
	targetObj.renderByLayer = renderByLayer
	targetObj
)

function validNumber i_num defaultVal:0 =
(
	local retval = defaultVal
	If i_num != undefined then
	(
		retVal = i_num
	)
	retVal
)

function deleteCameraPath = 
(
	if isValidObj $CameraPath then
	(
		delete $CameraPath
	)
)

function deleteShotCamera = 
(
	if isValidObj $ShotCamera then
	(
		delete $ShotCamera*
	)
)

function deleteRenderCamera = 
(
	if isValidObj $RenderCamera then
	(
		delete $RenderCamera
	)
)

function deleteSpinnerCamera = 
(
	if isValidObj $SpinnerCamera then
	(
		delete $SpinnerCamera
	)
)

function deleteCameras =
(
	deleteCameraPath()
	deleteShotCamera()	
	deleteRenderCamera()
	deleteSpinnerCamera()
)

fn setAnimationState startFrame: endFrame: =
(
	frameRate = 24
	animationRange = interval startFrame endFrame
)

function resetAnimation =
(
	slidertime = 0f
	deleteKeys objects #allKeys
	setAnimationState startFrame:0 endFrame:1
)

function selectObjKeys i_obj frameRange: =
(
	if isValidObj i_obj then
	(
		selectKeys i_obj frameRange
	)
)

function deleteObjKeysSelected i_object =
(
	if isValidObj i_object then
	(
		deleteKeys i_object #selection
	)
)

function deleteObjKeysAll i_object =
(
	if isValidObj i_object then
	(
		deleteKeys i_object #allKeys
	)
)

function moveObjKeysSelected i_object frame: =
(
	if isValidObj i_object then
	(
		moveKeys i_object frame #selection
	)
)

function deleteAllLightsKeys =
(
	deleteObjKeysAll $KeyLight
	deleteObjKeysAll $FillLight
	deleteObjKeysAll $BackLight
)

function deselectObjKeys i_object =
(
	if isValidObj i_object then
	(
		deselectKeys i_object
	)
)

function selectAllObjKeys frameRange: =
(
	selectObjKeys $ShotCamera frameRange:frameRange
	selectObjKeys $CameraPath frameRange:frameRange
	selectObjKeys $HeroObjectGroup frameRange:frameRange
	selectObjKeys $ShadowPlane frameRange:frameRange
	selectObjKeys $KeyLight frameRange:frameRange
	selectObjKeys $FillLight frameRange:frameRange
	selectObjKeys $BackLight frameRange:frameRange
)

function deleteAllObjKeysSelected =
(
	deleteObjKeysSelected $ShotCamera
	deleteObjKeysSelected $CameraPath	
	deleteObjKeysSelected $HeroObjectGroup
	deleteObjKeysSelected $ShadowPlane
	deleteObjKeysSelected $KeyLight
	deleteObjKeysSelected $FillLight
	deleteObjKeysSelected $BackLight
)

function moveAllObjKeysSelected  frame: =
(
	moveObjKeysSelected $ShotCamera  frame:frame 
	moveObjKeysSelected $CameraPath  frame:frame 	
	moveObjKeysSelected $HeroObjectGroup  frame:frame
	moveObjKeysSelected $ShadowPlane  frame:frame 
	moveObjKeysSelected $KeyLight  frame:frame 
	moveObjKeysSelected $FillLight  frame:frame 
	moveObjKeysSelected $BackLight  frame:frame 
)

function deselectAllObjKeys =
(
	deselectObjKeys $ShotCamera
	deselectObjKeys $CameraPath
	deselectObjKeys $HeroObjectGroup
	deselectObjKeys $ShadowPlane
	deselectObjKeys $KeyLight
	deselectObjKeys $FillLight
	deselectObjKeys $BackLight
)

function updateKeyLight i_selection value: =
(	
	if $KeyLight == undefined then
	(
		"No Key Light"
	)
	else
	(
		if i_selection >= 8 then
		(
			if i_selection == 8 then
			(
				$KeyLight.multiplier = 100 * value
			)
			if i_selection == 9 then
			(
				$KeyLight.multiplier = 25.5 * value
			)
		)
		else
		(
			$KeyLight.multiplier = 29 * value
		)
	)
)

function updateFillLight i_selection value: =
(
	if $FillLight == undefined then
	(
		"No Fill Light"
	)
	else
	(
		if i_selection >= 8 then
		(
			if i_selection == 8 then
			(
				$FillLight.multiplier = 15 * value
			)
			if i_selection == 9 then
			(
				$FillLight.multiplier = 9 * value
			)
		)
		else
		(
			$FillLight.multiplier = 22 * value
		)
	)
)

function updateBackLight i_selection value: =
(
	if $BackLight == undefined then
	(
		"No Back Light"
	)
	else
	(
		if i_selection == 8 then
		(
			$BackLight.multiplier = 50 * value
		)
		else
		(
			$BackLight.multiplier = 22 * value
		)
	)
)

function updateKeySpec i_selection value: =
(
	if $KeySpec == undefined then
	(
		"No Key Spec"
	)
	else
	(
		$KeySpec.multiplier = 10 * value
	)
)

function updateFillSpec i_selection value: =
(
	if $FillSpec == undefined then
	(
		"No Key Spec"
	)
	else
	(
		$FillSpec.multiplier = 10 * value
	)
)

fn showShadowPlane = 
(
	with animate on
	(
		if $SpinnerCamera.position.z >= 0 then
		(
			$ShadowPlane.visibility = true
		)
		else
		(
			$ShadowPlane.visibility = false
		)
	)
)

--********************************************************************************
--  Camera Rig Angle Function, returns the frame for the start of the next latitude
--********************************************************************************	
fn setCameraSpin startFrame: endFrame: spinX: =
(
	--print ( "\t\tsetCameraSpin [" + (startFrame as string ) + "][" + (endFrame as string ) + "][" + (spinX as string ) + "]" )
	
	local pathnode = $CameraPath
	with animate on
	(
		for t in startFrame to endFrame do
		(
			sliderTime = t
			
			-- set camera position ( at time t ) 
			PathCurTransform = pathnode.transform
			currentMatrix = matrix3 1
			currentMatrix.pos = PathCurTransform.pos
			--print ( "\t\t\t[" + (t as string ) + "]\tcurrentMatrix.pos[" + (currentMatrix.pos as string ) + "]" )		

			preRotate currentMatrix (eulertoquat (eulerAngles spinX 0 0))
			pathnode.transform = currentMatrix
			showShadowPlane()
			sliderTime += 1	

			--set camera rotation ( at time t + 1 )
			$CameraPath.rotation.x_rotation = spinX
		)
	)
	sliderTime
)

--********************************************************************************
--  create Spinner Camera Rig Angle animation
--********************************************************************************	
fn createCameraRigAnim =
(
	-- top half of spinner
	local camSpinX = -90.0
	local sframe = setCameraSpin startFrame:0f endFrame:0f spinX:camSpinX
	for i in 1 to 7 do
	(
		camSpinX += 11.25
		sframe = setCameraSpin startFrame:sframe endFrame:(sframe + 15) spinX:camSpinX
	)

	camSpinX = 0.0
	sframe = setCameraSpin startFrame:sframe endFrame:(sframe + 15) spinX:camSpinX

	-- lower half of spinner
	for i in 1 to 6 do
	(
		camSpinX += 11.25
		sframe = setCameraSpin startFrame:sframe endFrame:(sframe + 15) spinX:camSpinX
	)
		
	camSpinX = 90.0
	sframe = setCameraSpin startFrame:225 endFrame:225 spinX:camSpinX
	
	slidertime = 0f
)

--********************************************************************************
--  Lock Camera transforms to keep from accidentally movement
--********************************************************************************	
fn lockAntiBumpCam =
(
	setTransformLockFlags $SpinnerCamera #all
)
	
--********************************************************************************
--  Alters Half Spinner Angles for tall objects
--********************************************************************************	
fn AdjustHalfSpinCameraRig =
(
	local HW = $HeroObjectGroup.max.x - $HeroObjectGroup.min.x
	local HL = $HeroObjectGroup.max.y - $HeroObjectGroup.min.y
	local HH = ($HeroObjectGroup.max.z - $HeroObjectGroup.min.z) * .65

	setAnimationState startFrame:0 endFrame:128
	
	setCameraSpin startFrame:0f endFrame:0f spinX:-90.0
	
	sframe = 1f
	camSpinX = -90.0
	
	if HW <= HH or HL <= HH then
	(
		for i in 1 to 8 do
		(
			camSpinX += 12.85
			setCameraSpin startFrame:sframe endFrame:(sframe + 15) spinX:camSpinX
			sframe += 16
		)
		showShadowPlane()
		slidertime = 0f
	)
)

--********************************************************************************
--  create HeroObjectGroup Spinner animation
--********************************************************************************	
fn createGroupAnim startFrame: endFrame: =
(
	local Obj = $HeroObjectGroup
	local Shad = $ShadowPlane
	
	with animate on
	(
		-- always set first frames to zero
		for t in 0f to 1f do
		(
			sliderTime = t
			Obj.rotation.z_rotation = 0
			Shad.rotation.z_rotation = 0
		)
		
		for t in startFrame to endFrame do
		(
			sliderTime = t
			Obj.rotation.z_rotation = (Obj.rotation.z_rotation - 22.5)
			Shad.rotation.z_rotation = (Shad.rotation.z_rotation - 22.5)
		)
		slidertime = 0f
	)
)

-- *************************************************************************
-- PixelSquid Stage Setup UI
-- *************************************************************************
fn validate_scene =
(
	retVal = True
	getInstalledVRayVersion()	
	if ( (get_vray_version()) == 0.0 ) then
	(
		messagebox "Required Chaos Group's VRay Plugin not installed.\r\nPlease install VRay 2.3 - 3.6 or V_Ray_Next"
		retVal = False
	)
	else
	(
		if ( objects.count == 0  ) then
		(
			messagebox ( "Scene is empty, please load scene before running " + TS_SCRIPT_FULLNAME() )
			retVal = False
		)
	)
	retVal
)

if ( validate_scene() ) then
(
	try(closeRolloutFloater theNewFloater )catch(print "ok")

	rollout PsSTAGESETUP "PixelSquid Stage Setup" width:500 height:500
	(
		-- ----------------------------------------------------------------------------------------
		-- UI items
		-- ----------------------------------------------------------------------------------------
		GroupBox grp1 "Scene Preparation" pos:[6,4] width:445 height:70
		button clear_btn "Clear Scene" pos:[14,22] width:196 height:21 tooltip:"Deletes everything in your scene if needing to start over."
		checkbox keep_selection_only "Keep Selection in Scene" pos:[28,47] width:160 height:15 tooltip:"Using Clear Scene button will delete everything except selected objects when checked."
		button prepare_scene "Prep Scene" pos:[246, 22] width:196 height:21 tooltip:"Groups all objects in scene together. Then builds stage around model group setting required preferences and render settings for linear workflow."
		checkbox use_selection_only "Use Selection as Model" pos:[260,47] width:160 height:15 tooltip:"Prep Scene button uses only selection as Object Group when checked."

		GroupBox grp3 "Lighting" pos:[6,77] width:445 height:100
		dropdownlist lightrig_dd pos:[14,97] width:196 height:21 items:#("Product Shot","Outdoors - Morning","Outdoors - Mid Day","Outdoors - Sunset","Automotive - Classic","Automotive - Tech","Character","Food") tooltip:"Choose the Light Studio setup that would best fit the model type."
		button rig_btn "Create Light Rig" pos:[14,125] width:196 height:21 tooltip:"Creates general use 3-Point Light rig with left focus. HDRI Dome Light created for ambient light and reflections."
		spinner rig_pt_level "3-Point Intensity:" pos:[110,150] width:70 height:16 range:[0,1e+009,1] tooltip:"Evenly controls the Light Intensity on VRay Plane lights."
		spinner rig_dom_level "HDRI Intensity:" pos:[350,130] width:70 height:16 range:[0,1e+009,1] tooltip:"Controls Dome Light intensity for HDRI and Environment HDRI multiplier."
		spinner e_height "Character Eye Level:" pos:[350,150] width:70 height:16 height:16 range:[0,100,92] tooltip:"Adjust the height of Hi Lights for the eyes."
		label rig_tag "Current Rig:" pos:[243,99]
		combobox rig_choice pos:[303,97] width:140 height:0 items:#(" None","Product Shot","Outdoors - Morning","Outdoors - Mid Day","Outdoors - Sunset","Automotive - Classic","Automotive - Tech","Character","Food") enabled:false
		
		GroupBox grp4 "Render Setting" pos:[6,181] width:445 height:54
		button loq_btn "Low Quality" pos:[14,201] width:140 height: 21 tooltip:"Rough 600x600 renders for quick view. Ideal for saving time viewing changes during texturing process."
		button miq_btn "Medium Quality" pos:[158,201] width:140 height: 21 tooltip:"Clean 1024x1024 renders for larger more detailed view. Best for fine tuning textures and checking for render issues."
		button hiq_btn "High Quality" pos:[303,201] width:140 height: 21 tooltip:"Final Quality 2048x2048 renders for submission. Long render times. Use only when ready to submit."
		
		-- ----------------------------------------------------------------------------------------
		-- Functions
		-- ----------------------------------------------------------------------------------------
		fn lockRollout =
		(
			lightrig_dd.enabled = false		
			rig_btn.enabled = false
			rig_pt_level.enabled = false
			rig_dom_level.enabled = false
			e_height.enabled =false
			loq_btn.enabled = false
			miq_btn.enabled = false
			hiq_btn.enabled = false
		)
		
		fn unlockRollout =
		(
			lightrig_dd.enabled = true
			rig_btn.enabled = true
			rig_pt_level.enabled = true
			rig_dom_level.enabled = true
			e_height.enabled = true
			loq_btn.enabled = true
			miq_btn.enabled = true
			hiq_btn.enabled = true
		)
		
		function findExistingObjects = 
		(
			cameraObj = $ShotCamera
			camP = $CameraPath
			
			if isValidObj cameraObj and isValidObj camP then
			(
				sphereRadius = camP.radius
			)
		)
		
		function makeThreePoint = 
		(
			-- create LightRig
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			
			If $KeyLight == undefined then
			(
				VRayLight name:"KeyLight" pos:((normalize [-88.615,-211.47,120.052]) * lightRadius * 3.6) on:true type:0 multiplier:(29 * rig_pt_level.value) invisible:true size0:(lightRadius * .333) size1:(lightRadius * .333) lightDistribution:0 subdivs:24
				setTransformLockFlags $KeyLight #{7..9}
				$KeyLight.rotation.controller = LookAt_Constraint()
				$KeyLight.rotation.controller.appendTarget $HeroObjectGroup 50
				$KeyLight.rotation.controller.target_axis = 2
				$KeyLight.rotation.controller.upnode_axis = 1
				$KeyLight.rotation.controller.StoUP_axis = 1
				$KeyLight.rotation.controller.target_axisFlip = on
				$KeyLight.rotation.controller.upnode_axis = 2
				$KeyLight.affect_specualr = off
				$KeyLight.affect_reflections = off
				
				freezeObj $KeyLight
			)
			
			If $FillLight == undefined then
			(
				VRayLight name:"FillLight" pos:((normalize [182.496,-103.242,270.779]) * lightRadius * 5) on:true type:0 multiplier:(22 * rig_pt_level.value) invisible:true size0:(lightRadius * .4) size1:(lightRadius * .4) lightDistribution:0 subdivs:24
				setTransformLockFlags $FillLight #{7..9}
				$FillLight.rotation.controller = LookAt_Constraint()
				$FillLight.rotation.controller.appendTarget $HeroObjectGroup 50
				$FillLight.rotation.controller.target_axis = 2
				$FillLight.rotation.controller.upnode_axis = 1
				$FillLight.rotation.controller.StoUP_axis = 1
				$FillLight.rotation.controller.target_axisFlip = on
				$FillLight.rotation.controller.upnode_axis = 2
				$FillLight.affect_specualr = off
				$FillLight.affect_reflections = off
				
				freezeObj $FillLight
			)
			
			If $BackLight == undefined then
			(
				VRayLight name:"BackLight" pos:((normalize [18.546,216.322,270.258]) * lightRadius * 5) on:true type:0 multiplier:(22 * rig_pt_level.value) invisible:true size0:(lightRadius * .333) size1:(lightRadius * .333) lightDistribution:0 subdivs:24
				setTransformLockFlags $BackLight #{7..9}
				$BackLight.rotation.controller = LookAt_Constraint()
				$BackLight.rotation.controller.appendTarget $HeroObjectGroup 50
				$BackLight.rotation.controller.target_axis = 2
				$BackLight.rotation.controller.upnode_axis = 1
				$BackLight.rotation.controller.StoUP_axis = 1
				$BackLight.rotation.controller.target_axisFlip = on
				$BackLight.rotation.controller.upnode_axis = 2
				$BackLight.affect_specualr = off
				$BackLight.affect_reflections = off
				
				freezeObj $BackLight
			)
			
			If $KeySpec == undefined then
			(
				VRayLight name:"KeySpec" pos:((normalize [-98.2,.35,60]) * lightRadius * 1.9425) on:true type:0 multiplier:(10 * rig_pt_level.value) invisible:true size0:(lightRadius * .5) size1:(lightRadius * .5) lightDistribution:0 subdivs:24
				setTransformLockFlags $KeySpec #{7..9}
				$KeySpec.rotation.controller = LookAt_Constraint()
				$KeySpec.rotation.controller.appendTarget $HeroObjectGroup 50
				$KeySpec.rotation.controller.target_axis = 2
				$KeySpec.rotation.controller.upnode_axis = 1
				$KeySpec.rotation.controller.StoUP_axis = 1
				$KeySpec.rotation.controller.target_axisFlip = on
				$KeySpec.rotation.controller.upnode_axis = 2
				$KeySpec.castShadows = off
				$KeySpec.affect_diffuse = off
				$KeySpec.affect_specualr = on
				$KeySpec.affect_reflections = off
				
				freezeObj $KeySpec
			)
			
			If $FillSpec == undefined then
			(
				VRayLight name:"FillSpec" pos:((normalize [97,.326,106]) * lightRadius * 2.847) on:true type:0 multiplier:(10 * rig_pt_level.value) invisible:true size0:(lightRadius * .5) size1:(lightRadius * .5) lightDistribution:0 subdivs:24
				setTransformLockFlags $FillSpec #{7..9}
				$FillSpec.rotation.controller = LookAt_Constraint()
				$FillSpec.rotation.controller.appendTarget $HeroObjectGroup 50
				$FillSpec.rotation.controller.target_axis = 2
				$FillSpec.rotation.controller.upnode_axis = 1
				$FillSpec.rotation.controller.StoUP_axis = 1
				$FillSpec.rotation.controller.target_axisFlip = on
				$FillSpec.rotation.controller.upnode_axis = 2
				$FillSpec.castShadows = off
				$FillSpec.affect_diffuse = off
				$FillSpec.affect_specualr = on
				$FillSpec.affect_reflections = off
				
				freezeObj $FillSpec
			)
		)
		
		function makeMRThreePoint = 
		(
			-- create LightRig
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			lightMulti = .5*(length groupdiag)/44
			
			If $KeyLight == undefined then
			(
				miAreaLight name:"KeyLight" pos:((normalize [-136.971,-178.896,117.97]) * lightRadius * 3.6) on:true target:(targetObject pos:[0,0,0]) Rectangle_Height:(lightRadius * .2985) Rectangle_Width:(lightRadius * .2985) coneShape:2 hotspot:0.5 falloff:179.5
				$KeyLight.multiplier = ((lightMulti * 11) * rig_pt_level.value)
				$KeyLight.affectSpecular = off
				$KeyLight.castShadows = on
				$Keylight.attenDecay =  2
				setTransformLockFlags $KeyLight #{7..9}
				
				freezeObj $KeyLight
			)
			
			If $FillLight == undefined then
			(
				miAreaLight name:"FillLight" pos:((normalize [82.496,-103.242,270.779]) * lightRadius * 5) on:true target:(targetObject pos:[0,0,0]) Rectangle_Height:(lightRadius * .35) Rectangle_Width:(lightRadius * .35) coneShape:2 hotspot:0.5 falloff:179.5
				$FillLight.multiplier = ((lightMulti * 8) * rig_pt_level.value)
				$FillLight.affectSpecular = off
				$FillLight.castShadows = on
				$FillLight.attenDecay =  2
				setTransformLockFlags $FillLight #{7..9}
				
				freezeObj $FillLight
			)
			
			If $BackLight == undefined then
			(
				miAreaLight name:"BackLight" pos:((normalize [18.546,216.322,270.258]) * lightRadius * 5) on:true target:(targetObject pos:[0,0,0]) Rectangle_Height:(lightRadius * .2985) Rectangle_Width:(lightRadius * .2985) coneShape:2 hotspot:0.5 falloff:179.5
				$BackLight.multiplier = ((lightMulti * 8) * rig_pt_level.value)
				$BackLight.affectSpecular = off
				$BackLight.castShadows = on
				$BackLight.attenDecay =  2
				setTransformLockFlags $BackLight #{7..9}
				
				freezeObj $BackLight
			)
			
			If $KeySpec == undefined then
			(
				miAreaLight name:"KeySpec" pos:((normalize [-98.2,.35,60]) * lightRadius * 1.9425) on:true target:(targetObject pos:[0,0,0]) Rectangle_Height:(lightRadius * .2985) Rectangle_Width:(lightRadius * .2985) coneShape:2 hotspot:0.5 falloff:179.5 castShadows:off
				$KeySpec.multiplier = ((lightMulti * 2) * rig_pt_level.value)
				$KeySpec.affectDiffuse = off
				$KeySpec.affectSpecular = on
				$KeySpec.castShadows = off
				$KeySpec.attenDecay =  2
				setTransformLockFlags $KeySpec #{7..9}
				
				freezeObj $KeySpec
			)
			
			If $FillSpec == undefined then
			(
				miAreaLight name:"FillSpec" pos:((normalize [97,.326,106]) * lightRadius * 2.847) on:true target:(targetObject pos:[0,0,0]) Rectangle_Height:(lightRadius * .2985) Rectangle_Width:(lightRadius * .2985) coneShape:2 hotspot:0.5 falloff:179.5 castShadows:off
				$FillSpec.multiplier = ((lightMulti * 2) * rig_pt_level.value)
				$FillSpec.affectDiffuse = off
				$FillSpec.affectSpecular = on
				$FillSpec.castShadows = off
				$FillSpec.attenDecay =  2
				setTransformLockFlags $FillSpec #{7..9}
				
				freezeObj $FillSpec
			)
		)
		
		fn ObjCheck =
		(
			if objects.count == 0 then
			(
				prepare_scene.enabled = false
			)
			else
			(
				prepare_scene.enabled = true
			)
		)
		
		
		-- *************************************************************************
		-- Group lights with 0,0,0 pivot
		-- *************************************************************************
		fn GroupLights =
		(
			clearselection()
			
			dummy name:"LightDummy"
			Group $LightDummy name:"RigControlGroup"
			setGroupOpen $RigControlGroup true
			(layerManager.getLayerFromName "Lights").select true
			lrig = getCurrentSelection()
			attachNodesToGroup lrig $RigControlGroup
			delete $LightDummy
			
			setGroupOpen $RigControlGroup false
			
			local layer = getLayerName name:"Lights"
			layer.addNode $RigControlGroup
			
			clearselection()
		)
		
		fn RendSetClose =
		(
			if RenderSceneDialog.isOpen() == true then
			(
				RendDialStatus = true
				RenderSceneDialog.close()
			)
			else
			(
				RendDialStatus = false
			)
		)
		
		fn RendSetOpen =
		(
			if RendDialStatus == true then
			(
				RenderSceneDialog.open()
			)
			else		
			(
				RenderSceneDialog.close()
			)
		)
		
		-- ----------------------------------------------------------------------------------------
		-- Event handlers
		-- ----------------------------------------------------------------------------------------
		
		-- load persistant values
		on PsSTAGESETUP open do 
		(
			useVray = true
			
			getInstalledVRayVersion  currentVersion:false
			
			registerRollout PsSTAGESETUP RolloutName:#SetupRollout
			ObjCheck()
			
			if not isValidObj $HeroObjectGroup then
			(
				lockRollout()
			)
			if isValidObj $SunLight then
			(
				rig_pt_level.enabled = false
			)
			
			prepare_scene.enabled = not sceneHasBeenPrepped()
			
			g_lightlevel = validNumber g_lightlevel defaultVal:1.0
			rig_pt_level.value = g_lightlevel
			
			d_lightlevel = validNumber d_lightlevel defaultVal:1.0
			rig_dom_level.value = d_lightlevel
		
			rig_sel = validNumber rig_sel defaultVal:1		
			rig_choice.selection = rig_sel
			
			if rig_sel == 5 then
			(
				e_height.enabled = true
			)
			else
			(
				e_height.enabled = false
			)
		
			eye_h = validNumber eye_h defaultVal:92	
			e_height.value = eye_h
			
			keep_selection_only.checked = true
		)
		
		-- save persistant values
		on PsSTAGESETUP close do 
		(
			g_lightlevel = rig_pt_level.value
			d_lightlevel = rig_dom_level.value
	-- 		c_lightlevel = rig_card_level.value
	-- 		c_rotatelevel = card_rot_level.value
			eye_h = e_height.value
			rig_sel = rig_choice.selection
		)
		
		on rig_pt_level changed light_value do
		(
			undo on
			(
				If (isValidOBJ $KeyLight and $KeyLight.multiplier.isAnimated == true) or (isValidOBJ $FillLight and $FillLight.multiplier.isAnimated == true) or (isValidOBJ $BackLight and $BackLight.multiplier.isAnimated == true) then
				(
					if querybox "This will clear any multiplier keyframes on the point lights. Do you want to continue?" beep:true then
					(
						deleteAllLightsKeys()
						if $KeyLight == undefined or $FillLight == undefined then
						(
							rig_pt_level.enabled = false
							messagebox "One or more of the required lights cannot be found. Generate light rig."
						)
						if useVray == true then
						(
							updateKeyLight rig_choice.selection value:light_value
							updateFillLight rig_choice.selection value:light_value
							updateBackLight rig_choice.selection value:light_value
							updateKeySpec rig_choice.selection  value:light_value
							updateFillSpec rig_choice.selection  value:light_value
						)
						else
						(
							updateKeyLightMR rig_choice.selection value:light_value
							updateFillLightMR rig_choice.selection value:light_value
							updateBackLightMR rig_choice.selection value:light_value
							updateKeySpecMR rig_choice.selection  value:light_value
							updateFillSpecMR rig_choice.selection  value:light_value
						)
					)
				)
				else
				(
					if $KeyLight == undefined or $FillLight == undefined then
					(
						rig_pt_level.enabled = false
						messagebox "One or more of the required lights cannot be found. Generate light rig."
					)
					if useVray == true then
					(
						updateKeyLight rig_choice.selection value:light_value
						updateFillLight rig_choice.selection value:light_value
						updateBackLight rig_choice.selection value:light_value
						updateKeySpec rig_choice.selection  value:light_value
						updateFillSpec rig_choice.selection  value:light_value
					)
					else
					(
						updateKeyLightMR rig_choice.selection value:light_value
						updateFillLightMR rig_choice.selection value:light_value
						updateBackLightMR rig_choice.selection value:light_value
						updateKeySpecMR rig_choice.selection  value:light_value
						updateFillSpecMR rig_choice.selection  value:light_value
					)
				)
			)
		)
		
		fn intMorning i_d_light_value =
		(
			$SunLight.multiplier = (6 *  i_d_light_value)
		)
		fn intMorningMR i_d_light_value =
		(
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightMulti = .5*(length groupdiag)/44
			$SunLight.multiplier = ((lightMulti * 60) *  i_d_light_value)
		)
			
		fn intMidDay i_d_light_value =
		(
			$SunLight.multiplier = (6 *  i_d_light_value)
		)
		fn intMidDayMR i_d_light_value =
		(
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightMulti = .5*(length groupdiag)/44
			$SunLight.multiplier = ((lightMulti * 60) *  i_d_light_value)
		)
			
		fn intSunset i_d_light_value =
		(
			$SunLight.multiplier = (6 *  i_d_light_value)
		)
		fn intSunsetMR i_d_light_value =
		(
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightMulti = .5*(length groupdiag)/44
			$SunLight.multiplier = ((lightMulti * 60) *  i_d_light_value)
		)
				
		fn intNight i_d_light_value =
		(
			$SunLight.multiplier = (.75 *  i_d_light_value)
		)
		fn intNightMR i_d_light_value =
		(
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightMulti = .5*(length groupdiag)/44
			$SunLight.multiplier = ((lightMulti * 7.5) *  i_d_light_value)
		)
		
		fn setColorMappingVersionDefault vrayVersion =
		(
			if vrayVersion[1] == 2.3 then
			(
				renderers.current.colorMapping_adaptationOnly = true                
			)
			else if vrayVersion[1] == 2.4 then
			(
				-- vray changed colorMapping_adaptationOnly from boolean to integer at  version 2_40_04
				if vrayVersion[2] < 4 then
				(
					renderers.current.colorMapping_adaptationOnly = true
				)
				else
				(
					renderers.current.colorMapping_adaptationOnly = 2
				)                
			)
			else
			(
				renderers.current.colorMapping_adaptationOnly = 2                
			)
		)
		
		/*
		Assign Renderer to the current vray installed 2.3 - 3.6
		Enable VRay Frame Buffer
		Turn on VRay GI
		Set Anitaliasing Parameters
		Set VRay Environment Map  Parameters
		Set Color Mapping Parameters for Linear Workflow
		Setting Adjustments
		*/
		
		fn setCurrentRenderer_VRAY =
		(
			local d_lightlevel = rig_dom_level.value
			
			vrayVersion = (getInstalledVRayVersion  currentVersion:false)
			print ( vrayVersion )
			
			local createVray = ( vrayVersion[3] as string ) + "()"
				
			renderers.current = execute( createVray )
			
			vr = renderers.current					
			setColorMappingVersionDefault( vrayVersion )
			
			vr.output_on = true
			vr.gi_on = true
			vr.gi_irradmap_showCalcPhase = true
			vr.gi_irradmap_showDirectLight = true
			vr.lightcache_showCalcPhase = 1
			vr.gi_primary_type = 0
			vr.gi_secondary_type = 3
			vr.gi_irradmap_preset = 2
			
			vr.imageSampler_type = 1
			vr.filter_on = true
			vr.filter_kernel = Mitchell_Netravali()
			
			vr.environment_gi_on = true
			vr.environment_gi_color = (color 255 255 255)
			vr.environment_gi_color_multiplier = 1
			vr.environment_rr_on =true
			vr.environment_rr_color = (color 255 255 255)
			vr.environment_rr_color_multiplier = 1
			
			vr.colorMapping_type = 0
			vr.colorMapping_darkMult = 1
			vr.colorMapping_brightMult = 1
			vr.colorMapping_gamma = 2.2
			vr.colorMapping_subpixel = true
			vr.colorMapping_clampOutput = false
			vr.colorMapping_affectBackground = false
			vr.colorMapping_linearWorkflow = false
			
			vr.dmc_earlyTermination_minSamples = 8
			vr.dmc_subdivs_mult = 1
			vr.system_raycaster_memLimit = 4000
			vr.system_region_x = 60
				
			If (get_vray_version()) >= 3 then
			(
				vr.imageSampler_type = 1
				vr.imageSampler_shadingRate = 16
				vr.filter_kernel = Area()
				vr.twoLevel_useDMCSamplerThresh = false
				vr.gi_irradmap_maxRate = -1
				vr.adv_irradmap_useCurrentPassSamples = false
				vr.lightcache_subdivs = 600
				vr.lightcache_prefilter_on = true
				vr.lightcache_prefilter_samples = 30
				vr.lightcache_interpSamples = 10
				vr.lightcache_useForGlossyRays = false
				vr.lightcache_retrace_on = false	
			)
		)
		
		on rig_dom_level changed d_light_value do
		(
			undo on
			(
				if $SunLight == undefined then
				(
					"No Sunlight"
				)
				else
				(
					case outrig of
					(
						1:
						(
							if useVray == true then
							(
								intMorning d_light_value
							)
							else
							(
								intMorningMR d_light_value
							)
						)
						2:
						(
							if useVray == true then
							(
								intMidDay d_light_value
							)
							else
							(
								intMidDayMR d_light_value
							)
						)
						3:
						(
							if useVray == true then
							(
								intSunset d_light_value
							)
							else
							(
								intSunsetMR d_light_value
							)
						)
						4:
						(
							if useVray == true then
							(
								intNight d_light_value
							)
							else
							(
								intNightMR d_light_value
							)
						)
						default:
						(
							throw ( "unknown outrig=[" + ( outrig as string ) + "]" )
						)
					)
				)
				
				if useVray == true then
				(
					If meditMaterials["Environment_HDRI"] == undefined then
					(
						messagebox "Environment_HDRI is not in the Material Editor or is missing. Instance material from Environment Override slots to the Material Editor or generate light rig."
					)
					else
					(
						meditMaterials["Environment_HDRI"].multiplier = 1 * d_light_value
					)
				)
				else
				(
					If environmentMap == undefined then
					(
						messagebox "Environment_HDRI is not in the Material Editor or is missing. Instance material from Environment Override slots to the Material Editor or generate light rig."
					)
					else
					(
						meditMaterials[24] = environmentMap
						meditMaterials[24].environment_shader.output.output_amount = d_light_value
					)
				)
			)
		)
		
		on e_height changed h_level do
		(
			undo on
			(
				$HiLight_Target.pos.z = $HeroObjectGroup.max.z * (h_level/100)
				$HiLight1.pos.z = ($HeroObjectGroup.max.z * (h_level/100)) + 13.146
				$HiLight2.pos.z = ($HeroObjectGroup.max.z * (h_level/100)) + 13.146
			)
		)
		
		--********************************************************************************
		--  create Lighting Rig "Product Shot" on i_layer
		--********************************************************************************	
		fn createLightRigProductShot i_layer =
		(
			deleteLights()
			environmentMap = none
			
			local env =  getTextureFileAndPath texFile:#TSHERO_HDRI
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2 horizontalRotation:45
			EnvHDR.horizontalFlip = false
			
			meditMaterials[24] = EnvHDR
			
			makeThreePoint()
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			i_layer.addNode $KeyLight
			i_layer.addNode $FillLight
			i_layer.addNode $BackLight
			i_layer.addNode $KeySpec
			i_layer.addNode $FillSpec
			
			rig_pt_level.enabled = true
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			rig_choice.selection = 2
			UseEnvironmentMap = off
		)
		
		--********************************************************************************
		--  create Lighting Rig 'Outdoors - Morning' on i_layer
		--********************************************************************************	
		fn createLightRigOutdoorsMorning i_layer =
		(
			deleteLights()
			environmentMap = none
			outrig = 1
			
			local env = getTextureFileAndPath texFile:#HDRISKY_MORNING 
			local sun = getTextureFileAndPath texFile:#HDRISUN_MORNING
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local Light_tex = Bitmaptexture name:"Morning_Sun" filename:sun
			Light_tex.coords.U_Tiling = 2
			Light_tex.coords.V_Tiling= 2
			Light_tex.coords.U_Tile = false
			Light_tex.coords.V_Tile= false
			Light_tex.coords.blur = 0.1
			
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2 horizontalRotation:150
			EnvHDR.horizontalFlip = false
			
			meditMaterials[24] = EnvHDR
			
			-- create LightRig
			If $SunLight == undefined then
			(
				VRayLight name:"SunLight" pos:((normalize [-242.147,-0,141.159]) * lightRadius * 3.6) on:true texmap:Light_tex type:0 multiplier:(6 * d_lightlevel) invisible:true size0:(lightRadius * .0205) size1:(lightRadius * .0205) lightDistribution:0 subdivs:24
				sunCurTransform = $SunLight.transform
				currentMatrix = matrix3 1
				currentMatrix.pos = sunCurTransform.pos
				Rotate currentMatrix (eulertoquat (eulerAngles 0 0  30))
				$SunLight.transform = currentMatrix
				
				$SunLight.rotation.controller = LookAt_Constraint()
				$SunLight.rotation.controller.appendTarget $ShadowPlane 50
				$SunLight.rotation.controller.target_axis = 2
				$SunLight.rotation.controller.upnode_axis = 1
				$SunLight.rotation.controller.StoUP_axis = 1
				$SunLight.rotation.controller.target_axisFlip = on
				$SunLight.rotation.controller.upnode_axis = 2
				$SunLight.noDecay = on
				$SunLight.affect_diffuse = on
				$SunLight.affect_specualr = on
				$SunLight.affect_reflections = on
				
				i_layer.addNode $SunLight
				freeze $SunLight
			)
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			rig_pt_level.enabled = false
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			rig_choice.selection = 3
			UseEnvironmentMap = off
		)

		--********************************************************************************
		--  create Lighting Rig 'Outdoors - Mid Day' on i_layer
		--********************************************************************************	
		fn createLightRigOutdoorsMidDay i_layer =
		(
			deleteLights()
			environmentMap = none
			outrig = 2
			
			local env = getTextureFileAndPath texFile:#HDRISKY_MIDDAY
			local sun = getTextureFileAndPath texFile:#HDRISUN_MIDDAY
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local Light_tex = Bitmaptexture name:"Mid-Day_Sun" filename:sun
			Light_tex.coords.U_Tiling = 1
			Light_tex.coords.V_Tiling= 1
			Light_tex.coords.U_Tile = false
			Light_tex.coords.V_Tile= false
			Light_tex.coords.blur = 0.1
			
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2 horizontalRotation:150
			EnvHDR.horizontalFlip = false
			
			meditMaterials[24] = EnvHDR
			
			-- create LightRig
			If $SunLight == undefined then
			(
				VRayLight name:"SunLight" pos:((normalize [-185.332,-0,307.441]) * lightRadius * 3.6) on:true texmap:Light_tex texmap_resolution:1024 type:0 multiplier:(6 * d_lightlevel) invisible:true size0:(lightRadius * .0205) size1:(lightRadius * .0205) lightDistribution:0 subdivs:24
				sunCurTransform = $SunLight.transform
				currentMatrix = matrix3 1
				currentMatrix.pos = sunCurTransform.pos
				Rotate currentMatrix (eulertoquat (eulerAngles 0 0  30))
				 $SunLight.transform = currentMatrix
				
				$SunLight.rotation.controller = LookAt_Constraint()
				$SunLight.rotation.controller.appendTarget $ShadowPlane 50
				$SunLight.rotation.controller.target_axis = 2
				$SunLight.rotation.controller.upnode_axis = 1
				$SunLight.rotation.controller.StoUP_axis = 1
				$SunLight.rotation.controller.target_axisFlip = on
				$SunLight.rotation.controller.upnode_axis = 2
				$SunLight.noDecay = on
				$SunLight.affect_diffuse = on
				$SunLight.affect_specualr = on
				$SunLight.affect_reflections = on
				
				i_layer.addNode $SunLight
				freezeObj $SunLight
			)
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			rig_pt_level.enabled = false
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			rig_choice.selection = 4
			UseEnvironmentMap = off
		)
		
		--********************************************************************************
		--  create Lighting Rig 'Outdoors - Sunset' on i_layer
		--********************************************************************************	
		fn createLightRigOutdoorsSunset i_layer =
		(
			deleteLights()
			environmentMap = none
			outrig = 3
			
			local env = getTextureFileAndPath texFile:#HDRISKY_SUNSET
			local sun = getTextureFileAndPath texFile:#HDRISUN_SUNSET
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local Light_tex = Bitmaptexture name:"Sunset_Sun" filename:sun
			Light_tex.coords.U_Tiling = 2
			Light_tex.coords.V_Tiling= 2
			Light_tex.coords.U_Tile = false
			Light_tex.coords.V_Tile= false
			Light_tex.coords.blur = 0.1
			
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2 horizontalRotation:150
			EnvHDR.horizontalFlip = false
			
			meditMaterials[24] = EnvHDR
			
			-- create LightRig
			If $SunLight == undefined then
			(
				VRayLight name:"SunLight" pos:((normalize [-242.152,-0,42.479]) * lightRadius * 3.6) on:true texmap:Light_tex type:0 multiplier:(6 * d_lightlevel) invisible:true size0:(lightRadius * .0205) size1:(lightRadius * .0205) lightDistribution:0 subdivs:24
				sunCurTransform = $SunLight.transform
				currentMatrix = matrix3 1
				currentMatrix.pos = sunCurTransform.pos
				Rotate currentMatrix (eulertoquat (eulerAngles 0 0  30))
				$SunLight.transform = currentMatrix
				
				$SunLight.rotation.controller = LookAt_Constraint()
				$SunLight.rotation.controller.appendTarget $ShadowPlane 50
				$SunLight.rotation.controller.target_axis = 2
				$SunLight.rotation.controller.upnode_axis = 1
				$SunLight.rotation.controller.StoUP_axis = 1
				$SunLight.rotation.controller.target_axisFlip = on
				$SunLight.rotation.controller.upnode_axis = 2
				$SunLight.noDecay = on
				$SunLight.affect_diffuse = on
				$SunLight.affect_specualr = on
				$SunLight.affect_reflections = on
				
				i_layer.addNode $SunLight
				freeze $SunLight
			)
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			rig_pt_level.enabled = false
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			rig_choice.selection = 5
			UseEnvironmentMap = off
		)
		
		--********************************************************************************
		--  create Lighting "Automotive - Classic" on i_layer
		--********************************************************************************	
		fn createLightRigAutomotiveClassic i_layer =
		(
			deleteLights()
			environmentMap = none

			local env = getTextureFileAndPath texFile:#TSHERO_CARCLASSIC
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2
			
			meditMaterials[24] = EnvHDR
			
			makeThreePoint()
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			rig_pt_level.enabled = true
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			i_layer.addNode $KeyLight
			i_layer.addNode $FillLight
			i_layer.addNode $BackLight
			i_layer.addNode $KeySpec
			i_layer.addNode $FillSpec
			
			rig_choice.selection = 6
			UseEnvironmentMap = off
		)
		
		--********************************************************************************
		--  create Lighting "Automotive - Tech" on i_layer
		--********************************************************************************	
		fn createLightRigAutomotiveTech i_layer =
		(
			deleteLights()
			environmentMap = none
			
			local env = getTextureFileAndPath texFile:#TSHERO_CARTECH
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2
			
			meditMaterials[24] = EnvHDR
			
			makeThreePoint()
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			rig_pt_level.enabled = true
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			i_layer.addNode $KeyLight
			i_layer.addNode $FillLight
			i_layer.addNode $BackLight
			i_layer.addNode $KeySpec
			i_layer.addNode $FillSpec
			
			rig_choice.selection = 7
			UseEnvironmentMap = off
		)

		--********************************************************************************
		--  create Lighting Rig Character on i_layer
		--********************************************************************************	
		fn createLightRigCharacter i_layer =
		(
			deleteLights()
			environmentMap = none
			
			local env = getTextureFileAndPath texFile:#TSHERO_HDRI
			local lightTex = getTextureFileAndPath texFile:#LIGHTGLOW_CARD

			local Light_tex = Bitmaptexture name:"Lights" filename:LightTex
			Light_tex.coords.U_Tiling = 1
			Light_tex.coords.V_Tiling= 1
			Light_tex.coords.U_Tile = false
			Light_tex.coords.V_Tile= false
			Light_tex.coords.blur = 0.1
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2 horizontalRotation:90
			EnvHDR.horizontalFlip = false
			local targ3 = targetObject name:"3-Point Target" pos:[0,0,$HeroObjectGroup.max.z * .83]
			local targHi = targetObject name:"HiLight_Target" pos:[0,0,$HeroObjectGroup.max.z * (eye_h/100)]
			
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			
			meditMaterials[24] = EnvHDR
			
			If $HiLight1 == undefined then
			(
				VRayLight name:"HiLight1" pos:[-79.369,-65.894,($HeroObjectGroup.max.z * (eye_h/100)) + 13.146] target:targHi on:true type:0 multiplier:(1) invisible:true size0:(lightRadius * .0138) size1:(lightRadius * .0138) lightDistribution:.75 subdivs:24
				setTransformLockFlags $HiLight1 #{7..9}
				$HiLight1.affect_diffuse = off
				$HiLight1.affect_specualr = on
				$HiLight1.affect_reflections = on
				
				freezeObj $HiLight1
			)
			
			If $HiLight2 == undefined then
			(
				VRayLight name:"HiLight2" pos:[79.369,-65.894,($HeroObjectGroup.max.z * (eye_h/100)) + 13.146] target:targHi on:true type:0 multiplier:(1) invisible:true size0:(lightRadius * .0138) size1:(lightRadius * .0138) lightDistribution:.75 subdivs:24
				setTransformLockFlags $HiLight2 #{7..9}
				$HiLight2.affect_diffuse = off
				$HiLight2.affect_specualr = on
				$HiLight2.affect_reflections = on
				
				freezeObj $HiLight2
			)
			
			If $KeyLight == undefined then
			(
				VRayLight name:"KeyLight" pos:((normalize [-267.372,-139.643,154.87]) * lightRadius * .46814) target:targ3 on:true texmap:Light_tex type:0 multiplier:(100 * lightlevel) invisible:true size0:(lightRadius * .087115) size1:(lightRadius * .12172) lightDistribution:0 subdivs:24
				setTransformLockFlags $KeyLight #{7..9}
				$KeyLight.affect_diffuse = on
				$KeyLight.affect_specualr = on
				$KeyLight.affect_reflections = on
				
				freezeObj $KeyLight
			)
			
			If $FillLight == undefined then
			(
				VRayLight name:"FillLight" pos:((normalize [266.63,-104.305,153.942]) * lightRadius * .4488) target:targ3 on:true texmap:Light_tex type:0 multiplier:(15 * lightlevel) invisible:true size0:(lightRadius * .087115) size1:(lightRadius * .12172) lightDistribution:0 subdivs:24
				setTransformLockFlags $FillLight #{7..9}
				$FillLight.affect_diffuse = on
				$FillLight.affect_specualr = on
				$FillLight.affect_reflections = on
				
				freezeObj $FillLight
			)
			
			If $BackLight == undefined then
			(
				VRayLight name:"BackLight" pos:((normalize [204.149,199.56,233.717]) * lightRadius * .509365) target:targ3 on:true texmap:Light_tex type:0 multiplier:(50 * lightlevel) invisible:true size0:(lightRadius * .16567) size1:(lightRadius * .12172) lightDistribution:0 subdivs:24
				setTransformLockFlags $BackLight #{7..9}

				$BackLight.affect_diffuse = on
				$BackLight.affect_specualr = on
				$BackLight.affect_reflections = on
				
				freezeObj $BackLight
			)
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			i_layer.addNode $KeyLight
			i_layer.addNode $FillLight
			i_layer.addNode $BackLight
			i_layer.addNode $HiLight1
			i_layer.addNode $HiLight2
			
			rig_pt_level.enabled = true
			rig_dom_level.enabled = true
			e_height.enabled = true
			
			rig_choice.selection = 8
			UseEnvironmentMap = off
		)
		
		--********************************************************************************
		--  create Lighting Rig 'food' on i_layer
		--********************************************************************************	
		fn createLightRigFood i_layer =
		(
			deleteLights()
			environmentMap = none

			local env = getTextureFileAndPath texFile:#TSHERO_HDRI
			local card = getTextureFileAndPath texFile:#LIGHTBOX_10K
			local lightTex = getTextureFileAndPath texFile:#LIGHTGLOW_CARD
			
			local Light_tex = Bitmaptexture name:"Lights" filename:LightTex
			Light_tex.coords.U_Tiling = 1
			Light_tex.coords.V_Tiling= 1
			Light_tex.coords.U_Tile = false
			Light_tex.coords.V_Tile= false
			Light_tex.coords.blur = 0.1
			
			local lightlevel = rig_pt_level.value
			local d_lightlevel = rig_dom_level.value
			local EnvHDR = VRayHDRI name:"Environment_HDRI" HDRIMapName:env multiplier:(1 * d_lightlevel) maptype:2 horizontalRotation:90
			EnvHDR.horizontalFlip = false
			FoodCardMat = VrayLightMtl name:"Food_Card" texmap:(Bitmaptexture name:"LightBox" filename:card) multiplier:1 twoSided:on
			FoodCardMat.texmap.coords.U_Tiling = 0.95
			FoodCardMat.texmap.coords.V_Tiling= 0.95
			
			groupmx = $HeroObjectGroup.max
			groupmn = $HeroObjectGroup.min
			groupdiag = groupmx-groupmn
			lightRadius = 1.1*(length groupdiag)/(2.0*tan(0.5*26.991))
			
			meditMaterials[24] = EnvHDR
			
			If $KeyLight == undefined then
			(
				VRayLight name:"KeyLight" pos:((normalize [-19.689,-26.109,17.161]) * lightRadius * 2.1494) on:true texmap:Light_tex type:0 multiplier:(25.5 * lightlevel) invisible:true size0:(lightRadius * .4655) size1:(lightRadius * .6985) lightDistribution:0 subdivs:24
				setTransformLockFlags $KeyLight #{7..9}
				$KeyLight.rotation.controller = LookAt_Constraint()
				$KeyLight.rotation.controller.appendTarget $HeroObjectGroup 50
				$KeyLight.rotation.controller.target_axis = 2
				$KeyLight.rotation.controller.upnode_axis = 1
				$KeyLight.rotation.controller.StoUP_axis = 1
				$KeyLight.rotation.controller.target_axisFlip = on
				$KeyLight.rotation.controller.upnode_axis = 2
				$KeyLight.affect_specualr = on
				$KeyLight.affect_reflections = on
				
				freezeObj $KeyLight
			)
			
			If $FillLight == undefined then
			(
				VRayLight name:"FillLight" pos:((normalize [32.253,-5.525,3.095]) * lightRadius * 1.913) on:true texmap:Light_tex type:0 multiplier:(9 * lightlevel) invisible:true size0:(lightRadius * .4655) size1:(lightRadius * .6985) lightDistribution:0 subdivs:24
				setTransformLockFlags $FillLight #{7..9}
				$FillLight.rotation.controller = LookAt_Constraint()
				$FillLight.rotation.controller.appendTarget $HeroObjectGroup 50
				$FillLight.rotation.controller.target_axis = 2
				$FillLight.rotation.controller.upnode_axis = 1
				$FillLight.rotation.controller.StoUP_axis = 1
				$FillLight.rotation.controller.target_axisFlip = on
				$FillLight.rotation.controller.upnode_axis = 2
				$FillLight.affect_specualr = on
				$FillLight.affect_reflections = on
				
				freezeObj $FillLight
			)
			
			
			If $FoodCard == undefined then
			(
				f_card = Plane name:"FoodCard" pos:((normalize [-.764,18.137,9]) * lightRadius * 1.2) length:(lightRadius * 3) width:(lightRadius * 3) lengthsegs:1 widthsegs:1
				CenterPivot f_card
				rotateF = f_card.transform
				preRotate rotateF (eulertoquat (eulerAngles 105 0 0))
				f_card.transform = rotateF
				f_card.material = FoodCardMat
				f_card.castShadows = off
				f_card.receiveshadows = off
				f_card.primaryVisibility = off
				f_card.backfaceCull = on
			
				getuserpropbuffer f_card
				i_layer.addNode f_card
				freeze f_card
			)
			
			vr = renderers.current
			vr.environment_gi_map = EnvHDR
			vr.environment_gi_map_on = true
			vr.environment_rr_map = EnvHDR
			vr.environment_rr_map_on = true
			vr.environment_refract_on = false
			vr.environment_refract_color = white
			vr.environment_refract_map = none
			vr.environment_refract_map_on = false
			
			i_layer.addNode $KeyLight
			i_layer.addNode $FillLight
			
			rig_pt_level.enabled = true
			rig_dom_level.enabled = true
			e_height.enabled = false
			
			rig_choice.selection = 9
			UseEnvironmentMap = off
		)
		
		on rig_btn pressed do
		(	
			undo on
			(
				if not validateSceneForRigGeneration() then
				( 
					return false
				)
				
				local lightlevel = rig_pt_level.value
				local d_lightlevel = rig_dom_level.value
				
				If (isValidOBJ $RigControlGroup and $RigControlGroup.rotation.isAnimated == true) or (isValidOBJ $KeyLight and $KeyLight.multiplier.isAnimated == true) or (isValidOBJ $FillLight and $FillLight.multiplier.isAnimated == true) or (isValidOBJ $BackLight and $BackLight.multiplier.isAnimated == true) or (isValidOBJ $SunLight and $SunLight.multiplier.isAnimated == true)then
				(
					if querybox "This will clear the current light rig and any keyframes it has. Do you want to continue?" beep:true then
					(
						if isValidObj $KeyLight then
						(
							deleteKeys $KeyLight #allKeys
						)
						if isValidObj $FillLight then
						(
							deleteKeys $FillLight #allKeys
						)
						if isValidObj $BackLight then
						(
							deleteKeys $BackLight #allKeys
						)
						if isValidObj $SunLight then
						(
							deleteKeys $SunLight #allKeys
						)
						if isValidObj $RigControlGroup then
						(
							deleteKeys $RigControlGroup #allKeys
						)
						
						findExistingObjects()
						
						local layer = getLayerName name:"Lights"
						
						case lightrig_dd.selection of
						(
							1:
							(
								createLightRigProductShot layer
							)
							2:
							(
								createLightRigOutdoorsMorning layer
							)
							3:
							(
								createLightRigOutdoorsMidDay layer
							)
							4:
							(
								createLightRigOutdoorsSunset layer
							)
							5:
							(
								createLightRigAutomotiveClassic layer
							)
							6:
							(
								createLightRigAutomotiveTech layer
							)
							7:
							(
								createLightRigCharacter layer
							)
							8:
							(
								createLightRigFood layer
							)
							default:
							(
								throw ( "unknown lightrig_dd.selection=[" + ( lightrig_dd.selection as string ) + "]" )
							)
						)
						rig_sel = rig_choice.selection
						GroupLights()
					)
				)
				
				else
				(
					findExistingObjects()
						
					local layer = getLayerName name:"Lights"
					
					case lightrig_dd.selection of
					(
						1:
						(
							createLightRigProductShot layer
						)
						2:
						(
							createLightRigOutdoorsMorning layer
						)
						3:
						(
							createLightRigOutdoorsMidDay layer
						)
						4:
						(
							createLightRigOutdoorsSunset layer
						)
						5:
						(
							createLightRigAutomotiveClassic layer
						)
						6:
						(
							createLightRigAutomotiveTech layer
						)
						7:
						(
							createLightRigCharacter layer
						)
						8:
						(
							createLightRigFood layer
						)
						default:
						(
							throw ( "unknown lightrig_dd.selection=[" + ( lightrig_dd.selection as string ) + "]" )
						)
					)
					rig_sel = rig_choice.selection
					GroupLights()
				)
				
				
				
				enableRegisteredCreateRigButton RolloutName:#SpinnerCameraRollout
				lockRegisteredCameraControls RolloutName:#SpinnerCameraRollout
			)
		)
		
		on clear_btn pressed do
		(
			undo on
			(	
				-- wipe scene clean
				slidertime = 0f
				
				local keepSelection = keep_selection_only.checked
				local objectsToProcess = (if keepSelection then objects else selection) as array
					
				if keepSelection then
				(
					delete (for obj in objectsToProcess where not obj.isSelected collect obj)
				)
				else
				(
					delete objects
				)
			
				macros.run "Medit Tools" "clear_medit_slots"
				renderers.current = Default_Scanline_Renderer()
				environmentMap = none
				prepare_scene.enabled = true
				
				if isValidObj $HeroObjectGroup then
				(
					setGroupOpen $HeroObjectGroup false
					ungroup $HeroObjectGroup
				)
			)
		)
		
		fn prep =
		(
			undo on
			(
				renderSceneDialog.close()
				messageBox ("Hello");
				/*
					1. Move Object to rest at 0,0,0 World Origin.
					2. Build an ShadowPlane grid object with 400x400cm dimensions, center it on the grouped scene geometry and align it to the lowest vertex on the model. Don't cast shadows or reflection/refractions.
					3. Create BouncePlane object matching shadow plane dimensions. Invisible to camera.
					4. Apply a preset Matte/Shadow material provided in .mtl
					5. Set render settings for linear workflow
				*/
				local useSelectionOnly = use_selection_only.checked
				local objectsToProcess = (if useSelectionOnly then selection else objects) as array
				local camLightsLayer

				local sceneObjects = for obj in objectsToProcess where (not isHeroObject(obj) and obj.layer != camLightsLayer) collect obj
				
				-- remove all nodes from'HeroObjectGroup' and delete the group itself
				local groupObj = $HeroObjectGroup
				if isValidObj groupObj then
				(
					ungroup groupObj
				)

				-- group all scene objects into a new 'HeroObjectGroup' group,
				-- move the group to the default layer
				group sceneObjects name:"HeroObjectGroup"
				groupObj = $HeroObjectGroup
				setGroupOpen groupObj true

				--local layer = LayerManager.getLayer 0
				--layer.addNode groupObj
				
				-- move object group to World Origin
				move groupObj [- groupObj.pos.x, - groupObj.pos.y, - groupObj.min.z]
				
				-- build an ShadowPlane grid object with 400x400cm dimensions, 
				-- center it on the grouped scene geometry and align it to the lowest vertex on the model.
				-- turn off cast shadows and visible to reflection/refraction to prevent bounce and reflected light disappearing at keyframe
				local planePos = groupObj.center
				planePos.z = (groupObj.min.z - .001)
				

				local groupObj = $HeroObjectGroup

				local mx = groupObj.max
				local mn = groupObj.min
				local diag = mx-mn
				shadow_bounce_size = 1.5*(length diag)

				if $ShadowPlane == undefined then 
				(
					plane pos:planePos length:shadow_bounce_size width:shadow_bounce_size name:"ShadowPlane" lengthsegs:1 widthsegs:1
				)
				
				local planeObj = $ShadowPlane
				planeObj.gbufferChannel  = 1
				planeObj.visibility = true
				planeObj.visibility.controller = Boolean_Float()
				planeObj.secondaryVisibility = true
				planeObj.castShadows = false
				planeObj.gbufferchannel = 0
				planeObj.backfaceCull = on

				backgroundColor = color 255 255 255
				
				-- Set Gamma/LUT settings up for Linear Workflow
				IDisplayGamma.colorCorrectionMode = #gamma --enable Gamma
				IDisplayGamma.gamma = 2.2
				IDisplayGamma.affectColorPickers = true
				IDisplayGamma.affectMEdit = true
				FileinGamma = 2.2
				FileOutGamma = 1.0
				
				-- Set Submission Frames
				rendPickupFrames = "83,91,0,225,113,117,121,125"

				-- Render Output Size
				renderWidth = 600
				renderHeight = 600
				
				setCurrentRenderer_VRAY()
				
				-- Create Shadow Matte material
				local Gradient_tex = Gradient_Ramp Gradient_Type:8
				Gradient_tex.gradient_ramp.flag__1.color = white
				Gradient_tex.gradient_ramp.flag__2.color = black
				Gradient_tex.gradient_ramp.flag__3.color = color 230 230 230
				Gradient_tex.gradient_ramp.flag__3.position = 64
				
				local Gradient_clip = Gradient_Ramp Gradient_Type:8
				Gradient_clip.gradient_ramp.flag__1.color = white
				Gradient_clip.gradient_ramp.flag__2.color = black
				Gradient_clip.gradient_ramp.flag__3.color = color 128 128 128
				Gradient_clip.gradient_ramp.flag__3.position = 50
				
				local Shadow_AO = VRayDirt radius:(2.5 * (length diag)) subdivs:16 Distribution:10
				Shadow_AO.occluded_color = white
				Shadow_AO.unoccluded_color = black
				
				local Contact_AO = VRayDirt radius:(.25 * (length diag))subdivs:16 Distribution:1
				Contact_AO.occluded_color = white
				Contact_AO.unoccluded_color = black
				
				local Comp_Tex = CompositeTexture()
				Comp_Tex.name = "AO_Comp"
				Comp_Tex.add()
				Comp_Tex.mapList = #(Falloff name:"Shadow_Base" type:3 map1:Shadow_AO, Contact_AO, Falloff name:"BaseShadow_Clip" type:3 map1:Gradient_clip)
				Comp_Tex.blendMode[1] = 11
				Comp_Tex.blendMode[2] = 11
				Comp_Tex.blendMode[3] = 5
				Comp_Tex.opacity[3] = 50
				
				local Opac_comp = CompositeTexture()
				Opac_comp.name = "Shadow_Mask"
				Opac_comp.add()
				Opac_comp.maplist = #(Gradient_tex, Comp_tex)
				Opac_comp.blendmode[2] = 5
				
				ShadowMaterial = VRayMtlWrapper name:"Shadow_Matte" baseMtl:(VRayMtl name:"Shadow_Base" diffuse:black texmap_opacity:Opac_comp)
				ShadowMaterial.generateGI = on
				ShadowMaterial.receiveGI = on
				ShadowMaterial.generateCaustics = off
				ShadowMaterial.receiveCaustics = off
				ShadowMaterial.matteSurface = on
				ShadowMaterial.alphaContribution = 0
				ShadowMaterial.secondaryMatte = on
				ShadowMaterial.matte_shadows = on
				ShadowMaterial.matte_shadowsAffectAlpha = on
				ShadowMaterial.matte_shadowColor = black
				
				-- apply a preset Matte/Shadow material based on the active renderer
				planeObj.material = ShadowMaterial
				
				-- move to correct Layer
				local layer = getLayerName name:"StageLayer"
				local deflayer = getLayerName name:"0"
				
				layer.addNode planeObj
				deflayer.addNode groupObj
				
				setuserprop planeObj "VRay_GI_VisibleToRefractions" false
				freeze planeObj
				
				-- Adds Render Elements and names them to spec
				local rem = maxops.getcurrenderelementmgr()
				local illum = VRaySelfIllumination elementName: "Illumination"
				local shi = VRaySpecular elementName: "Shine"
				local flec = VRayReflection elementName: "Reflection"
				local trans = VRaySSS2 elementName: "Translucency"
				local frac = VRayRefraction elementName: "Refraction"
				local lig = VRayLighting elementName: "Lighting"
				local base = VRayGlobalIllumination elementName: "Base"
				local alp = VRayAlpha elementName: "Object Alpha"
				
				-------------------------------------
				-- QA elements
				-------------------------------------
				local ior = VRayReflectionFilter elementName: "IOR"
				local rgloss = VRayMtlReflectGlossiness elementName: "GlossinessReflect"
				local hgloss = VRayMtlReflectHilightGlossiness elementName: "GlossinessHiLight"
				local uvs = VRaySamplerInfo elementName: "UV" type:4
				local fres = VRayRawTotalLighting elementName: "Fresnel" color_mapping:false multiplier:0.5
				
				for n = (rem.NumRenderElements()-1) to 0 by -1 do
				(
					elm = rem.GetRenderElement n
					rem.RemoveRenderElement elm
				)
				
				if (notExistsRenderElement rem "VRaySelfIllumination") then rem.AddRenderElement illum
				if (notExistsRenderElement rem "VRaySpecular") then rem.AddRenderElement shi
				if (notExistsRenderElement rem "VRayReflection") then rem.AddRenderElement flec
				if (notExistsRenderElement rem "VRaySSS2") then rem.AddRenderElement trans
				if (notExistsRenderElement rem "VRayLighting") then rem.AddRenderElement lig
				if (notExistsRenderElement rem "VRayRefraction") then rem.AddRenderElement frac
				if (notExistsRenderElement rem "VRayGlobalIllumination") then rem.AddRenderElement base
				if (notExistsRenderElement rem "VRayAlpha") then rem.AddRenderElement alp
				-------------------------------------
				-- QA elements
				-------------------------------------
				if (notExistsRenderElement rem "VRayReflectionFilter") then rem.AddRenderElement ior
				if (notExistsRenderElement rem "VRayMtlReflectGlossiness") then rem.AddRenderElement rgloss
				if (notExistsRenderElement rem "VRayMtlReflectHilightGlossiness") then rem.AddRenderElement hgloss
				if (notExistsRenderElement rem "VRaySamplerInfo") then rem.AddRenderElement uvs
				if (notExistsRenderElement rem "VRayRawTotalLighting") then rem.AddRenderElement fres
			)
		)
		
		on prepare_scene pressed do
		(
			g_stageversion = TS_SCRIPT_FULLNAME()
			
			vrayVersion = getInstalledVRayVersion  currentVersion:false
			if ( vrayVersion[1] > 0.0 ) then
			(
				useVray = true
			)
			
			if objects.count == 0 then
			(
				lockRollout()
				messagebox "There are no objects in the scene."
			)
			else
			(
				prep()
				unlockRollout()
			)
			prepare_scene.enabled = false
			RendSetOpen()
		)
		
		fn hiQual =
		(
			vr = renderers.current
			vr.output_on = true
			vr.gi_on = true
			vr.gi_irradmap_showCalcPhase = true
			vr.gi_primary_type = 0
			vr.gi_secondary_type = 3
			vr.gi_irradmap_preset = 5
			vr.adaptiveSubdivision_maxRate = 4
			vr.dmc_earlyTermination_minSamples = 16
			vr.dmc_subdivs_mult = 1
			vr.system_raycaster_memLimit = 4000
			vr.system_region_x = 64
		
			If  (get_vray_version()) >= 3 then
			(
				vr.imageSampler_type = 1
				vr.imageSampler_shadingRate = 16
				vr.filter_kernel = Area()
				vr.dmc_subdivs_mult = 1
				vr.twoLevel_useDMCSamplerThresh = false
				vr.gi_irradmap_maxRate = -1
				vr.adv_irradmap_useCurrentPassSamples = false
				vr.lightcache_subdivs = 600
				vr.lightcache_prefilter_on = true
				vr.lightcache_prefilter_samples = 30
				vr.lightcache_interpSamples = 10
				vr.lightcache_useForGlossyRays = false
				vr.lightcache_retrace_on = false	
			)
			
			sceneMaterials["Shadow_Matte"].baseMtl.texmap_opacity.mapList[2].mapList[2].subdivs = 8
			
			local useSelectionOnly = use_selection_only.checked
			local objectsToProcess = (if useSelectionOnly then selection else objects) as array
			local camLightsLayer
			
			for obj in objectsToProcess where (not isHeroObject(obj) and isVrayLight(obj)) do 
			(
				obj.subdivs = 8
			)
		)
		
		on hiq_btn pressed do
		(
			if not validateSceneForRigGeneration() then
			(
				return false
			)
			RendSetClose()
			-- Render Output Size
			renderWidth = 2048
			renderHeight = 2048
			
			hiQual()
			
			RendSetOpen()
		)
		
		fn midQual =
		(
			vr = renderers.current
			vr.output_on = true
			vr.gi_on = true
			vr.gi_irradmap_showCalcPhase = true
			vr.gi_primary_type = 0
			vr.gi_secondary_type = 3
			vr.gi_irradmap_preset = 3
			vr.adaptiveSubdivision_maxRate = 2
			vr.dmc_earlyTermination_minSamples = 8
			vr.dmc_subdivs_mult = 1
			vr.system_raycaster_memLimit = 4000
			vr.system_region_x = 64
			
			If  (get_vray_version()) >= 3 then
			(
				vr.imageSampler_type = 1
				vr.imageSampler_shadingRate = 10
				vr.filter_kernel = Area()
				vr.twoLevel_useDMCSamplerThresh = false
				vr.gi_irradmap_maxRate = -1
				vr.adv_irradmap_useCurrentPassSamples = false
				vr.lightcache_subdivs = 600
				vr.lightcache_prefilter_on = true
				vr.lightcache_prefilter_samples = 30
				vr.lightcache_interpSamples = 10
				vr.lightcache_useForGlossyRays = false
				vr.lightcache_retrace_on = false	
			)
			
			sceneMaterials["Shadow_Matte"].baseMtl.texmap_opacity.mapList[2].mapList[2].subdivs = 6
			
			local useSelectionOnly = use_selection_only.checked
			local objectsToProcess = (if useSelectionOnly then selection else objects) as array
			local camLightsLayer
			
			for obj in objectsToProcess where (not isHeroObject(obj) and isVrayLight(obj)) do 
			(
				obj.subdivs = 6
			)
		)
		
		on miq_btn pressed do
		(
			if not validateSceneForRigGeneration() then
			(
				return false
			)
			RendSetClose()
			-- Render Output Size
			renderWidth = 1024
			renderHeight = 1024
			
			midQual()
			
			RendSetOpen()
		)
		
		fn lowQual =
		(
			vr = renderers.current
			vr.output_on = true
			vr.gi_on = true
			vr.gi_irradmap_showCalcPhase = true
			vr.gi_primary_type = 0
			vr.gi_secondary_type = 3
			vr.gi_irradmap_preset = 1
			vr.adaptiveSubdivision_maxRate = 2
			vr.dmc_earlyTermination_minSamples = 4
			vr.dmc_subdivs_mult = .5
			vr.system_raycaster_memLimit = 4000
			vr.system_region_x = 64
			
			If  (get_vray_version()) >= 3 then
			(
				vr.imageSampler_type = 1
				vr.imageSampler_shadingRate = 1
				vr.filter_kernel = Area()
				vr.twoLevel_useDMCSamplerThresh = false
				vr.adv_irradmap_useCurrentPassSamples = false
				vr.lightcache_subdivs = 600
				vr.lightcache_prefilter_on = true
				vr.lightcache_prefilter_samples = 30
				vr.lightcache_interpSamples = 10
				vr.lightcache_useForGlossyRays = false
				vr.lightcache_retrace_on = false	
			)
			
			sceneMaterials["Shadow_Matte"].baseMtl.texmap_opacity.mapList[2].mapList[2].subdivs = 4
			
			local useSelectionOnly = use_selection_only.checked
			local objectsToProcess = (if useSelectionOnly then selection else objects) as array
			local camLightsLayer
			
			for obj in objectsToProcess where (not isHeroObject(obj) and isVrayLight(obj)) do 
			(
				obj.subdivs = 4
			)
		)
		
		on loq_btn pressed do
		(
			if not validateSceneForRigGeneration() then
			(
				return false
			)
			RendSetClose()
			-- Render Output Size
			renderWidth = 600
			renderHeight = 600
			
			lowQual()
			
			RendSetOpen()
		)
	)

	rollout SpinnerCam "Spinner Camera Rig" width:500 height:500
	(
		-- ----------------------------------------------------------------------------------------
		-- UI items
		-- ----------------------------------------------------------------------------------------
		GroupBox grp2 "Camera Rig" pos:[6,7] width:445 height:85
		dropdownlist cam_dd pos:[14,27] width:196 height:21 items:#("15mm", "20mm", "24mm", "28mm", "35mm", "50mm", "85mm", "135mm", "200mm") tooltip:"Choose the Camera Lens that would work best for the model type."
		dropdownlist spintype_dd pos:[14,50] width:196 height:21 items:#("Full Spinner","Top Half") tooltip:"Choose to render the full spherical view or just the top half."
		button generate_rig "Generate Spinner Camera" pos:[246,27] width:196 height:21 tooltip:"Animates model and creates camera rig required for Spinner rendering."
		spinner sphere_size "Cam Distance:" pos:[295,57] width:100 height:16 range:[0,1e+009,25] tooltip:"Adjust the camera distance for desired object framing. Scrub through animation to make sure object does not go off camera."
		button reset_dist "Reset" pos:[400,53] width:40 height:21 tooltip:"Reset Camera Distance to default of lense selection."

		-- ----------------------------------------------------------------------------------------
		-- Functions
		-- ----------------------------------------------------------------------------------------
		function disableCreateRigButton =
		(
			generate_rig.enabled = false
			cam_dd.enabled = false
			spintype_dd.enabled = false
		)
		
		function enableCreateRigButton =
		(
			generate_rig.enabled = true	
			cam_dd.enabled = true	
			spintype_dd.enabled = true
		)
		
		fn lockCameraControls =
		(
			sphere_size.enabled = false
			reset_dist.enabled = false
		)
		
		fn unlockCameraControls =
		(
			sphere_size.enabled = true
			reset_dist.enabled = true
		)		

		fn lockRollout =
		(
			disableCreateRigButton()	
			lockCameraControls()
		)

		fn unlockRollout =
		(
			enableCreateRigButton()
			unlockCameraControls()	
		)
		
		function validateSceneForRigGeneration = 
		(
			if not isValidObj $HeroObjectGroup then
			(
				generate_rig.enabled = false
				lockCameraControls()
				messageBox "HeroObjectGroup is missing. You need to prepare the scene again for the rig to work."
				false
			)
			
			else
			(
				true
			)
		)
		
		function validateSceneForCamGeneration = 
		(
			if not isValidObj $CameraPath and not isValidObj $SpinnerCamera then
			(
				lockCameraControls()
				generate_rig.enabled = true
				messageBox "The Shot Camera is not being used or part of the rig may be missing. Generate Shot Camera Rig to use."
				false
			)
			else
			(
				true
			)
		)

		--********************************************************************************
		--  Create Full Camera Rig
		--********************************************************************************	
		fn makeCamera =
		(
			groupObj = $HeroObjectGroup
			PC = Path_Constraint follow:true allowUpsideDown:true
			
			mx = groupObj.max
			mn = groupObj.min
			diag = mx-mn
			spherePos = (mx+mn)/2.0
			sphereRadius = 1.1*(length diag)/(2.0*tan(0.5*CamFov))
			sphere_size.value = sphereRadius
			sphere_size.enabled = true
				
			--print ( "\t\tspherePos[" + (spherePos as string ) + "]" )
				
			if not isValidObj $CameraPath then
			(
				camP = Circle name:"CameraPath" pos:[0,0,$HeroObjectGroup.pos.z] radius:sphere_size.value pos:(groupObj.pos)
				PC.path = camP
			)
			else
			(
				$CameraPath.radius = sphere_size.value
			)
				
			-- create/attach camera and target
			
			local cameraObj = $SpinnerCamera
				
			if not isValidObj cameraObj then (
				cameraObj = FreeCamera fov:CamFov name:"SpinnerCamera"
				cameraObj.pos.controller = PC
				rotate cameraObj (angleaxis 180 [0,1,0])
				cameraObj.pos.controller.percent = -25
			) else (
				cameraObj.pos.controller = PC
				cameraObj.fov = CamFov
				cameraObj.pos.controller.percent = -25
			)
			deleteKeys cameraObj.pos.controller
			
			cameraObj.displayByLayer = true
			cameraObj.renderByLayer = true
			
			local layer = LayerManager.getLayerFromName "StageLayer"
			if layer == undefined do
				layer = LayerManager.newLayerFromName "StageLayer"
			
			layer.addNode cameraObj
			layer.addNode camP
			
			freeze cameraObj
			freeze $CameraPath
			
			layer.display = #wireframe
			layer.renderable = false
			
			viewport.setCamera cameraObj
			displaySafeFrames = true
		)

		--********************************************************************************
		--  create Camera Rig
		--********************************************************************************	
		fn createCameraRig =
		(
			makeCamera()
			local groupObj = $HeroObjectGroup
			
			local mx = groupObj.max
			local mn = groupObj.min
			local diag = mx-mn
			spherePos = (mx+mn)/2.0
			sphereRadius = 1.1*(length diag)/(2.0*tan(0.5*CamFov))
			sphere_size.value = sphereRadius
				
			--print ( "\t\tspherePos[" + (spherePos as string ) + "]" )		
			$CameraPath.radius = sphereRadius
			$SpinnerCamera.fov = CamFov
		)
		
		--********************************************************************************
		--  Upate Camera Rig
		--********************************************************************************	
		fn updateCameraRig =
		(
			local curFrame = slidertime
			
			slidertime = 0f
			
			local groupObj = $HeroObjectGroup
			local mx = groupObj.max
			local mn = groupObj.min
			local diag = mx-mn
			spherePos = (mx+mn)/2.0
			sphereRadius = 1.1*(length diag)/(2.0*tan(0.5*CamFov))
			sphere_size.value = sphereRadius
				
			--print ( "\t\tspherePos[" + (spherePos as string ) + "]" )		
				
			$CameraPath.radius = sphereRadius
			$CameraPath.pos.z = $HeroObjectGroup.pos.z
			$SpinnerCamera.fov = CamFov
			slidertime = curFrame
		)
		
		-- *************************************************************************
		-- Reset Camera Distance based on lens choice
		-- *************************************************************************
		function resetRadius =
		(
			curFrame = slidertime
			
			slidertime = 0f
			
			local mx = $HeroObjectGroup.max
			local mn =  $HeroObjectGroup.min
			local diag = mx-mn
			spherePos = (mx+mn)/2.0
			sphereRadius = 1.1*(length diag)/(2.0*tan(0.5*CamFov))
			sphere_size.value = sphereRadius
				
			--print ( "\t\tspherePos[" + (spherePos as string ) + "]" )		
				
			$CameraPath.radius = sphere_size.value
			slidertime = curFrame
			showShadowPlane()
		)
		
		-- ----------------------------------------------------------------------------------------
		-- Event handlers
		-- ----------------------------------------------------------------------------------------
		
		-- load persistant values
		on SpinnerCam open do 
		(
			registerRollout SpinnerCam RolloutName:#SpinnerCameraRollout
			
			lockRollout()		
			if isValidObj $HeroObjectGroup then
			(		
				enableCreateRigButton()
				
				If isValidObj $SpinnerCamera then
				(
					unlockCameraControls()	
				)
				If isValidObj $ShotCamera and isValidObj $CameraPath then
				(
					lockCameraControls()	
					disableCreateRigButton()
				)
			)
			c_distancelevel = validNumber c_distancelevel defaultVal:0
			sphere_size.value = c_distancelevel
			cam_mm = validNumber cam_mm defaultVal:6
			cam_dd.selection = cam_mm
			SpinType = validNumber SpinType defaultVal:1
			spintype_dd.selection = SpinType
		)
		
		-- save persistant values
		on SpinnerCam close do 
		(
			-- only write if this is the active camera
			if true == sphere_size.enabled then
			(
				c_distancelevel = sphere_size.value
			)
		)
		
		function updateCamera i_cameraType =
		(
			case i_cameraType of
			(
				1:
				(
					CamFov = 100.39 --15mm
					updateCameraRig()
					cam_mm = 1
				)
				2:
				(
					CamFov = 83.97 --20mm
					updateCameraRig()
					cam_mm = 2
				)
				3:
				(
					CamFov = 73.74 --24mm
					updateCameraRig()
					cam_mm = 3
				)
				4:
				(
					CamFov = 65.47 --28mm
					updateCameraRig()
					cam_mm = 4
				)
				5:
				(
					CamFov = 54.43 --35mm
					updateCameraRig()
					cam_mm = 5
				)
				6:
				(
					CamFov = 39.60 --50mm
					updateCameraRig()
					cam_mm = 6
				)
				7:
				(
					CamFov = 23.91 --85mm
					updateCameraRig()
					cam_mm = 7
				)
				8:
				(
					CamFov = 15.19 --135mm
					updateCameraRig()
					cam_mm = 8
				)
				9:
				(
					CamFov = 10.29 --200mm
					updateCameraRig()
					cam_mm = 9
				)
			)
		)

		function generateCamera i_cameraType =
		(
			case i_cameraType of
			(
				1:
				(
					CamFov = 100.39 --15mm
					createCameraRig()
					cam_mm = 1
				)
				2:
				(
					CamFov = 83.97 --20mm
					createCameraRig()
					cam_mm = 2
				)
				3:
				(
					CamFov = 73.74 --24mm
					createCameraRig()
					cam_mm = 3
				)
				4:
				(
					CamFov = 65.47 --28mm
					createCameraRig()
					cam_mm = 4
				)
				5:
				(
					CamFov = 54.43 --35mm
					createCameraRig()
					cam_mm = 5
				)
				6:
				(
					CamFov = 39.60 --50mm
					createCameraRig()
					cam_mm = 6
				)
				7:
				(
					CamFov = 23.91 --85mm
					createCameraRig()
					cam_mm = 7
				)
				8:
				(
					CamFov = 15.19 --135mm
					createCameraRig()
					cam_mm = 8
				)
				9:
				(
					CamFov = 10.29 --200mm
					createCameraRig()
					cam_mm = 9
				)
			)
		)
		
		function GenSpinType partspintype =
		(
			case partspintype of
			(
				1:
				(
					SpinType = 1
				)
				2:
				(
					SpinType = 2
				)
			)
		)
		
		on generate_rig pressed do
		(
			undo on
			(
				if not validateSceneForRigGeneration() then
				(
					return false
				)
				if ((isValidObj $ShotCamera and isValidObj $CameraPath) or isValidObj $RenderCamera or (isValidObj $SpinnerCamera and not isValidObj $CameraPath)) then
				(
					messagebox "You must clear and prepare the scene again in order to update the camera rig."
					disableCreateRigButton()
					unlockCameraControls()
				)
				else
				(
					-- set to full so we can write entire frame rate
					setAnimationState startFrame:0 endFrame:225
					if isValidObj $SpinnerCamera and isValidObj $CameraPath then
					(
						unlockCameraControls()
						GenSpinType spintype_dd.selection
						updateCamera cam_dd.selection
						createCameraRigAnim()
						lockAntiBumpCam()
					)
					else
					(
						-- add camera and sphere to a separate 'StageLayer'
						-- make this layer wireframe and non-renderable
						local layer = "StageLayer"
					
						unlockCameraControls()
						GenSpinType spintype_dd.selection
						generateCamera cam_dd.selection
						createGroupAnim startFrame:2 endFrame:225
						createCameraRigAnim()
						lockAntiBumpCam()
					)
					
					-- set range to actual range based on spintype
					case SpinType of
					(
						1:
						(
							setAnimationState startFrame:0 endFrame:225
						)
						2:
						(
							setAnimationState startFrame:0 endFrame:128
						)
					)

	-- 				enableRegisteredCreateRigButton RolloutName:#ShotCameraRollout
	-- 				lockRegisteredCameraControls RolloutName:#ShotCameraRollout\
					
					unlockCameraControls()
					hide $CameraPath
				)
			)
			true
		)
		
		on sphere_size changed new_sphere_radius do
		(
			undo on
			(
				if not validateSceneForCamGeneration() do return false
				if $SpinnerCamera == undefined  then
				(
					sphere_size.enabled = false
					messagebox "Spinner Camera is not in use."
				)
				else
				(
					sphere_size.enabled = true
					sphereRadius = sphere_size.value
					sphereRadius = new_sphere_radius
					sphere_size.value = sphereRadius
					$CameraPath.radius = sphere_size.value
				)
			)
			showShadowPlane()
		)
		
		on reset_dist pressed do
		(
			undo on
			(
				if not validateSceneForCamGeneration() do return false
				resetRadius()
			)
		)
	)

	-- create the floater and add rollout to it
	local theNewFloater = newRolloutFloater ( TS_SCRIPT_FULLNAME() ) 472 400
	addRollout PsSTAGESETUP theNewFloater
	addRollout SpinnerCam theNewFloater
	PsSTAGESETUP.findExistingObjects()
	)	
)