/*
	Copyright (c) 2010, Laurent "MrPingouin" CHEA
	All rights reserved.

	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
	
	- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
	- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
	- Neither the name of LAURENTCHEA.COM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 
	BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
	GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
	OF SUCH DAMAGE.

*********************************************************************************************************

	MrPingouin's Wide Ratio Camera Tool 0.1
	contact@laurentchea.com
	http://www.laurentchea.com
	
	dec 2010
	
	This script creates a camera-based rig that displays an overrided camera Ratio.
	For example : 2 black masks that simulate a 2.35 image ratio on an HDTV (1.77) image output.
	
	It works on 3dsmax's basic camera (free, target), and on VrayPhysicalCamera.
	
	NOTES : 
	
		As Vray simulates real camera physics, the target distance has an impact on the angle of view and thus could make the rig result wrong :
	
		Target distance > 5m : "specify focus" can be unchecked, everything should be ok
		Target distance < 5m : "specify focus" must be checked and "focus distance" set on "infinity" (big value). The smaller the value of target distance, the bigger the error.
		
	TODO :
	
		See if it's possible to get rid of this target distance issue.
*/

g_app_name = "Wide Ratio Camera Tool"
g_app_version = "0.1"

struct CustomCameraRatio_App 
(
	_camera,
	_rootHelper,
	_upperMask,
	_lowerMask,
	
	-----------------------------------------------------------------------------------------------------------------------
	-- Constructor
	-----------------------------------------------------------------------------------------------------------------------
	
	function createApp cam_node = 
	(
		-- The UI already checks for the node type, but one more time doesn't hurt anyone
		if superclassof cam_node == camera then
		(
			local c = CustomCameraRatio_App()
			c._camera = cam_node
			return c
		)
		else
			return undefined
	),
	
	--------------------------------------------------------------------------------------------------------------------------
	-- <void> initMasks (void)
	-- Creates and init the top and bottom masks,
	-- assign them a black material
	-- align + link them to the camera
	-- initializes their position_list
	--------------------------------------------------------------------------------------------------------------------------
	
	function initMasks =
	(
		mat = StandardMaterial()
		mat.reflectionLevel = 0.0
		mat.diffuse = mat.specular = color 0 0 0 0
		
		-- UPPER MASK first-----------------------------------------------------------------------------------------
		
		_upperMask = box length:0 width:0 height:0
		_upperMask.parent = _camera
		_upperMask.name = _upperMask.parent.name + "__upperMask"
		_upperMask.wireColor = color 0 0 0 0
		_upperMask.material = mat
		
		-- Properly align mask's xform to camera, before creating position_list
		
		_upperMask.transform  = _camera.objectTransform
		in coordsys local rotate _upperMask (eulerangles 90 0 0)
		
		_upperMask.position.controller = position_list()
		_upperMask.position.controller.available.controller = position_xyz()
		_upperMask.position.controller.setName 1 "Frozen Position"
		
		_upperMask.position.controller.setActive 2
		
		-- LOWER MASK -----------------------------------------------------------------------------------------
		
		_lowerMask = box length:0 width:0 height:0
		_lowerMask.parent = _camera
		_lowerMask.name = _lowerMask.parent.name + "__lowerMask"
		_lowerMask.wireColor = color 0 0 0 0
		_lowerMask.material = mat
		
		-- Properly align mask's xform to camera, before creating position_list
		
		_lowerMask.transform  = _camera.objectTransform
		in coordsys local rotate _lowerMask (eulerangles -90 0 0)
		
		_lowerMask.position.controller = position_list()
		_lowerMask.position.controller.available.controller = position_xyz()
		_lowerMask.position.controller.setName 1 "Frozen Position"
		
		_lowerMask.position.controller.setActive 2
		
		-- Freeze them, this way the rootHelper will be the only one selected when pressing "select children" shortcut
		
		--freeze _upperMask
		--freeze _lowerMask
		_upperMask.showFrozenInGray = false
		_lowerMask.showFrozenInGray = false
	),
	
	--------------------------------------------------------------------------------------------------------------------------
	-- <void> connectMasks_StandardCam (void)
	-- Creates the script controllers that handle each mask dimensions, it's camera-type dependant
	--------------------------------------------------------------------------------------------------------------------------

	function connectMasks_StandardCam = 
	(
		_upperMask.width.controller = Float_Script()
		_upperMask.width.controller.addTarget "aov" _camera.baseObject[#fov]
		_upperMask.width.controller.addTarget "distToCam" _rootHelper.modifiers[1].distToCam.controller
		_upperMask.width.controller.setExpression "2 * tan(aov/2) * distToCam"
		
		_upperMask.height.controller = Float_Script()
		_upperMask.height.controller.addTarget "movieRatio" _rootHelper.modifiers[1].movieRatio.controller
		_upperMask.height.controller.addTarget "aov" _camera.baseObject[#fov]
		_upperMask.height.controller.addTarget "distToCam" _rootHelper.modifiers[1].distToCam.controller
		_upperMask.height.controller.setExpression "w = 2 * tan(aov/2) * distToCam\nif movieRatio > getRendImageAspect() then\n\t(w/getRendImageAspect() - w/movieRatio)/2\nelse\n\t0"
	),
	
	--------------------------------------------------------------------------------------------------------------------------
	-- <void> connectMasks_VrayPhysicalCam (void)
	-- Creates the script controllers that handle each mask dimensions, it's camera-type dependant
	--------------------------------------------------------------------------------------------------------------------------
	
	function connectMasks_VrayPhysicalCam = 
	(
		_upperMask.width.controller = Float_Script()
		_upperMask.width.controller.addTarget "film_width" _camera.baseObject[#film_width]
		_upperMask.width.controller.addTarget "focal_length" _camera.baseObject[#focal_length]
		_upperMask.width.controller.addTarget "distToCam" _rootHelper.modifiers[1].distToCam.controller
		_upperMask.width.controller.setExpression "aov = 2 * atan (film_width / (2*focal_length))\n2 * tan(aov/2) * distToCam"
		
		_upperMask.height.controller = Float_Script()
		_upperMask.height.controller.addTarget "film_width" _camera.baseObject[#film_width]
		_upperMask.height.controller.addTarget "focal_length" _camera.baseObject[#focal_length]
		_upperMask.height.controller.addTarget "movieRatio" _rootHelper.modifiers[1].movieRatio.controller
		_upperMask.height.controller.addTarget "distToCam" _rootHelper.modifiers[1].distToCam.controller
		_upperMask.height.controller.setExpression "aov = 2 * atan (film_width / (2*focal_length))\nw = 2 * tan(aov/2) * distToCam\nif movieRatio > getRendImageAspect() then\n\t(w/getRendImageAspect() - w/movieRatio)/2\nelse\n\t0"
	),
	
	--------------------------------------------------------------------------------------------------------------------------
	-- <void> connectDimensionsFromLowerToUpper (void)
	-- Lower Mask has the same dimensions than Upper Mask
	--------------------------------------------------------------------------------------------------------------------------
	
	function connectDimensionsFromLowerToUpper = 
	(
		paramWire.connect _upperMask.baseObject[#width] _lowerMask.baseObject[#width] "width"
		paramWire.connect _upperMask.baseObject[#height] _lowerMask.baseObject[#height] "height"
	),
	
	--------------------------------------------------------------------------------------------------------------------------
	-- <void> connectMasks_VrayPhysicalCam (void)
	-- Once the masks dimensions are automatically calculated, we connect them to their position_list
	-- This part is common between StandardCam and VrayPhysicalCams
	--------------------------------------------------------------------------------------------------------------------------
	
	function setPositionControllers = (
		_upperMask.position.controller[2][2].controller = Float_Script()
		_upperMask.position.controller[2][2].controller.addTarget "width" _upperMask.baseObject[#width]
		_upperMask.position.controller[2][2].controller.setExpression "width/getRendImageAspect()/2.0"
		
		_upperMask.position.controller[2][3].controller = Float_Script()
		_upperMask.position.controller[2][3].controller.addTarget "distToCam" _rootHelper.modifiers[1].distToCam.controller
		_upperMask.position.controller[2][3].controller.setExpression "-distToCam"
		
		_lowerMask.position.controller[2][2].controller = Float_Script()
		_lowerMask.position.controller[2][2].controller.addTarget "width" _upperMask.baseObject[#width]
		_lowerMask.position.controller[2][2].controller.setExpression "-width/getRendImageAspect()/2.0"
		
		_lowerMask.position.controller[2][3].controller = Float_Script()
		_lowerMask.position.controller[2][3].controller.addTarget "distToCam" _rootHelper.modifiers[1].distToCam.controller
		_lowerMask.position.controller[2][3].controller.setExpression "-distToCam"
	),
	
	--------------------------------------------------------------------------------------------------------------------------
	-- <void> createRootHelper (void)
	-- This is the "c-letter" object that holds the rig attributes : distance to camera, and movie ratio
	--------------------------------------------------------------------------------------------------------------------------
	
	function createRootHelper = 
	(
		_rootHelper = text()
		
		_rootHelper.text = "c"
		_rootHelper.size = 10.0
		_rootHelper.transform = _camera.objectTransform
		_rootHelper.parent = _camera
		
		_rootHelper.name = _rootHelper.parent.name + "_customRatio"
		in coordsys parent move _rootHelper [5,0,0]
		
		addModifier _rootHelper (EmptyModifier())
		
		ca = attributes "CameraRatio"
		(
			parameters params rollout:CustomCameraRatio_R
			(
				movieRatio type:#float ui:movieRatioSpn default:2.35
				distToCam type:#worldUnits ui:distToCamSpn default:5
			)
			
			rollout CustomCameraRatio_R "Camera Ratio"
			(
				spinner movieRatioSpn "Movie Ratio :" range:[1,4,2.35]
				spinner distToCamSpn "Dist. to Cam. :" range:[5,50,5]
			)
		)
		
		custAttributes.add _rootHelper.modifiers[1] ca
		
		-- By default, custom attributes parameters don't seem to have any controller, you have to assign them basic bezier_float, otherwise the connections (paramWire or script_controllers) are not possible
		_rootHelper.modifiers[1].movieRatio.controller = Bezier_Float()
		_rootHelper.modifiers[1].distToCam.controller = Bezier_Float()
		
	),
	
	-- This is the main function
	
	function buildCameraRig =
	(
		initMasks()
		createRootHelper()
		
		case (classof _camera) of 
		(
			VrayPhysicalCamera : connectMasks_VrayPhysicalCam()
			FreeCamera : connectMasks_StandardCam()
			TargetCamera : connectMasks_StandardCam()
			default : print "Unexpected error"
		)
		setPositionControllers()
		connectDimensionsFromLowerToUpper()
		select _rootHelper
	)
)

clearListener()

rollout CustomCameraRatio_R "Camera Custom Ratio" 
(	
	function filter_cam cam_node = 
	(
		superclassof cam_node == camera
	)
	pickbutton chooseCamera_btn "Pick camera" filter:filter_cam
	
	on chooseCamera_btn picked cam_node do with undo on
	(
		local ccf = CustomCameraRatio_App.createApp cam_node
		if ccf != undefined then
			ccf.buildCameraRig()
	)
)

rollout Notes_R "Help"
(
	edittext ee text:"If you use VrayPhysicalCam, please note\nthat \"target distance\" affects operations :\n\n> 5m : \"specify focus\" can be unchecked\neverything should be ok\n\n< 5m : \"specify focus\" must be checked,\nwith \"focus distance\" set on a huge value\n(infinity)." height:130
)

rollout About_R "About"
(
	group ""
	(
		label lbl "Wide Ratio Camera Tool"
		label lbl2 "Laurent \"MrPingouin\" CHEA - 2010"
		label lbl3 "http://www.laurentchea.com"
	)
)
nf = newRolloutFloater (g_app_name + " " + g_app_version)  250 345
addRollout CustomCameraRatio_R  nf
addRollout Notes_R  nf
addRollout About_R  nf
