'''
CreateCameraFromView.py
Alex Forsythe, 5/29/2012
A simple Maya script for creating cameras from existing views.
An example for the tech-artists.org forum. Based on the work on Shawn Freuh.
http://tech-artists.org/forum/showthread.php?2712-Create-camera-from-view
'''
import random
import maya.cmds as cmds
# If False, uses whatever view has focus, including the script editor!
PERSP_VIEW_ONLY = True
def CreateCameraFromView(interactive = True, newCameraName = ''):
'''
Duplicates the active camera to create a new camera with the specified
name. If called with interactive enabled, newCameraName will be ignored
and the user will be asked to supply a new name. If no name is given,
one will be generated automatically. The new camera will be selected after
it is created, replacing the previous selection.
'''
if interactive:
result = cmds.promptDialog(title = 'Create Camera From View',
message = 'New camera name:', button = ['OK', 'Cancel'],
defaultButton = 'OK', cancelButton = 'Cancel',
dismissString = 'Cancel', text = newCameraName)
if result == 'OK':
text = cmds.promptDialog(query = True, text = True)
if text:
newCameraName = text
else:
return
newCamera = DuplicateCurrentCamera(newCameraName)
cmds.select(newCamera, replace = True)
cmds.showHidden(newCamera)
def DuplicateCurrentCamera(newCameraName = ''):
'''
Finds the active camera and creates a copy of it with the specified name.
If no name is given, one will be randomly generated based on the name of
the original camera.
'''
cameraTransform, cameraShape = GetCurrentCamera()
if not newCameraName:
newCameraName = GeneratePlaceholderName(cameraTransform)
cmds.duplicate(cameraShape, name = newCameraName)
return newCameraName
def GetCurrentCamera():
'''
Returns a 2-tuple containing the currently active camera's transform node
and shape node.
'''
if PERSP_VIEW_ONLY:
panel = cmds.getPanel(withLabel = 'Persp View')
else:
panel = cmds.getPanel(withFocus = True)
camera = cmds.modelEditor(panel, query = True, camera = True)
return camera, cmds.listRelatives(camera, type = 'camera')[0]
def GeneratePlaceholderName(baseNodeName):
'''
Given an existing node name as a basis, appends a randomly generated hex
string to create a placeholder name.
'''
return '_'.join([baseNodeName, hex(random.randint(0, 16777215))[2:]])
if __name__ == '__main__':
CreateCameraFromView()