def _cvTracker( node, shapeName, cvID, fRange ): shape = node['curves'].toElement( shapeName ) # SHAPE CONTROL POINT try: shapePoint = shape[cvID] except IndexError: nuke.message( 'Index %s not found in %s.%s' % ( ) ) return # ANIM CONTROL POINT animPoint = shapePoint.center # CREATE A TRACKER NODE TO HOLD THE DATA tracker = nuke.createNode( 'Tracker3' ) tracker['label'].setValue( 'tracking cv#%s in %s.%s' % ( cvID, node.name(), shape.name ) ) trackerKnob = tracker['track1'] trackerKnob.setAnimated() # SET UP PROGRESS BAR task = nuke.ProgressTask( 'CV Tracker' ) task.setMessage( 'tracking CV' ) # DO THE WORK for f in fRange: if task.isCancelled(): nuke.executeInMainThread( nuke.message, args=( "CV Track Cancelled" ) ) break task.setProgress( int( float(f)/fRange.last() * 100 ) ) # GET POSITION pos = animPoint.getPosition( f ) nuke.executeInMainThreadWithResult( trackerKnob.setValueAt, args=( pos.x, f, 0 ) ) # SET X VALUE nuke.executeInMainThreadWithResult( trackerKnob.setValueAt, args=( pos.y, f, 1 ) ) # SET Y VALUE
def gameloop(self): self.ball.reset(self.gamebox) time.sleep(0.1) while not self.stop: self.ball.nudge() toincrement = None try: self.ball.check_gamebox(self.gamebox) except Player1Score: print "Player 1 scored" toincrement = self.gamebox['p1_score'] except Player2Score: print "Player 2 scored" toincrement = self.gamebox['p2_score'] if toincrement is not None: cur = nuke.executeInMainThreadWithResult(toincrement.value) if cur is None: cur = 0 new = cur + 1 nuke.executeInMainThreadWithResult(toincrement.setValue, new) self.ball.reset(self.gamebox) self.ball.check_paddle(paddle=self.left) self.ball.check_paddle(paddle=self.right) time.sleep(0.01)
def run_checks(self): """ Set of checks to determine wether a creation of masks is possible or not. """ #read_node_name if not(nuke.executeInMainThreadWithResult(nuke.exists, (self.read_node_name))): print('Read node with name: {0} does not exist. Returning...'.format(self.read_node_name)) return False #write_node_name if not(nuke.executeInMainThreadWithResult(nuke.exists, (self.write_node_name))): print('Write node with name: {0} does not exist. Returning...'.format(self.write_node_name)) return False #photo_dir if not(os.path.isdir(self.photo_dir)): print('Photo dir with name: {0} does not exist. Returning...'.format(self.photo_dir)) return False #masks_dir if not(os.path.isdir(self.masks_dir)): print('Masks dir with name: {0} does not exist. Returning...'.format(self.masks_dir)) return False return True
def run( self ): incs = 10 for i in xrange( incs ): for n in self.nodes: oldPos = self.posDict[ n ][ 0 ] newPos = self.posDict[ n ][ 1 ] curPos = oldPos + ( newPos - oldPos ) / incs * (i+1) if self.direction == 'x': nuke.executeInMainThreadWithResult( n.setXpos, int(curPos) ) else: nuke.executeInMainThreadWithResult( n.setYpos, int(curPos) ) time.sleep(.02)
def evalcmd(self, cmdstr): import nuke retvalue = nuke.executeInMainThreadWithResult( self._run_with_result, kwargs={'cmdstr': cmdstr}) if retvalue is None: return {"status": "unknown"} return retvalue
def get(self, data): ''' Perform whatever action is requested, and return the result ''' obj = self.get_object(data['id']) params = data['parameters'] result = None action = data['action'] try: if data['action'] == "initiate": if self.verify_connection(params): result = "accept" else: result = "deny" elif data['action'] == "test": result = True elif data['action'] == "getattr": result = getattr(obj, params) elif action == "setattr": setattr(obj, params[0], params[1]) elif action == "getitem": # If we're actually getting from globals(), then raise NameError instead of KeyError if data['id'] == -1 and params not in obj: raise NameError("name '%s' is not defined" % params) result = obj[params] elif action == "setitem": obj[params[0]] = params[1] elif action == "call": if nuke.NUKE_VERSION_MAJOR < 10: result = nuke.executeInMainThreadWithResult( obj, args=params['args'], kwargs=params['kwargs']) else: result = obj(*params['args'], **params['kwargs']) elif action == "len": result = len(obj) elif action == "str": result = str(obj) elif action == "repr": result = ` obj ` elif data['action'] == "del": del obj elif data['action'] == "isinstance": result = obj.__instancecheck__(params) elif data['action'] == "issubclass": result = issubclass(params, obj) elif action == "import": result = imp.load_module(params, *imp.find_module(params)) elif action == "shutdown": # This keyword triggers the server shutdown raise SystemExit except Exception, e: result = e
def start(self): while 1: try: (conn, addr) = self.s.accept() data = conn.recv(4096) data = data.strip() print "TACTIC [%s]" %data result = nuke.executeInMainThreadWithResult(tactic_exec, (data,) ) conn.send(str(result)) conn.close() except Exception, e: print str(e) print "Error: restarting ..."
def sendObjMesh(target_clientID, sender, tabTarget, alembic=False, frames=[0,0]): try: selectedNode = nuke.selectedNode() except ValueError: return False meshOut = {} geoType = ".obj" if alembic: geoType = ".abc" curFrame = int(nuke.knob("frame")) tmpfilePath = tempfile.gettempdir() + "\\hcom_tmp_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) + geoType tmpWriterName = "tmp_geoWriter_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) result = nuke.executeInMainThreadWithResult(_createObjWriter, args=(tmpWriterName, tmpfilePath, selectedNode, curFrame, alembic, frames)) if not result: return False with open(tmpfilePath, 'rb') as f: data = f.read() try: os.remove(tmpfilePath) except: pass meshOut["MESH_TYPE"] = geoType meshOut["MESH_NAME"] = selectedNode.name() meshOut["MESH_DATA"] = data w = nuke.toNode(tmpWriterName) if w: nuke.delete(w) outType = "mesh" if alembic: outType = "alembic" meshOut["NAME"]= selectedNode.name() meshOut["FRAME_RANGE"] = frames meshOut["DATA"]= data result = _sendData(target_clientID, sender, meshOut, outType, tabTarget) return result
def get(self, data): ''' Perform whatever action is requested, and return the result ''' obj = self.get_object(data['id']) params = data['parameters'] result = None action = data['action'] try: if data['action'] == "initiate": if self.verify_connection(params): result = "accept" else: result = "deny" elif data['action'] == "test": result = True elif data['action'] == "getattr": result = getattr(obj, params) elif action == "setattr": setattr(obj, params[0], params[1]) elif action == "getitem": # If we're actually getting from globals(), then raise NameError instead of KeyError if data['id'] == -1 and params not in obj: raise NameError("name '%s' is not defined" % params) result = obj[params] elif action == "setitem": obj[params[0]] = params[1] elif action == "call": result = nuke.executeInMainThreadWithResult(obj, args=params['args'], kwargs=params['kwargs']) elif action == "len": result = len(obj) elif action == "str": result = str(obj) elif action == "repr": result = `obj` elif data['action'] == "del": del obj elif data['action'] == "isinstance": result = obj.__instancecheck__(params) elif data['action'] == "issubclass": result = issubclass(params, obj) elif action == "nonzero": result = bool(obj) elif action == "import": result = imp.load_module(params, *imp.find_module(params)) elif action == "shutdown": # This keyword triggers the server shutdown raise SystemExit except Exception, e: result = e
def _pointsToKeys(curve, knob, fRange): ''' Set keys along a shape. args: shape - CubicCurve to define animation path knob - knob to set keys on. This needs to be an Array_Knob fRange - frame range across which to set keys (first frame = start of shape, last frame = end of shape) ''' task = nuke.ProgressTask('Shape Tracker') task.setMessage('tracking shape') for f in fRange: # TAKE CARE OF PROGRESS BAR if task.isCancelled(): nuke.executeInMainThread(nuke.message, args=("Shape Track Cancelled")) break task.setProgress(int(float(f) / fRange.last() * 100)) # DO THE WORK curPoint = curve.getPoint(float(f) / fRange.last()) nuke.executeInMainThreadWithResult(knob.setValueAt, args=(curPoint.x, f, 0)) nuke.executeInMainThreadWithResult(knob.setValueAt, args=(curPoint.y, f, 1))
def verify_connection(self, host): ''' If the server has specified that new connections need to be verified by the user, pop up a dialog asking them if a connection can be made. ''' if self._verify_connection == VERIFY_CONNECTION_NONE or \ (self._verify_connection == VERIFY_CONNECTION_ONLY_REMOTE and \ host in ["localhost", os.getenv("HOST")]): return True # If Nuke isn't running in GUI mode, then allow the connection to verify if nuke.GUI: return nuke.executeInMainThreadWithResult(nuke.ask, ("Something is trying to connect to Nuke from %s.\nDo you wish to allow this?" % host,)) return True
def verify_connection(self, host): ''' If the server has specified that new connections need to be verified by the user, pop up a dialog asking them if a connection can be made. ''' if self._verify_connection == VERIFY_CONNECTION_NONE or \ (self._verify_connection == VERIFY_CONNECTION_ONLY_REMOTE and \ host in ["localhost", os.getenv("HOST")]): return True # If Nuke isn't running in GUI mode, then allow the connection to verify if nuke.GUI: return nuke.executeInMainThreadWithResult(nuke.ask, ( "Something is trying to connect to Nuke from %s.\nDo you wish to allow this?" % host, )) return True
def server_start(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(5) while 1: client, address = s.accept() try: data = client.recv(4096) if data: result = nuke.executeInMainThreadWithResult(_exec, args=(data)) client.send(str(result)) except SystemExit: result = self.encode('SERVER: Shutting down...') client.send(str(result)) raise finally: client.close()
def render_mask(self, image_name): """ Render mask """ #read_node read_node = nuke.executeInMainThreadWithResult(nuke.toNode, (self.read_node_name)) #write_node write_node = nuke.executeInMainThreadWithResult(nuke.toNode, (self.write_node_name)) #photo_list_index photo_list_index = self.photos_images_list.index(image_name) #photo_path photo_path = self.photos_images_path_list[photo_list_index] #set in read_node nuke.executeInMainThreadWithResult(read_node.knob('file').setValue, (photo_path)) #write_node_file_path write_node_file_path = os.path.join(self.masks_dir, image_name).replace('\\', '/') #set in write_node nuke.executeInMainThreadWithResult(write_node.knob('file').setValue, (write_node_file_path)) #render nuke.executeInMainThreadWithResult(nuke.render, (self.write_node_name, 1, 1, 1)) #while file not yet created print a queue dot while not (os.path.isfile(write_node_file_path)): QtCore.QCoreApplication.processEvents() print('.'), self.msleep(150) #log print('Rendered mask: {0}'.format(write_node_file_path))
def handle(self): tempfile_path = self.request.recv(2048) # Multiplex by app if self.server.app == "hiero": import hiero result = hiero.core.executeInMainThreadWithResult( self._hiero_execfile_wrapper, args=(tempfile_path)) elif self.server.app == "nuke": result = nuke.executeInMainThreadWithResult(self._execfile, args=(tempfile_path)) else: raise RuntimeError("Unknown App") # Send back the output or <No Output> if result is not None and len(result): self.request.send(result.strip()) else: self.request.send("<No Output>")
def handle(self): tempfile_path = self.request.recv(2048) # Multiplex by app if self.server.app == "hiero": import hiero result = hiero.core.executeInMainThreadWithResult( self._hiero_execfile_wrapper, args=(tempfile_path)) elif self.server.app == "nuke": result = nuke.executeInMainThreadWithResult( self._execfile, args=(tempfile_path)) else: raise RuntimeError("Unknown App") # Send back the output or <No Output> if result is not None and len(result): self.request.send(result.strip()) else: self.request.send("<No Output>")
def run(self): node = None incs = 1 for i in range(incs): for n, m in self.adult_dict.items(): if not m: nukescripts.clear_selection_recursive() continue node = nuke.createNode("Dot") x = m["pos"][0] y = m["pos"][1] color = m["color"] nuke.executeInMainThreadWithResult(node.setXpos, int(x)) nuke.executeInMainThreadWithResult(node.setYpos, int(y)) nuke.executeInMainThreadWithResult(node["tile_color"].setValue, (int(color)))
def sendNodeOuput(target_clientID, sender, tabTarget): fileType = HComNukeUtils.readIni()["OUTPUT_IMAGE_FORMAT"] try: selectedNode = nuke.selectedNode() except ValueError: return False curFrame = int(nuke.knob("frame")) tmpfilePath = tempfile.gettempdir() + "\\hcom_tmp_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) + "." + fileType tmpWriterName = "tmp_writer_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) result = nuke.executeInMainThreadWithResult(_createWriter, args=(tmpWriterName, tmpfilePath, selectedNode, curFrame)) if not result: return False with open(tmpfilePath, 'rb') as f: data = f.read() outImdageData = {} outImdageData["IMAGE_NAME"] = os.path.basename(selectedNode.name()) + "." + fileType outImdageData["BINARY_DATA"] = data try: os.remove(tmpfilePath) except: pass w = nuke.toNode(tmpWriterName) if w: nuke.delete(w) result = _sendData(target_clientID, sender, outImdageData, "pic", tabTarget) return result
def _func(*args, **kwargs): if nuke.GUI and current_thread().name != 'MainThread': return nuke.executeInMainThreadWithResult(func, args, kwargs) return func(*args, **kwargs)
def threaded_wrapper(func, *args, **kwargs): return nuke.executeInMainThreadWithResult(func, args, kwargs)
def evalcmd(self, cmdstr): import nuke retvalue = nuke.executeInMainThreadWithResult(self._run_with_result, kwargs = {'cmdstr': cmdstr}) if retvalue is None: return {"status": "unknown"} return retvalue
def launchBugSubmitPanel(toolName, extraInfo, debugQueue=None, parentPanel=None): '''get info from the user (if any), return user-entered description''' #setup debugging if not debugQueue: def debug(inter, stringer): print(stringer) else: def debug(inter, stringer): debugQueue.put_nowait((inter, stringer)) try: if parentPanel: results=showPanel(toolName, extraInfo, parent=parentPanel) else: app = QApplication.instance() if app is None: #it does not exist then a QApplication is created debug(3, "no qapp available, creating one before displaying bug submit") app = QApplication([]) results=showPanel(toolName, extraInfo, parent=app) else: #here we'll check if we're in a gui instance or a simple qcore instance (such as nuke -t) if type(app)==QtCore.QCoreApplication: #we're in a terminal instance without access to a gui, so we'll just send the report debug(2, "NO GUI AVAILABLE - sending bug report as-is") return "TERMINAL SESSION" else: #if app is nuke, we need to launch in main thread or else it will lock #the function name is different in qt 4 and 5 function=app.applicationDisplayName try: if "Nuke" in function(): debug(3, "found nuke gui session") from nuke import executeInMainThreadWithResult #@UnresolvedImport results=executeInMainThreadWithResult(showPanel, args=(toolName, extraInfo)) else: #other applications can be handled here specially here debug(3, "displaying panel in application: "+app.applicationDisplayName()) results=showPanel(toolName, extraInfo, parent=app) except: debug(2, 'unknown error attempting to determine gui context (nuke or otherwise)') debug(2, format_exc()) results=showPanel(toolName, extraInfo, parent=app) if results: accepted=results[0] description=results[1] if accepted: return description else: return None else: return None except: #if for some reason, we failed to open the bug submit panel, we might be in an environment without it #so we'll just submit the bug silently message="Error launching bug submit panel: <br /><br />"+format_exc() print(message) return message
def _exec(self): self._receiver.settimeout(0.01) debugMsg('Server running on ' + str(self._receiver.getsockname())) connections = [] READ_LENGTH = 1024 # Main loop: check for new connections, and process data from them while True: # Accept pending incoming connections try: new_conn, details = self._receiver.accept() new_conn.settimeout(0.01) debugMsg('New connection on ' + str(details)) connections.append(new_conn) except socket.timeout: pass except socket.error as err: if err[0] != 4: # ignore "interrupted system call" (retry next loop) raise # Check each open connection for new data for conn in list(connections): # make a copy so we can safely modify the original data_block = '' # Receive data while some is available and we don't have an error while True: # Receive data try: new_data = conn.recv(READ_LENGTH) except socket.timeout: break except Exception as exc: errorMsg("Closing connection due to unhandled exception in socket receive: " + str(exc)) connections.remove(conn) break # Receiving an empty string means the socket has been closed - but we may still have data to process if new_data == '': debugMsg('Closing ' + str(conn.getpeername())) connections.remove(conn) break # Append to previously received data, and continue receiving if we got less than a buffer full data_block += new_data if len(new_data) < READ_LENGTH: break # Loop through all segments to process, using Ctrl+D as an optional delimiter data_segments = (text for text in data_block.split('\x04') if text != "") for data in data_segments: # Debug info trace_text = data[:100] if len(data) > len(trace_text): trace_text += "..." debugMsg("Received: " + trace_text) if data.startswith(_nuke_exec_cmd): # Received an execute command request = data.replace(_nuke_exec_cmd, '') debugMsg('Executing in Nuke') # Request a result (but ignore it) to ensure that the command finishes before returning nuke.executeInMainThreadWithResult(runPython, request) elif data.startswith(_nuke_eval_cmd): # Received an evaluate command request = data.replace(_nuke_eval_cmd, '') debugMsg('Evaluating in Nuke') result = str(nuke.executeInMainThreadWithResult(evalPython, request)) debugMsg('Sending: %s' % result) try: conn.send(result) debugMsg('Send complete') except socket.timeout: debugMsg('Send timed out') except socket.error as err: if err[0] == 32 or err[0] == 104: # Broken pipe or connection reset by peer => closed (ignore; will be removed next check) debugMsg('Send cancelled (connection closed)') else: raise elif data == ':exit:': # Received a request to close the connection debugMsg('Close connection requested by ' + str(conn.getpeername())) self._receiver.close() return
def thread_dispatch(): return nuke.executeInMainThreadWithResult(openRecent, ())
def run(self): nodeToSnap = None if self.node == 'Axis': nodeToSnap = nuke.executeInMainThreadWithResult( nuke.createNode, 'Axis2') elif self.node == 'Card': nodeToSnap = nuke.executeInMainThreadWithResult( nuke.createNode, 'Card2') elif self.node == 'Sphere': nodeToSnap = nuke.executeInMainThreadWithResult( nuke.createNode, 'Sphere') elif self.node == 'Cube': nodeToSnap = nuke.executeInMainThreadWithResult( nuke.createNode, 'Cube') elif self.node == 'Cylinder': nodeToSnap = nuke.executeInMainThreadWithResult( nuke.createNode, 'Cylinder') elif self.node == 'Selected Node': nodeToSnap = nuke.executeInMainThreadWithResult( nuke.selectedNode, ()) nuke.executeInMainThreadWithResult(nodeToSnap['translate'].setAnimated, ()) nuke.executeInMainThreadWithResult(nodeToSnap['rotate'].setAnimated, ()) nuke.executeInMainThreadWithResult(nodeToSnap['rot_order'].setValue, (0)) for frame in range(self.first, self.last + 1): nuke.executeInMainThreadWithResult(nuke.frame, frame) P = nuke.executeInMainThreadWithResult(getPoints, ()) A = P[1] - P[0] B = P[2] - P[0] A.normalize() N = A.cross(B) #create the normal of A and B N.normalize() C = N.cross(A) #create the orthogonal axis centroid = (P[0] + P[1] + P[2]) / 3 #generate the Rotation Matrix Colums r11 = A[0] r21 = A[1] r31 = A[2] r12 = C[0] r22 = C[1] r32 = C[2] r13 = N[0] r23 = N[1] r33 = N[2] #generate Euler Angles rx = math.atan2(r32, r33) ry = math.atan2(-r31, math.sqrt(r32**2 + r33**2)) rz = math.atan2(r21, r11) # set the knobs nuke.executeInMainThreadWithResult( nodeToSnap['translate'].setValue, [centroid[0], centroid[1], centroid[2]]) nuke.executeInMainThreadWithResult( nodeToSnap['rotate'].setValue, [math.degrees(rx), math.degrees(ry), math.degrees(rz)]) self.updateProgress.emit((float(frame) / self.last * 100)) nuke.executeInMainThreadWithResult(nuke.frame, self.first) self.gui.trackBTN.setEnabled(True) self.gui.typeCombo.setEnabled(True)
def executeInThread(function, arg): nuke.executeInMainThreadWithResult(function, args=arg)
def run(self): nodeToSnap = None if self.node == 'Axis': nodeToSnap = nuke.executeInMainThreadWithResult(nuke.createNode,'Axis2') elif self.node == 'Card': nodeToSnap = nuke.executeInMainThreadWithResult(nuke.createNode,'Card2') elif self.node == 'Sphere': nodeToSnap = nuke.executeInMainThreadWithResult(nuke.createNode,'Sphere') elif self.node == 'Cube': nodeToSnap = nuke.executeInMainThreadWithResult(nuke.createNode,'Cube') elif self.node == 'Cylinder': nodeToSnap = nuke.executeInMainThreadWithResult(nuke.createNode,'Cylinder') elif self.node == 'Selected Node': nodeToSnap = nuke.executeInMainThreadWithResult(nuke.selectedNode,()) nuke.executeInMainThreadWithResult(nodeToSnap['translate'].setAnimated,()) nuke.executeInMainThreadWithResult(nodeToSnap['rotate'].setAnimated,()) nuke.executeInMainThreadWithResult(nodeToSnap['rot_order'].setValue,(0)) for frame in range(self.first,self.last+1): nuke.executeInMainThreadWithResult(nuke.frame,frame) P=nuke.executeInMainThreadWithResult(getPoints,()) A = P[1] - P[0] B = P[2] - P[0] A.normalize() N = A.cross(B) #create the normal of A and B N.normalize() C = N.cross(A) #create the orthogonal axis centroid = (P[0]+P[1]+P[2])/3 #generate the Rotation Matrix Colums r11 = A[0] r21 = A[1] r31 = A[2] r12 = C[0] r22 = C[1] r32 = C[2] r13 = N[0] r23 = N[1] r33 = N[2] #generate Euler Angles rx=math.atan2(r32,r33) ry=math.atan2(-r31,math.sqrt( r32**2 + r33**2)) rz=math.atan2(r21,r11) # set the knobs nuke.executeInMainThreadWithResult(nodeToSnap['translate'].setValue,[centroid[0],centroid[1],centroid[2]]) nuke.executeInMainThreadWithResult(nodeToSnap['rotate'].setValue,[math.degrees(rx),math.degrees(ry),math.degrees(rz)]) self.updateProgress.emit((float(frame)/self.last*100)) nuke.executeInMainThreadWithResult(nuke.frame,self.first) self.gui.trackBTN.setEnabled(True) self.gui.typeCombo.setEnabled(True)