macroScript RecNavPath category:"Bobo_s Tools" tooltip:"Record Viewport Navigation"
(
	---------------------------------------------------
	--Record Camera Navigation Path
	--Version 0.5.0
	--Started: 2004-04-03
	--Edited:  2004-10-16
	--Code by Borislav 'Bobo' Petrov
	--http://www.scriptspot.com/bobo
	--bobo@franticfilms.com
	---------------------------------------------------
	
	local record_file														--the output file for recording
	local out_filename = (GetDir #preview + "\\path_recording.cnp")			--the default filename to write to
	local theStartView = 0													--the active view index when starting recording
	local theINIfile = (GetDir #plugcfg + "\\RrecordNavigationPath.ini") 	--the INI file to store last settings
	local recorded_samples_count = 0										--a counter for the number of recorded samples
	
	rollout Record_Navigation_Path_Rollout "Record Navigation Path v0.5"
	(
	
		local cnp_record_flight_path										--the function used to record the camera

		timer theTimer interval:(1000.0/FrameRate) active:false				--the timer UI element used for Polled recording. Set ticking rate to 1/FPS in milliseconds
		
		button get_path "Get..." across:2 align:#left width:36 height:18	--the button to get a new output file name
		edittext out_path_name "" text:out_filename align:#right width:240	--the file name and path display

		dropdownlist recording_mode items:#("EventDriven Recording","Polled Recording") width:136 align:#left across:2		
		checkbutton start_recording "START RECORDING" width:136 align:#right tooltip:"Toggle Recording. When EventDriven is selected, only changes to the camera view will be recorded."
		
		listbox log_window items:#("Ready.") align:#center					--ui log window for feedback display
		
		dropdownlist creation_mode items:#("Realtime Animation","All Recorded Samples") width:136 align:#left across:2
		button import_animation "IMPORT ANIMATION..." width:136 align:#right tooltip:"Select a CNP file and apply animation to a single selected object or create a new animated Camera."
		
		group "Walkthrough Options"
		(
			spinner spn_stepSize "Step Size" range:[0.0001,10000.0,walkThroughOps.stepSize] align:#left across:2 
			spinner spn_sensitivity "Sensitivity" range:[0.0001,10000.0,walkThroughOps.sensitivity] align:#right
			button btn_level 	"Level" width:136 align:#left across:2 tooltip:"Align the view to be parallel to the XY World Plane." 
			button btn_start_gamenav 	"Enable Walkthrough..." width:136 align:#right tooltip:"Enable WalkThrough Navigation Controls"
		)
		
		on spn_stepSize changed val do walkThroughOps.stepSize = val
		on spn_sensitivity changed val do walkThroughOps.sensitivity = val
------------------------------------------------------------------		
--Handler to access Game Nav. Options and enable Game Nav. Mode
------------------------------------------------------------------		
		on btn_start_gamenav pressed do walkThroughOps.start()
		on btn_level pressed do walkThroughOps.level()

-----------------------------		
--Handler to get new path
-----------------------------	
		on get_path pressed do
		(
			tmp = getSaveFileName caption:"CNP File Name to Save:" types:"Camera Navigration Path (*.cnp)|*.cnp" filename:(GetDir #preview + "\\")	--get new filename
			if tmp != undefined then										--if cancel was not pressed,
				out_path_name.text = tmp									--set the UI display to the new name
		)--end on
		
-------------------------------------------------------		
--Handlers to record changes to the drop-down lists
-------------------------------------------------------		
		on recording_mode selected itm do
			setINIsetting theINIfile "Preferences" "RecordingMode" (itm as string)

		on creation_mode selected itm do
			setINIsetting theINIfile "Preferences" "CreationMode" (itm as string)
		

----------------------------------------------
--Function to load preferences from INI file 
----------------------------------------------
		
		fn load_ini_file =
		(
			if (theVal = execute (getINIsetting theINIfile "Preferences" "RecordingMode")) != OK then recording_mode.selection = theVal
			if (theVal = execute (getINIsetting theINIfile "Preferences" "CreationMode")) != OK then creation_mode.selection = theVal
		)--end fn

----------------------------------------------
--Function to output info to the log window
----------------------------------------------
		fn ui_log txt =		--txt is the string to display
		(
			log_window.items = append log_window.items txt			--append the string to the items array
			log_window.selection = log_window.items.count			--and set the list highlight to the last item
		)--end fn
	
----------------------------------------------
--Function to stop recording
----------------------------------------------
		fn stop_recording =
		(
			start_recording.text = "START RECORDING"				--reset the button text
			start_recording.state = false							--uncheck the button
			try(close record_file)catch()							--try to close the output file if it is still open
			unRegisterRedrawViewsCallback cnp_record_flight_path	--unregister the viewport callback function (if in EventDriven mode)
			theTimer.active = false									--deactivate the time UI element (if in Polled mode)
			ui_log ("++Recording STOPPED!")							--report success to the UI log
			ui_log (">Recorded " + recorded_samples_count as string + " Samples.")   --report the number of samples recorded
			ui_log ("Ready.")										
		)--end fn

----------------------------------------------
--Function to record the camera to file
----------------------------------------------
		fn cnp_record_flight_path =
		(
			if viewport.activeViewport == theStartView then						--if the camera is still the one we started with 
			(
				theCamera = viewport.GetCamera()
				try													--then write the time and TM to file.
				(
					if theCamera == undefined then
					(			
						format "%,%\n" (timestamp()) (inverse (viewport.getTM())) to:record_file
						recorded_samples_count += 1						--increase the counter by 1
					)	
					else
					(
						format "%,%\n" (timestamp()) theCamera.transform to:record_file
						recorded_samples_count += 1						--increase the counter by 1
					)	
				)
				catch
				(
					ui_log "--Something went wrong, Aborting..."	--let the user know an error has occured
					stop_recording()								--If recording fails for any reason, stop recording.
				)	 
			)	
			else													--if the camera is not the one we started with, incl. undefined, then 
			(
				ui_log "--Viewport Changed, Aborting..."			--let the user know the viewport has changed
				stop_recording()									--and stop the recording
			)	
		)--end fn

----------------------------------------------------
--Handler for the START/STOP RECORDING checkbutton		
----------------------------------------------------
		on start_recording changed state do					
		(
			if state then											--if the button was checked, then
			(
				theCamera = viewport.getCamera() 					--get the camera from the current viewport
				theStartView = viewport.activeViewport				--get the current viewport index
				
				try(close record_file)catch()					--try to close the file if for some reason still open
				try(record_file = createFile out_path_name.text)catch(record_file=undefined)		--try to create the file using the current output name
				if record_file != undefined then
				(
					ui_log "++Recording STARTED..."				--let the user know recording is starting
					if theCamera != undefined then 						
						ui_log (">Viewport:"+ theStartView as string+ " Camera: ["+ theCamera.name+"]")		--tell him the name of the camera
					else	
						ui_log (">Non-Camera Viewport:"+ theStartView as string+ " ["+ (viewport.getType()) as string +"]")		--tell him the name of the view
					start_recording.text = "STOP RECORDING"			--set the text on the button to "STOP..."
					recorded_samples_count = 0						--reset the counter back to 0
					case recording_mode.selection of				--select the right recording mode
					(
						1: (
							registerRedrawViewsCallback cnp_record_flight_path				--ED mode requires a viewport callback
							ui_log (">Event Recording Using Viewport Redraw Callback...")	--tell the user what mode he is using
							)
						2: (
							theTimer.active = true											--Polled mode requires the timer to be ticking
							ui_log (">Polled Recording Using Timer At " + FrameRate as string + "fps")	--let the user know what FPS he is recording
							)
					)--end case
				)
				else													--if the record file could not be created (wrong path?)
				(
					ui_log ("--ERROR: Cannot create output file!")		--let the user know
					start_recording.state = false						--and uncheck the button
				)	

/*				
				else														--if the viewport is not a camera,
				(
					ui_log ("--ERROR: Viewport is NOT a Camera!")			--let the user know 
					start_recording.state = false							--and uncheck the button
				)
*/				
			)
			else
			(
				stop_recording()											--if the button was unchecked, stop recording
			)
		)--end on	
		

---------------------------------------------
--Handler for the Timer - Polled Recording		
---------------------------------------------
		on theTimer tick do cnp_record_flight_path()  						--if the timer is ticking, call the recording function


------------------------------------------
--Handler of the Import animation button		
------------------------------------------
		on import_animation pressed do											
		(
			local current_frame = 0
			--select a file for loading
			in_filename = getOpenFileName caption:"Select CNP Animation File:" types:"Camera Navigration Path (*.cnp)|*.cnp" filename:(GetDir #preview + "\\")
			if in_filename != undefined then								--if the cancle button was not pressed and a valid file was selected, then
			(
				in_file = openFile in_filename 								--open the file
				if in_file != undefined then								--if the file could be opened, then
				(
					ui_log ("++Importing Animation...")						--report to the user that the animation import begins
					ui_log (">File: ["+ in_filename+"]")					--report the file name loaded
					q = false												--define a flag variable, set to false by default
					if selection.count == 1 do								--if a single object is selected in the scene, ask whether the animation should be assigned to it
						q = querybox ("There is exactly one object selected in the scene - ["+ selection[1].name +"}\nPress YES if you want to apply the animation to it.\nPress NO if you want to animate a NEW Free Camera!") title:"Importing Animation:"

					if q then 												--if the flag is true, the selected object should be animated, otherwise (default) a new free camera should be created
					(	
						animated_object = selection[1]									--get the selected object
						ui_log (">Custom Object: ["+ animated_object.name+"]")			--report the name of the custom object selected
					)	
					else
					(
						animated_object = FreeCamera name:(uniquename "Camera_CNP_")	--create a new free camera with a unique name
						ui_log (">New Free Camera: ["+ animated_object.name+"]")		--and report the name of the new camera
					)
						
				
					try
					(
						last_timestamp = readvalue in_file						--try to read the first time stamp value and store in a variable
						tm_value = readvalue in_file							--read the first transformation matrix value
						at time current_frame animated_object.transform = tm_value 	--set the new camera's transformation on the first frame 
						while not eof in_file do								--repeat until the end of the file
						(
							time_stamp = readvalue in_file						--read the time stamp
							tm_value = readvalue in_file						--read the transformation matrix
							case creation_mode.selection of						--depending on the creation mode,
							(
							1: (												--if "Realtime" was selected, then
									if time_stamp - last_timestamp >= 1000.0/FrameRate then	--check whether the new timestamp is equal or higher than the length of a frame
									(
										last_timestamp = time_stamp				--if it is, then record the new timestamp as the last one
										current_frame += 1						--increase the frame counter by one 
										with animate on at time current_frame animated_object.transform = tm_value 	--and animate the camera on the new frame using the TM 
									)
								)
							2:	(
									current_frame += 1							--if "All Samples" were requested, then just increase the frame counter
									with animate on at time current_frame animated_object.transform = tm_value 		--and animate the camera on that frame
								)	
							)--end case	
						)--end while
					)
					catch	--in case there is ANY error during reading the file, let the user know
					(
						ui_log "--ERROR: The File could not be read correctly!"
					)	
					close in_file	--close the file
				)
				else	--in case the file could not be opened for some reason, let the user know
				(
					ui_log "--ERROR: The File could not be opened!"
				)
				
				if current_frame > animationRange.end then					--if the last frame read from the file is higher than the current scene segment, then
					animationRange= interval 0f (current_frame as time)		--set the end of the animation segment to that frame
				ui_log (">Animation: [0 : "+ current_frame as string +"]")	--then let the user know how many frames were read in
				if superclassof animated_object == Camera do
					viewport.setCamera animated_object						--set the current viewport to the new camera (if it is a camera)
				select animated_object										--and select the camera so the user can see the keys in the trackbar
			)	
			else															--if the user hit Cancel in the file selector, then 
			(
				ui_log "--No Record File Specified!"						--let him know what he did :o)
			)
			ui_log ("Ready.")										
		)--end on
		
		on Record_Navigation_Path_Rollout close do stop_recording()			--if the user closed the dialog, make sure no recording is going on - stop it!
		on Record_Navigation_Path_Rollout moved pos do 
		(
			setINIsetting theINIfile "Dialog" "Position" (pos as string)
		)
	
		
	)--end roll
	try(destroyDialog Record_Navigation_Path_Rollout)catch()				--try to close an existing dialog
	thePos = execute (getInisetting theINIfile "Dialog" "Position")
	if thePos == OK then thePos = [100,100]
	createDialog Record_Navigation_Path_Rollout 300 300	thePos.x thePos.y	--and create a new one 
	Record_Navigation_Path_Rollout.load_ini_file()							--finally, load the stored preferences from the INI file
)--end script