def __init__(self): self._view = om2UI.M3dView() # the camera self._mfn = None # viewport size self._width = 0 self._height = 0 # camera settings self._ratio = 0 self._hPan = 0 self._vPan = 0 # dragger context self._startX = 0 self._startY = 0 self._endX = 0 self._endY = 0 # Switch to prevent the release event to run when the press # command has been performed in an ortho view. self._isOrtho = False # create the preference settings if they don't exist self._setOptionVars() self._viewType = 2
def getPointer(s): """ Get intersection point on the mesh from the mouse click. """ if s.meshes: try: # Grab screen co-ords viewX, viewY, viewZ = cmds.draggerContext(s.tool, q=True, dp=True) # Set up empty vectors position = om.MPoint() direction = om.MVector() # Convert 2D positions into 3D positions omui.M3dView().active3dView().viewToWorld(int(viewX), int(viewY), position, direction) # Check our meshes for mesh in s.meshes: selection = om.MSelectionList() selection.add(mesh) dagPath = selection.getDagPath(0) fnMesh = om.MFnMesh(dagPath) # Shoot a ray and check for intersection intersection = fnMesh.closestIntersection(om.MFloatPoint(position), om.MFloatVector(direction), om.MSpace.kWorld, 99999, False) # hitPoint, hitRayParam, hitFace, hitTriangle, hitBary1, hitBary2 = intersection if intersection and intersection[3] != -1: return (mesh, intersection[2]) # hit mesh and face ID except RuntimeError: pass
def _press(self): """Method to be executed when the mouse button is pressed. Get the current camera and it's settings. """ self._view = om2UI.M3dView().active3dView() self._mfn = om2.MFnCamera(self._view.getCamera()) # Exit, if it's not a perspective view. if self._mfn.isOrtho(): logger.warning("Quick Zoom only works in a perspective view.") return # If the current modifier is the ctrl key toggle the pan/zoom # state. modifier = cmds.draggerContext(CONTEXT_NAME, query=True, modifier=True) if modifier == "ctrl": self.togglePanZoom() return # Get all necessary info about the view and camera settings. self._ratio = self._mfn.aspectRatio() self._hPan = self._mfn.horizontalPan self._vPan = self._mfn.verticalPan self._width = float(self._view.portWidth()) self._height = float(self._view.portHeight())
def get_coord_on_drag(self, selected, ctx): vpX, vpY, _ = cmds.draggerContext(ctx, query=True, dragPoint=True) position = om.MPoint() # 3D point with double-precision coordinates direction = om.MVector() # 3D vector with double-precision coordinates omui.M3dView().active3dView().viewToWorld( int(vpX), int(vpY), position, # world point direction) # world vector for mesh in selected: selectionList = om.MSelectionList() selectionList.add(mesh) dagPath = selectionList.getDagPath(0) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection( om.MFloatPoint(position), # raySource om.MFloatVector(direction), # rayDirection om.MSpace.kWorld, # space 99999, # maxParam True) # testBothDirections hitPoint, hitRayParam, hitFace, hitTriangle, \ hitBary1, hitBary2 = intersection x, y, z, _ = hitPoint return x, y, z
def __init__(self): self._view = om2UI.M3dView() self._dag = None self._meshDag = None # Switch to make sure that values are present when using the # move mode. self._isSet = False # the world point of reflection on the surface self._reflPoint = None # The distance of the object from the surface. # This is used to store the distance during placing as well as # moving because the move mode needs a static base value to # calculate the new distance from. self._dist = 0.0 # The distance of the object from the surface after moving. # This is used to be able to remember the last moved position # in case the move mode is performed with a new press and drag # operation after the placement. If this value is not stored the # new drag would always start from the self._dist position and # not from the last known self._moveDist position. self._moveDist = 0.0 # the reflection vector self._reflVector = None # create the preference settings if they don't exist self._setOptionVars() self._axis = 2 self._invert = True self._translate = True self._rotate = True self._speedSlow = 0.001 self._speedFast = 0.01
def onPress(): vpX, vpY, _ = cmds.draggerContext(context, query=True, dragPoint=True) pos = om.MPoint() dir = om.MVector() omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, dir) for mesh in cmds.ls(type='mesh'): selectionList = om.MSelectionList() selectionList.add(mesh) dagPath = selectionList.getDagPath(0) fnMesh = om.MFnMesh(dagPath) hit = fnMesh.allIntersections(om.MFloatPoint(pos), om.MFloatVector(dir), om.MSpace.kWorld, 99999, False) if hit: try: hit1 = hit[0][0] hit2 = hit[0][1] mySel = cmds.ls(sl=True)[-1] pos = [(hit1[0] + hit2[0]) / 2, (hit1[1] + hit2[1]) / 2, (hit1[2] + hit2[2]) / 2] cmds.setAttr(mySel + '.translate', pos[0], pos[1], pos[2], type='double3') except: pass
def slider_changed(self, *args): if self.busy or not self.dragging: return self.busy = True slider_value = self.slider.value() if self.interpolation_mode == options.BlendingMode.between: self.slider_label.setText(str(int(slider_value * 0.5 + 50))) elif self.interpolation_mode in [options.BlendingMode.towards, options.BlendingMode.average, options.BlendingMode.curve, options.BlendingMode.default]: self.slider_label.setText(str(slider_value)) if self.live_preview: blend = slider_value / 100.0 tween.interpolate(blend=blend, mode=self.interpolation_mode) view = omui2.M3dView() view = view.active3dView() view.refresh() qApp.processEvents() self.busy = False
def _release(self): """Method to be executed when the mouse button is released. Clear the view and object to place. """ self._view = om2UI.M3dView() self._dag = None self._meshDag = None
def viewToWorld(screenX, screenY): worldPos = om.MPoint() # out variable worldDir = om.MVector() # out variable activeView = omui2.M3dView().active3dView() activeView.viewToWorld(int(screenX), int(screenY), worldPos, worldDir) return worldPos, worldDir
def worldToQtView(worldPos): ''' This function will take in a world space point [0,10,0] and return a screen space pixel position. ''' activeView = omui2.M3dView().active3dView() worldPos = om.MPoint(*worldPos) screenX, screenY, clipped = activeView.worldToView(worldPos) return (screenX, activeView.portHeight() - screenY)
def _press(self): """Method to be executed when the mouse button is pressed. Get the current view and object to place. """ self._view = om2UI.M3dView().active3dView() # get the MDagPath of the object to place self._dag = self._asDagPath() # Set the distance to the last move distance so that the move # doesn't start from the original distance but the last modified # position. self._dist = self._moveDist
def click(s): try: # Grab mouse co-ords on screen viewX, viewY, viewZ = cmds.draggerContext(s.myTool, q=True, ap=True) position = om.MPoint() direction = om.MVector() # Convert 2D screen positions into 3D world positions omui.M3dView().active3dView().viewToWorld(int(viewX), int(viewY), position, direction) sel = om.MSelectionList() sel.add(s.sel) dagPath = sel.getDagPath(0) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection( om.MFloatPoint(position), om.MFloatVector(direction), om.MSpace.kWorld, 99999, False) # Did our ray intersect with the object? if intersection: hitPoint, hitRayParam, hitFace, hitTriangle, hitBary1, hitBary2 = intersection if hitTriangle != -1: # Grab Skin Cluster skin = mel.eval("findRelatedSkinCluster %s" % s.sel) if skin: # Get Face points cmds.select("%s.f[%s]" % (s.sel, hitFace)) face = cmds.polyInfo(fv=True) # Get vertexes verts = [ "%s.vtx[%s]" % (s.sel, v) for v in findall(r"\s(\d+)\s", face[0]) ] # Get Joints cmds.select(verts, r=True) joints = cmds.skinPercent(skin, q=True, t=None) # Get weights weights = sorted( [(j, cmds.skinPercent(skin, t=j, q=True)) for j in joints], key=lambda x: x[1], reverse=True) cmds.select(weights[0][0], r=True) else: print "No skin found" # Return to previous tool cmds.setToolTo(s.tool) cmds.refresh() except RuntimeError: print "There was an issue selecting the object."
def maintainCamera(panel, camera): """Context Manager to allow the client to set the current modelpanel to a different camera temporary before setting back to the original camera. :param panel: the maya model panel :type panel: str :param camera: the fullpathName of the camera. :type camera: str """ view = om2ui.M3dView() currentCamera = view.getM3dViewFromModelPanel(panel) cmds.lookThru(panel, camera) yield cmds.lookThru(panel, currentCamera.fullPathName())
def __init__(self): self._view = om2UI.M3dView() # the camera self._mfn = None # viewport size self._width = 0 self._height = 0 # camera settings self._ratio = 0 self._hPan = 0 self._vPan = 0 # dragger context self._startX = 0 self._startY = 0 self._endX = 0 self._endY = 0
def applyData(self, items=list(), maya=False): ''' This is temporary to read in json files. ''' # read in the file with the read function which will return the # data into a dictionary we can unpack # if there is data, then we will iterate through the dictionary and make the data # set the center point as zero and check if the scene is passed. If scene is passed if not items: items = self._data.keys() center_point = QtCore.QPointF() if self.scene: center_point = self.scene.sceneRect().center() for item in items: if self._data.has_key(item): # store the point array for the button so we can create a polygon. if maya: import rigrepo.ui.viewport as viewport import maya.api.OpenMayaUI as omui2 activeView = omui2.M3dView().active3dView() point_array = list() for point in self._data[item]["points"]: pointXY = viewport.viewToWorld( point[0], activeView.portHeight() - point[1]) print point, pointXY pointZ = self._data[item]["zValue"] point_array.append( (pointXY[0].x, pointXY[0].y, pointZ)) color = QtGui.QColor(*self._data[item]["color"]) color = color.getRgbF() # create the polygon using the points mc.polyCreateFacet(name=item, ch=False, tx=1, s=1, p=point_array) # select the polygon so we can assign the vertex colors to it. mc.select(item) mc.polyColorPerVertex(rgb=color[0:3], a=color[3], cdo=True) mc.addAttr(item, ln="selectableItems", dt="string") mc.setAttr("{}.selectableItems".format(item), self._data[item]["selectableItems"], type="string") if self._data[item].has_key("buttonType"): button_type = self._data[item]["buttonType"] mc.addAttr(item, ln="buttonType", dt="string") mc.setAttr("{}.buttonType".format(item), self._data[item]["buttonType"], type="string") else: point_array = [ center_point + QtCore.QPoint(*point) for point in self._data[item]["points"] ] # default button type is going to be null. button_type = "null" if self._data[item].has_key("buttonType"): button_type = self._data[item]["buttonType"] # check the different button types and make sure we create the correct one. # if the button is null, we will just create a PolygonItem if button_type == "null": button_item = graphicsWidgets.PolygonItem( item, color=QtGui.QColor(*self._data[item]["color"]), polygon=QtGui.QPolygonF(point_array)) elif button_type == "select": button_item = mayaGraphicsWidgets.SelectButtonItem( item, color=QtGui.QColor(*self._data[item]["color"]), polygon=QtGui.QPolygonF(point_array), selectableItems=self._data[item] ["selectableItems"]) elif button_type == "command": button_item = mayaGraphicsWidgets.SelectButtonItem( item, color=QtGui.QColor(*self._data[item]["color"]), polygon=QtGui.QPolygonF(point_array), command=self._data[item]["command"]) # set the Z depth for the button. if self._data[item].has_key("zValue"): button_item.setZValue(self._data[item]["zValue"]) if self.scene: self.scene.addItem(button_item)
def place_marker(): """ Called each time the user left-clicks in the viewport. """ nodes = maya.cmds.ls( selection=True, long=True, type='transform' ) or [] if len(nodes) == 0: msg = 'No nodes selected! Please select Marker nodes to place.' LOG.warning(msg) return mkr_nodes = mmapi.filter_marker_nodes(nodes) if len(mkr_nodes) == 0: msg = 'No Marker nodes selected!' LOG.warning(msg) return mkr_list = [mmapi.Marker(node=n) for n in mkr_nodes] if len(mkr_list) == 0: msg = 'No Marker nodes!' LOG.warning(msg) return # Get viewport coordinate. Viewport coordinate is relative to the # viewport resolution in pixels. vpX, vpY, vpZ = maya.cmds.draggerContext( const.CTX, query=True, dragPoint=True) view = OpenMayaUI.M3dView().active3dView() # Get the camera nodes from 3D viewport. camDag = view.getCamera() camShp = camDag.fullPathName() camDag.pop() camTfm = camDag.fullPathName() # 'Image resolution' is used to make sure the film back aspect # ratio is respected. imageWidth = maya.cmds.getAttr(camShp + '.horizontalFilmAperture') * 100.0 imageHeight = maya.cmds.getAttr(camShp + '.verticalFilmAperture') * 100.0 # Get the world-space location for the clicked point. position = OpenMaya.MPoint() direction = OpenMaya.MVector() view.viewToWorld( int(vpX), int(vpY), position, direction) # Compute the Marker coordinates for the given camera. frame = maya.cmds.currentTime(query=True) coord = maya.cmds.mmReprojection( worldPoint=(position.x, position.y, position.z), camera=(camTfm, camShp), asMarkerCoordinate=True, imageResolution=(imageWidth, imageHeight), time=frame ) if coord is None: msg = 'Could not get Marker coordinate.' LOG.warning(msg) return assert len(coord) == 3 # Set the marker position for mkr in mkr_list: mkr_grp = mkr.get_marker_group() mkr_grp_node = mkr_grp.get_node() plug_overscan_x = mkr_grp_node + '.overscanX' plug_overscan_y = mkr_grp_node + '.overscanY' overscan_x = maya.cmds.getAttr(plug_overscan_x) overscan_y = maya.cmds.getAttr(plug_overscan_y) node = mkr.get_node() plug_tx = node + '.translateX' plug_ty = node + '.translateY' value_tx = coord[0] * overscan_x value_ty = coord[1] * overscan_y lock_tx = maya.cmds.getAttr(plug_tx, lock=True) lock_ty = maya.cmds.getAttr(plug_tx, lock=True) if lock_tx is False and lock_ty is False: maya.cmds.setAttr(plug_tx, value_tx) maya.cmds.setAttr(plug_ty, value_ty) else: msg = 'Did not set Marker position, node is locked; node=%r' LOG.warning(msg, node) maya.cmds.select(nodes, replace=True) maya.cmds.refresh() return
def onPress(): vpX, vpY, _ = cmds.draggerContext(ctx, query=True, anchorPoint=True) pos = om.MPoint() dir = om.MVector() # calling view to world returns the camera position and viewing direction in the variables pos and dir activeView = omui.M3dView().active3dView() activeView.viewToWorld(int(vpX), int(vpY), pos, dir) camera = activeView.getCamera() farClippingPlane = cmds.getAttr(str(camera) + ".farClipPlane") # Use API to go through all the meshes in the scene and check if they intersect # with a ray from position "pos" in direction "dir" for mesh in cmds.ls(type='mesh'): selectionList = om.MSelectionList() selectionList.add(mesh) dagPath = selectionList.getDagPath(0) fnMesh = om.MFnMesh(dagPath) # cast a ray with length "farClippingPlane" from the camera through the viewplane. intersection = fnMesh.closestIntersection(om.MFloatPoint(pos), om.MFloatVector(dir), om.MSpace.kWorld, farClippingPlane, False) if intersection: hitPoint, hitRayParam, hitFace, hitTriangle, hitBary1, hitBary2 = intersection # when nothing intersects the hitpoint will be (0,0,0,1) if hitPoint != om.MFloatPoint(0, 0, 0, 1): x, y, z, _ = hitPoint normal = fnMesh.getClosestNormal(om.MPoint(hitPoint))[0] vNormal = np.array([ normalize(normal)[0], normalize(normal)[1], normalize(normal)[2] ]) vDirection = np.array(dir) vReflection = vDirection - (2 * np.dot(vDirection, vNormal) * vNormal) aim_locator = cmds.spaceLocator()[0] cmds.setAttr("{0}.translate".format(aim_locator), x, y, z) #cam_locator = cmds.spaceLocator(p= [x,y,z] - (vDirection * int(dialog.distance_lineEdit.text()))) #print "We've hit {0}!".format(dagPath), "{0}.f[{1}]".format(om.MFnDependencyNode(dagPath.transform()).name(),hitFace), hitPoint, dir #print "Surface normal = {0} \nIncidence Vector = {1}\nReflection Vector = {2}".format(vNormal,vDirection,vReflection) new_light_position = [x, y, z] + ( vReflection * int(dialog.distance_lineEdit.text())) cmds.setAttr( "{0}.translate".format( dialog.light_list_combo.currentText()), new_light_position[0], new_light_position[1], new_light_position[2]) temp_aim_constraint = cmds.aimConstraint( aim_locator, dialog.light_list_combo.currentText(), aim=(0, 0, -1)) cmds.delete(temp_aim_constraint) cmds.delete(aim_locator) # Since we've hit something we can break the loop and stop searching break else: print "No Intersection"