def mirrorGeo():
	cbVal = cmds.checkBox("cb1", q=True, v=True)
	rbVal = cmds.radioButtonGrp("rb1", q=True, sl=True)
	myDir=0
	if(rbVal==1):
		if(cbVal):
			# +X
			myDir = 0
		else:
			# -X
			myDir = 1
	elif(rbVal==2):
		if(cbVal):
			# +Y
			myDir = 2
		else:
			# -Y
			myDir = 3
	else:
		if(cbVal):
			# +Z
			myDir = 4
		else:
			# -Z
			myDir = 5
	cmds.polyMirrorFace( ws=1, d=myDir, mergeMode=1, ch=1 )	
def mirrorGeometry(node, across=0, merge=True, softEdge=True, threshold=0.001):
    shapes = cmds.listRelatives(node, s=True, pa=True)
    if not shapes:
        return False
    if cmds.objectType(shapes[0]) != 'mesh':
        return False
    shape = shapes[0]
    pivot = cmds.xform(node, q=True, ws=True, piv=True)

    if across == 0:
        direction = 4
        index = 2
    elif across == 1:
        direction = 0
        index = 0
    else:
        direction = 2
        index = 1

    kwargs = {}
    if merge:
        kwargs['mm'] = True
        kwargs['mt'] = threshold
    else:
        kwargs['mm'] = False

    cmds.polyMirrorFace(shape, ws=True, d=direction, p=pivot[0:3], **kwargs)

    if softEdge:
        vertices = cmds.polyListComponentConversion(shape,
                                                    fv=1,
                                                    ff=1,
                                                    fe=1,
                                                    fuv=1,
                                                    fvf=1,
                                                    tv=1)
        vertices = cmds.ls(vertices, fl=True)

    centerVertices = []
    for vertex in vertices:
        pos = cmds.pointPosition(vertex, w=True)
        if abs(pivot[index] - pos[index]) <= threshold:
            centerVertices.append(vertex)

    centerEdges = []
    if centerVertices:
        centerEdges = cmds.polyListComponentConversion(centerVertices,
                                                       fv=1,
                                                       ff=1,
                                                       fuv=1,
                                                       fvf=1,
                                                       te=1,
                                                       internal=1)
    if centerEdges:
        cmds.polySoftEdge(centerEdges, a=180)
 def ldmt_mirror(self):
     cmds.undoInfo(ock=1)
     # exec mirror function
     mirrored = cmds.polyMirrorFace(n="polyMirrorFace#")
     # prepare all attribute name
     mirrored_axis = mirrored[0] + ".axis"
     mirrored_mirrorAxis = mirrored[0] + ".mirrorAxis"
     mirrored_axisDirection = mirrored[0] + ".axisDirection"
     mirrored_mergeThreshold = mirrored[0] + ".mergeThreshold"
     mirrored_cutMesh = mirrored[0] + ".cutMesh"
     # get current value
     if self.radioButton_x.isChecked():
         targetAxis = 0
     elif self.radioButton_y.isChecked():
         targetAxis = 1
     elif self.radioButton_z.isChecked():
         targetAxis = 2
     if self.checkBox_weld.isChecked():
         ifCutmesh = 1
     else:
         ifCutmesh = 0
     if self.checkBox_reverse.isChecked():
         ifReverse = 0
     else:
         ifReverse = 1
     if self.checkBox_local.isChecked():
         mirrorAxis = 0
     else:
         mirrorAxis = 2
     cmds.setAttr(mirrored_axis, targetAxis)
     cmds.setAttr(mirrored_cutMesh, ifCutmesh)
     cmds.setAttr(mirrored_mirrorAxis, mirrorAxis)
     cmds.setAttr(mirrored_axisDirection, ifReverse)
     cmds.setAttr(mirrored_mergeThreshold, 0.2)
     cmds.undoInfo(cck=True)
Esempio n. 4
0
def poly_mirror(nodes=None,
                axis=AXIS.X,
                direction=DIRECTION.NEGATIVE,
                mirror_axis=MIRROR_AXIS.OBJECT):
    """Mirror geometry across an axis

    This method doesnt do anything fancy other than keep some
    settings consistent

    Args:
        axis(str): x, y, z
        direction: +:0, -:1
        mirror_axis: {
                        0: "Bounding Box",
                        1: "Object",
                        2: "World"
                    }
    """
    if nodes is None:
        nodes = cmds.ls(selection=True, long=True)

    axis_map = {
        AXIS.X: 0,
        AXIS.Y: 1,
        AXIS.Z: 2,
    }

    if axis not in axis_map:
        if axis not in axis_map.values():
            raise RuntimeError("Axis \"%s\" not valid" % axis)

    for node in nodes:
        cmds.polyMirrorFace(node,
                            cutMesh=True,
                            axis=axis_map[axis],
                            axisDirection=direction,
                            mergeMode=1,  # Merge Border Vertices
                            mirrorAxis=mirror_axis,
                            mirrorPosition=0,
                            mergeThresholdType=1,  # Merge Threshold custom
                            mergeThreshold=0.001,
                            flipUVs=False,
                            smoothingAngle=30,
                            constructionHistory=True,
                            )
Esempio n. 5
0
def makeSym(*args):
    selLs = cmds.ls(sl = True)

    # When user select center edge loop.
    if '.e' in selLs[0]:
        numOfShells = cmds.polyEvaluate(shell = True)
        if numOfShells > 1:
            cmds.confirmDialog(title = 'Warning', message = 'Selected mesh is made of combining several geometry.\nSeparate mesh and try it again.')
            return False

        centerEdgeLoop = selLs
        objName = centerEdgeLoop[0].split('.')[0]
        uvKeepGeo = cmds.duplicate(objName, n = '{0}_uvKeep_geo'.format(objName))

        mel.eval('PolySelectConvert 3;')
        tak_misc.zeroVtx()

        cmds.select(centerEdgeLoop, r = True)
        cmds.DetachComponent()

        leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName)

        symOpt = cmds.radioButtonGrp('symOptRadButGrp', q = True, select = True)

        # If user select 'x to -x' mean left to right.
        if symOpt == 1:
            rightestVtx = getSidestVtx(rightVtxDic)
            cmds.select(rightestVtx, r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.

            rightestFace = cmds.ls(sl = True, fl = True)[0]
            rightestFaceId = int(re.search(r'.+f\[(\d+)\]', rightestFace).group(1))
            cmds.polySelect(extendToShell = rightestFaceId)
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, mergeMode = 0, mergeThreshold = 0.001, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)

        # If user select '-x to x' mean right to left.
        if symOpt == 2:
            leftestVtx = getSidestVtx(leftVtxDic)
            cmds.select(leftestVtx, r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.

            leftestFace = cmds.ls(sl = True, fl = True)[0]
            leftestFaceId = int(re.search(r'.+f\[(\d+)\]', leftestFace).group(1))
            cmds.polySelect(extendToShell = leftestFaceId)
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, mergeMode = 0, mergeThreshold = 0.001, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)

    # When user select object.
    else:
        objName = selLs[0]
        uvKeepGeo = cmds.duplicate(objName, n = '{0}_uvKeep_geo'.format(objName))

        leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName)

        symOpt = cmds.radioButtonGrp('symOptRadButGrp', q = True, select = True)

        if centerVtxDic.keys():
            cmds.select(centerVtxDic.keys(), r = True)
            mel.eval('SelectEdgeLoopSp;')
            tak_misc.zeroVtx()

        leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName) # Refresh vertex position information.

        # If user select 'x to -x' mean left to right.
        if symOpt == 1:
            cmds.select(rightVtxDic.keys(), r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)

        # If user select 'x to -x' mean right to left.
        if symOpt == 2:
            cmds.select(leftVtxDic.keys(), r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)


    leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName)
    if centerVtxDic.keys():
        cmds.select(centerVtxDic.keys(), r = True)
        cmds.polyMergeVertex(distance = 0.001)


    # Copy uv from uv keeped geometry to new symmetrized geometry.
    smpSpc = cmds.radioButtonGrp('symSmpSpcRdoBtn', q = True, select = True)
    if smpSpc == 2:
        smpSpc = 4
    elif smpSpc == 3:
        smpSpc = 5
    cmds.transferAttributes(uvKeepGeo, objName, transferUVs = 2, sampleSpace = smpSpc)

    # cmds.select(objName, r = True)
    # mel.eval("SoftPolyEdgeElements 1;")

    # cmds.select(objName, r = True)
    # mel.eval('polyNormalPerVertex -ufn true;')

    cmds.delete(objName, ch = True)
    cmds.delete(uvKeepGeo)

    cmds.select(objName, r = True)
import maya.cmds as cmds

if not cmds.commandPort(':4434', query=True):
    cmds.commandPort(name=':4434')
#body
cmds.polySphere(sx=15, sy=15, r=1.5)
cmds.move(0, 1.5, 0)
cmds.polySphere(sx=15, sy=15, r=1.2)
cmds.move(0, 3.5, 0)
cmds.polySphere(sx=15, sy=15, r=.8)
cmds.move(0, 5.2, 0)

#buttons
button = cmds.polySphere(sx=6, sy=6, r=.1)
cmds.move(0, 3, 1.1)
button2 = cmds.duplicate(button, rr=True)
cmds.select(button2)
cmds.move(0, .6, .1, r=True)
cmds.duplicate(button2, rr=True)
cmds.move(0, .53, -.2, r=True)

eye = cmds.polySphere(sx=8, sy=8, r=.15)
cmds.move(-.25, 5.4, .7)
cmds.polyMirrorFace(
    axis=0,
    cutMesh=0,
    mergeMode=3,
)

#cmds.polyCylinder(r=.6, h=1.5)
def makeBarrel(*args):
    #Molding and Shaping first Plank
    cmds.polyCube( sx=8, sy=8, sz=4, h=20 )
    cmds.scale( 1, 1, 0.3 )
    cmds.select('pCube1.e[32:39]', 'pCube1.e[128:135]', 'pCube1.e[420:423]', 'pCube1.e[472:475]')
    cmds.softSelect(ssd=19, sud=0.5)
    cmds.move( 0, 0, -2, relative = True)
    cmds.softSelect(ssd=12.5, sud=0.5)
    cmds.scale(1.4,1,1)
    cmds.softSelect(ssd=5, sud=0.2)
    cmds.select('pCube1.e[56:63]', 'pCube1.e[104:111]', 'pCube1.e[432:435]', 'pCube1.e[484:487]')
    cmds.scale(1.05,1,1)
    cmds.select('pCube1.e[8:15]', 'pCube1.e[152:159]', 'pCube1.e[408:411]', 'pCube1.e[460:463]')
    cmds.scale(1.05,1,1)
    cmds.sets('pCube1', addElement = toBeGrouped)
    
    #Moving WholePlank & Duplication Process
    cmds.select('pCube1.vtx[4]')
    cmds.softSelect(ssd=500, sud=1)
    cmds.move(-cmds.pointPosition('pCube1.vtx[4]')[0], -cmds.pointPosition('pCube1.vtx[4]')[1], -cmds.pointPosition('pCube1.vtx[4]')[2], relative = True)
    cmds.move(0,0,-4, rotatePivotRelative = True, relative = True)
    cmds.select('pCube1')
    cmds.rename('pCube1', 'BarrelPlank1')
    
    i=0
    while (i < 23):
        cmds.duplicate(returnRootsOnly = True)
        cmds.rotate(0,15,0, relative = True)
        i = i+1
        
    #Creates Metal Rings With Variation
    
    #Chance of Top Four Top Rings
    i = 0 
    numbOfTopRings = rand.randint(1,4)
    openLoc = [0,0,0,0]
    while (i < numbOfTopRings):
        location = rand.randint(0,3)
        while (openLoc[location] == 1):
            location = rand.randint(0,3)
        if(location == 0):
            #0
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,19.5,0,relative = True)
            cmds.scale(4.55,45.1,4.55, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        elif(location == 1):
            #1
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,18,0,relative = True)
            cmds.scale(4.83,45.1,4.83, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        elif(location == 2):
            #2
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,16.5,0,relative = True)
            cmds.scale(5.05,60,5.05, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        else:
            #3
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,12.5,0,relative = True)
            cmds.scale(5.45,70,5.45, relative = True)
            cmds.select('pTorus1.e[40:59]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.98, 0.98, 0.98, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            
        i += 1   
    
    
    
    #Guarented bottom ring then a change of two others
    #Guarented
    cmds.softSelect(ssd=5, sud=0.2)
    cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
    cmds.move(0,0.45,0,relative = True)
    cmds.scale(4.55,45.1,4.55, relative = True)
    cmds.select('pTorus1.e[120:139]')
    cmds.softSelect(ssd=1.05, sud = 0.2)
    cmds.scale(0.97, 0.97, 0.97, relative = True)
    cmds.sets('pTorus1', addElement = toBeGrouped)
    cmds.rename('pTorus1', 'MetalRing1')
    
    i = 0 
    numbOfTopRings = rand.randint(0,2)
    openLoc = [0,0]
    while (i < numbOfTopRings):
        location = rand.randint(0,1)
        while (openLoc[location] == 1):
            location = rand.randint(0,1)
        if(location == 0):
            #0
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,3.8,0,relative = True)
            cmds.scale(5.12,60,5.12, relative = True)
            cmds.select('pTorus1.e[120:139]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        else:
            #1
            cmds.softSelect(ssd=5, sud=0.2)
            cmds.polyTorus(sx=20, sy=8, r=1, sr=0.01)
            cmds.move(0,5.5,0,relative = True)
            cmds.scale(5.38,60,5.38, relative = True)
            cmds.select('pTorus1.e[120:139]')
            cmds.softSelect(ssd=1.05, sud = 0.2)
            cmds.scale(0.97, 0.97, 0.97, relative = True)
            cmds.sets('pTorus1', addElement = toBeGrouped)
            cmds.rename('pTorus1', 'MetalRing1')
            openLoc[location] = 1
        i += 1 
    
    #Make the lid and bottom
    #Bottom
    cmds.polyCube(sx=2, sy = 1, sz = 1, h = 0.143, d = 8.07)
    cmds.sets('pCube1', addElement = toBeGrouped)
    cmds.move(0,0.143,0)
    #Create planks off of first
    i = 0
    while (i < 4):
        if(i<4):
            cmds.duplicate(returnRootsOnly = True)
            cmds.move(1.01,0,0, relative = True)
            i = i+1
            
    #Shape Planks into rounded bottom
    cmds.softSelect(sse=0)
    def shapeLidPlank(plank,scale1,scale2,scale3): #ScalesPlankEdges
        i = 0
        while (i < 2):
            selectCube = cmds.format('pCube^1s.e', stringArg=(plank))
            cmds.select("{0}[{1}]".format(selectCube,8), "{0}[{1}]".format(selectCube,11), "{0}[{1}]".format(selectCube,14), "{0}[{1}]".format(selectCube,17))
            cmds.scale(1, 1, scale1, relative = True)
            cmds.select("{0}[{1}]".format(selectCube,9), "{0}[{1}]".format(selectCube,12), "{0}[{1}]".format(selectCube,15), "{0}[{1}]".format(selectCube,18))
            cmds.scale(1, 1, scale2, relative = True)
            cmds.select("{0}[{1}]".format(selectCube,10), "{0}[{1}]".format(selectCube,13), "{0}[{1}]".format(selectCube,16), "{0}[{1}]".format(selectCube,19))
            cmds.scale(1, 1, scale3, relative = True)
            i = i+1
    
    shapeLidPlank(2,0.997351,0.98069,0.962469)
    shapeLidPlank(3,0.963,0.925,0.885)
    shapeLidPlank(4,0.8835,0.8,0.7)
    shapeLidPlank(5,0.698,0.4,0.2)
    cmds.select('pCube5.f[1]','pCube5.f[3]','pCube5.f[5]','pCube5.f[7:8]')
    cmds.delete()
    cmds.polyCloseBorder('pCube5.e[5]', 'pCube5.e[7]', 'pCube5.e[9]', 'pCube5.e[11]')
    #mirror half of the lid
    cmds.polyUnite('pCube1','pCube2','pCube3','pCube4','pCube5')
    cmds.delete(ch = True)
    cmds.polyMirrorFace( 'polySurface1', direction=0, mergeMode=1 )
    cmds.sets('polySurface1', addElement = toBeGrouped)
    cmds.rename('polySurface1', 'LidBottom')
    
    #Decide To create top & Where to Place Top
    lidOn = 0
    if(cmds.radioButtonGrp(queryDic['lidControl'], q=True, select=True)==3):
        lidOn = rand.randint(0,4)
    if(cmds.radioButtonGrp(queryDic['lidControl'], q=True, select=True)==1 or lidOn > 0):
        #createTop
        cmds.duplicate(returnRootsOnly = True)
        cmds.polyCube(w = 7.433, h = 0.13)
        cmds.move(0,0,0.973)
        cmds.select('pCube1.e[8:9]')
        cmds.scale(1.07,1,1, relative = True)
        cmds.polyMirrorFace( 'pCube1', direction = 0, mergeMode=1, axis = 2 )
        cmds.polyUnite( 'pCube1', 'LidBottom1', n='Lid' )
        cmds.sets('Lid', addElement = toBeGrouped)
        cmds.rename('Lid', 'LidTop')
        cmds.delete(ch = True)
        cmds.delete('LidBottom1')
        
        lidLocRan = 0
        if(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==4):
            lidLocRan = rand.randint(1,3)
        if(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==1 or lidLocRan==1):
            cmds.move(0,19.5,0)
        elif(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==2 or lidLocRan==2):
            cmds.move(0,19.5,0)
            cmds.rotate(0,rand.random()*359,rand.random()*16, r=True, ws = True)
            cmds.rotate(0,rand.random()*359,0, r=True, ws = True)
        elif(cmds.radioButtonGrp(queryDic['lidLoc'], q=True, select=True)==3 or lidLocRan==3):
            cmds.rotate(0,rand.random()*359, 98.852097)
            cmds.move(6.2,4.3,0)
            
            
    #Finaly Group everything in the toBeGrouped set and cleanup
    cmds.select( toBeGrouped )
    cmds.group( n='Barrel1' )
    cleanUp()
Esempio n. 8
0
    def generateCity(self, *args):
        map_file = cmds.textField(self.widgets["osmFileTextField"], q = True, fi = True)
        winds_file = cmds.textField(self.widgets["wrfFileTextField"], q = True, fi = True)
        heights_file = cmds.textField(self.widgets["demFileTextField"], q = True, fi = True)
        jams_file = cmds.textField(self.widgets["jamsFileTextField"], q = True, fi = True)

        raw_wrf = cmds.checkBox(self.widgets["wrfCheckBox"], q=True, v=True)
        raw_dem = cmds.checkBox(self.widgets["demCheckBox"], q=True, v=True)

        if raw_wrf:
            if platform.system() == 'Windows':
                s = subprocess.check_output(["where", "python"], shell=True)
            else:
                s = subprocess.check_output(["which", "python"], shell=False)
            python_path = s.splitlines()[-1]
            script_dir = os.path.dirname(os.path.realpath(__file__))
            winds_file = subprocess.check_output([python_path, script_dir + "\NetCDF_converter.py", map_file, winds_file], shell=False).rstrip()

        if raw_dem:
            if platform.system() == 'Windows':
                s = subprocess.check_output(["where", "python"], shell=True)
            else:
                s = subprocess.check_output(["which", "python"], shell=False)
            python_path = s.splitlines()[-1]
            script_dir = os.path.dirname(os.path.realpath(__file__))
            heights_file = subprocess.check_output([python_path, script_dir + "\DEM_converter.py", map_file, heights_file], shell=False).rstrip()


        if cmds.objExists('city'):
            cmds.delete('city')

        def calc_emmiter_level(waypoints):
            if (jams_file == ""):
                return 0

            jams_data = open(jams_file, 'r')
            sum_jams_level = 0
            jams_points = 0

            shift_lat = -0.00766
            shift_lon = 0.006868

            for waypoint in waypoints:
                for line in jams_data:
                    tmp = line.split(' ')
                    lon = float(tmp[0]) - shift_lon
                    lat = float(tmp[1]) - shift_lat
                    if lat < minlat or lat > maxlat or lon < minlon or lon > maxlon:
                        continue
                    data = float(tmp[2])
                    jams_point = convert_coordinates(lon, lat)
                    dist = math.sqrt(math.pow(waypoint[0]-jams_point[0], 2)+math.pow(waypoint[2]-jams_point[2], 2))
                    if dist < (25.0/size_multiplier):
                        sum_jams_level += data
                        jams_points += 1

            if jams_points >= (len(waypoints) * 0.5):
                return 1.0*sum_jams_level/jams_points
            else:
                return 0

            jams_data.close()


        def convert_coordinates(lon, lat):
            centered_lat = (lat-minlat) - (maxlat-minlat)/2
            centered_lon = (lon-minlon) - (maxlon-minlon)/2
            normalized_lat = centered_lat * norm_lat
            normalized_lon = centered_lon * norm_lon
            return [normalized_lon, 0, -normalized_lat]

        #meters
        size_multiplier = float(cmds.textField(self.widgets["sizeMultTextField"], q = True, tx = True))
        emit_multiplier = float(cmds.textField(self.widgets["emitMultTextField"], q = True, tx = True))
        hasl = float(cmds.textField(self.widgets["haslTextField"], q = True, tx = True))

        xmlData = xml.dom.minidom.parse(map_file)

        points_ids = []
        points = []
        heights = []

        bounds = xmlData.getElementsByTagName("bounds")[0]
        minlat = float(bounds.getAttribute('minlat'))
        maxlat = float(bounds.getAttribute('maxlat'))
        minlon = float(bounds.getAttribute('minlon'))
        maxlon = float(bounds.getAttribute('maxlon'))

        dist_lon = self.coordinates_dist(minlon, minlat, maxlon, minlat)
        dist_lat = self.coordinates_dist(minlon, minlat, minlon, maxlat)

        norm_lat = (dist_lat/size_multiplier)/(maxlat-minlat)
        norm_lon = (dist_lon/size_multiplier)/(maxlon-minlon)

        #============================Get heights===================================
        heights_data = open(heights_file, 'r')

        rows = 0
        cols = 0
        start_lon = 0
        start_lat = 0
        delta_lon = 0
        delta_lat = 0

        heights_matrix = []

        for line in heights_data:
            tmp = line.strip().split(' ')

            if rows == 0:
                rows = float(tmp[0])
                cols = float(tmp[1])
            elif start_lon == 0:
                start_lon = float(tmp[0])
                start_lat = float(tmp[1])
            elif delta_lon == 0:
                delta_lon = float(tmp[0])
                delta_lat = float(tmp[1])
            else:
                row = []
                for cell in tmp:
                    row.append(int(cell)-hasl)
                heights_matrix.append(row)

        #==========================================================================

        maxprogress = 0
        ways = xmlData.getElementsByTagName('way')
        for way in ways:
            tags = way.getElementsByTagName('tag')
            for tag in tags:
                tag_type = str(tag.getAttribute('k'))
                if (tag_type == 'highway'):
                    subtype = str(tag.getAttribute('v'))
                    if not(subtype == 'pedestrian') and not(subtype == 'steps') and not(subtype == 'footway') and not(subtype == 'cycleway'):
                        maxprogress += 1
                if (tag_type == 'building'):
                    maxprogress += 1

        progress = 0
        cmds.progressWindow(title='Generating city', min = 0, max = maxprogress,  progress = progress, status = 'Processing nodes', isInterruptable = False)

        #============================Handle nodes==================================
        nodes = xmlData.getElementsByTagName('node')
        for node in nodes:
            lat = float(node.getAttribute('lat'))
            lon = float(node.getAttribute('lon'))

            if lat < minlat or lat > maxlat or lon < minlon or lon > maxlon:
                continue

            point = convert_coordinates(lon, lat)

            points_ids.append(int(node.getAttribute('id')))
            points.append(point)
            heights.append(heights_matrix[int(math.floor((lon-start_lon)/delta_lon))][int(math.floor((lat-start_lat)/delta_lat))])
        #==========================================================================

        #=============================Handle ways==================================
        roads = 0
        buildings = 0
        emitter = 0

        cmds.particle(n='nParticle')
        cmds.particle('nParticle', e=True, at='mass', order=0, fv=1e-5)
        cmds.setAttr('nParticleShape.lifespanMode', 2)
        cmds.setAttr('nParticleShape.lifespan', 6)
        cmds.setAttr('nParticleShape.lifespanRandom', 2)

        cmds.select('nParticleShape', r=True)
        cmds.addAttr(longName='betterIllumination', at='bool', defaultValue=False )
        cmds.addAttr(longName='surfaceShading', at='float', defaultValue=0, minValue=0, maxValue=1)
        cmds.addAttr(longName='threshold', at='float', defaultValue=0, minValue=0, maxValue=10)
        cmds.addAttr(longName='radius', at='float', defaultValue=1, minValue=0, maxValue=20)
        cmds.addAttr(longName='flatShaded', at='bool', defaultValue=False)

        cmds.setAttr('nParticleShape.particleRenderType', 8)
        cmds.setAttr('nParticleShape.radius', 0.06)

        cmds.setAttr('particleCloud1.transparency', 0.53, 0.53, 0.53, type='double3')
        cmds.setAttr('particleCloud1.color', 1.0, 0.0, 0.483, type='double3')
        cmds.setAttr('particleCloud1.incandescence', 1.0, 0.0, 0.850, type='double3')
        cmds.setAttr('particleCloud1.glowIntensity', 0.111)


        ways = xmlData.getElementsByTagName('way')
        for way in ways:
            waypoints = []
            heights_sum = 0
            nodes = way.getElementsByTagName('nd')
            tags = way.getElementsByTagName('tag')

            for node in nodes:
                ref = int(node.getAttribute('ref'))
                try:
                    index = points_ids.index(ref)
                except ValueError:
                    index = -1

                if index != -1:
                    waypoints.append(points[index])
                    heights_sum += heights[index]

            for tag in tags:
                tag_type = str(tag.getAttribute('k'))
                if tag_type == 'highway':
                    subtype = str(tag.getAttribute('v'))
                    if not(subtype == 'pedestrian') and not(subtype == 'steps') and not(subtype == 'footway') and not(subtype == 'cycleway'):
                        roads += 1
                        progress += 1
                        cmds.progressWindow(edit=True, progress = progress, status='Generating road: ' + str(roads))

                        lanes = 2
                        for tag in tags:
                            tag_type = str(tag.getAttribute('k'))
                            if tag_type == 'lanes':
                                lanes = float(str(tag.getAttribute('v')))

                        if len(waypoints) >= 2:
                            cmds.curve(n='pathcurve_' + str(roads), p=waypoints, d=1)
                            sx = waypoints[0][0]
                            sz = waypoints[0][2]
                            dx = waypoints[0][2]-waypoints[1][2]
                            dz = waypoints[1][0]-waypoints[0][0]
                            ln = math.sqrt(math.pow(2*dx, 2) + math.pow(2*dz, 2))
                            dx /= (ln*size_multiplier)/(3*lanes)
                            dz /= (ln*size_multiplier)/(3*lanes)
                            ln = 0

                            for i in range(0, len(waypoints)-2):
                                ln += math.trunc(math.sqrt(math.pow(waypoints[i+1][0]-waypoints[i][0], 2) + math.pow(waypoints[i+1][2]-waypoints[i][2], 2))) + 1
                            cmds.curve(n='extrudecurve_' + str(roads), p=[(sx-dx, 0, sz-dz), (sx+dx, 0, sz+dz)], d=1)
                            cmds.rebuildCurve('pathcurve_' + str(roads), rt=0, s=200)
                            cmds.nurbsToPolygonsPref(f=2, pt=1, ut=1, un=2, vt=1, vn=ln * 5 + 30)
                            cmds.extrude('extrudecurve_' + str(roads), 'pathcurve_' + str(roads), n='road_' + str(roads), et=2, po=1)
                            cmds.delete('extrudecurve_' + str(roads),)


                            emitter_level = calc_emmiter_level(waypoints)
                            if emitter_level > 0:
                                emitter += 1
                                cmds.select('pathcurve_' + str(roads), r=True)
                                cmds.move(0, 0.03, 0)
                                cmds.emitter(n='emitter_' + str(emitter), type='omni', r=emit_multiplier*emitter_level, spd=0.1, srn=0, sp=0)
                                cmds.connectDynamic('nParticle', em='emitter_' + str(emitter))


                            cmds.select('road_' + str(roads), r=True)
                            cmds.move(0, 0.004, 0)


                elif tag_type == 'building':
                    temp = str(tag.getAttribute('v'))
                    if temp == 'yes':
                        buildings += 1
                        progress += 1
                        cmds.progressWindow(edit=True, progress = progress, status='Generating building: ' + str(buildings))

                        if len(waypoints) >= 3:
                            cmds.polyCreateFacet(n='building_' + str(buildings), p=waypoints)
                            cmds.select('building_' + str(buildings), r=True)
                            normal = cmds.polyInfo(fn=True)[0].partition('0: ')[2].split(' ')[1]
                            if float(normal) < 0:
                                cmds.polyMirrorFace(direction=2, p=(0, 0, 0), mergeMode=0, worldSpace=1)
                                cmds.polyDelFacet('building_' + str(buildings) + '.f[0]')

                            avg_height = heights_sum / len(waypoints)

                            cmds.polyExtrudeFacet('building_' + str(buildings) + '.f[0]',  ltz=(1.0 * avg_height/size_multiplier))

                            cmds.select('building_' + str(buildings), r=True)

                            cmds.collision('building_' + str(buildings), 'nParticle')

        #==========================================================================

        #============================Handle winds==================================
        winds_data = open(winds_file, 'r')
        winds = 0
        cmds.progressWindow(edit=True, progress = progress, status='Setting winds')
        for line in winds_data:
            winds += 1

            tmp = line.split(' ')
            lon = float(tmp[0])
            lat = float(tmp[1])
            x = float(tmp[2])
            y = float(tmp[3])
            z = float(tmp[4])

            magn = math.sqrt(math.pow(x, 2) + math.pow(y, 2) + math.pow(z, 2))
            max_dist = self.coordinates_dist(0, 0, 0.006364, 0.006364)/size_multiplier
            volume_size = self.coordinates_dist(0, 0, 0.0045, 0.0045)/size_multiplier
            position = convert_coordinates(lon, lat)

            cmds.air(n='wind_' + str(winds), pos=position, wns=True, dx=x, dy=y, dz=z, m=magn, s=1, mxd=max_dist)
            cmds.setAttr('wind_' + str(winds) + '.volumeShape', 1)
            cmds.setAttr('wind_' + str(winds) + '.volumeOffsetY', 1)
            cmds.scale(volume_size, volume_size/2, volume_size, 'wind_' + str(winds))
            cmds.connectDynamic('nParticle', f='wind_' + str(winds))
            cmds.select(cl=True)
        #==========================================================================

        cmds.gravity(n='gravity', m=9.8*1e-5)
        cmds.connectDynamic('nParticle', f='gravity')
        cmds.polyPlane(n='ground', sx=(maxlon-minlon), sy=(maxlat-minlat), w=(maxlon-minlon)*norm_lon, h=(maxlat-minlat)*norm_lat)
        cmds.collision('ground', 'nParticle')

        cmds.select('building_*', r=True)
        cmds.select('road_*', tgl=True)
        cmds.select('ground', tgl=True)
        cmds.select('nParticle', tgl=True)
        cmds.editRenderLayerGlobals(currentRenderLayer='AOLayer')
        cmds.editRenderLayerMembers('AOLayer')

        cmds.select('road_*', r=True)
        cmds.group(n='roads')

        cmds.select('building_*', r=True)
        cmds.group(n='buildings')

        cmds.select('pathcurve_*', r=True)
        cmds.group(n='emitters')

        cmds.select('roads', r=True)
        cmds.select('buildings', tgl=True)
        cmds.select('emitters', tgl=True)
        cmds.select('nParticle', tgl=True)
        cmds.select('gravity', tgl=True)
        cmds.select('ground', tgl=True)
        cmds.select('wind_1', tgl=True)
        cmds.group(n='city')

        xmlData.unlink()
        winds_data.close()
        heights_data.close()

        if raw_wrf:
            os.remove(winds_file)

        if raw_dem:
            os.remove(heights_file)

        cmds.progressWindow(endProgress = True)
Esempio n. 9
0
def left_branch(base_hieght, previous_angle, previous_rise, previous_slide,
                r_previous_rise, r_previous_slide, left_hieght, branch_angle,
                branch_start_height_factor, max, left_sub_x, left_sub_y,
                left_radius, branch_decrease_factor_r,
                branch_decrease_factor_h, include_right, coral_base):

    if max != 0:
        left_inst = cmds.polyCone(n='left#',
                                  sx=left_sub_x,
                                  sy=left_sub_y,
                                  r=left_radius,
                                  h=left_hieght)
        angle = branch_angle + previous_angle
        rise = previous_rise + (base_hieght * branch_start_height_factor *
                                math.cos(math.radians(previous_angle)))
        slide = previous_slide + (math.sin(math.radians(previous_angle)) *
                                  base_hieght * branch_start_height_factor)
        left_move_y = rise + left_hieght / 2 - (
            (left_hieght - left_hieght * math.cos(math.radians(angle))) / 2)
        left_move_z = slide + left_hieght * math.sin(math.radians(angle)) * 0.5
        cmds.move(0, left_move_y, left_move_z, left_inst[0])
        cmds.select(left_inst[0])
        cmds.rotate(str(angle) + 'deg', 0, 0, r=True)

        previous_rise = rise
        previous_slide = slide

        if include_right:
            right_inst = cmds.polyCone(n='right#',
                                       sx=left_sub_x,
                                       sy=left_sub_y,
                                       r=left_radius,
                                       h=left_hieght)
            if (branch_angle + previous_angle) <= 90:
                r_angle = 360 - (branch_angle + previous_angle)
            else:
                r_angle = 360 - (branch_angle + previous_angle) + 90
            r_rise = r_previous_rise + (base_hieght *
                                        branch_start_height_factor *
                                        math.cos(math.radians(previous_angle)))
            r_slide = r_previous_slide + (
                math.sin(math.radians(previous_angle)) * base_hieght *
                branch_start_height_factor)
            right_move_y = r_rise + left_hieght / 2 - (
                (left_hieght - left_hieght * math.cos(math.radians(r_angle))) /
                2)
            right_move_z = r_slide + left_hieght * math.sin(
                math.radians(r_angle)) * 0.5
            cmds.move(0, right_move_y, right_move_z, right_inst[0])
            cmds.select(right_inst[0])
            cmds.rotate(str(r_angle) + 'deg', 0, 0, r=True)

            r_previous_rise = r_rise
            r_previous_slide = r_slide

    else:
        return None

    prev_hieght = left_hieght
    left_radius = left_radius / branch_decrease_factor_r
    left_hieght = left_hieght / branch_decrease_factor_h

    left_name = cmds.ls(left_inst[0])
    cmds.polyMirrorFace(left_name[0], a=2)

    if include_right:
        right_name = cmds.ls(right_inst[0])
        cmds.polyMirrorFace(right_name[0], a=2)

    branches = cmds.group(empty=True, name="Branches")
    cmds.parent(left_inst, branches)
    if include_right:
        cmds.parent(right_inst, branches)

    cmds.parent(branches, coral_base)

    return left_branch(prev_hieght, angle, previous_rise, previous_slide,
                       r_previous_rise, r_previous_slide, left_hieght,
                       branch_angle, branch_start_height_factor, max - 1,
                       left_sub_x, left_sub_y, left_radius,
                       branch_decrease_factor_r, branch_decrease_factor_h,
                       include_right, coral_base)