def holdFrames ( node, holdRange='all' ): """ Append frameHold node for each frame in range. if holdRange = 'all', the node's frame range is processed. if holdRange = valid frame range string, then range is processed if holdRange is not 'all', and not a valid frame range string, a panel is launched to get a valid range from the user. """ if holdRange == 'all': fr = node.frameRange() else: try: fr = nuke.FrameRange( holdRange ) except: str = nuke.getFramesAndViews( 'Hold Frames', '%s-%sx1' % (node['first'].value(), node['last'].value()) ) if not str: return fr = nuke.FrameRange( str[0] ) newNodes = [] for f in xrange( fr.first(), fr.last()+1, +fr.increment() ): fh = nuke.nodes.FrameHold( first_frame=f, postage_stamp = True ) fh.setInput( 0, node ) newNodes.append( fh ) node['postage_stamp'].setValue(False) return newNodes
def bakeCamFrame( bakeNode ): #Get frame range to bake getRange = nuke.getFramesAndViews( "Bake projection curves?", "%s-%s" % ( nuke.root().firstFrame(), nuke.root().lastFrame() ) ) if not getRange: return fRange = nuke.FrameRange( getRange[0] ) views = getRange[1] bakeCamExpressions( bakeNode, fRange.first(), fRange.last(), fRange.increment(), views )
def bakeIt(): #FRAME RANGE timerange = nuke.getFramesAndViews( 'Get Frame Range', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frange = nuke.FrameRange(timerange[0]) #GETTING MAIN MATRIX for i in frange: knobValue = knob.valueAt(i) for each in range(0, 16): sourceMatrix[each] = knobValue[each] sourceMatrix.transpose() #SCALE MATRIX smatrix = nuke.math.Matrix4(sourceMatrix) smatrix.scaleOnly() #SCALE VALUES scaleX = smatrix[0] scaleY = smatrix[5] scaleZ = smatrix[10] #ROTATION MATRIX rmatrix = nuke.math.Matrix4(sourceMatrix) rmatrix.rotationOnly() rmatrixv = rmatrix.rotationsZXY() #ROTATION VALUES degreeX = math.degrees(rmatrixv[0]) degreeY = math.degrees(rmatrixv[1]) degreeZ = math.degrees(rmatrixv[2]) #TRANSLATION MATRIX tmatrix = nuke.math.Matrix4(sourceMatrix) tmatrix.translationOnly() #TRANSLATION VALUES translateX = tmatrix[12] translateY = tmatrix[13] translateZ = tmatrix[14] #PRINTING print '\ntranslateX: ', 'x=', translateX, '', 'Y=', translateY, '', 'Z=', translateZ print '\nrotate: ', 'x=', degreeX, '', 'y=', degreeY, '', 'z=', degreeZ print '\nscale: ', 'x=', scaleX, '', 'y=', scaleY, '', 'z=', scaleZ #SETTING VALUES for each in (target['translate'], target['rotate'], target['scaling']): each.setAnimated() target['translate'].setValueAt(translateX, i, 0) target['translate'].setValueAt(translateY, i, 1) target['translate'].setValueAt(translateZ, i, 2) target['rotate'].setValueAt(degreeX, i, 0) target['rotate'].setValueAt(degreeY, i, 1) target['rotate'].setValueAt(degreeZ, i, 2) target['scaling'].setValueAt(scaleX, i, 0) target['scaling'].setValueAt(scaleY, i, 1) target['scaling'].setValueAt(scaleZ, i, 2)
def expressBaker(): ''' GUI wrapper for bakeExpressions function ''' input = nuke.getFramesAndViews("Range to Bake", "%d-%d" % (nuke.root().firstFrame(), nuke.root().lastFrame())) range = input[0] if not re.match("^\d+-\d+$", range): return first, last = range.split("-") bakeExpressions(int(first), int(last))
def bakeCamFrame(bakeNode): #Get frame range to bake getRange = nuke.getFramesAndViews( "Bake projection curves?", "%s-%s" % (nuke.root().firstFrame(), nuke.root().lastFrame())) if not getRange: return fRange = nuke.FrameRange(getRange[0]) views = getRange[1] bakeCamExpressions(bakeNode, fRange.first(), fRange.last(), fRange.increment(), views)
def setFrameRange(): ret = nuke.getFramesAndViews('Set Frame Range', '101-1000') getFrame = ret[0] convertFrame = nuke.FrameRange(getFrame) nuke.root().knob('first_frame').setValue(convertFrame.first()) nuke.root().knob('last_frame').setValue(convertFrame.last()) for i in nuke.selectedNodes(): if i.Class() == 'Read': i.knob('first').setValue(convertFrame.first()) i.knob('last').setValue(convertFrame.last()) i.knob('origfirst').setValue(convertFrame.first()) i.knob('origlast').setValue(convertFrame.last())
def bakeSelectedNodes(): '''bake selected nodes' knobs that carry expressions''' ret = nuke.getFramesAndViews( 'bake curves in selected nodes?', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) if not ret: return fRange = nuke.FrameRange(ret[0]) views = ret[1] for n in nuke.selectedNodes(): bakeExpressionKnobs(n, fRange.first(), fRange.last(), fRange.increment(), views)
def getRange(gizmo): ''' getRange(node): This function set a range in order to execute an action to the node. It depends on the gizmo's knob 'tdRangeMode'. If the 'tdRangeMode' is set to 'Custom' it opens a pop-up window where we can set a user range before executing the action. Other range modes could be choose like 'Global' or 'Current'. @param 'gizmo': Must be a Gizmo object Nuke. Created on March 11, 2013 @author: Ryuu ''' #| TESTS |------------------------------------------------------------------------------------- if gizmo != None: if (gizmo.__class__.__name__) != 'Gizmo': tdLogger.printError('td.nuke.gizmos.vertexTracker3D', 'getRange()', "Argument 'node' must be a Gizmo object Nuke") #| VARIABLES |--------------------------------------------------------------------------------- rangeMode = gizmo.knob('tdRangeMode').value() #| EXECUTE |----------------------------------------------------------------------------------- if rangeMode == 'Custom': firstFrame = nuke.root().firstFrame() lastFrame = nuke.root().lastFrame() userInput = nuke.getFramesAndViews('Range', '%s-%s' %(firstFrame, lastFrame)) if not userInput: pass else: views = userInput[1] if views == ['main']: views = ['L', 'R'] userRange = nuke.FrameRange(userInput[0]) userFirstFrame = userRange.first() userLastFrame = userRange.last() userIncrFrame = userRange.increment() execRange(gizmo, userFirstFrame, userLastFrame, userIncrFrame, views) elif rangeMode == 'Global': views = nuke.views() firstFrame = nuke.root().firstFrame() lastFrame = nuke.root().lastFrame() execRange(gizmo, firstFrame, lastFrame, 1, ['L', 'R']) elif rangeMode == 'Current': views = nuke.views() currentFrame = nuke.frame() execRange(gizmo, currentFrame, currentFrame, 1, ['L', 'R'])
def bakeDependentNodes(): '''Add this to onUserDestroy callback - not yet implemented''' parentNode = nuke.thisNode() depNodes = parentNode.dependent(nuke.EXPRESSIONS) ret = nuke.getFramesAndViews( 'bake curves in dependent nodes?', '%s-%s' % (parentNode.firstFrame(), parentNode.lastFrame())) if not ret: return fRange = nuke.FrameRange(ret[0]) views = ret[1] for n in depNodes: bakeExpressionKnobs(n, fRange.first(), fRange.last(), fRange.increment(), views)
def createVrayCamera( node ): ''' create camera with vray exr metadata looks at metadata in current pipe and creates camera node accordingly ''' node_data = node.metadata() required_fields = ['exr/camera%s' % i for i in ('FocalLength', 'Aperture', 'Transform')] if not set(required_fields).issubset( node_data ): nuke.message('ERROR: No relevant camera metadata found.') return first_frame = node.firstFrame() last_frame = node.lastFrame() ret = nuke.getFramesAndViews( 'Create Camera from Metadata', '%s-%s' %( first_frame, last_frame ) ) frame_range = nuke.FrameRange( ret[0] ) cam = nuke.createNode( 'Camera2' ) cam['useMatrix'].setValue( False ) for camera_attr in ( 'focal', 'haperture', 'translate', 'rotate'): cam[camera_attr].setAnimated() for current_task, frame in enumerate( frame_range ): horiz_aperture = node.metadata( 'exr/cameraAperture', frame) fov = node.metadata( 'exr/cameraFov', frame) # get camera FOV focal = horiz_aperture / ( 2 * math.tan(math.radians(fov) / 2.0)) cam['focal'].setValueAt(float(focal),frame) cam['haperture'].setValueAt(float(horiz_aperture),frame) matrix_camera = node.metadata( 'exr/cameraTransform', frame) # get camera transform data matrix_created = nuke.math.Matrix4() for key,val in enumerate(matrix_camera): matrixCreated[key] = val # this is needed for VRay. It's a counter clockwise rotation matrix_created.rotateX(math.radians(-90)) # Get a vector that represents the camera translation translate = matrix_created.transform(nuke.math.Vector3(0,0,0)) # give us xyz rotations from cam matrix (must be converted to degrees) rotate = matrix_created.rotationsZXY() # set camera translate & rotate cam['translate'].setValueAt(float(translate.x), frame, 0) cam['translate'].setValueAt(float(translate.y), frame, 1) cam['translate'].setValueAt(float(translate.z), frame, 2) cam['rotate'].setValueAt(float(math.degrees(rotate[0])), frame, 0) cam['rotate'].setValueAt(float(math.degrees(rotate[1])), frame, 1) cam['rotate'].setValueAt(float(math.degrees(rotate[2])), frame, 2)
def bakeDependentNodes(): '''Add this to onUserDestroy callback - not yet implemented''' parentNode = nuke.thisNode( ) # THIS IS GIVEN TO US BY THE CALLBACK, i.e. WHEN A NODE IS DELETED - WELL, NOT YET depNodes = parentNode.dependent(nuke.EXPRESSIONS) ret = nuke.getFramesAndViews( 'bake curves in dependent nodes?', '%s-%s' % (parentNode.firstFrame(), parentNode.lastFrame())) if not ret: return fRange = nuke.FrameRange(ret[0]) views = ret[1] for n in depNodes: bakeExpressionKnobs(n, fRange.first(), fRange.last(), fRange.increment(), views)
def promptAndBake(): ''' Simple GUI wrapper for the ``bakeExpressions`` function that prompts for an input frame range and view list, and always operates on the selected nodes. ''' nodes = nuke.selectedNodes() if not nodes: nuke.message('No nodes selected') return fr = nuke.getFramesAndViews("Range to Bake", str(nuke.root().frameRange())) if fr is None: return fr, v = fr try: fr = nuke.FrameRange(fr) except ValueError as e: nuke.message(str(e)) return bakeExpressions(nodes=nodes, start=fr.first(), end=fr.last(), views=v)
def createExrCamMandelbulber(): #Create a camera node based on Mandelbulber EXR metadata. print "\nCreating Camera Node based on Mandelbulber EXR metadata in selected Read Node...\n" ##### get selected read node node = nuke.selectedNode() ##### get metadata meta = node.metadata() #### check required metadata reqFields = [ "exr/camera.x", "exr/camera.y", "exr/camera.z", "exr/camera_rotation.x", "exr/camera_rotation.y", "exr/camera_rotation.z", "exr/target.x", "exr/target.y", "exr/target.z", "exr/top.x", "exr/top.y", "exr/top.z", "exr/fov", "exr/perspective_type", "exr/stereo_enabled", "exr/stereo_eye_distance", "exr/stereo_infinite_correction", "input/height", "input/width" ] if not set(reqFields).issubset(meta): print 'Required Metdata for Camera Creation not found.' return ###### get range first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews('Create Camera from Metadata', '%s-%s' % (first, last)) fRange = nuke.FrameRange(ret[0]) perspective_type = meta[ "exr/perspective_type"] #"persp_three_point", "persp_equirectangular", stereo_enabled = meta["exr/stereo_enabled"] #"yes", "no" stereo_infinite_correction = int( meta["exr/stereo_infinite_correction"]) #[0, 1] width = float(node.metadata("input/width", 0)) height = float(node.metadata("input/height", 0)) aspect = width / height print "Perspective Type: {}".format(perspective_type) print "Stereo Enabled: {}".format(stereo_enabled) print "Stereo Infinite Correction: {}".format(stereo_infinite_correction) ###### create camera stereocam_path = os.path.join(os.path.dirname(__file__), "gizmos/stereo_cam.nk") stereocam_path = stereocam_path.replace("\\", "/") if stereo_enabled == "yes": if perspective_type == "persp_equirectangular": cam = paste_stereo_nodeset(stereocam_path) cam["stereo_width"].setAnimated() cam["projection_mode"].setValue(3) elif perspective_type == "persp_three_point": cam = paste_stereo_nodeset(stereocam_path) cam["stereo_width"].setAnimated() cam["projection_mode"].setValue(0) else: raise Exception( "Perspective Type '{}' not supported by Nuke.".format( perspective_type)) if stereo_enabled == "no": if perspective_type == "persp_equirectangular": cam = nuke.createNode('Camera2') cam["projection_mode"].setValue(3) elif perspective_type == "persp_three_point": cam = nuke.createNode('Camera2') cam["projection_mode"].setValue(0) else: raise Exception( "Perspective Type '{}' not supported by Nuke.".format( perspective_type)) cam_aperture_base = 36.0 cam_vr_focal = 18.0 haperture = cam_aperture_base vaperture = haperture / aspect cam['haperture'].setValue(haperture) cam['vaperture'].setValue(vaperture) ###### set animated knobs overall for k in ('focal', 'stereo_width', 'translate', 'rotate'): try: cam[k].setAnimated() except: pass #set rotation order to ZXY cam["rot_order"].setValue(4) ##### iterate over frames for curTask, frame in enumerate(fRange): #get values from metadata #camera position translate_x = float(node.metadata("exr/camera.x", frame)) translate_y = float(node.metadata("exr/camera.y", frame)) translate_z = float(node.metadata("exr/camera.z", frame)) translate = nuke.math.Vector3(translate_x, translate_y, translate_z) #camera rotation / not correctly exported from mandelbulber #thus cam xform matrix calculated from cam vectors... #camera target target_x = float(node.metadata("exr/target.x", frame)) target_y = float(node.metadata("exr/target.y", frame)) target_z = float(node.metadata("exr/target.z", frame)) target = nuke.math.Vector3(target_x, target_y, target_z) #camera top (up) top_x = float(node.metadata("exr/top.x", frame)) top_y = float(node.metadata("exr/top.y", frame)) top_z = float(node.metadata("exr/top.z", frame)) top = nuke.math.Vector3(top_x, top_y, top_z) # calculate vectors forward = translate - target forward.normalize() top.normalize() right = top.cross(forward) up = forward.cross(right) #build matrix right_c = [right.x, right.y, right.z, 0] up_c = [up.x, up.y, up.z, 0] forward_c = [forward.x, forward.y, forward.z, 0] translate_c = [translate.x, translate.y, translate.z, 1] m_val_list = right_c + up_c + forward_c + translate_c m = nuke.math.Matrix4() for i, val in enumerate(m_val_list): m[i] = val #extract rotations m.rotationOnly() rotate = m.rotationsZXY() rotate_x = math.degrees(rotate[0]) rotate_y = math.degrees(rotate[1]) rotate_z = math.degrees(rotate[2]) #set values on camera cam['translate'].setValueAt(translate_x, frame, 0) cam['translate'].setValueAt(translate_y, frame, 1) cam['translate'].setValueAt(translate_z, frame, 2) cam['rotate'].setValueAt(rotate_x, frame, 0) cam['rotate'].setValueAt(rotate_y, frame, 1) cam['rotate'].setValueAt(rotate_z, frame, 2) #get values from metadata #calulate focal length based on fov and "cam_aperture_base" fov = float(node.metadata("exr/fov", frame)) focal = cam_aperture_base / (2 * math.tan(math.radians(fov) / 2)) stereo_eye_distance = 2 * float( node.metadata("exr/stereo_eye_distance", frame)) #if vr cam if perspective_type == "persp_equirectangular": focal = cam_vr_focal cam['focal'].setValueAt(focal, frame) if stereo_enabled == "yes": cam['stereo_width'].setValueAt(stereo_eye_distance, frame) #if normal perspective cam if perspective_type == "persp_three_point": cam['focal'].setValueAt(focal, frame) if stereo_enabled == "yes": cam['stereo_width'].setValueAt(stereo_eye_distance, frame) #select camera cam.setSelected(1) print "\nCamera successfully created from Mandelbulber EXR Image Sequence.\n\n"
except ValueError, e: # In this case we have to extract from the error message the # correct frame range format string representation. # I'm expecting to have a error like: "Frame Range invalid (-1722942,-1722942)" msg = e.__str__() inrange = msg[msg.index("(") + 1:msg.index(")")] same_range = (inrange == prev_inrange) prev_inrange = inrange if same_range: inrange = prev_userrange if framesAndViews is None: r = nuke.getFramesAndViews(label = "Frames to flipbook:", default = inrange, \ maxviews = 1) if r is None: return else: r = framesAndViews range_input = r[0] views_input = r[1] prev_userrange = range_input f = nuke.FrameRange(range_input) start = f.first() end = f.last() incr = f.increment()
def createCam_Cam_VraytoNuke(node): try: mDat = node.metadata() reqFields = [ 'exr/camera%s' % i for i in ('FocalLength', 'Aperture', 'Transform') ] if not set(reqFields).issubset(mDat): nuke.critical( 'No metadata for camera found! Please select a read node with EXR metadata from VRay!' ) return nuke.message( "Creating a camera node based on VRay metadata. This works specifically on VRay data coming from Maya!\n\nIf you get both focal and aperture as they are in the metadata, there's no guarantee your Nuke camera will have the same FOV as the one that rendered the scene (because the render could have been fit to horizontal, to vertical, etc). Nuke always fits to the horizontal aperture. If you set the horizontal aperture as it is in the metadata, then you should use the FOV in the metadata to figure out the correct focal length for Nuke's camera. Or, you could keep the focal as is in the metadata, and change the horizontal_aperture instead. I'll go with the former here. Set the haperture knob as per the metadata, and derive the focal length from the FOV." ) first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews('Create Camera from Metadata', '%s-%s' % (first, last)) if ret is None: return fRange = nuke.FrameRange(ret[0]) cam = nuke.createNode('Camera2') cam['useMatrix'].setValue(False) for k in ('focal', 'haperture', 'vaperture', 'translate', 'rotate'): cam[k].setAnimated() task = nuke.ProgressTask('Baking camera from meta data in %s' % node.name()) for curTask, frame in enumerate(fRange): if task.isCancelled(): break task.setMessage('processing frame %s' % frame) hap = node.metadata('exr/cameraAperture', frame) # get horizontal aperture fov = node.metadata('exr/cameraFov', frame) # get camera FOV focal = float(hap) / ( 2.0 * math.tan(math.radians(fov) * 0.5) ) # convert the fov and aperture into focal length width = node.metadata('input/width', frame) height = node.metadata('input/height', frame) aspect = float(width) / float( height) # calulate aspect ratio from width and height vap = float( hap) / aspect # calculate vertical aperture from aspect ratio cam['focal'].setValueAt(float(focal), frame) cam['haperture'].setValueAt(float(hap), frame) cam['vaperture'].setValueAt(float(vap), frame) matrixCamera = node.metadata('exr/cameraTransform', frame) # get camera transform data # create a matrix to shove the original data into matrixCreated = nuke.math.Matrix4() for k, v in enumerate(matrixCamera): matrixCreated[k] = v matrixCreated.rotateX( math.radians(-90) ) # this is needed for VRay, it's a counter clockwise rotation translate = matrixCreated.transform(nuke.math.Vector3( 0, 0, 0)) # get a vector that represents the camera translation rotate = matrixCreated.rotationsZXY( ) # give us xyz rotations from cam matrix (must be converted to degrees) cam['translate'].setValueAt(float(translate.x), frame, 0) cam['translate'].setValueAt(float(translate.y), frame, 1) cam['translate'].setValueAt(float(translate.z), frame, 2) cam['rotate'].setValueAt(float(math.degrees(rotate[0])), frame, 0) cam['rotate'].setValueAt(float(math.degrees(rotate[1])), frame, 1) cam['rotate'].setValueAt(float(math.degrees(rotate[2])), frame, 2) task.setProgress(int(float(curTask) / fRange.frames() * 100)) except: nuke.message('ERROR: Select a EXR from Max / VRay')
def createCam_Cam_MayatoNuke(): try: selectedNode = nuke.selectedNode() nodeName = selectedNode.name() node = nuke.toNode(nodeName) if nuke.getNodeClassName(node) != 'Read': nuke.message('Please select a read Node') print('Please select a read Node') return metaData = node.metadata() reqFields = ['exr/%s' % i for i in ('worldToCamera', 'worldToNDC')] if not set(reqFields).issubset(metaData): nuke.message('no basic matrices for camera found') return else: print('found needed data') imageWidth = metaData['input/width'] imageHeight = metaData['input/height'] aspectRatio = float(imageWidth) / float(imageHeight) hAperture = 36.0 vAperture = hAperture / aspectRatio # get additional stuff first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews('Create Camera from Metadata', '%s-%s' % (first, last)) frameRange = nuke.FrameRange(ret[0]) camViews = (ret[1]) for act in camViews: cam = nuke.nodes.Camera(name="Camera %s" % act) #enable animated parameters cam['useMatrix'].setValue(True) cam['haperture'].setValue(hAperture) cam['vaperture'].setValue(vAperture) for k in ('focal', 'matrix', 'win_translate'): cam[k].setAnimated() task = nuke.ProgressTask('Baking camera from meta data in %s' % node.name()) for curTask, frame in enumerate(frameRange): if task.isCancelled(): break task.setMessage('processing frame %s' % frame) #get the data out of the exr header wTC = node.metadata('exr/worldToCamera', frame, act) wTN = node.metadata('exr/worldToNDC', frame, act) #set the lenshiift if additional metadata is available or manage to calculate it from the toNDC matrix #cam['win_translate'].setValue( lensShift, 0 , frame ) # get the focal length out of the worldToNDC Matrix # thats the wip part any ideas ?? worldNDC = wTN lx = (-1 - worldNDC[12] - worldNDC[8]) / worldNDC[0] rx = (1 - worldNDC[12] - worldNDC[8]) / worldNDC[0] by = (-1 - worldNDC[13] - worldNDC[9]) / worldNDC[5] ty = (1 - worldNDC[13] - worldNDC[9]) / worldNDC[5] swW = max(lx, rx) - min(lx, rx) # Screen Window Width swH = max(by, ty) - min(by, ty) # Screen Window Height focal = hAperture / swW cam['focal'].setValueAt(float(focal), frame) # do the matrix math for rotation and translation matrixList = wTC camMatrix = getMetadataMatrix(wTC) flipZ = nuke.math.Matrix4() flipZ.makeIdentity() flipZ.scale(1, 1, -1) transposedMatrix = nuke.math.Matrix4(camMatrix) transposedMatrix.transpose() transposedMatrix = transposedMatrix * flipZ invMatrix = transposedMatrix.inverse() for i in range(0, 16): matrixList[i] = invMatrix[i] for i, v in enumerate(matrixList): cam['matrix'].setValueAt(v, frame, i) # UPDATE PROGRESS BAR task.setProgress( int(float(curTask) / frameRange.frames() * 100)) except: nuke.message('ERROR: Select a EXR from Maya')
def ExrToCamera(): try: selectedNode = nuke.selectedNode() nodeName = selectedNode.name() node = nuke.toNode(nodeName) if nuke.getNodeClassName(node) != 'Read': nuke.message('Please select a read Node') print 'Please select a read Node' return metaData = node.metadata() reqFields = ['exr/%s' % i for i in ('worldToCamera', 'worldToNDC')] if not set( reqFields ).issubset( metaData ): nuke.message('no basic matrices for camera found') print 'no basic matrices for camera found' return else: print 'found needed data' imageWidth = metaData['input/width'] imageHeight = metaData['input/height'] aspectRatio = float(imageWidth)/float(imageHeight) hAperture = 36.0 vAperture = hAperture/aspectRatio # get additional stuff first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews( 'Create Camera from Metadata', '%s-%s' %( first, last ) ) frameRange = nuke.FrameRange( ret[0] ) camViews = (ret[1]) for act in camViews: cam = nuke.nodes.Camera (name="Camera %s" % act) #enable animated parameters cam['useMatrix'].setValue( True ) cam['haperture'].setValue ( hAperture ) cam['vaperture'].setValue ( vAperture ) for k in ( 'focal', 'matrix', 'win_translate'): cam[k].setAnimated() task = nuke.ProgressTask( 'Baking camera from meta data in %s' % node.name() ) for curTask, frame in enumerate( frameRange ): if task.isCancelled(): break task.setMessage( 'processing frame %s' % frame ) #get the data out of the exr header wTC = node.metadata('exr/worldToCamera',frame, act) wTN = node.metadata('exr/worldToNDC',frame, act) #set the lenshiift if additional metadata is available or manage to calculate it from the toNDC matrix #cam['win_translate'].setValue( lensShift, 0 , frame ) # get the focal length out of the worldToNDC Matrix # thats the wip part any ideas ?? worldNDC = wTN lx = (-1 - worldNDC[12] - worldNDC[8]) / worldNDC[0] rx = (1 - worldNDC[12] - worldNDC[8]) / worldNDC[0] by = (-1 - worldNDC[13] - worldNDC[9]) / worldNDC[5] ty = (1 - worldNDC[13] - worldNDC[9]) / worldNDC[5] swW = max( lx , rx ) - min( lx , rx ) # Screen Window Width swH = max( by , ty ) - min( by , ty ) # Screen Window Height focal = hAperture / swW cam['focal'].setValueAt( float( focal ), frame ) # do the matrix math for rotation and translation matrixList = wTC camMatrix = getMetadataMatrix(wTC) flipZ=nuke.math.Matrix4() flipZ.makeIdentity() flipZ.scale(1,1,-1) transposedMatrix = nuke.math.Matrix4(camMatrix) transposedMatrix.transpose() transposedMatrix=transposedMatrix*flipZ invMatrix=transposedMatrix.inverse() for i in range(0,16): matrixList[i]=invMatrix[i] for i, v in enumerate( matrixList ): cam[ 'matrix' ].setValueAt( v, frame, i) # UPDATE PROGRESS BAR task.setProgress( int( float(curTask) / frameRange.frames() *100) ) except: print 'select at least one read node'
def CP_to_Matrix(): node = nuke.thisNode() parentNode = node.input(0) imageWidth = float(node.width()) imageHeight = float(node.height()) xps = node['xpos'].value() yps = node['ypos'].value() #CREATING EMPTY MATRICES cornerPinMatrixTo = nuke.math.Matrix4() cornerPinMatrixFrom = nuke.math.Matrix4() #CREATING KNOBS baked = nuke.nodes.CornerPin2D(name=node.name() + '_Matrix', xpos=xps + 100, ypos=yps) baked['from2'].setValue(imageWidth, 0) baked['from3'].setValue(imageWidth, 0) baked['from3'].setValue(imageHeight, 1) baked['from4'].setValue(imageHeight, 1) baked['to2'].setValue(imageWidth, 0) baked['to3'].setValue(imageWidth, 0) baked['to3'].setValue(imageHeight, 1) baked['to4'].setValue(imageHeight, 1) baked.setInput(0, parentNode) tab = nuke.Tab_Knob('plus', 'plus') switcher = nuke.Enumeration_Knob('switcher', 'Matrix Type', [ 'All', 'Scale Only', 'Rotation Only', 'Translate Only', 'ScaleAndRotate Only' ]) finalMatrixArr = nuke.Array_Knob('finalMatrixKnob', 'All', 16) mtxScaleArr = nuke.Array_Knob('mtxScaleKnob', 'Scale Only', 16) mtxRotationArr = nuke.Array_Knob('mtxRotationKnob', 'Rotation Only', 16) mtxTranslationArr = nuke.Array_Knob('mtxTranslationKnob', 'Translate Only', 16) mtxScaleRotationArr = nuke.Array_Knob('mtxScaleRotationKnob', 'ScaleAndRotate Only', 16) #ADDING KNOBS check = node.knob('plus') if check is not None: baked.addKnob(switcher) for each in (finalMatrixArr, mtxScaleArr, mtxRotationArr, mtxTranslationArr, mtxScaleRotationArr): baked.addKnob(each) each.setVisible(False) else: baked.addKnob(tab) baked.addKnob(switcher) for each in (finalMatrixArr, mtxScaleArr, mtxRotationArr, mtxTranslationArr, mtxScaleRotationArr): baked.addKnob(each) each.setVisible(False) #FRAME RANGE range = nuke.getFramesAndViews( 'Get Frame Range', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frange = nuke.FrameRange(range[0]) for n in frange: #GETTING KNOBS VALUES vectorsTo = [ nuke.math.Vector2(node[f].getValueAt(n)[0], node[f].getValueAt(n)[1]) for f in sorted(node.knobs().keys()) if f.startswith('to') ] vectorsFrom = [ nuke.math.Vector2(node[f].getValueAt(n)[0], node[f].getValueAt(n)[1]) for f in sorted(node.knobs().keys()) if f.startswith('from') ] #CONVERTING CORNER PIN TO MATRICES cornerPinMatrixTo.mapUnitSquareToQuad(vectorsTo[0].x, vectorsTo[0].y, vectorsTo[1].x, vectorsTo[1].y, vectorsTo[2].x, vectorsTo[2].y, vectorsTo[3].x, vectorsTo[3].y) cornerPinMatrixFrom.mapUnitSquareToQuad( vectorsFrom[0].x, vectorsFrom[0].y, vectorsFrom[1].x, vectorsFrom[1].y, vectorsFrom[2].x, vectorsFrom[2].y, vectorsFrom[3].x, vectorsFrom[3].y) #FINAL MATRIX VALUE finalMatrix = cornerPinMatrixTo * cornerPinMatrixFrom.inverse() finalMatrix.transpose() #DERIVATIVES mtxRotation = nuke.math.Matrix4(finalMatrix) mtxRotation.rotationOnly() mtxScale = nuke.math.Matrix4(finalMatrix) mtxScale.scaleOnly() mtxTranslation = nuke.math.Matrix4(finalMatrix) mtxTranslation.translationOnly() mtxScaleRotation = nuke.math.Matrix4(finalMatrix) mtxScaleRotation.scaleAndRotationOnly() #SET ANIMATED baked['finalMatrixKnob'].setAnimated() baked['mtxScaleKnob'].setAnimated() baked['mtxRotationKnob'].setAnimated() baked['mtxTranslationKnob'].setAnimated() baked['mtxScaleRotationKnob'].setAnimated() #ASSIGNING MATRICES TO KNOBS knobsCount = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] [(baked['finalMatrixKnob'].setValueAt(finalMatrix[i], n, i)) for i in knobsCount] [(baked['mtxScaleKnob'].setValueAt(mtxScale[i], n, i)) for i in knobsCount] [(baked['mtxRotationKnob'].setValueAt(mtxRotation[i], n, i)) for i in knobsCount] [(baked['mtxTranslationKnob'].setValueAt(mtxTranslation[i], n, i)) for i in knobsCount] [(baked['mtxScaleRotationKnob'].setValueAt(mtxScaleRotation[i], n, i)) for i in knobsCount] baked['transform_matrix'].setExpression('finalMatrixKnob') print finalMatrix
def Matrix_to_CP_toolbar(): #DEFINING VARIABLES node = nuke.selectedNode() if node.Class() != 'CornerPin2D': nuke.message("please select a cornerpin node") else: knob = node.knob('transform_matrix') imageWidth = float(node.width()) imageHeight = float(node.height()) xps = node['xpos'].value() yps = node['ypos'].value() parent = node.input(0) sourceMatrix = nuke.math.Matrix4() #FRAME RANGE timerange = nuke.getFramesAndViews( 'Get Frame Range', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frange = nuke.FrameRange(timerange[0]) #CREATING FROM MATRIX (IDENTITY MATRIX * IMAGE SIZE) cpFrom = nuke.math.Matrix4() cpFrom.mapUnitSquareToQuad(0, 0, imageWidth, 0, imageWidth, imageHeight, 0, imageHeight) #CREATING TO VECTOR BEFORE APPLYING MATRIX vectorTo1 = nuke.math.Vector4(0, 0, 0, 1) vectorTo2 = nuke.math.Vector4(1, 0, 0, 1) vectorTo3 = nuke.math.Vector4(1, 1, 0, 1) vectorTo4 = nuke.math.Vector4(0, 1, 0, 1) #CREATING CORNERPIN NODE cpFromMatrix = nuke.nodes.CornerPin2D(name=node.name() + '_fromMatrix', xpos=xps + 100, ypos=yps) cpFromMatrix.setInput(0, parent) [ cpFromMatrix[f].setAnimated() for f in sorted(node.knobs().keys()) if f.startswith('to') ] for i in frange: knobValue = knob.valueAt(i) for each in range(0, 16): sourceMatrix[each] = knobValue[each] sourceMatrix.transpose() finalMatrix = sourceMatrix * cpFrom transformedvectorTo1 = finalMatrix.transform(vectorTo1) to1 = ((transformedvectorTo1.x / transformedvectorTo1.w), (transformedvectorTo1.y / transformedvectorTo1.w)) transformedvectorTo2 = finalMatrix.transform(vectorTo2) to2 = ((transformedvectorTo2.x / transformedvectorTo2.w), (transformedvectorTo2.y / transformedvectorTo2.w)) transformedvectorTo3 = finalMatrix.transform(vectorTo3) to3 = ((transformedvectorTo3.x / transformedvectorTo3.w), (transformedvectorTo3.y / transformedvectorTo3.w)) transformedvectorTo4 = finalMatrix.transform(vectorTo4) to4 = ((transformedvectorTo4.x / transformedvectorTo4.w), (transformedvectorTo4.y / transformedvectorTo4.w)) print "\nto1 = ", to1, "\nto2 = ", to2, "\nto3 = ", to3, "\nto4 = ", to4 for x in (0, 1): cpFromMatrix['to1'].setValueAt(to1[x], i, x) cpFromMatrix['to2'].setValueAt(to2[x], i, x) cpFromMatrix['to3'].setValueAt(to3[x], i, x) cpFromMatrix['to4'].setValueAt(to4[x], i, x) cpFromMatrix['from2'].setValueAt(imageWidth, i, 0) cpFromMatrix['from3'].setValueAt(imageWidth, i, 0) cpFromMatrix['from3'].setValueAt(imageHeight, i, 1) cpFromMatrix['from4'].setValueAt(imageHeight, i, 1)
def createExrCamVray(node): ''' Create a camera node based on VRay metadata. This works specifically on VRay data coming from maya. ''' #Big thanks to Ivan Busquets who helped me put this together! #(ok, ok, he really helped me a lot) #Also thanks to Nathan Dunsworth for giving me solid ideas and some code to get me started. ### TODO : add progress bar (even though it's really not needed here) that works mDat = node.metadata() reqFields = [ 'exr/camera%s' % i for i in ('FocalLength', 'Aperture', 'Transform') ] if not set(reqFields).issubset(mDat): print 'no metdata for camera found' return first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews('Create Camera from Metadata', '%s-%s' % (first, last)) fRange = nuke.FrameRange(ret[0]) cam = nuke.createNode('Camera2') cam['useMatrix'].setValue(False) for k in ('focal', 'haperture', 'translate', 'rotate'): cam[k].setAnimated() #task = nuke.ProgressTask( 'Baking camera from meta data in %s' % node.name() ) for curTask, frame in enumerate(fRange): #if task.isCancelled(): #nuke.executeInMainThread( nuke.message, args=( "Phew!" ) ) #break; #task.setMessage( 'processing frame %s' % frame ) # IB. If you get both focal and aperture as they are in the metadata, there's no guarantee # your Nuke camera will have the same FOV as the one that rendered the scene (because the render could have been fit to horizontal, to vertical, etc) # Nuke always fits to the horizontal aperture. If you set the horizontal aperture as it is in the metadata, # then you should use the FOV in the metadata to figure out the correct focal length for Nuke's camera # Or, you could keep the focal as is in the metadata, and change the horizontal_aperture instead. # I'll go with the former here. Set the haperture knob as per the metadata, and derive the focal length from the FOV val = node.metadata('exr/cameraAperture', frame) # get horizontal aperture fov = node.metadata('exr/cameraFov', frame) # get camera FOV focal = val / (2 * math.tan(math.radians(fov) / 2.0) ) # convert the fov and aperture into focal length cam['focal'].setValueAt(float(focal), frame) cam['haperture'].setValueAt(float(val), frame) matrixCamera = node.metadata('exr/cameraTransform', frame) # get camera transform data #Create a matrix to shove the original data into matrixCreated = nuke.math.Matrix4() for k, v in enumerate(matrixCamera): matrixCreated[k] = v matrixCreated.rotateX( math.radians(-90) ) # this is needed for VRay. It's a counter clockwise rotation translate = matrixCreated.transform(nuke.math.Vector3( 0, 0, 0)) # Get a vector that represents the camera translation rotate = matrixCreated.rotationsZXY( ) # give us xyz rotations from cam matrix (must be converted to degrees) cam['translate'].setValueAt(float(translate.x), frame, 0) cam['translate'].setValueAt(float(translate.y), frame, 1) cam['translate'].setValueAt(float(translate.z), frame, 2) cam['rotate'].setValueAt(float(math.degrees(rotate[0])), frame, 0) cam['rotate'].setValueAt(float(math.degrees(rotate[1])), frame, 1) cam['rotate'].setValueAt(float(math.degrees(rotate[2])), frame, 2)
def create_exr_cam_vray(node): """ Create a camera node based on VRay metadata. This works specifically on VRay data coming from maya. """ #Big thanks to Ivan Busquets who helped me put this together! #(ok, ok, he really helped me a lot) #Also thanks to Nathan Dunsworth for giving me solid ideas and some code to get me started. ### TODO : add progress bar (even though it's really not needed here) that works mDat = node.metadata() reqFields = ['exr/camera%s' % i for i in ('FocalLength', 'Aperture', 'Transform')] if not set( reqFields ).issubset( mDat ): print 'no metdata for camera found' return first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews( 'Create Camera from Metadata', '%s-%s' %( first, last ) ) fRange = nuke.FrameRange( ret[0] ) cam = nuke.createNode( 'Camera2' ) cam['useMatrix'].setValue( False ) for k in ( 'focal', 'haperture', 'translate', 'rotate'): cam[k].setAnimated() #task = nuke.ProgressTask( 'Baking camera from meta data in %s' % node.name() ) for curTask, frame in enumerate( fRange ): #if task.isCancelled(): #nuke.executeInMainThread( nuke.message, args=( "Phew!" ) ) #break; #task.setMessage( 'processing frame %s' % frame ) # IB. If you get both focal and aperture as they are in the metadata, there's no guarantee # your Nuke camera will have the same FOV as the one that rendered the scene (because the render could have been fit to horizontal, to vertical, etc) # Nuke always fits to the horizontal aperture. If you set the horizontal aperture as it is in the metadata, # then you should use the FOV in the metadata to figure out the correct focal length for Nuke's camera # Or, you could keep the focal as is in the metadata, and change the horizontal_aperture instead. # I'll go with the former here. Set the haperture knob as per the metadata, and derive the focal length from the FOV val = node.metadata( 'exr/cameraAperture', frame) # get horizontal aperture fov = node.metadata( 'exr/cameraFov', frame) # get camera FOV focal = val / (2 * math.tan(math.radians(fov)/2.0)) # convert the fov and aperture into focal length cam['focal'].setValueAt(float(focal),frame) cam['haperture'].setValueAt(float(val),frame) matrixCamera = node.metadata( 'exr/cameraTransform', frame) # get camera transform data #Create a matrix to shove the original data into matrixCreated = nuke.math.Matrix4() for k,v in enumerate(matrixCamera): matrixCreated[k] = v matrixCreated.rotateX(math.radians(-90)) # this is needed for VRay. It's a counter clockwise rotation translate = matrixCreated.transform(nuke.math.Vector3(0,0,0)) # Get a vector that represents the camera translation rotate = matrixCreated.rotationsZXY() # give us xyz rotations from cam matrix (must be converted to degrees) cam['translate'].setValueAt(float(translate.x),frame,0) cam['translate'].setValueAt(float(translate.y),frame,1) cam['translate'].setValueAt(float(translate.z),frame,2) cam['rotate'].setValueAt(float(math.degrees(rotate[0])),frame,0) cam['rotate'].setValueAt(float(math.degrees(rotate[1])),frame,1) cam['rotate'].setValueAt(float(math.degrees(rotate[2])),frame,2)
def animatedCP2MTX(): try: input = nuke.selectedNode() #---------------------------------------------------------------------------------------------------------- if input.Class() == 'CornerPin2D': node_in = input.input(0) cp = nuke.nodes.CornerPin2D( name = 'CornerPin_to_Matrix') xpos = input['xpos'].value() ypos = input['ypos'].value() cp_width = cp.screenWidth() cp_height = cp.screenHeight() cp.setXYpos(int(xpos) + int(cp_width) + 25 , int(ypos)) cp.knob('extra matrix').setValue(True) cp.setInput(0, node_in) nuke.show(cp) cp_em = cp.knob('transform_matrix') #--------------------------------------------------------------------------------------- # conversion cp_to_mtx def getAnimatedCPasMTX(cornerpin, iterator): i = iterator cp = cornerpin pmTo = nuke.math.Matrix4() pmFrom = nuke.math.Matrix4() imageWidth = float(cp.width()) imageHeight = float(cp.height()) to1x = cp['to1'].getValueAt(i)[0] to1y = cp['to1'].getValueAt(i)[1] to2x = cp['to2'].getValueAt(i)[0] to2y = cp['to2'].getValueAt(i)[1] to3x = cp['to3'].getValueAt(i)[0] to3y = cp['to3'].getValueAt(i)[1] to4x = cp['to4'].getValueAt(i)[0] to4y = cp['to4'].getValueAt(i)[1] from1x = cp['from1'].getValueAt(i)[0] from1y = cp['from1'].getValueAt(i)[1] from2x = cp['from2'].getValueAt(i)[0] from2y = cp['from2'].getValueAt(i)[1] from3x = cp['from3'].getValueAt(i)[0] from3y = cp['from3'].getValueAt(i)[1] from4x = cp['from4'].getValueAt(i)[0] from4y = cp['from4'].getValueAt(i)[1] pmTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y) pmFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y) mtx = pmTo*pmFrom.inverse() mtx.transpose() return mtx #--------------------------------------------------------------------------------------- #--------------------------------''' Define Frame Range'''--------------------------------- frames = nuke.getFramesAndViews('get FrameRange', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frame_range = nuke.FrameRange( frames[0] ) #--------------------------------------------------------------------------------------- for i in frame_range: mtx = getAnimatedCPasMTX(input, i) #------------------------------------------------------------------------------ #apply values cp_em.setAnimated() for j in range(16): cp_em.setValueAt(mtx[j], i, j ) #----------------------------------------------------------------------------------------------- else: nuke.message('please select a CornerPin node') except: nuke.message('please select a CornerPin node')
def ExrToCamera(node=False, gui=True): if not node: try: node = nuke.selectedNode() except: nuke.message('select a read node with exrs') return if node.Class() != 'Read': nuke.message('no read node selected') return fileName = node['file'].getValue() if not fileName.endswith('.exr'): nuke.message('no exr found cant proceed') return if fileName.__contains__('_%v.'): maxViews = 2 else: maxViews = 1 mDat = node.metadata() reqFields = ['exr/%s' % i for i in ('worldToCamera', 'worldToNDC')] addFields = ['exr/%s' % i for i in ('SR_focalLength','SR_interAxial','SR_zeroParallax')] if not set( reqFields ).issubset( mDat ): nuke.message('no basic matrices for camera found') logger.info('no basic matrices for camera found') return else: logger.info('found needed data') if set (addFields).issubset(mDat): customMeta = True logger.info('Custom metadata found') else: customMeta = False logger.info('No Custom Metadata found! Cant produce correct stereo Cams') hAperture = 36.0 vAperture = hAperture/1.85 first = node.firstFrame() last = node.lastFrame() if gui: ret = nuke.getFramesAndViews( 'Create Camera from Metadata', '%s-%s' %( first, last ),maxviews = maxViews ) if not ret: return fRange = nuke.FrameRange( ret[0] ) camViews = (ret[1]) else: ''' this only comes of use if it is launched with gui=False ''' try: import pyseq except: logger.info('no pyseq found cannot proceed') return else: seq = pyseq.img2pyseq(node['file'].evaluate()) if seq.views: camViews = ['left','right'] else: camViews = ['left'] fRange = seq.frames() if len(camViews) > 1: stereo = True else: stereo = False if stereo: card = nuke.nodes.Card(inputs=[None],xpos = node.xpos()-400, ypos = node.ypos()-150) card['useMatrix'].setValue( True ) card['deform_rows'].setValue(1) card['deform_columns'].setValue(1) card['render_mode'].setValue('off') card['display'].setValue('wireframe') card['name'].setValue('zeroP') scene = nuke.nodes.Scene(inputs=[card], xpos = node.xpos()-375, ypos = node.ypos()-100) join = nuke.nodes.JoinViews(xpos = node.xpos()-200, ypos = node.ypos()-50) else: scene = nuke.nodes.Scene(xpos = node.xpos()-375, ypos = node.ypos()-100) const = nuke.nodes.Constant(xpos = node.xpos()-400, ypos = node.ypos()+25) for e,act in enumerate(camViews): cam = nuke.nodes.Camera (name="Camera %s" % act, xpos = node.xpos()-250+(100*e), ypos = node.ypos()-150) cam['useMatrix'].setValue( True ) cam['haperture'].setValue( hAperture ) cam['vaperture'].setValue( vAperture ) if stereo: join.setInput(e,cam) card['z'].setAnimated() card['matrix'].setAnimated() for k in ( 'focal', 'matrix', 'win_translate'): cam[k].setAnimated() else: for k in ( 'focal', 'matrix'): cam[k].setAnimated() task = nuke.ProgressTask('Baking camera from meta data in %s' % node.name() ) for curTask, frame in enumerate( fRange ): if task.isCancelled(): break task.setMessage( 'processing frame %s' % frame ) wTC = node.metadata('exr/worldToCamera',frame, act) wTN = node.metadata('exr/worldToNDC') # do the matrix math for rotation and translation matrixList = wTC camMatrix = getMetadataMatrix(matrixList) ### get the focal lenght out of the matrices invCamMatrix = camMatrix.inverse() worldProjectionMatrix = getMetadataMatrix(wTN) projectionMatrix = worldProjectionMatrix * invCamMatrix vectorX = nuke.math.Vector4(1,0,1,1) vectorXProjected = projectionMatrix.transform(vectorX) pxProjected = vectorXProjected.x / vectorXProjected.w focal = (pxProjected * hAperture) / 2.0 cam['focal'].setValueAt( float( focal ), frame ) if customMeta and stereo: focal = float ( node.metadata('exr/SR_focalLength', frame, act)) iA = float (node.metadata('exr/SR_interAxial',frame,act)) zeroP = float( node.metadata('exr/SR_zeroParallax',frame,act)) delta1 = (0.5*iA*(1.0/10.0*focal)) delta2 =(2.54*zeroP) delta = delta1/delta2 lensShift = ((2/hAperture)*delta*25.4)*-1 if act == 'left': lensShift = 0.0 card['z'].setValueAt( float( zeroP ), frame ) else: lensShift = float(lensShift) cam['win_translate'].setValue( lensShift, 0 , frame ) cam['focal'].setValueAt( float( focal ), frame ) flipZ=nuke.math.Matrix4() flipZ.makeIdentity() flipZ.scale(1,1,-1) transposedMatrix = nuke.math.Matrix4(camMatrix) transposedMatrix.transpose() transposedMatrix=transposedMatrix*flipZ invMatrix=transposedMatrix.inverse() for i in range(0,16): matrixList[i]=invMatrix[i] for i, v in enumerate( matrixList ): cam[ 'matrix' ].setValueAt( v, frame, i) if stereo: for i, v in enumerate( matrixList ): card[ 'matrix' ].setValueAt( v, frame, i) # UPDATE PROGRESS BAR if gui: task.setProgress( int( float(curTask) / fRange.frames() *100) ) else: task.setProgress( int( float(curTask) / len(fRange) *100) ) if stereo: cam = join render = nuke.nodes.ScanlineRender(inputs=[const,scene,cam],name="Render ExrToCamera", xpos = node.xpos()-200, ypos = node.ypos()+50)
def cpToMatrix(targetNode, sourceNode): input = sourceNode #---------------------------------------------------------------------------------------------------------- if input.Class() == 'CornerPin2D': target = targetNode targetKnob = target.knob('transform_matrix') #--------------------------------------------------------------------------------------- # conversion cp_to_mtx def getAnimatedCPasMTX(cornerpin, iterator): i = iterator cp = cornerpin pmTo = nuke.math.Matrix4() pmFrom = nuke.math.Matrix4() imageWidth = float(cp.width()) imageHeight = float(cp.height()) to1x = cp['to1'].getValueAt(i)[0] to1y = cp['to1'].getValueAt(i)[1] to2x = cp['to2'].getValueAt(i)[0] to2y = cp['to2'].getValueAt(i)[1] to3x = cp['to3'].getValueAt(i)[0] to3y = cp['to3'].getValueAt(i)[1] to4x = cp['to4'].getValueAt(i)[0] to4y = cp['to4'].getValueAt(i)[1] from1x = cp['from1'].getValueAt(i)[0] from1y = cp['from1'].getValueAt(i)[1] from2x = cp['from2'].getValueAt(i)[0] from2y = cp['from2'].getValueAt(i)[1] from3x = cp['from3'].getValueAt(i)[0] from3y = cp['from3'].getValueAt(i)[1] from4x = cp['from4'].getValueAt(i)[0] from4y = cp['from4'].getValueAt(i)[1] pmTo.mapUnitSquareToQuad(to1x, to1y, to2x, to2y, to3x, to3y, to4x, to4y) pmFrom.mapUnitSquareToQuad(from1x, from1y, from2x, from2y, from3x, from3y, from4x, from4y) mtx = pmTo * pmFrom.inverse() mtx.transpose() return mtx #--------------------------------------------------------------------------------------- #--------------------------------''' Define Frame Range'''--------------------------------- frames = nuke.getFramesAndViews( 'get FrameRange', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frame_range = nuke.FrameRange(frames[0]) #--------------------------------------------------------------------------------------- for i in frame_range: mtx = getAnimatedCPasMTX(input, i) #------------------------------------------------------------------------------ #apply values targetKnob.setAnimated() for j in range(16): targetKnob.setValueAt(mtx[j], i, j) #----------------------------------------------------------------------------------------------- else: nuke.message('please select a CPin node')
def createExrRSCam(): node = nuke.selectedNode() if "Read" not in node.Class(): nuke.message('Please select a RS rendered EXR.') return mDat = node.metadata() reqFields = [ 'exr/rs/camera/%s' % i for i in ('fov', 'aperture', 'transform') ] if not set(reqFields).issubset(mDat): print('no metadata for camera found') return first = node.firstFrame() last = node.lastFrame() ret = nuke.getFramesAndViews('Create Camera from Metadata', '%s-%s' % (first, last)) fRange = nuke.FrameRange(ret[0]) cam = nuke.createNode('Camera2') cam['useMatrix'].setValue(False) for k in ('focal', 'haperture', 'vaperture', 'translate', 'rotate'): cam[k].setAnimated() for curTask, frame in enumerate(fRange): # IB. If you get both focal and aperture as they are in the metadata, there's no guarantee # your Nuke camera will have the same FOV as the one that rendered the scene (because the render could have been fit to horizontal, to vertical, etc) # Nuke always fits to the horizontal aperture. If you set the horizontal aperture as it is in the metadata, # then you should use the FOV in the metadata to figure out the correct focal length for Nuke's camera # Or, you could keep the focal as is in the metadata, and change the horizontal_aperture instead. # I'll go with the former here. Set the haperture knob as per the metadata, and derive the focal length from the FOV val = node.metadata()['exr/rs/camera/aperture'] #camera units are inches, mm in nuke valh = val[0] * 25.4 valv = val[1] * 25.4 cam['haperture'].setValueAt(float(valh), frame) cam['vaperture'].setValueAt(float(valv), frame) fov = node.metadata()['exr/rs/camera/fov'] # get camera FOV focal = (valh / (2 * math.tan(math.pi * fov / 360))) cam['focal'].setValueAt(float(focal), frame) cam['haperture'].setValueAt(float(valh), frame) cam['vaperture'].setValueAt(float(valv), frame) matrixCamera = node.metadata('exr/rs/camera/transform', frame) # get camera transform data #Create a matrix to shove the original data into matrixCreated = nuke.math.Matrix4() for k, v in enumerate(matrixCamera): matrixCreated[k] = v matrixCreated.rotateY(math.radians(-180)) # backwards translate = matrixCreated.transform(nuke.math.Vector3( 0, 0, 0)) # Get a vector that represents the camera translation rotate = matrixCreated.rotationsZXY( ) # give us xyz rotations from cam matrix (must be converted to degrees) cam['translate'].setValueAt(float(translate.x), frame, 0) cam['translate'].setValueAt(float(translate.y), frame, 1) cam['translate'].setValueAt(float(translate.z), frame, 2) cam['rotate'].setValueAt(float(math.degrees(rotate[0])), frame, 0) cam['rotate'].setValueAt(float(math.degrees(rotate[1])), frame, 1) cam['rotate'].setValueAt(-float(math.degrees(rotate[2])), frame, 2)
def animatedCP2MTX(): try: input = nuke.selectedNode() #---------------------------------------------------------------------------------------------------------- if input.Class() == 'CornerPin2D': node_in = input.input(0) cp = nuke.nodes.CornerPin2D( name = 'CornerPin_to_Matrix') xpos = input['xpos'].value() ypos = input['ypos'].value() cp_width = cp.screenWidth() cp_height = cp.screenHeight() cp.setXYpos(int(xpos) + int(cp_width) + 25 , int(ypos)) cp.knob('extra matrix').setValue(True) cp.setInput(0, node_in) nuke.show(cp) cp_em = cp.knob('transform_matrix') #--------------------------------------------------------------------------------------- # conversion cp_to_mtx def getAnimatedCPasMTX(cornerpin, iterator): i = iterator cp = cornerpin pmTo = nuke.math.Matrix4() pmFrom = nuke.math.Matrix4() imageWidth = float(cp.width()) imageHeight = float(cp.height()) to1x = cp['to1'].getValueAt(i)[0] to1y = cp['to1'].getValueAt(i)[1] to2x = cp['to2'].getValueAt(i)[0] to2y = cp['to2'].getValueAt(i)[1] to3x = cp['to3'].getValueAt(i)[0] to3y = cp['to3'].getValueAt(i)[1] to4x = cp['to4'].getValueAt(i)[0] to4y = cp['to4'].getValueAt(i)[1] from1x = cp['from1'].getValueAt(i)[0] from1y = cp['from1'].getValueAt(i)[1] from2x = cp['from2'].getValueAt(i)[0] from2y = cp['from2'].getValueAt(i)[1] from3x = cp['from3'].getValueAt(i)[0] from3y = cp['from3'].getValueAt(i)[1] from4x = cp['from4'].getValueAt(i)[0] from4y = cp['from4'].getValueAt(i)[1] pmTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y) pmFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y) mtx = pmTo*pmFrom.inverse() mtx.transpose() return mtx #--------------------------------------------------------------------------------------- #--------------------------------''' Define Frame Range'''--------------------------------- frames = nuke.getFramesAndViews('get FrameRange', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) frame_range = nuke.FrameRange( frames[0] ) #--------------------------------------------------------------------------------------- for i in frame_range: mtx = getAnimatedCPasMTX(input, i) #------------------------------------------------------------------------------ #apply values cp_em.setAnimated() for j in range(16): cp_em.setValueAt(mtx[j], i, j ) #----------------------------------------------------------------------------------------------- else: nuke.message('please select a CornerPin node') except: nuke.message('please select a CornerPin node') #end script