Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An openFOAM-tailored OBJ exporter for FreeCAD
#***************************************************************************
#* *
#* Copyright (c) 2015 *
#* Yorik van Havre <yorik@uncreated.net> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
__title__ = "FreeCAD openfoam-ready OBJ importer"
__author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org"
import FreeCAD,FreeCADGui,DraftGeomUtils,Part,MeshPart
# below is a safeguard in case we redefine "open" later in this script
if open.__module__ == '__builtin__':
pythonopen = open
def export(exportlist,filename,tessellation=1,scaling=0.001,mesher="builtin",\
grading=0.3,segperedge=1,segperradius=2,secondorder=0,optimize=1,allowquad=0):
"""export(exportlist,filename,tessellation=1,scaling=0.001,mesher="builtin",
grading=0.3,segperedge=1,segperradius=2,secondorder=0,optimize=1,allowquad=0):
exports the given objects list to the given OBJ filename. The objects will be
exported with separate regions defined by face color. Using smaller
tessellation values will result in coarser meshes. mesher can be builtin,
mefisto or netgen. Attributes after mesher are only used for netgen"""
def triangulate(face):
"triangulates the given face"
if mesher == "builtin":
return face.tessellate(tessellation)
elif mesher == "mefisto":
return MeshPart.meshFromShape(Shape=face,MaxLength=tessellation).Topology
elif mesher == "netgen":
return MeshPart.meshFromShape(Shape=face,GrowthRate=grading,SegPerEdge=segperedge,SegPerRadius=segperradius,SecondOrder=secondorder,Optimize=optimize,AllowQuad=allowquad).Topology
# build a dictionary of faces sorted by color
colordict = {}
for obj in exportlist:
if obj.isDerivedFrom("Part::Feature"):
sh = obj.Shape.cleaned()
if sh.Faces:
if len(obj.ViewObject.DiffuseColor) == len(sh.Faces):
# per-face colors are defined
for i in range(len(obj.ViewObject.DiffuseColor)):
colordict.setdefault(obj.ViewObject.DiffuseColor[i],[]).append(sh.Faces[i])
else:
# one color for whole object
for f in sh.Faces:
colordict.setdefault(obj.ViewObject.ShapeColor,[]).append(f)
if not colordict:
FreeCAD.Console.PrintError("Unable to retrieve color information from the given objects\n")
return
# build a dictionary of vectors
temp = {}
vectorsdict = {}
offset = 1
for color,faces in colordict.items():
temp[color] = []
for f in faces:
# test the need for triangulation
tris = None
for e in f.Edges:
if not isinstance(e.Curve,Part.Line):
# there are curved edges
if not tris:
tris = triangulate(f)
if len(f.Wires) > 1:
# there is a hole in this face
tris = triangulate(f)
if tris:
# triangulating the face
for f in tris[1]:
findex = []
for i in f:
if tuple(tris[0][i]) in vectorsdict:
findex.append(vectorsdict[tuple(tris[0][i])])
else:
vectorsdict[tuple(tris[0][i])] = offset
findex.append(offset)
offset += 1
temp[color].append(findex)
else:
# no triangulation
findex = []
# OCC vertex list can be in wrong order, we sort them here
edges = DraftGeomUtils.sortEdges(f.OuterWire.Edges)
for e in edges:
v = e.Vertexes[0].Point
if tuple(v) in vectorsdict:
findex.append(vectorsdict[tuple(v)])
else:
vectorsdict[tuple(v)] = offset
findex.append(offset)
offset += 1
temp[color].append(findex)
colordict = temp
# debug
print "vectors: ",vectorsdict
print "facegroups: ",colordict
# write the obj file
outfile = pythonopen(filename,"wb")
ver = FreeCAD.Version()
outfile.write("# FreeCAD v" + ver[0] + "." + ver[1] + " build" + ver[2] + " OpenFOAM exporter\n")
outfile.write("# http://www.freecadweb.org\n")
# sort and write verts first
vecs = vectorsdict.keys()
l = sorted(range(len(vecs)),key=lambda x:vectorsdict.values()[x])
vecs = [vecs[i] for i in l]
for v in vecs:
outfile.write("v " + str(v[0]*scaling) + " " + str(v[1]*scaling) + " " + str(v[2]*scaling) + "\n")
# write color groups
idx = 1
for color,faces in colordict.items():
# build a group name from the color data
outfile.write("g patch" + str(idx) + "\n")
# write face indexes
for f in faces:
outfile.write("f")
for i in f:
outfile.write(" " + str(i))
outfile.write("\n")
idx += 1
outfile.close()
FreeCAD.Console.PrintMessage("Successfully exported "+filename+"\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.