from smesh import *

SetCurrentStudy(salome.myStudy)

box1 = geompy.MakeBoxDXDYDZ(180,100,100)
box2 = geompy.MakeTranslation( box1, 90, 0, 0 )
model = geompy.Partition( [box1, box2] )

def GetGroupName( internalFace ):
    idInModel = geompy.GetSubShapeID( model, intFace )
    return "Group on face %s" % idInModel

solids = geompy.SubShapeAllSorted( model, geompy.ShapeType["SOLID"])

nbSeg = 10
thickness = 5
numberOfLayers = 5
stretchFactor = 1.5

previuosMesh = None
for i, solid in enumerate( solids ):

    isFinalMesh = (i == len( solids ) - 1)
    if isFinalMesh:
        meshName = "Final mesh"
    else:
        meshName = "part %s" % (i+1)
    mesh = Mesh( solid, meshName )
    mesh.Segment().NumberOfSegments( nbSeg )
    mesh.Quadrangle()
    algo3D = mesh.Hexahedron()

    # define viscous layers on internal faces

    facesOfOtherSolids = []
    for j, otherSolid in enumerate( solids ):
        if i != j:
            facesOfOtherSolids += geompy.SubShapeAll( otherSolid, geompy.ShapeType["FACE"])
    
    externalFaces = []
    internalFaces = []
    for face in geompy.SubShapeAll( solid, geompy.ShapeType["FACE"]):
        isShared = False
        for faceOther in facesOfOtherSolids:
            if faceOther.IsSame( face ):
                isShared = True; break
        if isShared:
            internalFaces.append( face )
        else:
            externalFaces.append( face )

    algo3D.ViscousLayers( thickness, numberOfLayers, stretchFactor, externalFaces )

    # import previously meshed part of the model
    if previuosMesh:
        for intFace in internalFaces:
            groupName = GetGroupName( intFace )
            for group in previuosMesh.GetGroups():
               if GetName( group ) == groupName: 
                   importAlgo = mesh.UseExisting2DElements( intFace )
                   importAlgo.SourceFaces( [group], toCopyMesh=True)

    mesh.Compute()

    # create a group of 2D elements on internal faces
    if not isFinalMesh:
        for intFace in internalFaces:
            groupName = GetGroupName( intFace )
            mesh.GroupOnGeom( intFace, groupName, SMESH.FACE )

    previuosMesh = mesh
    
