Beispiel #1
0
def reference_plane(flip, **kwargs):
    """
    Creates reference planes based on kwargs and boolean "flip"

    If height of image is greater than or equal to 700, scaleFactor of 0.25 is applied.

    Kwargs -
        axis - (1, 2, 3) for (X, Y, Z)
        dict - image dictionary
        term - search term
        width - image width
        height - image height
        scaleFactor - 1*
        
    Returns reference plane
    """
    fallback_dict = {'path': "", "width": 0, "height": 0}
    radio = kwargs.setdefault('axis')
    image_dict = kwargs.setdefault('dict', fallback_dict)
    name = kwargs.setdefault('term')+'_reference'
    path = kwargs.setdefault('path', image_dict['path'])
    material = create_material(path)
    scale_factor = kwargs.setdefault('scaleFactor', 1)

    dict_width = float(image_dict['width'])
    dict_height = float(image_dict['height'])

    width = kwargs.setdefault('width', dict_width)
    height = kwargs.setdefault('height', dict_height)
    print height
    if height >= 700:
        scale_factor = 0.25

    width *= scale_factor
    height *= scale_factor

    if radio is 3:
        plane = py.polyPlane(n=name, ax=(0, 0, 1), w=width, h=height, sx=1, sy=1)[0]
        py.move(0, (0.5*height), 0, plane)
        py.xform(plane, piv=(0, -0.5*height, 0))
    elif radio is 2:
        plane = py.polyPlane(n=name, ax=(0, 1, 0), w=width, h=height, sx=1, sy=1)[0]
    else:
        plane = py.polyPlane(n=name, ax=(1, 0, 0), w=width, h=height, sx=1, sy=1)[0]
        py.move(0, (0.5*height), 0, plane)
        py.xform(plane, piv=(0, -0.5*height, 0))
    if flip is True:
        py.setAttr(plane+'.scaleZ', -1)
    apply_material(plane, material, freeze=True)
    reference_layer(plane)

    return plane
def FTM_createRulerPlane( control, axisPlane, isMainDirX, transformParent, dummyRulerTransform ):
	obj = pm.polyPlane( axis=axisPlane, ch=True, w=1, h=1, sx=1, sy=1 )
	if isMainDirX == True:
		bDir = 'width'
		bSubDir = 'subdivisionsWidth'
		sDir = 'height'
		sSubDir = 'subdivisionsHeight'
	else:
		sDir = 'width'
		sSubDir = 'subdivisionsWidth'
		bDir = 'height'
		bSubDir = 'subdivisionsHeight'
	
	pm.connectAttr( control+'.controlSize2', obj[1]+'.'+bDir)
	pm.connectAttr( control+'.rulerDivisions2', obj[1]+'.'+bSubDir)
	pm.connectAttr( control+'.rulerSmallSize', obj[1]+'.'+sDir)

	shapeTransformDriver = dummyRulerTransform
	if shapeTransformDriver is None:
		shapeTransformDriver = obj[0]
	outShp = FTM_createTransformedGeometry(obj[0], 'outMesh', 'inMesh', shapeTransformDriver )

	#shps = pm.listRelatives(obj[0],s=True)
	pm.connectAttr( control+'.rulerDisplay', outShp+'.visibility')
	pm.setAttr(outShp+'.template', 1)

	if transformParent is None:
		pm.parent(obj[0], control)
		return obj[0]
	else:
		pm.parent(outShp,transformParent, add=True, s=True)
		pm.delete( obj[0] )
    def setUp(self):
        self.mf = mf.MatchingFaces()
        pm.newFile(f=True)
        self.res = 10

        # Two overlapping planes
        self.p1 = pm.polyPlane(n='plane1', sx=self.res, sy=self.res)[0]
        self.p2 = pm.polyPlane(n='plane2', sx=self.res, sy=self.res)[0]
        self.p3 = pm.polyPlane(n='plane3', sx=self.res, sy=self.res)[0]

        self.p1 = pm.PyNode(self.p1)
        self.p2 = pm.PyNode(self.p2)
        self.p3 = pm.PyNode(self.p3)

        # Non-overlapping plane
        pm.move(1, 1, 1, self.p3)
Beispiel #4
0
    def _createRefPlanes(self):
        self.refPlaneRootGrp = pm.group(n='refPlaneRoot_grp', empty=True)

        self.baseGeoBoundingBox = self.baseGeo.getBoundingBox(space='world')
        boundingBoxWidth = self.baseGeoBoundingBox.width()
        boundingBoxHeight = self.baseGeoBoundingBox.height()

        self.centerPlane = pm.polyPlane(n='centerPlane', w=boundingBoxWidth, h=boundingBoxHeight, sw=1, sh=1, axis=[1, 0, 0], ch=False)[0]
        self.leftBorderPlane = self.centerPlane.duplicate(n='leftBorderPlane')[0]
        self.rightBorderPlane = self.centerPlane.duplicate(n='rightBorderPlane')[0]

        self.refPlaneRootGrp | self.centerPlane
        self.centerPlane | self.leftBorderPlane
        self.centerPlane | self.rightBorderPlane

        self.refPlaneRootGrp.setTranslation(self.targetGeo.getBoundingBox(space='world').center())
        self.centerPlane.translate.set(0, 0, 0)
        pm.parentConstraint(self.outGeo, self.refPlaneRootGrp, mo=True)

        leftBorderPlaneInvXMul = pm.createNode('multiplyDivide', n='leftBorderPlaneInvX_mul')
        leftBorderPlaneInvXMul.input2X.set(-1)

        self.leftBorderPlane.translateX >> leftBorderPlaneInvXMul.input1X
        leftBorderPlaneInvXMul.outputX >> self.rightBorderPlane.translateX

        borderMargin = 0.1
        self.leftBorderPlane.translateX.set(boundingBoxWidth/2 + borderMargin)
    def test_apply_dict(self):
        # New scene
        pm.newFile(f=True)

        # Create plane and ncloth
        self.plane = pm.polyPlane()[0]
        pm.select(self.plane, r=1)

        nClothCreate()

        self.ncloth = pm.PyNode('nCloth1')
        self.nucleus = pm.PyNode('nucleus1')

        d = {'bounce': 3.0, 'evaluationOrder': 1}

        ims.apply_dict(self.ncloth, d)

        self.assertEqual(self.ncloth.getShape().bounce.get(), 3.0)
        self.assertEqual(self.ncloth.getShape().evaluationOrder.get(), 1)

        d = {'planeNormal': (0.0, 0.0, 1.0)}

        ims.apply_dict(self.nucleus, d)

        self.assertEqual(self.nucleus.planeNormal.get(), (0.0, 0.0, 1.0))
    def test_apply_dict(self):
        # New scene
        pm.newFile(f=True)

        # Create plane and ncloth
        self.plane = pm.polyPlane()[0]
        pm.select(self.plane, r=1)

        nClothCreate()

        self.ncloth = pm.PyNode('nCloth1')
        self.nucleus = pm.PyNode('nucleus1')

        d = {'bounce': 3.0,
             'evaluationOrder': 1}

        ims.apply_dict(self.ncloth, d)

        self.assertEqual(self.ncloth.getShape().
                         bounce.get(), 3.0)
        self.assertEqual(self.ncloth.getShape().
                         evaluationOrder.get(), 1)

        d = {'planeNormal': (0.0, 0.0, 1.0)}

        ims.apply_dict(self.nucleus, d)

        self.assertEqual(self.nucleus.planeNormal.get(), (0.0, 0.0, 1.0))
    def addShadowPlane(self):
        print 'Creating the shadow plane'
        shadowPlane = pm.polyPlane(n='shadowPlane',
                                   w=10,
                                   h=10,
                                   sx=1,
                                   sy=1,
                                   ax=(0, 1, 0),
                                   cuv=2,
                                   ch=0)
        shadowJoint = pm.joint(n='shadowJoint')
        pm.skinCluster(shadowJoint, shadowPlane)

        root = pm.ls("Root", type='joint')[0]
        pm.parent(shadowJoint, root)

        # rig the plane
        hips = pm.ls("Hips", type='joint')[0]
        leftFoot = pm.ls("LeftFoot", type='joint')[0]
        rightFoot = pm.ls("RightFoot", type='joint')[0]

        pm.pointConstraint(hips, shadowJoint, mo=0, skip='y')
        pm.pointConstraint(leftFoot, shadowJoint, mo=0, skip='y')
        pm.pointConstraint(rightFoot, shadowJoint, mo=0, skip='y')

        # default T pose Y value for the hips will be stored as reference
        # pm.addAttr(hips, ln = 'startY',t = 'double')
        hipsY = hips.getTranslation(space='world').y
        # pm.setAttr(hips.name() + '.startY',hipsY)

        shadowPlaneRV = pm.createNode('remapValue', n='shadowPlane_RV')
        shadowPlaneRV.imx.set(hipsY * 2.0)
        shadowPlaneRV.outputMin.set(2.0)
        shadowPlaneRV.outputMax.set(0)

        hips.translateY.connect(shadowPlaneRV.inputValue)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleX)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleY)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleZ)

        shadowPlaneCgfx = self.importCgfxShader()
        shadowPlaneCgfx.rename('shadowPlane_cgfx')
        shadowPlaneSg = pm.listConnections('%s.outColor' % shadowPlaneCgfx)[0]
        shadowPlaneSg.rename('shadowPlane_cgfxSG')

        shadowPlaneTxt = pm.shadingNode('file',
                                        asTexture=1,
                                        name='shadowPlane_file')

        shadowPlaneTxt.fileTextureName.set(
            'sourceimages\\groundshadow_diffusecolor.tga')
        shadowPlaneTxt.outColor.connect(shadowPlaneCgfx.diffuseMapSampler)

        pm.select(shadowPlane)
        pm.mel.eval('sets -e -forceElement ' + shadowPlaneSg)

        print 'Shadow plane created!!'
def buildJacket():
	planeBack = pm.polyPlane(
		width=jacketBack,
		height=paperLength,
		subdivisionsX=paperSubdivisionsX,
		subdivisionsY=paperSubdivisionsY,
		axis=(0, 1, 0),
		createUVs=UVnormalized,
		ch=1,
		name="planeBack"
		)
	
	planeLeft = pm.polyPlane(
		width=paperWidth,
		height=paperLength,
		subdivisionsX=jointNumber,
		subdivisionsY=paperSubdivisionsY,
		axis=(1, 0, 0),
		createUVs=UVnormalized,
		ch=1,
		name="planeLeft"
		)
	
	pm.move(planeLeft, (((jacketBack/2)*-1),paperLength/2,0))
	
	planeRight = pm.polyPlane(
		width=paperWidth,
		height=paperLength,
		subdivisionsX=jointNumber,
		subdivisionsY=paperSubdivisionsY,
		axis=(1, 0, 0),
		createUVs=UVnormalized,
		ch=1,
		name="planeRight"
		)
	
	pm.move(planeRight, (((jacketBack/2)),paperLength/2,0))
	
	jacket = pm.polyUnite(planeBack, planeRight, planeLeft,
		ch=0, name="jacket_geo")
	
	pm.select(cl=1)
	
	return jacket
def randPrims(numPrims, maxSize, minX, maxX, minY, maxY, minZ, maxZ, minSize=0.1): 
	prims = []
	
	for m in range(numPrims):
	# roll a random whole number between 0 to 4:
		p = random.randrange(0,5)
		if p == 0:
	# roll a random number between 0 and max sizes for all parameters
			radiusSphere = random.uniform(minSize, maxSize)
			x = random.uniform(minX, maxX)
			y = random.uniform(minY, maxY)
			z = random.uniform(minZ, maxZ)
			# store the object in a variable temporarily so it's easier to append it to the list
			n = pm.polySphere(r=radiusSphere)[0]
			pm.move(n, x, y, z)
			prims.append(n) 
		# create elif statements in case we roll 1, 2, 3 or 4
		elif p == 1:
			volCube = random.uniform(minSize, maxSize)
			x = random.uniform(minX, maxX)
			y = random.uniform(minY, maxY)
			z = random.uniform(minZ, maxZ)
			n = pm.polyCube(w=volCube, h=volCube, d=volCube)[0]
			pm.move(n, x, y, z)
			prims.append(n)
		elif p == 2:
			radiusCyl = random.uniform(minSize, maxSize)
			heightCyl = random.uniform(minSize, maxSize)
			x = random.uniform(minX, maxX)
			y = random.uniform(minY, maxY)
			z = random.uniform(minZ, maxZ)
			n = pm.polyCylinder(h=heightCyl, r=radiusCyl)[0]
			pm.move(n, x, y, z)
			prims.append(n)
		elif p == 3:
			radiusCone = random.uniform(minSize, maxSize)
			heightCone = random.uniform(minSize, maxSize)
			x = random.uniform(minX, maxX)
			y = random.uniform(minY, maxY)
			z = random.uniform(minZ, maxZ)
			n = pm.polyCone(h=heightCone, r=radiusCone)[0]
			pm.move(n, x, y, z)
			prims.append(n)
		elif p == 4:
			widthPlane = random.uniform(minSize, maxSize)
			heightPlane = random.uniform(minSize, maxSize)
			x = random.uniform(minX, maxX)
			y = random.uniform(minY, maxY)
			z = random.uniform(minZ, maxZ)
			n = pm.polyPlane(h=heightPlane, w=widthPlane)[0]
			pm.move(n, x, y, z)
			prims.append(n)
			
	return prims
Beispiel #10
0
def create_mirror_plane():
    # returns transform node

    plane = pm.polyPlane(name='MirrorToolPlane',
                         axis=(1.0, 0.0, 0.0),
                         subdivisionsHeight=1,
                         subdivisionsWidth=1,
                         height=100,
                         width=100)[0]

    return plane
Beispiel #11
0
def makePlane(point, name= "temp") :
    if len(point) != 4 :
        print "4つの座標を入力してください(makePlane)"
    pl = pm.polyPlane(n = name, sx=1, sy=1)
    
    pm.move(pl[0].vtx[0],[point[0][0],point[0][1],point[0][2]])
    pm.move(pl[0].vtx[1],[point[1][0],point[1][1],point[1][2]])
    pm.move(pl[0].vtx[3],[point[2][0],point[2][1],point[2][2]])
    pm.move(pl[0].vtx[2],[point[3][0],point[3][1],point[3][2]])

    return pl[0]
Beispiel #12
0
    def create_guide(self, parent):

        if self.options.use_nurbs:
            xform, _ = pm.nurbsPlane(p=[0, 0, 0],
                                     ax=[0, 0, 1],
                                     w=1,
                                     lr=1,
                                     d=3,
                                     u=1,
                                     v=1,
                                     ch=1)

        else:
            # -- Create the mesh
            xform, _ = pm.polyPlane(
                w=1,
                h=1,
                sx=1,
                sy=1,
                ax=[0, 1, 0],
                cuv=2,
                ch=1,
            )

        # -- Clear all history
        pm.delete(xform, constructionHistory=True)

        # -- Re-get the surface, as we're not working with a polyPlane any longer
        # -- but instead a mesh shape
        surface = xform.getShape()

        # -- Parent the surface under guide root
        xform.setParent(parent)

        # -- Tag the surface so we can retrieve it later
        self.tag(xform, 'GuideSurface')

        # -- Now create the follicle
        follicle = self.create_follicle(
            description='Guide{}'.format(self.options.description),
            side=self.options.side,
            parent=parent,
            surface=surface,
            u=0.5,
            v=0.5,
        )
        follicle.visibility.set(False)

        # -- Tag the surface so we can retrieve it later
        self.tag(follicle, 'GuideFollicle')

        return True
Beispiel #13
0
def createPreviewGrid( gridScale=1000):
    mesh = pm.polyPlane(sh=10,sw=10)
    mesh[0].s.set(gridScale,gridScale,gridScale) #그리드 하나당 1m
    mesh[0].getShape().overrideEnabled.set(True)
    mesh[0].getShape().overrideDisplayType.set(1) # 템플릿
    mesh[0].getShape().instObjGroups.disconnect()
    pm.polyDelEdge( [mesh[0].e[11], mesh[0].e[32], mesh[0].e[53], mesh[0].e[74], mesh[0].e[95], mesh[0].e[105], mesh[0].e[107], mesh[0].e[109], mesh[0].e[111], mesh[0].e[113], mesh[0].e[115:117], mesh[0].e[119], mesh[0].e[121], mesh[0].e[123], mesh[0].e[137], mesh[0].e[158], mesh[0].e[179], mesh[0].e[200]], cv=True, ch=1 )

    mesh2 = pm.polyPlane(sh=2,sw=2,h=1.005,w=1.005)
    #mesh2[0].s.set(gridScale,gridScale,gridScale) #그리드 하나당 1m
    mesh2[0].getShape().overrideEnabled.set(True)
    mesh2[0].getShape().overrideDisplayType.set(2) # 템플릿
    mesh2[0].getShape().instObjGroups.disconnect()

    pm.parent( mesh2[0].getShape(), mesh[0], s=True, r=True )
    pm.delete( mesh2[0] )   
    
    mesh[0].rename('previewGrid_10mx10m')

    if pm.objExists('Hips'):
        pm.delete( pm.pointConstraint('Hips',mesh[0]) )
        mesh[0].ty.set(0)
Beispiel #14
0
    def test_getCenters(self):
        p1 = pm.polyPlane(n='plane1', sx=1, sy=1)[0]
        p2 = pm.polyPlane(n='plane2', sx=2, sy=2)[0]

        expected1 = [pm.dt.Point(0, 0, 0)]
        expected2 = [
            pm.dt.Point(0.25, 0.0, 0.25),
            pm.dt.Point(0.25, 0.0, -0.25),
            pm.dt.Point(-0.25, 0.0, -0.25),
            pm.dt.Point(-0.25, 0.0, 0.25)
        ]

        faces1 = [p1.f]
        faces2 = p2.f

        centers1 = self.mf._getCenters(faces1)
        centers2 = self.mf._getCenters(faces2)

        self.assertListEqual(expected1, centers1)

        # Crappy test, but asserting points almost
        # equal each other is a pain in the ass...
        exp2 = []
        for p in expected2:
            exp2.append(p.x)
            exp2.append(p.y)
            exp2.append(p.z)
        cent2 = []
        for p in centers2:
            cent2.append(p.x)
            cent2.append(p.y)
            cent2.append(p.z)
        exp2.sort()
        cent2.sort()

        for x, y in zip(exp2, cent2):
            self.assertAlmostEqual(x, y)
Beispiel #15
0
    def setUp(self):
        # New scene
        pm.newFile(f=True)

        # Get ncloth attributes from file
        self.ncloth_attrs = []
        self.ncloth_attrsFile = os.path.dirname(__file__).\
            replace('tests', 'tool')
        self.ncloth_attrsFile = self.ncloth_attrsFile + \
            os.sep + 'ncloth_attrs.txt'

        if not os.path.exists(self.ncloth_attrsFile):
            msg = 'File not found: ', self.ncloth_attrsFile
            raise Exception(msg)

        f = open(self.ncloth_attrsFile, 'r')
        self.ncloth_attrs = f.readlines()
        f.close()

        # Get nucleus attributes from file
        self.nucleus_attrs = []
        self.nucleus_attrsFile = os.path.dirname(__file__).\
            replace('tests', 'tool')
        self.nucleus_attrsFile = self.nucleus_attrsFile + \
            os.sep + 'nucleus_attrs.txt'

        if not os.path.exists(self.nucleus_attrsFile):
            msg = 'File not found: ', self.nucleus_attrsFile
            raise Exception(msg)

        f = open(self.nucleus_attrsFile, 'r')
        self.nucleus_attrs = f.readlines()
        f.close()

        # Create plane and ncloth
        self.plane = pm.polyPlane()[0]
        pm.select(self.plane, r=1)

        nClothCreate()

        self.ncloth = pm.PyNode('nCloth1')
        self.nucleus = pm.PyNode('nucleus1')

        # Create expected name
        now = datetime.now()
        self.name = self.ncloth.name() + '_' + \
            str(now.year) + '-' + str(now.month) + '-' + \
            str(now.day) + '_' + \
            str(now.hour) + '-' + str(now.minute)
    def setUp(self):
        # New scene
        pm.newFile(f=True)

        # Get ncloth attributes from file
        self.ncloth_attrs = []
        self.ncloth_attrsFile = os.path.dirname(__file__).\
            replace('tests', 'tool')
        self.ncloth_attrsFile = self.ncloth_attrsFile + \
            os.sep + 'ncloth_attrs.txt'

        if not os.path.exists(self.ncloth_attrsFile):
            msg = 'File not found: ', self.ncloth_attrsFile
            raise Exception(msg)

        f = open(self.ncloth_attrsFile, 'r')
        self.ncloth_attrs = f.readlines()
        f.close()

        # Get nucleus attributes from file
        self.nucleus_attrs = []
        self.nucleus_attrsFile = os.path.dirname(__file__).\
            replace('tests', 'tool')
        self.nucleus_attrsFile = self.nucleus_attrsFile + \
            os.sep + 'nucleus_attrs.txt'

        if not os.path.exists(self.nucleus_attrsFile):
            msg = 'File not found: ', self.nucleus_attrsFile
            raise Exception(msg)

        f = open(self.nucleus_attrsFile, 'r')
        self.nucleus_attrs = f.readlines()
        f.close()

        # Create plane and ncloth
        self.plane = pm.polyPlane()[0]
        pm.select(self.plane, r=1)

        nClothCreate()

        self.ncloth = pm.PyNode('nCloth1')
        self.nucleus = pm.PyNode('nucleus1')

        # Create expected name
        now = datetime.now()
        self.name = self.ncloth.name() + '_' + \
            str(now.year) + '-' + str(now.month) + '-' + \
            str(now.day) + '_' + \
            str(now.hour) + '-' + str(now.minute)
Beispiel #17
0
	def _createRenderProxy( self, args ):
		mel.eval('setCurrentRenderer mentalRay')
		self.scene_name = mel.eval('file -q -sn -shn')
		for hi in args:
			if len(hi.split('|')) > 1 :
				hi=hi.split('|')[-1]
			#If the path doesn't exist for the file, create it.
			bipx_path = self._getBipxPath()
			if not os.path.exists(bipx_path):
				os.makedirs(bipx_path)
	
			#create the low geometry to take the proxy
			lo_proxy_name = hi+'_PROXY'
			lo = pm.polyPlane(w=1,h=1,sx=1,sy=1,ax=(0,1,0),cuv=2,ch=0,n=lo_proxy_name)[0]
			#Create the bipx if necessary
			bipx_name = hi+'_BINPROXY'
			if pm.objExists(bipx_name): bipx = pm.PyNode(bipx_name)
			else: bipx = pm.createNode('mip_binaryproxy', n=bipx_name)

			#turn the lo geometry shader on
			lo.miExportGeoShader.set(1)

			#connect the proxy to the lo's geo shader
			bipx.outValue.connect(lo.miGeoShader, f=True)

			#connect the hi to the proxy and set the write to 1 and set the file path
			hi.message.connect(bipx.geometry, f=True)
			bipx.write_geometry.set(1)
			bipx_filePath = bipx_path+hi+"_BINPROXY.mib"
			bipx.object_filename.set(bipx_filePath)

			#set the resolution width/height and store the originals to reset later
			res_wh = [pm.getAttr("defaultResolution.width"), pm.getAttr("defaultResolution.height")]
			pm.setAttr("defaultResolution.width", 5)
			pm.setAttr("defaultResolution.height", 5)

			#Perform a render, make the render globals really small square then reset after
			print ("Creating a file for object: %s" % (bipx_filePath))
			mel.eval("renderWindowRender redoPreviousRender renderView;")
			try:
				with open(bipx_filePath):
					print 'File created Successfully.'
			except IOError:
				print 'Oh dear.'
			pm.setAttr("defaultResolution.width", res_wh[0])
			pm.setAttr("defaultResolution.height", res_wh[1])

			bipx.write_geometry.set(0)
			hi.message.disconnect(bipx.geometry)
Beispiel #18
0
def createPaper(pageName):
    paper = pm.polyPlane(
		width=paperWidth,
		height=paperLength,
		subdivisionsX=paperSubdivisionsX,
		subdivisionsY=paperSubdivisionsY,
		axis=(1, 0, 0),
		createUVs=UVnormalized,
		ch=1,
		name=pageName+"_paper_geo"
		)
    pm.move(paper, 0, paperLength/2, 0)
    
    pm.select(cl=1)
    return paper
Beispiel #19
0
def create_colorchecker(name):
    '''
    Creates three spheres (white, 50% grey and chrome ball) and a colorchecker/Macbeth chart
    Args:
        name(String): Name of the object
    Returns:
        colorchecker
    '''

    colorchart = pm.polyPlane(name='%s:colorchart_geo' % NAMESPACE,
                              width=35.83,
                              height=25.25,
                              axis=(0, 0, 1),
                              constructionHistory=False)[0]
    return colorchart
Beispiel #20
0
    def addShadowPlane(self):
        print 'Creating the shadow plane'
        shadowPlane = pm.polyPlane( n='shadowPlane', w=10 , h=10, sx=1, sy= 1, ax=( 0, 1, 0),cuv = 2, ch = 0)
        shadowJoint = pm.joint(n='shadowJoint')
        pm.skinCluster(shadowJoint,shadowPlane)

        root = pm.ls("Root",type='joint')[0]
        pm.parent(shadowJoint,root)


        #rig the plane
        hips = pm.ls("Hips",type='joint')[0]
        leftFoot = pm.ls("LeftFoot",type='joint')[0]
        rightFoot = pm.ls("RightFoot",type='joint')[0]

        pm.pointConstraint(hips,shadowJoint,mo=0,skip='y')
        pm.pointConstraint(leftFoot,shadowJoint,mo=0,skip='y')
        pm.pointConstraint(rightFoot,shadowJoint,mo=0,skip='y')

        #default T pose Y value for the hips will be stored as reference
        #pm.addAttr(hips, ln = 'startY',t = 'double')
        hipsY = hips.getTranslation(space='world').y
        #pm.setAttr(hips.name() + '.startY',hipsY)

        shadowPlaneRV = pm.createNode('remapValue', n ='shadowPlane_RV')
        shadowPlaneRV.imx.set(hipsY * 2.0)
        shadowPlaneRV.outputMin.set(2.0)
        shadowPlaneRV.outputMax.set(0)

        hips.translateY.connect(shadowPlaneRV.inputValue)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleX)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleY)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleZ)

        shadowPlaneCgfx = self.importCgfxShader()
        shadowPlaneCgfx.rename('shadowPlane_cgfx')
        shadowPlaneSg = pm.listConnections('%s.outColor'%shadowPlaneCgfx)[0]
        shadowPlaneSg.rename('shadowPlane_cgfxSG')        

        shadowPlaneTxt = pm.shadingNode('file',asTexture=1,name='shadowPlane_file')

        shadowPlaneTxt.fileTextureName.set('sourceimages\\groundshadow_diffusecolor.tga')
        shadowPlaneTxt.outColor.connect(shadowPlaneCgfx.diffuseMapSampler)

        pm.select(shadowPlane)
        pm.mel.eval('sets -e -forceElement ' + shadowPlaneSg)

        print 'Shadow plane created!!'
 def _testSwap(self, func, swap):
     global denormalized_skin
     denormalized_skin = func
     joints = [
         pmc.joint(p=(-3.0, 0.0,-12.0)),
         pmc.joint(p=(-3.0, 0.0, -5.0)),
         pmc.joint(p=(1.0, 0.0, 5.5)),
         pmc.joint(p=(6.0, 0.0, 10.0))]
     plane = pmc.polyPlane(w=20.0,h=20.0,sx=25,sy=25)[0]
     cl = pmc.skinCluster(joints, plane)[0]
     def getweight(ind):
         return pmc.skinPercent(cl, plane.vtx[0], q=True, t=joints[ind])
     self.assertEqual(getweight(0), 0.0)
     self.assertEqual(getweight(1), 0.5)
     swap(cl, plane.vtx[0], joints[0], joints[1])
     self.assertEqual(getweight(0), 0.5)
     self.assertEqual(getweight(1), 0.0)
Beispiel #22
0
def polySkeleton(cards=None):
    ''' Make cylinders to represent a skeleton (for use in zbrush).
    '''

    if not cards:
        cards = core.find.blueprintCards()

    jointGroup = group(em=True, n='jointGroup')
    # Make cylinders to represent joints
    made = {}
    for card in cards:
        
        for j in card.joints:
            p = j.parent
            
            if p:
                bone = makeFakeBone()
                pdil.dagObj.moveTo(bone, p)
                s = pdil.dagObj.distanceBetween(j, p) * 0.5
                bone.sy.set(s)
                delete(aimConstraint(j, bone, aim=(0, 1, 0), u=(0, 0, 1)))
                makeIdentity(bone, apply=True, s=True)
                made[j] = bone

    # Setup fake joints parentage since they all exist
    for j, bone in made.items():
        p = j.parent
        if p in made:
            bone.setParent( made[p] )
        else:
            bone.setParent( jointGroup )

        
    # Make polygon cards
    cardGroup = group(em=True, n='jointGroup')
    for card in cards:
        points  = [ xform( x, q=True, ws=True, t=True) for x in card.cv ]
        
        poly = polyPlane(sh=True, sw=True)[0]
        poly.setParent(cardGroup)
        
        pdil.dagObj.matchTo(poly, card)
        
        for p, v in zip(points, poly.vtx):
            xform(v, ws=True, t=p)
Beispiel #23
0
def createCamSolidBG( camera=None ):
    '''
    카메라 백으로 사용할 솔리드한 Plane을 세움,
    카메라 이름을 명시하거나, 모델패털을 포커스한 상태에서 실행.

    Version : 2015-02-24
    
    >>> camSolidBG()
    (nt.Transform(u'persp_camSolidBG_grp'), nt.Transform(u'persp_camSolidBG_mesh'), nt.SurfaceShader(u'persp_camSolidBG_surfaceShader'), nt.ShadingEngine(u'persp_camSolidBG_SG'))
    
    >>> camSolidBG( camera='side' )
    (nt.Transform(u'side_camSolidBG_grp'), nt.Transform(u'side_camSolidBG_mesh'), nt.SurfaceShader(u'side_camSolidBG_surfaceShader'), nt.ShadingEngine(u'side_camSolidBG_SG'))
    '''
    if not camera:
        camera = pm.modelPanel( pm.playblast(activeEditor=True).split('|')[-1], q=True, camera=True )

    mesh = pm.polyPlane(sh=1, sw=1, ch=False)[0]
    grp  = pm.group()
    
    pm.parentConstraint(camera, grp)
    mesh.t.set(0,0,-500)
    mesh.r.set(90,0,0)
    mesh.s.set(150,150,150)
    
    shader, SG = pm.createSurfaceShader('surfaceShader')
    shader.outColor.set(0.5,0.5,0.5)
    pm.select(mesh)
    pm.hyperShade(assign=shader)
    
    mesh.castsShadows.set(False)
    mesh.receiveShadows.set(False)
    mesh.motionBlur.set(False)
    mesh.smoothShading.set(False)
    mesh.visibleInReflections.set(False)
    mesh.visibleInRefractions.set(False)
    
    grp.   rename('%s_camSolidBG_grp' % camera)
    mesh.  rename('%s_camSolidBG_mesh' % camera)
    shader.rename('%s_camSolidBG_surfaceShader' % camera)
    SG.    rename('%s_camSolidBG_SG' % camera)
    
    return grp, mesh, shader, SG
    def _testSwap(self, func, swap):
        global denormalized_skin
        denormalized_skin = func
        joints = [
            pmc.joint(p=(-3.0, 0.0, -12.0)),
            pmc.joint(p=(-3.0, 0.0, -5.0)),
            pmc.joint(p=(1.0, 0.0, 5.5)),
            pmc.joint(p=(6.0, 0.0, 10.0))
        ]
        plane = pmc.polyPlane(w=20.0, h=20.0, sx=25, sy=25)[0]
        cl = pmc.skinCluster(joints, plane)[0]

        def getweight(ind):
            return pmc.skinPercent(cl, plane.vtx[0], q=True, t=joints[ind])

        self.assertEqual(getweight(0), 0.0)
        self.assertEqual(getweight(1), 0.5)
        swap(cl, plane.vtx[0], joints[0], joints[1])
        self.assertEqual(getweight(0), 0.5)
        self.assertEqual(getweight(1), 0.0)
Beispiel #25
0
def paperbloc_base(w, d, h, name):

    name_fill = name + '_fill'
    d = d
    w = w
    h = h
    sw = floatToInt(w)
    sh = floatToInt(h)
    sd = floatToInt(d)

    bloc = pmc.polyCube(n=name + '__temp', w=w, d=d, h=h, sx=sw, sz=sd, sy=sh)
    fill = pmc.polyPlane(n=name_fill + '__temp', w=w, h=d, sx=sw, sy=sd)

    fCount = pmc.polyEvaluate(bloc[0], f=True)
    sel = pmc.select(bloc[0].f + '[0:' + str(fCount) + ']')
    pmc.move(h / 2, y=True, r=True)
    pmc.select(cl=True)

    sel = pmc.ls(fill[0], bloc[0])

    return sel
Beispiel #26
0
def create_plane(normal=[0,1,0]):
    normal_x = normal[0]
    normal_y = normal[1]
    normal_z = normal[2]
    transform, polyPlane = pymel.polyPlane(sx=1, sy=1)
    shape = transform.getShape()

    # There's no parameter to re-orient a plane so we'll move all of it's vertices if needed.
    pymel.delete(polyPlane)
    offset_tm = None
    if normal_x != 0.0:
        offset_tm = pymel.datatypes.Matrix([[0,1,0,0], [1,0,0,0], [0,0,-normal_x,0], [0,0,0,1]]) #X
    elif normal_y != 0.0:
        offset_tm = pymel.datatypes.Matrix([[normal_y,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]]) #Y
    elif normal_z != 0.0:
        offset_tm = pymel.datatypes.Matrix([[1,0,0,0], [0,0,1,0], [0,-normal_z,0,0], [0,0,0,1]]) #Z

    for v in shape.vtx:
        v.setPosition(v.getPosition() * offset_tm)

    return transform
Beispiel #27
0
def create_cloth_flap(flap, subdivisions_width=1, subdivisions_height=1):
    '''
    Create flap geometry that will be used for nCloth simulation.

    :param flap: Flap object that will later be wrap deformed
    :param subdivisions_width: Number of subdivisions along X-axis
    :param subdivisions_height: Number of subdivisions in Y-axis
    '''

    bounds = flap.boundingBox()
    plane, plane_shape = pm.polyPlane(
        width=bounds.width(),
        height=bounds.height(),
        sx=subdivisions_width,
        sy=subdivisions_height,
        axis=[0, 0, 1],
        cuv=1,
    )
    plane.setTranslation(bounds.center())
    pm.makeIdentity(plane, apply=True, t=True, r=True, s=True, n=False)
    plane.setPivots([0, 0, 0])
    return plane
Beispiel #28
0
def create_ratio_plane(file_node, name, flag_alpha, mult):
    """
    -gets a file node and creates a poly plane with the file node image proportions
    -calls the method create_lambert_mtl() to create a lambert shader and connects the file node to it
    -assigns the shader to the plane

    :param file_node: a PyNode, file node
    :param name: a string, the name for the nodes creation
    :param flag_alpha: a flag, indicates if to connect the transparency as well
    :param mult: a float, if not None - used as a uniform multiplier for the plane proportions in creation
    :return: a PyNode, poly plane
    """
    size_x = file_node.osx.get()
    size_y = file_node.osy.get()
    print(size_x, size_y)
    if not mult is None:
        size_x *= mult
        size_y *= mult

    poly_plane, ch = pm.polyPlane(sx=1,
                                  sy=1,
                                  w=size_x,
                                  h=size_y,
                                  n=name + "_card")
    ch.rename(name + "_polyPlane")

    # create shader
    shd, shdSG = create_lambert_mtl(name)
    file_node.outColor >> shd.attr("color")

    # handle alpha
    if flag_alpha:
        file_node.outTransparency >> shd.transparency

    # assign shader to plane
    pm.sets(shdSG, forceElement=poly_plane)
    return poly_plane
Beispiel #29
0
        plugin_fn.registerNode(CarpetRoll.TYPE_NAME, CarpetRoll.TYPE_ID,
                               CarpetRoll.creator, CarpetRoll.initialize,
                               ommpx.MPxNode.kDeformerNode)
    except:
        pm.displayError("Failed to register node {0}".format(
            CarpetRoll.TYPE_NAME))


def uninitializePlugin(plugin):

    plugin_fn = ommpx.MFnPlugin(plugin)
    try:
        plugin_fn.deregisterNode(CarpetRoll.TYPE_ID)
    except:
        pm.displayError("Failed to deregister node {0}".format(
            CarpetRoll.TYPE_NAME))


if __name__ == "__main__":

    pm.newFile(f=1)
    plugin_name = "E:/Maya/MayaAPI/Deforner/CarpetRoll.py"
    if pm.pluginInfo(plugin_name, q=1, loaded=True):
        pm.unloadPlugin(os.path.basename(plugin_name), f=True)
    pm.loadPlugin(plugin_name)
    pplane_transform, pplane_shape = pm.polyPlane()
    pplane_shape.subdivisionsWidth.set(20)
    pplane_shape.subdivisionsHeight.set(20)
    pm.select(pplane_transform)
    pm.deformer(type="CarpetRoll")
Beispiel #30
0
def lcRetopoBasicUI(dockable=False, asChildLayout=False, *args, **kwargs):
    """ """
    global lct_cfg
    global prefix

    ci = 0  # color index iterator
    windowName = 'lcRetopoBasic'
    shelfCommand = 'import lct.src.{0}.{0} as {1}\nreload({1})\n{1}.{0}UI()'.format(
        windowName, prefix)
    commandString = 'import lct.src.{0}.{0} as {1}\nreload({1})\n{1}.{0}UI(asChildLayout=True)'.format(
        windowName, prefix)
    icon = os.path.join(basePath, 'lcRetopoBasic.png')
    winWidth = 205
    winHeight = height

    if pm.window(windowName, ex=True):
        pm.deleteUI(windowName)

    if not asChildLayout:
        lcUI.UI.lcToolbox_child_popout(prefix + '_columnLayout_main',
                                       windowName, height, commandString,
                                       iconPath, lct_cfg)
        mainWindow = lcUI.lcWindow(prefix=prefix,
                                   windowName=windowName,
                                   width=winWidth,
                                   height=winHeight,
                                   icon=icon,
                                   shelfCommand=shelfCommand,
                                   annotation=annotation,
                                   dockable=dockable,
                                   menuBar=True)
        mainWindow.create()

    pm.columnLayout(prefix + '_columnLayout_main')

    # SETUP
    pm.button(l='Setup for Retopo',
              bgc=colorWheel.getColorRGB(ci),
              w=200,
              h=25,
              annotation='Setup a high res mesh for retopology',
              command=lambda *args: rtb_setup_live_mesh(highresListDropdown))
    ci += 1

    # List
    pm.rowColumnLayout(nc=3, cw=([1, 25], [2, 150], [3, 25]))
    pm.symbolButton(
        h=25,
        image=os.path.join(iconPath, 'reloadMeshList.png'),
        annotation='Reload the list of high res meshes',
        command=lambda *args: rtb_highres_list_populate(highresListDropdown))
    highresListDropdown = pm.optionMenu(
        prefix + '_optionMenu_highres_list',
        w=150,
        h=23,
        bgc=[0.5, 0.5, 0.5],
        annotation='List of high res meshes in the scene')
    highresListDropdown.changeCommand(
        lambda *args: rtb_choose_active(highresListDropdown))
    remove_mesh_button = pm.symbolButton(
        h=25,
        image=os.path.join(iconPath, 'removeMeshFromList.png'),
        annotation=
        'Remove current high res mesh from the list and return it to a normal state',
        command=lambda *args: rtb_remove(highresListDropdown))
    popup_remove_mesh = pm.popupMenu(parent=remove_mesh_button)
    pm.menuItem(l='Remove all live meshes',
                parent=popup_remove_mesh,
                command=lambda *args: rtb_remove_all(highresListDropdown))
    pm.setParent(prefix + '_columnLayout_main')

    # Scale
    pm.rowColumnLayout(nc=4, cw=([1, 50], [2, 100], [3, 25], [4, 25]))
    pm.picture(prefix + '_picture_layer_mesh',
               image=os.path.join(iconPath, 'meshLayering.png'),
               annotation='Drag slider to change mesh layering')
    pm.floatSlider(
        prefix + '_floatSlider_layer_mesh',
        h=25,
        step=0.01,
        min=0,
        max=1,
        v=lct_cfg.get('lcRetopoBasicLayering'),
        dragCommand=lambda *args: rtb_scale_layer_mesh(highresListDropdown))
    button_xray = pm.symbolButton(
        prefix + '_symbolButton_xray',
        h=25,
        image=os.path.join(iconPath, 'toggleXray.png'),
        bgc=[0.27, 0.27, 0.27],
        annotation='Toggle Mesh X-Ray',
        command=lambda *args: rtb_toggle_xray(highresListDropdown, 'active'))
    popup_xray = pm.popupMenu(parent=button_xray)
    pm.menuItem(l='xRay on/off all',
                parent=popup_xray,
                command=lambda *args: rtb_toggle_xray(highresListDropdown))

    button_hide = pm.symbolButton(
        prefix + '_symbolButton_hide',
        h=25,
        image=os.path.join(iconPath, 'hideMesh.png'),
        bgc=[0.27, 0.27, 0.27],
        annotation='Hide/Show Current High-Res',
        command=lambda *args: rtb_toggle_hide(highresListDropdown, 'active'))
    popup_hide = pm.popupMenu(parent=button_hide)
    pm.menuItem(
        l='Hide/Show all',
        parent=popup_hide,
        command=lambda *args: rtb_toggle_hide(highresListDropdown, 'all'))
    pm.menuItem(
        l='Hide/Show others',
        parent=popup_hide,
        command=lambda *args: rtb_toggle_hide(highresListDropdown, 'others'))
    pm.setParent(prefix + '_columnLayout_main')

    # Shader
    pm.rowColumnLayout(nc=3, cw=([1, 50], [2, 100], [3, 50]))
    pm.picture(image=os.path.join(iconPath, 'shaderOpacity.png'),
               enable=False,
               annotation='Drag slider to change shader transparency')
    pm.floatSlider(prefix + '_floatSlider_topo_trans',
                   h=25,
                   step=0.1,
                   min=0,
                   max=1,
                   v=lct_cfg.get('lcRetopoBasicShader'),
                   dragCommand=lambda *args: rtb_update_topo_transparency())
    pm.symbolButton(
        h=25,
        image=os.path.join(iconPath, 'assignShader.png'),
        bgc=[0.27, 0.27, 0.27],
        annotation=
        'Create and/or assign a semi-transparent shader to selected low res mesh',
        command=lambda *args: rtb_create_retopo_shader())
    pm.setParent(prefix + '_columnLayout_main')
    pm.separator(style='in', h=5)

    # Relax and Shrinkwrap
    pm.rowColumnLayout(nc=2)
    pm.button(
        l='Relax',
        bgc=colorWheel.getColorRGB(ci),
        w=100,
        h=25,
        annotation='Relax selected verts and shrink-wrap them to the live mesh',
        command=lambda *args: rtb_vert_ops(highresListDropdown,
                                           operation='relax'))
    ci += 1
    pm.button(l='Shrink-Wrap',
              bgc=colorWheel.getColorRGB(ci),
              w=100,
              h=25,
              annotation='Shrink-wrap selected verts to the live mesh',
              command=lambda *args: rtb_vert_ops(highresListDropdown,
                                                 operation='shrink'))
    ci += 1
    pm.setParent(prefix + '_columnLayout_main')

    # PROG Bar
    pm.progressBar(prefix + '_progress_control',
                   en=False,
                   w=202,
                   isInterruptable=True)
    pm.separator(style='in', h=5)

    # Tool List
    pm.gridLayout(nrc=[1, 5], cwh=[40, 40])
    ##1
    pm.symbolButton(prefix + '_symbolButton_select_mode',
                    image='selectByComponent.png',
                    c=lambda *args: rtb_toggle_select_mode(),
                    annotation='Toggle Object/Component Modes')
    ##2
    create_mesh = pm.symbolButton(
        image='polyCylinder.png',
        c=lambda *args: pm.polyCylinder(
            r=1, h=2, sx=8, sy=1, sz=1, ax=(0, 1, 0), rcp=0, cuv=3, ch=1),
        annotation='Create Poly Cylinder')
    popup_create_mesh = pm.popupMenu(parent=create_mesh)
    pm.menuItem(l='polyPlane',
                parent=popup_create_mesh,
                command=lambda *args: pm.polyPlane(
                    w=2, h=2, sx=1, sy=1, ax=(0, 1, 0), cuv=2, ch=1))
    pm.menuItem(l='polyCube',
                parent=popup_create_mesh,
                command=lambda *args: pm.polyCube(
                    w=2, h=2, d=2, sx=1, sy=1, ax=(0, 1, 0), cuv=2, ch=1))
    ##3
    pm.symbolButton(image='polyUnite.png',
                    command=lambda *args: lcGeometry.Geometry.merge_and_weld(),
                    annotation='Combine and Weld')
    ##4
    button_zeroX = pm.symbolButton(image=os.path.join(iconPath, 'zeroX.png'),
                                   command=lambda *args: rtb_zero('x'),
                                   annotation='Zero to world axis')
    popup_zeroX = pm.popupMenu(parent=button_zeroX)
    pm.menuItem(l='Zero X',
                parent=popup_zeroX,
                command=lambda *args: rtb_zero('x'))
    pm.menuItem(l='Zero Y',
                parent=popup_zeroX,
                command=lambda *args: rtb_zero('y'))
    pm.menuItem(l='Zero Z',
                parent=popup_zeroX,
                command=lambda *args: rtb_zero('z'))
    ##5
    pm.symbolButton(image='modelToolkit.png',
                    c=lambda *args: pm.mel.eval('ToggleModelingToolkit'),
                    annotation='Modeling Toolkit')

    #
    if not asChildLayout:
        mainWindow.show()
        pm.window(mainWindow.mainWindow, edit=True, h=winHeight, w=winWidth)
    else:
        pm.setParent('..')
        pm.setParent('..')

    # edit menus
    optionsMenu, helpMenu = lcUI.UI.lcToolbox_child_menu_edit(
        asChildLayout, windowName)

    pm.menuItem(parent=optionsMenu, divider=True, dividerLabel=windowName)
    pm.menuItem(parent=optionsMenu,
                l='Remove all live meshes',
                command=lambda *args: rtb_remove_all(highresListDropdown))

    # populate drowpdowns
    rtb_highres_list_populate(highresListDropdown)

    # restore interface selections
    highresListDropdown.setSelect(lct_cfg.get('lcRetopoBasicListItem'))
    rtb_choose_active(highresListDropdown)

    # vertex animation cache in viewport 2.0 must be disabled or the mesh will not update properly
    if pm.objExists('hardwareRenderingGlobals'):
        pm.PyNode('hardwareRenderingGlobals').vertexAnimationCache.set(0)
    rtb_init_select_mode()
    if not pm.scriptJob(ex=lct_cfg.get('lcRetopoBasicScriptJob')
                        ) or lct_cfg.get('lcRetopoBasicScriptJob') == 0:
        jobNum = pm.scriptJob(
            e=["SelectModeChanged", lambda *args: rtb_init_select_mode()],
            protected=True)
        lct_cfg.set('lcRetopoBasicScriptJob', jobNum)
Beispiel #31
0
file_node.outSize.outSizeX >> ocio_node.width
file_node.outSize.outSizeY >> ocio_node.height
pm.select(cl=True)

#connect ocio node to shader
ocio_node.output_color >> shader_node.outColor
pm.select(cl=True)

#set texture file
file_node.fileTextureName.set(texture_dir + '/' + texture_name)

#polyplane_transform_node, polyplane_shape_node
polyplane_transform_node, polyplane_shape_node = pm.polyPlane(
    n='ocio_test_polyplane',
    sx=10,
    sy=10,
    axis=(0, 1, 0),
    width=12.8,
    height=7.8)
pm.select(cl=True)
#connect plane to shader
pm.sets(shading_group_node, forceElement=polyplane_transform_node.name())
pm.select(cl=True)

#render_cam
render_cam_transform, render_cam_shape = pm.camera()
pm.select(cl=True)
pm.rename(render_cam_transform, 'render_cam')
render_cam_transform.translate.set(0, 13, 7)
render_cam_transform.rotate.set(-65, 0, 0)
pm.setKeyframe(render_cam_transform, s=False)
    def _deformPlanes(self, autoGrp, baseGrp=None):
        """
        Create a plane and copy the deforms from base mesh, then constraint the autoGrp and baseGrp to the plane
        :param autoGrp:autoGrp, generally contains a controller as child
        :param baseGrp: to control a baseShape like wire deformer baseCure
        :return: planes
        """
        # create a small plane per point, then combine them
        planes = []
        for ctr in autoGrp:
            plane = pm.polyPlane(h=0.01, w=0.01, sh=1, sw=1, ch=False)[0]
            plane.setTranslation(ctr.getTranslation("world"), "world")
            planes.append(plane)

        # combine planes
        if len(planes) > 1:
            # len 1 gives an error with polyUnite
            planes = pm.polyUnite(planes, ch=False, mergeUVSets=True)[0]
        else:
            planes = planes[0]
            pm.makeIdentity(planes, a=True, r=True, s=True, t=True)
            planes.setPivots([0, 0, 0])

        planes.rename("%s_planes" % self._baseName)  # rename
        pm.polyAutoProjection(planes,
                              ch=False,
                              lm=0,
                              pb=0,
                              ibd=1,
                              cm=0,
                              l=2,
                              sc=1,
                              o=1,
                              p=6,
                              ps=0.2,
                              ws=0)  # uvs

        if self._MESH_SHAPE:
            # if skin sample, copy skin weights to planes
            # find skin node
            skinNode = pm.listHistory(self._MESH_SHAPE, type='skinCluster')[0]
            # joint list
            jointList = skinNode.influenceObjects()
            # create skinCluster
            copySkinCluster = pm.skinCluster(planes, jointList, mi=3)
            # copy skin weigths
            pm.copySkinWeights(ss=skinNode,
                               ds=copySkinCluster,
                               noMirror=True,
                               surfaceAssociation='closestPoint',
                               influenceAssociation=('closestJoint',
                                                     'closestJoint'))

        # connect each auto grp to each poly face
        numFaces = planes.getShape().numFaces()
        logger.debug("num Faces: %s" % numFaces)
        for i in range(numFaces):
            pm.select(planes.f[i], r=True)
            pm.select(autoGrp[i], add=True)
            pm.pointOnPolyConstraint(maintainOffset=True)
            pm.select(cl=True)
            if baseGrp:
                pm.select(planes.f[i], r=True)
                pm.select(baseGrp[i], add=True)
                pm.pointOnPolyConstraint(maintainOffset=True)
                pm.select(cl=True)

            #hammer weights
            try:
                #TODO: bad aproximation
                vertex = pm.modeling.polyListComponentConversion(planes.f[i],
                                                                 tv=True)
                pm.select(vertex, r=True)
                logger.debug("vertices %s:" % vertex)
                mel.eval("weightHammerVerts;")
                pm.select(cl=True)
            except:
                pm.select(cl=True)

        # parent planes to nonXform grp
        self._noXformGrp.addChild(planes)  # parent to noXform
        return planes
        pm.loadPlugin( 'twClothSolverBlockoutPlugins.py' )
        print('Successfully loaded plugin')
except:
	print('Error Reloading Plugin')




#TwClothSolverIOPaperBlockout
#----------------------------------
#----------------------------------

#create inputGeo
#----------------------------------
#inputGeo
inputGeoTrans = pm.polyPlane( sx=10, sy=10, w=10, h=10, ch = False)[0]
inputGeoShape = inputGeoTrans.getShape()
#transformPlane
inputGeoTrans.translateY.set(5)
inputGeoTrans.visibility.set(0)
pm.select(cl = True)
#pm.select(inputGeoTrans, r = True)
#pm.polyTriangulate(ch = False)
#pm.select(cl = True)

#create outputGeo
#----------------------------------
#outputGeo
outputGeoTrans = pm.polyPlane( sx=10, sy=10, w=10, h=10, ch = False)[0]
outputGeoShape = outputGeoTrans.getShape()
pm.select(cl = True)
Beispiel #34
0
    def importAsset(self, iAObj=None):
        component = ftrack.Component(iAObj.componentId)
        start, end = self.getStartEndFrames(component, iAObj)
        first_image = iAObj.filePath % start
        new_nodes = []

        # Image plane
        if iAObj.options["importType"] == "Image Plane":

            # Getting camera
            new_camera = False
            if iAObj.options["attachCamera"]:
                cam = pm.ls(selection=True)[0]
            else:
                cam = pm.createNode("camera")
                new_camera = True

            if iAObj.options["renameCamera"]:
                asset_name = component.getVersion().getAsset().getName()
                pm.rename(cam.getTransform(), asset_name)

            if new_camera:
                new_nodes.extend([cam.name(), cam.getTransform().name()])

            if iAObj.options["resolutionGate"]:
                cam.displayResolution.set(1)

            cam.farClipPlane.set(iAObj.options["imagePlaneDepth"] * 10)

            # Create image plane
            visibility = True
            option = "Hidden from other cameras"
            if iAObj.options["imagePlaneVisibility"] == option:
                visibility = False

            image_plane_transform, image_plane_shape = pm.imagePlane(
                camera=cam, fileName=first_image, showInAllViews=visibility)
            image_plane_shape.useFrameExtension.set(1)
            image_plane_shape.depth.set(iAObj.options["imagePlaneDepth"])

            new_nodes.extend(
                [image_plane_transform.name(),
                 image_plane_shape.name()])

            # Create ground plane
            if iAObj.options["createGround"]:
                ground_transform, ground_shape = pm.polyPlane(
                    name="ground",
                    height=iAObj.options["groundSize"],
                    width=iAObj.options["groundSize"])

                ground_shader = pm.shadingNode("lambert", asShader=True)
                visiblity = iAObj.options["groundVisibility"] / 100
                ground_shader.transparency.set(visiblity, visiblity, visiblity)
                pm.select(ground_transform)
                pm.hyperShade(assign=ground_shader.name())

                new_nodes.extend([
                    ground_transform.name(),
                    ground_shape.name(),
                    ground_shader.name()
                ])

        # File Node
        if iAObj.options["importType"] == "File Node":

            file_node = pm.shadingNode("file", asTexture=True)
            file_node.fileTextureName.set(first_image)
            file_node.useFrameExtension.set(1)

            exp = pm.shadingNode("expression", asUtility=True)
            exp.expression.set(file_node.name() + ".frameExtension=frame")

            new_nodes.extend([file_node.name(), exp.name()])

            # Connecting file node to color management in 2016+
            if pm.objExists("defaultColorMgtGlobals"):
                colMgmtGlob = pm.PyNode("defaultColorMgtGlobals")
                mapping = {
                    "cmEnabled": "colorManagementEnabled",
                    "configFileEnabled": "colorManagementConfigFileEnabled",
                    "configFilePath": "colorManagementConfigFilePath",
                    "workingSpaceName": "workingSpace"
                }
                for key, value in mapping.iteritems():
                    src_name = colMgmtGlob.name() + "." + key
                    dst_name = file_node.name() + "." + value
                    pm.PyNode(src_name) >> pm.PyNode(dst_name)

            texture = None
            if iAObj.options["fileNodeType"] != "Single Node":

                texture = pm.shadingNode("place2dTexture", asUtility=True)

                src_name = texture.name() + ".outUV"
                dst_name = file_node.name() + ".uvCoord"
                pm.PyNode(src_name) >> pm.PyNode(dst_name)
                src_name = texture.name() + ".outUvFilterSize"
                dst_name = file_node.name() + ".uvFilterSize"
                pm.PyNode(src_name) >> pm.PyNode(dst_name)

                connections = [
                    "rotateUV", "offset", "noiseUV", "vertexCameraOne",
                    "vertexUvThree", "vertexUvTwo", "vertexUvOne", "repeatUV",
                    "wrapV", "wrapU", "stagger", "mirrorU", "mirrorV",
                    "rotateFrame", "translateFrame", "coverage"
                ]
                for connection in connections:
                    src_name = texture.name() + "." + connection
                    dst_name = file_node.name() + "." + connection
                    pm.PyNode(src_name) >> pm.PyNode(dst_name)

                new_nodes.append(texture.name())

            if iAObj.options["fileNodeType"] == "Projection":
                projection = pm.shadingNode("projection", asUtility=True)
                texture3d = pm.shadingNode("place3dTexture", asUtility=True)

                src_name = file_node.name() + ".outColor"
                dst_name = projection.name() + ".image"
                pm.PyNode(src_name) >> pm.PyNode(dst_name)

                src_name = texture3d.name() + ".worldInverseMatrix"
                dst_name = projection.name() + ".placementMatrix"
                pm.PyNode(src_name) >> pm.PyNode(dst_name)

                new_nodes.extend([projection.name(), texture3d.name()])

        self.newData = set(new_nodes)
        self.oldData = set()

        self.linkToFtrackNode(iAObj)
Beispiel #35
0
def xpop(args=[], type='LOC', space=1, addSuffix='', parent=''):
    '''
    Function: takes args and matchesPos + duplicates specified type onto each arg
    Args = type=str, space=int, addSuffix=str, parent=str
    State: type=one of ['LOC','PLANE','CUBE','JNT','GRP','CAM','SLGT','DLGT','PLGT','ALGT']
                if in list of prespecified objects, will populate across. Explained:
                locator, plane, cube, joint, group, camera,
                spotlight, directional light, point light, area light
           
                space=1-4: check help for _SCRIPTS._LAYOUT.lib_position.matchPos for instruction on this
                           otherwise leave default
    Returns: list of PyNode(type)
    Example Usage: xpop(type='JNT', addSuffix='TEMP')
    '''
    print 'Populating type: %s' % type
    suffixes=['LOC','PLANE','CUBE','JNT','GRP','CAM','SLGT','DLGT','PLGT','ALGT']
    if type.upper() in suffixes or pm.objExists(type):
        if args==[]: args = pm.ls(sl=True)
        #Create or store group
        if parent=='': grp = 'populate_'+type+'_GRP'
        else: grp = parent
        
        if not pm.objExists(grp):
            grp = pm.group(em=True, n=grp)
        else: grp = pm.PyNode(grp)
        result=[]
        print type
        for arg in args:
            if addSuffix=='':
                pop = nami.replaceSuffix(type,args=arg.name(),validSuffix=True)
            else: pop = arg.name()+addSuffix
            
            if not pm.objExists(pop):
                if type=='LOC':
                    pop = pm.spaceLocator(n=pop)
                elif type=='PLANE':
                    pop = pm.polyPlane(n=pop,sx=1, sy=1)[0]
                elif type=='CUBE':
                    pop = pm.polyCube(n=pop)[0]
                elif type=='JNT':
                    pop = pm.joint( n=pop )
                    pop.radius.set(10)
                elif type=='GRP':
                    pop = pm.group(em=True,n=pop)
                elif type=='CAM':
                    pop = pm.camera(n=pop)[0]
                elif type=='SLGT':
                    pop = pm.spotLight().listRelatives(p=True)[0].rename(pop)
                elif type=='DLGT':
                    pop = pm.directionalLight().listRelatives(p=True)[0].rename(pop)
                elif type=='PLGT':
                    pop = pm.pointLight().listRelatives(p=True)[0].rename(pop)
                elif type=='ALGT':
                    pop = pm.createNode('areaLight').listRelatives(p=True)[0].rename(pop)
                else:
                    pop = pm.duplicate(type)[0]
            posi.matchPos(src=arg, args=[pop], type=1)
            pop.addAttr('target',dt='string')
            pop.target.set( arg )
            pop.setParent( grp )
            result.append(pop)
    else: pm.error('Unsupported object type, check the help() for supported types')
    return result
def joint_align_tool(nMid=0):
    plane = pm.polyPlane(w=1, h=1, sx=1, sy=1, ax=[0,0,1], cuv=False, ch=False)
    plane[0].translate.set(0.5,0,0)
    pm.xform(plane[0], rp=[0,0,0], sp=[0,0,0], ws=True)

    aimGrp = pm.group(empty=True)
    pm.parent(plane, aimGrp)
    
    allLocs = []
    
    startLoc = pm.spaceLocator()
    startLoc.translate.set(0,0,0)
    startLoc.scale.set(0.1,0.1,0.1)
    allLocs.append(startLoc)

    spacing = 1/float(nMid+1)
    for i in range(nMid):
        x = spacing * (i+1)
        midLoc = pm.duplicate(startLoc)[0]
        midLoc.tx.set(x)
        midLoc.tz.lock()
        pm.parent(midLoc, aimGrp)
        allLocs.append(midLoc)
            
    endLoc = pm.duplicate(startLoc)[0]
    endLoc.translate.set(1,0,0)
    allLocs.append(endLoc)
    
    distanceBtw = pm.createNode("distanceBetween")
    startLoc.getShape().worldPosition[0] >> distanceBtw.point1
    endLoc.getShape().worldPosition[0] >> distanceBtw.point2
    
    upGrp = pm.group(empty=True)
    pm.pointConstraint(startLoc, endLoc, upGrp, mo=False)
    upLoc = pm.duplicate(startLoc)[0]
    upLoc.translate.set(0.5,0.5,0)
    pm.parent(upLoc, upGrp)
    
    pm.pointConstraint(startLoc, aimGrp, mo=False)
    pm.aimConstraint(endLoc, aimGrp, mo=False, aimVector=[1,0,0], upVector=[0,1,0], worldUpType='object', worldUpObject=upLoc)
    
    aimLocs = []
    joints = []
    constGrp = pm.group(empty=True)    
    for i in range(len(allLocs)):
        x = spacing * (i)
        aimLoc = pm.group(empty=True)
        pm.parent(aimLoc, aimGrp)
        
        pm.pointConstraint(allLocs[i], aimLoc, mo=False)

        joint = pm.joint()
        const = pm.parentConstraint(aimLoc, joint, mo=False)
        pm.parent(const, constGrp)
        
        if aimLocs:
            pm.aimConstraint(aimLoc, aimLocs[i-1], mo=False, aimVector=[1,0,0], upVector=[0,1,0], worldUpType='object', worldUpObject=upLoc)
            pm.parent(joint, joints[i-1])
         
        joints.append(joint)
        aimLocs.append(aimLoc)
        

    for node in [aimGrp, upGrp]:
        distanceBtw.distance >> node.scaleX
        distanceBtw.distance >> node.scaleY
        distanceBtw.distance >> node.scaleZ
            
    grp = pm.group(empty=True)
    pm.parent(startLoc, endLoc, upGrp, joints[0], aimGrp, constGrp, grp)
    def CreateCloth(self,*args):
	    #TwClothSolverIOPaperBlockout
	    #----------------------------------
	    #----------------------------------
	
	    #Get Pasing Parameters:
	    subx = pm.intSliderGrp(self.GlobalVars["SubX"], q = True, value = True)
	    suby = pm.intSliderGrp(self.GlobalVars["SubY"], q = True, value = True)
	    grav = pm.floatSliderGrp(self.GlobalVars["GraV"], q = True, value = True)
	    wind_x = pm.floatSliderGrp(self.GlobalVars["Wind_X"], q = True, value = True)
	    wind_y = pm.floatSliderGrp(self.GlobalVars["Wind_Y"], q = True, value = True)
	    wind_z = pm.floatSliderGrp(self.GlobalVars["Wind_Z"], q = True, value = True)
	    noise = pm.floatSliderGrp(self.GlobalVars["Noise"], q = True, value = True)

	    #create inputGeo
	    #----------------------------------
	    #inputGeo
	    inputGeoTrans = pm.polyPlane( sx=subx, sy=suby, w=10, h=10, ch = False)[0]
	    inputGeoShape = inputGeoTrans.getShape()
	    #transformPlane
	    inputGeoTrans.translateY.set(5)
	    inputGeoTrans.visibility.set(0)
	    pm.select(cl = True)
	    #pm.select(inputGeoTrans, r = True)
	    #pm.polyTriangulate(ch = False)
	    #pm.select(cl = True)

	    #create outputGeo
	    #----------------------------------
	    #outputGeo
	    outputGeoTrans = pm.polyPlane( sx=subx, sy=suby, w=10, h=10, ch = False)[0]
	    outputGeoShape = outputGeoTrans.getShape()
	    pm.select(cl = True)
	    #set Texture
	    #if pm.checkBox(GlobalVars["DefaultText"], q = True, value = True) == True:
	    #	pm.sets("lambert2SG", e = True, forceElement = inputGeoTrans)
	
	    #create cloth solver node
	    #----------------------------------
	    clothSolver = pm.createNode('TwClothSolverIOPaperBlockout')
	    clothSolver.verbose.set(0)
	    clothSolver.repetitions.set(10)
	    self.GlobalVars["clothSolver"] = clothSolver
	    pm.select(cl = True)

	    #create positionConstraintLocators
	    #----------------------------------
	    positionConstraintLocatorIndex0Trans = pm.spaceLocator(n = 'positionConstraintLocatorIndex0')
	    positionConstraintLocatorIndex0Shape = positionConstraintLocatorIndex0Trans.getShape()
	    positionConstraintLocatorIndex0Trans.translate.set(-5,5,5)
	    pm.select(cl = True)

	    positionConstraintLocatorIndex110Trans = pm.spaceLocator(n = 'positionConstraintLocatorIndex110')
	    positionConstraintLocatorIndex110Shape = positionConstraintLocatorIndex110Trans.getShape()
	    positionConstraintLocatorIndex110Trans.translate.set(-5,5,-5)
	    pm.select(cl = True)

	    positionConstraintLocatorIndex120Trans = pm.spaceLocator(n = 'positionConstraintLocatorIndex120')
	    positionConstraintLocatorIndex120Shape = positionConstraintLocatorIndex120Trans.getShape()
	    positionConstraintLocatorIndex120Trans.translate.set(5,5,-5)
	    pm.select(cl = True)

	    positionConstraintLocatorIndex10Trans = pm.spaceLocator(n = 'positionConstraintLocatorIndex10')
	    positionConstraintLocatorIndex10Shape = positionConstraintLocatorIndex10Trans.getShape()
	    positionConstraintLocatorIndex10Trans.translate.set(5,5,5)
	    pm.select(cl = True)

	    positionConstraintLocatorIndex60Trans = pm.spaceLocator(n = 'positionConstraintLocatorIndex60')
	    positionConstraintLocatorIndex60Shape = positionConstraintLocatorIndex60Trans.getShape()
	    positionConstraintLocatorIndex60Trans.translate.set(0,5,0)
	    pm.select(cl = True)

	    #connect locators and set index attrs on clothSolver
	    #----------------------------------
	    clothSolver.positionConstraint[0].positionConstraintVertexIndex.set(0)
	    positionConstraintLocatorIndex0Shape.worldPosition >> clothSolver.positionConstraint[0].positionConstraintCoordinate
	    pm.select(cl = True)
	    clothSolver.positionConstraint[1].positionConstraintVertexIndex.set(((subx + 1)*(suby + 1) - 1) - subx)
	    positionConstraintLocatorIndex110Shape.worldPosition >> clothSolver.positionConstraint[1].positionConstraintCoordinate
	    pm.select(cl = True)
	    clothSolver.positionConstraint[2].positionConstraintVertexIndex.set((subx + 1)*(suby + 1) - 1)
	    positionConstraintLocatorIndex120Shape.worldPosition >> clothSolver.positionConstraint[2].positionConstraintCoordinate
	    pm.select(cl = True)
	    clothSolver.positionConstraint[3].positionConstraintVertexIndex.set(subx)
	    positionConstraintLocatorIndex10Shape.worldPosition >> clothSolver.positionConstraint[3].positionConstraintCoordinate
	    pm.select(cl = True)
	    clothSolver.positionConstraint[4].positionConstraintVertexIndex.set(((subx + 1)*(suby + 1) - 1)/2)
	    positionConstraintLocatorIndex60Shape.worldPosition >> clothSolver.positionConstraint[4].positionConstraintCoordinate
	    pm.select(cl = True)

	    #set clothSolver active attr
	    #----------------------------------
	    clothSolver.positionConstraint[0].positionConstraintActive.set(pm.checkBox(self.GlobalVars["Locator_LeftTopCorner"], q = True, value = True))
	    clothSolver.positionConstraint[1].positionConstraintActive.set(pm.checkBox(self.GlobalVars["Locator_RightTopCorner"], q = True, value = True))
	    clothSolver.positionConstraint[2].positionConstraintActive.set(pm.checkBox(self.GlobalVars["Locator_RightBottomCorner"], q = True, value = True))
	    clothSolver.positionConstraint[3].positionConstraintActive.set(pm.checkBox(self.GlobalVars["Locator_LeftBottomCorner"], q = True, value = True))
	    clothSolver.positionConstraint[4].positionConstraintActive.set(pm.checkBox(self.GlobalVars["Locator_Middle"], q = True, value = True))
	    #connect time
	    #----------------------------------
	    timeNode = pm.PyNode('time1')
	    pm.select(cl = True)
	    timeNode.outTime >> clothSolver.currentFrame

	    #connect inputGeo
	    #----------------------------------
	    inputGeoShape.outMesh >> clothSolver.inputGeo

	    #connect inputGeo parentMatrix
	    #----------------------------------
	    inputGeoShape.parentMatrix >> clothSolver.transformMatrix

	    #connect outputGeo
	    #----------------------------------
	    clothSolver.outputGeo >> outputGeoShape.inMesh

	    #set clothSolver gravity
	    #----------------------------------
	    gravityPerSec = -1.0 * grav
	    framesPerSec = 400
	    clothSolver.gravity.set(0,gravityPerSec/framesPerSec,0)

	    #set clothSolver WindForce
	    #----------------------------------
	    clothSolver.WindForce.set(wind_x/framesPerSec,wind_y/framesPerSec,wind_z/framesPerSec)
    
        #set clothSolber Noise
        #----------------------------------
	    clothSolver.Noise.set(noise/framesPerSec)

	    #set De
	    #set time range
	    #----------------------------------
	    pm.playbackOptions(ast = 1, aet = 5000, max = 5000, min = 1)

	
	    #rename and select clothSolver
	    #----------------------------------
	    clothSolverTrans = clothSolver.getParent()
	    pm.rename(clothSolver, 'twClothSolverShape')
	    pm.rename(clothSolverTrans, 'twClothSolver')
	    pm.select(clothSolver, r = True)
Beispiel #38
0
def renderBuddy(ren, arg=1):

####: REN
# 1 : mentalRay
# 2 : V-ray

####: ARGS
# 1 : create
# 2 : delete

    if arg is 1:
        
        # cleanup check
        if pm.objExists('LGT_REF_OBJ') | pm.objExists('diff_18SG') | pm.objExists('diff_18'):
            pm.delete('diff_80', 'diff_18', 'refl_100', 'refl_75', 'diff_18SG', 'diff_80SG', 'refl_01SG', 'refl_02SG', 'LGT_REF_OBJ')
        
        # create four spheres & a plane
        tmp1 = pm.polySphere(r = 1, n = "fBall_D1", ch = 0)
        diff01 = tmp1[0]
        tmp1 = pm.polySphere(r = 1, n = "fBall_D2", ch = 0)
        diff02 = tmp1[0]
        tmp1 = pm.polySphere(r = 1, n = "fBall_R1", ch = 0)
        refl01 = tmp1[0]
        tmp1 = pm.polySphere(r = 1, n = "fBall_R2", ch = 0)
        refl02 = tmp1[0]
        tmp1 = pm.polyPlane (n = "fGround", ch = 1)
        grid01 = tmp1[0]
        objs = [diff01, diff02, refl01, refl02, grid01]
        
        #shds = [shd_diff_80, shd_diff_18, shd_refl_01, shd_refl_02]
        #shgs = [shg_diff_80, shg_diff_18, shg_refl_01, shg_refl_02]
        
        # group them
        grp = pm.group(diff01, diff02, refl01, refl02, grid01, n = "LGT_REF_OBJ")
        grp.translateY.set(10)
        
        # move them around
        offset = 4.5
        
        for o in objs:
            o.translateX.set(offset)
            offset = offset -3
            
        grid01.scaleX.set(50)
        grid01.scaleZ.set(50)
        grid01.translateX.set(0)
        grid01.translateY.set(-10)
        
        # create shaders
        # 80% diffuse goes to mesh diff01
        shg_diff_80 = pm.sets(n = "diff_80SG", renderable = 1, empty = 1)
        shd_diff_80 = pm.shadingNode('lambert', asShader = 1, n = "diff_80")
        shd_diff_80.diffuse.set(0.8)
        shd_diff_80.color.set(1, 1, 1)
        pm.surfaceShaderList(shd_diff_80, add = shg_diff_80)
        pm.sets(shg_diff_80, e = 1, forceElement = diff01)
        
        # 18% diffuse goes to mesh diff02
        shg_diff_18 = pm.sets(n = "diff_18SG", renderable = 1, empty = 1)
        shd_diff_18 = pm.shadingNode('lambert', asShader = 1, n = "diff_18")
        shd_diff_18.diffuse.set(0.18)
        shd_diff_18.color.set(1, 1, 1)
        pm.surfaceShaderList(shd_diff_18, add = shg_diff_18)
        pm.sets(shg_diff_18, e = 1, forceElement = diff02)
        
        
        ### REFLECTION SPHERES DEPEND ON DIFFERENT SHADERS FOR MENTALRAY / VRAY ###
        
        if ren is 1:
        
            # (MENTALRAY) 100% glossy mia goes to mesh refl01
            shg_refl_01 = pm.sets(n = "refl_01SG", renderable = 1, empty = 1)
            shd_refl_01 = pm.shadingNode('mia_material_x_passes', asShader = 1, n = "refl_100")
            shd_refl_01.diffuse_weight.set(0)
            shd_refl_01.reflectivity.set(1)
            pm.disconnectAttr('lambert1.outColor', shg_refl_01.surfaceShader)
            pm.connectAttr(shd_refl_01.message, shg_refl_01.miMaterialShader)
            pm.sets(shg_refl_01, e = 1, forceElement = refl01)
            
            # (MENTALRAY) 75% glossy mia goes to mesh refl02
            shg_refl_02 = pm.sets(n = "refl_02SG", renderable = 1, empty = 1)
            shd_refl_02 = pm.shadingNode('mia_material_x_passes', asShader = 1, n = "refl_75")
            shd_refl_02.diffuse_weight.set(0)
            shd_refl_02.reflectivity.set(1)
            shd_refl_02.refl_gloss.set(0.75)
            pm.disconnectAttr('lambert1.outColor', shg_refl_02.surfaceShader)
            pm.connectAttr(shd_refl_02.message, shg_refl_02.miMaterialShader)
            pm.sets(shg_refl_02, e = 1, forceElement = refl02)
        
        if ren is 2:
            
            # (VRAY) 100% glossy vraymtl goes to mesh refl01
            shg_refl_01 = pm.sets(n = "refl_01SG", renderable = 1, empty = 1)
            shd_refl_01 = pm.shadingNode('VRayMtl', asShader = 1, n = "refl_100")
            shd_refl_01.diffuseColorAmount.set(0)
            shd_refl_01.reflectionColor.set(1,1,1)
            pm.surfaceShaderList(shd_refl_01, add = shg_refl_01)
            pm.sets(shg_refl_01, e = 1, forceElement = refl01)
            
            # (VRAY) 75% glossy vraymtl goes to mesh refl02
            shg_refl_02 = pm.sets(n = "refl_02SG", renderable = 1, empty = 1)
            shd_refl_02 = pm.shadingNode('VRayMtl', asShader = 1, n = "refl_75")
            shd_refl_02.diffuseColorAmount.set(0)
            shd_refl_02.reflectionColor.set(1,1,1)
            pm.surfaceShaderList(shd_refl_02, add = shg_refl_02)
            pm.sets(shg_refl_02, e = 1, forceElement = refl02)


    if arg is 2:
        pm.delete('diff_80', 'diff_18', 'refl_100', 'refl_75', 'diff_18SG', 'diff_80SG', 'refl_01SG', 'refl_02SG', 'LGT_REF_OBJ')
Beispiel #39
0
    def importAsset(self, iAObj=None):
        component = ftrack.Component(iAObj.componentId)
        start, end = self.getStartEndFrames(component, iAObj)
        new_nodes = []

        # Image plane
        if iAObj.options["importType"] == "Image Plane":

            movie_path = iAObj.filePath % start

            # Getting camera
            new_camera = False
            if iAObj.options["attachCamera"]:
                cam = pm.ls(selection=True)[0]
            else:
                cam = pm.createNode("camera")
                new_camera = True

            if iAObj.options["renameCamera"]:
                asset_name = component.getVersion().getAsset().getName()
                pm.rename(cam.getTransform(), asset_name)

            if new_camera:
                new_nodes.extend([cam.name(), cam.getTransform().name()])

            if iAObj.options["resolutionGate"]:
                cam.displayResolution.set(1)

            cam.farClipPlane.set(iAObj.options["imagePlaneDepth"] * 10)

            # Create image plane
            visibility = True
            option = "Hidden from other cameras"
            if iAObj.options["imagePlaneVisibility"] == option:
                visibility = False

            image_plane_transform, image_plane_shape = pm.imagePlane(
                camera=cam, showInAllViews=visibility)
            image_plane_shape.depth.set(iAObj.options["imagePlaneDepth"])
            # Need to get "type" by string, because its a method as well.
            pm.Attribute(image_plane_shape + ".type").set(2)
            image_plane_shape.imageName.set(movie_path)
            image_plane_shape.useFrameExtension.set(1)

            new_nodes.extend(
                [image_plane_transform.name(),
                 image_plane_shape.name()])

            # Create ground plane
            if iAObj.options["createGround"]:
                ground_transform, ground_shape = pm.polyPlane(
                    name="ground",
                    height=iAObj.options["groundSize"],
                    width=iAObj.options["groundSize"])

                ground_shader = pm.shadingNode("lambert", asShader=True)
                visiblity = iAObj.options["groundVisibility"] / 100
                ground_shader.transparency.set(visiblity, visiblity, visiblity)
                pm.select(ground_transform)
                pm.hyperShade(assign=ground_shader.name())

                new_nodes.extend([
                    ground_transform.name(),
                    ground_shape.name(),
                    ground_shader.name()
                ])

        self.newData = set(new_nodes)
        self.oldData = set()

        self.linkToFtrackNode(iAObj)
def setup_follow_through():
    """
    Setup follow through (jiggle planes) to each selected transform object.
    Jiggle deformers are returned to allow users to animate the deformer attributes
    before baking.
    
    :return: List of jiggle deformers.
    :rtype: list(pm.PyNode)
    """
    # -- Grab the selected transforms
    node_list = pm.selected(type='transform')

    # -- Validate node list
    if not node_list:
        pm.warning('Select at least 1 transform object!')
        return None

    # -- Grab the current start and end frames
    start_frame = pm.playbackOptions(q=True, min=True)
    end_frame = pm.playbackOptions(q=True, max=True)

    # -- Iterable variables for later
    to_delete = []
    plane_trans_list = []

    # -- For each node
    for node in node_list:

        # -- Create a 10x10 poly plane
        plane_trans = pm.polyPlane(
            w=10,
            h=10,
            sx=1,
            sy=1,
        )[0]
        plane_trans_list.append(plane_trans)

        # -- Constrain the plane to the give node (delete later)
        to_delete.append(pm.parentConstraint(node, plane_trans, mo=False))

    # -- Bake all planes in one go (translate and rotate).
    # -- This is to sever any dependency on the selected transforms, and
    # -- removing any potential cyclic issues.
    pm.bakeResults(
        plane_trans_list,
        time=[
            start_frame,
            end_frame,
        ],
        at=['t', 'r'],
        sm=True,
    )

    # -- Delete plane constraints
    pm.delete(to_delete)

    # -- List of jiggle deformers to select & return
    jiggle_list = []

    # -- Go to the first frame
    pm.currentTime(start_frame)

    # -- Setup and connect each node to plane
    for node, plane_trans in zip(node_list, plane_trans_list):

        # -- Create a jiggle deformer on the plane
        pm.select(plane_trans)
        pm.mel.CreateJiggleDeformer()

        # -- Get the plane's shape
        plane_shape = plane_trans.getShape()

        # -- Get the Jiggle deformer
        jiggle_deformer = plane_shape.inputs(type='jiggle')[0]
        jiggle_list.append(jiggle_deformer)

        # -- Set the default jiggle settings
        for attr, value in JIGGLE_DEFAULTS.iteritems():
            jiggle_deformer.attr(attr).set(value)

        # -- Create and setup a follicle on the plane's shape
        follicle = pm.createNode('follicle')

        # -- Get the follicle's transform node (parent)
        follicle_trans = follicle.getParent()

        plane_shape.outMesh.connect(follicle.inputMesh)
        plane_shape.worldMatrix[0].connect(follicle.inputWorldMatrix)
        follicle.outRotate.connect(follicle_trans.rotate)
        follicle.outTranslate.connect(follicle_trans.translate)

        # -- Position the follicle in the center of the plane
        follicle.parameterU.set(0.5)
        follicle.parameterV.set(0.5)

        # -- Lock the follicle_trans translate and rotate attributes
        follicle_trans.translate.lock()
        follicle_trans.rotate.lock()

        # -- Constrain the original node to the follicle_trans
        constraint = pm.parentConstraint(follicle_trans, node, mo=True)

        # -- Connect the plane_trans to a custom attribute
        # -- on the constraint for retrieval (when baking).
        # -- Add it to the constraint as we clean it up
        # -- anyway (no need to dirty the rig).
        constraint.addAttr('ld_jiggle_node', at='message')
        plane_trans.message.connect(constraint.ld_jiggle_node)

    # -- Delete animation on the nodes (constrained
    # -- by the planes by now anyway)
    pm.cutKey(node_list, at=['t', 'r'], cl=True)

    # -- Select the node list (allows the bake process to run
    # -- immediately after).
    # -- Would recommend selecting the jiggle_list to allow users
    # -- to animate the jiggle deformer instead.
    pm.select(node_list)

    return jiggle_list
Beispiel #41
0
def repeat_over_sphere( width, radius, rand_rot_min_max=[0,5], rotate_axis=[1, 1, 1] ):
	'''
	Args:
		width (float): width of panels
		radius (float): radius of disco ball
		rand_rot_min_max (list of float): min/max rotation random of list of size 2
	Returns: (None)
	Usage:
		repeat_over_sphere( .13, 1, rand_rot_min_max=[-2,2], rotate_axis=[1,1,.2] )
	'''	
	namer = lib_env.AssetNameFormatter()
	
	master = pm.polyPlane(w=width, h=width, sx=1, sy=1)[0]
	master.translate.set(0,0,radius)
	master.rotateX.set(90)
	
	main_grp = pm.group(n=namer.get(name='disco_ball', type='group'), em=True)
	#Initial column creation
	rotation_angle, num_copies = lib_math.get_repetitions_around_circle( width, radius )
	rotate_rand = rotation_angle/2
	#create seed rows
	rows, row_grps, panels = [], [], []
	for r in range(0, int( math.ceil(num_copies/2.0) )):
		mirror_alpha = chr( r+97 ).upper()
		name = 'mirror_row%02d_%02d'%( r, 0 )
		
		grp = pm.group( n=namer.get(name=name+'Offset', type='group'), em=True )
		dup = pm.duplicate( master, n=namer.get(name=name, type='mesh'), rr=True )[0]
		
		dup.setParent(grp)
		pm.rotate( grp, [(-1*rotation_angle*r)-90, 0, 0], r=True)
		panels.append( dup )
		rows.append( grp )
	
	for mirror_index, mirror in enumerate(rows):
		row_grp = pm.group(n=namer.get( name='mirror_row%02dOffset'%( mirror_index ), type='group'), em=True)
		mirror.setParent( row_grp )
		
		height = mirror.getBoundingBoxMax(space='world')[1]
		if height<0:
			height = mirror.getBoundingBoxMin(space='world')[1]
		cross_section_r = lib_math.get_sphere_cross_section_radius( radius, height )
		rotation_angle, num_copies = lib_math.get_repetitions_around_circle( width, cross_section_r )
		
		for i in range(1, num_copies):
			dup = pm.duplicate(mirror, n=namer.get( name='mirror_row%02d_%02dOffset'%( mirror_index, i ), type='group' ), rr=True)[0]
			dup.getChildren(type='transform')[0].rename( namer.get( name='mirror_row%02d_%02d'%( mirror_index, i ), type='mesh' ) )
			dup.setParent( row_grp )
			dup.rotatePivot.set( 0,0,0 )
			dup.scalePivot.set( 0,0,0 )
			pm.rotate( dup, [0, rotation_angle*i, 0], r=True )
			panels.append( dup.getChildren(type='transform')[0] )
		row_grp.setParent( main_grp )
		row_grps.append( row_grp )
	rot = rotate_rand
	#now rotate all the rows randomly to appear shifted
	for row_grp in row_grps:	
		row_grp.rotateY.set( rot )
		rot += rotate_rand*2
	#randomly rotate panels
	min, max = rand_rot_min_max
	if not min==max:
		for panel in panels:
			rand_rot = [(random.randrange(min, max)) * rotate_axis[0] + panel.rotate.get()[0],
						(random.randrange(min, max)) * rotate_axis[1] + panel.rotate.get()[1],
						(random.randrange(min, max)) * rotate_axis[2] + panel.rotate.get()[2]]
			panel.rotate.set( rand_rot )
	#cleanup
	pm.delete( master )
    def generateFollowPlane(self, *args):
        startTime = pm.playbackOptions(q=1, min=1)
        endTime = pm.playbackOptions(q=1, max=1)

        sel_list = pm.ls(sl=1, ni=1, type="transform")
        if not sel_list:
            pm.confirmDialog(message='请选择物体', button=['确定'])
            return

        for sel in sel_list:
            # snapshot = pm.snapshot(sel,st=startTime,et=endTime)[1]
            snapshot = pm.createNode("snapshot")
            sel.selectHandle.connect(snapshot.localPosition)
            sel.worldMatrix[0].connect(snapshot.inputMatrix)
            snapshot.startTime.set(startTime)
            snapshot.endTime.set(endTime)
            snapshot.increment.set(1)
            anim_curve = pm.curve(n=sel + "_follow_curve",
                                  d=3,
                                  p=snapshot.pts.get())
            pm.delete(snapshot)

            curve_length = pm.arclen(anim_curve, ch=0)
            plane, plane_node = pm.polyPlane(n=sel + "_follow_plane",
                                             sx=20,
                                             sy=3,
                                             w=curve_length,
                                             h=20)
            plane_grp = pm.group(plane, n=plane + "_grp")
            # NOTE 创建运动路径跟随
            motion_path = pm.pathAnimation(
                plane_grp,
                anim_curve,
                fractionMode=1,
                follow=1,
                followAxis="x",
                upAxis="y",
                worldUpType="vector",
                worldUpVector=(0, 1, 0),
                inverseUp=0,
                inverseFront=0,
                bank=0,
                startTimeU=startTime,
                endTimeU=endTime,
            )
            motion_path = pm.PyNode(motion_path)
            flow_node, ffd_node, lattice_node, ffd_base = pm.flow(plane_grp,
                                                                  dv=(100, 2,
                                                                      2))

            # NOTE 设置外部影响
            ffd_node.outsideLattice.set(1)
            ffd_node.local.set(1)
            plane_node.width.set(50)

            lattice_node.v.set(0)
            ffd_base.v.set(0)

            # NOTE 设置 Parametric Length 匹配位置
            motion_path.fractionMode.set(0)
            # NOTE 设置为 normal 朝向确保不会翻转
            motion_path.worldUpType.set(4)

            animCurve = motion_path.listConnections(type="animCurve")[0]
            # NOTE 关键帧设置为线性
            animCurve.setTangentTypes(range(animCurve.numKeys()),
                                      inTangentType="linear",
                                      outTangentType="linear")

            # NOTE 打组
            pm.group(lattice_node,
                     ffd_base,
                     plane_grp,
                     anim_curve,
                     n=sel + "_follow_grp")
            pm.select(plane)
#connect file to ocio node
file_node.outColor >> ocio_node.input_color
file_node.outSize.outSizeX >> ocio_node.width
file_node.outSize.outSizeY >> ocio_node.height
pm.select(cl = True)

#connect ocio node to shader
ocio_node.output_color >> shader_node.outColor
pm.select(cl = True)

#set texture file
file_node.fileTextureName.set(texture_dir +'/' +texture_name)

#polyplane_transform_node, polyplane_shape_node
polyplane_transform_node, polyplane_shape_node = pm.polyPlane(n = 'ocio_test_polyplane', sx = 10, sy = 10, axis = (0,1,0), width = 12.8, height = 7.8)
pm.select(cl = True)
#connect plane to shader
pm.sets(shading_group_node, forceElement = polyplane_transform_node.name())
pm.select(cl = True)


#render_cam
render_cam_transform, render_cam_shape = pm.camera()
pm.select(cl = True)
pm.rename(render_cam_transform, 'render_cam')
render_cam_transform.translate.set(0,13,7)
render_cam_transform.rotate.set(-65,0,0)
pm.setKeyframe(render_cam_transform, s = False)
pm.lookThru(render_cam_transform)