Esempio n. 1
0
    def export_stp(self, filename=None):
        """Exports an stp file for the Shape.solid. If the filename provided
            doesn't end with .stp or .step then .stp will be added. If a
            filename is not provided and the shape's stp_filename property is
            not None the stp_filename will be used as the export filename.

        Args:
            filename (str): the filename of the stp
        """

        if filename is not None:
            Pfilename = Path(filename)

            if Pfilename.suffix == ".stp" or Pfilename.suffix == ".step":
                pass
            else:
                Pfilename = Pfilename.with_suffix(".stp")

            Pfilename.parents[0].mkdir(parents=True, exist_ok=True)
        elif self.stp_filename is not None:
            Pfilename = Path(self.stp_filename)

        with open(Pfilename, "w") as f:
            exporters.exportShape(self.solid, "STEP", f)
        print("Saved file as ", Pfilename)

        return str(Pfilename)
def export_images():

    all_reactors = main()

    for reactor in all_reactors:
        with open(reactor.name + '.svg', "w") as f:
            exporters.exportShape(reactor.solid, "SVG", f)
Esempio n. 3
0
def show_object(result, name='web_view/assembly'):
    # WHAT ARE YOU DOING?
    # TODO: Come up with a better way to multi process things. This import is no good.
    from cadquery import exporters
    'generate a .JSON file for ThreeJS objects.'
    # Open stream
    output = StringIO.StringIO()

    # cadquery will stream a ThreeJS JSON (using old v3 schema, which is deprecated)
    exporters.exportShape(result, 'TJS', output)

    # store stream to a variable
    contents = output.getvalue()

    # Close stream
    output.close()

    # Overwrite the JSON color.
    col = [0.7412, 0.5765, 0.9765]
    old_col_str = '"colorDiffuse" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746]'
    new_col_str = '"colorDiffuse" : ' + str(col)
    new_contents = contents.replace(old_col_str, new_col_str)


    file_name = name + '.json'
    # Save the string to a json file
    with open(file_name, "w") as text_file:
        text_file.write(new_contents)
    return
Esempio n. 4
0
def cqgen(result, name='Output', color='#708090'):
    'generate a .JSON file for ThreeJS objects.'
    # Open stream
    output = StringIO.StringIO()

    # cadquery will stream a ThreeJS JSON (using old v3 schema, which is deprecated)
    exporters.exportShape(result, 'TJS', output)

    # store stream to a variable
    contents = output.getvalue()

    # Close stream
    output.close()

    # Overwrite the JSON color portion with user color. Disallows NAMED colors
    col = list(colors.hex2color(color))
    old_col_str = '"colorDiffuse" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746]'
    new_col_str = '"colorDiffuse" : ' + str(col)
    new_contents = contents.replace(old_col_str, new_col_str)


    file_name = name + '.json'
    # Save the string to a json file
    with open(file_name, "w") as text_file:
        text_file.write(new_contents)

    # print "Part generated : " + file_name

    return
Esempio n. 5
0
    def _exportBox(self,
                   eType,
                   stringsToFind,
                   tolerance=0.1,
                   angularTolerance=0.1):
        """
            Exports a test object, and then looks for
            all of the supplied strings to be in the result
            returns the result in case the case wants to do more checks also
        """
        p = Workplane("XY").box(1, 2, 3)

        if eType == exporters.ExportTypes.AMF:
            s = io.BytesIO()
        else:
            s = io.StringIO()

        exporters.exportShape(p,
                              eType,
                              s,
                              tolerance=tolerance,
                              angularTolerance=angularTolerance)

        result = "{}".format(s.getvalue())

        for q in stringsToFind:
            self.assertTrue(result.find(q) > -1)
        return result
def export_images():

    all_reactors = main()

    for reactor in all_reactors:
        with open(reactor.name + ".svg", "w") as f:
            exporters.exportShape(reactor.solid, "SVG", f)

        reactor.export_stp(output_folder=reactor.name)
Esempio n. 7
0
 def write_shapes(self,shape_list):
     for result in shape_list:
         shape = result.shape
         file_name = self._compute_file_name()
         info("Writing %s Output to '%s'" % (self.shape_format, file_name))
         s = open(file_name,'w')
         exporters.exportShape(shape,self.shape_format,s)
         s.flush()
         s.close()
Esempio n. 8
0
 def write_shapes(self, shape_list):
     for result in shape_list:
         shape = result.shape
         file_name = self._compute_file_name()
         info("Writing %s Output to '%s'" % (self.shape_format, file_name))
         s = open(file_name, 'w')
         exporters.exportShape(shape, self.shape_format, s)
         s.flush()
         s.close()
Esempio n. 9
0
def convscript(user_script):
    parsed_script = cqgi.parse(user_script)
    build_result = parsed_script.build(build_parameters={}, build_options={})
    if build_result.results:
        b = build_result.results[0]
        s = io.StringIO()
        exporters.exportShape(b.shape, "STL", s, 0.01)
        res = s.getvalue()
    else:
        res = str(build_result.exception)
    return res
    def _exportBox(self,eType,stringsToFind):
        """
            Exports a test object, and then looks for
            all of the supplied strings to be in the result
            returns the result in case the case wants to do more checks also
        """
        p = Workplane("XY").box(1,2,3)
        s = io.StringIO()
        exporters.exportShape(p,eType,s,0.1)

        result = s.getvalue()
        #print result
        for q in stringsToFind:
            self.assertTrue(result.find(q) > -1 )
        return result
Esempio n. 11
0
 def _exportBox(self,eType,stringsToFind):
     """
         Exports a test object, and then looks for 
         all of the supplied strings to be in the result
         returns the result in case the case wants to do more checks also
     """
     p = Workplane("XY").box(1,2,3)        
     s = StringIO.StringIO()
     exporters.exportShape(p,eType,s,0.1)
     
     result = s.getvalue()
     #print result
     for q in stringsToFind:
         self.assertTrue(result.find(q) > -1 )
     return result
Esempio n. 12
0
    def export_stp(self,
                   filename=None,
                   units='mm',
                   mode: str = 'solid') -> str:
        """Exports an stp file for the Shape.solid. If the filename provided
            doesn't end with .stp or .step then .stp will be added. If a
            filename is not provided and the shape's stp_filename property is
            not None the stp_filename will be used as the export filename.

        Args:
            filename (str): the filename of the stp
            units (str): the units of the stp file, options are 'cm' or 'mm'.
                Default is mm.
            mode (str, optional): the object to export can be either
                'solid' which exports 3D solid shapes or the 'wire' which
                exports the wire edges of the shape. Defaults to 'solid'.
        """

        if filename is not None:
            path_filename = Path(filename)

            if path_filename.suffix == ".stp" or path_filename.suffix == ".step":
                pass
            else:
                path_filename = path_filename.with_suffix(".stp")

            path_filename.parents[0].mkdir(parents=True, exist_ok=True)
        elif self.stp_filename is not None:
            path_filename = Path(self.stp_filename)

        with open(path_filename, "w") as out_file:
            if mode == 'solid':
                exporters.exportShape(self.solid, "STEP", out_file)
            elif mode == 'wire':
                exporters.exportShape(self.wire, "STEP", out_file)
            else:
                raise ValueError(
                    "The mode argument for export_stp \
                    only accepts 'solid' or 'wire'", self)

        if units == 'cm':
            _replace(path_filename, 'SI_UNIT(.MILLI.,.METRE.)',
                     'SI_UNIT(.CENTI.,.METRE.)')

        print("Saved file as ", path_filename)

        return str(path_filename)
Esempio n. 13
0
    def export_svg(self, filename):
        """Exports an svg file for the Reactor.solid. If the filename provided
        doesn't end with .svg it will be added.

        Args:
            filename (str): the filename of the svg file to be exported
        """

        Pfilename = Path(filename)

        if Pfilename.suffix != ".svg":
            Pfilename = Pfilename.with_suffix(".svg")

        Pfilename.parents[0].mkdir(parents=True, exist_ok=True)

        with open(Pfilename, "w") as f:
            exporters.exportShape(self.solid, "SVG", f)
        print("Saved file as ", Pfilename)
Esempio n. 14
0
    def __call__(self, filename='out.svg', world=False):

        # Getting cadquery Shape
        workplane = self.obj.world_obj if world else self.obj.local_obj
        shape = workplane.val()

        # call cadquery exporter
        try:
            with open(filename, 'w') as fh:
                cadquery.freecad_impl.exporters.exportShape(
                    shape=shape,
                    exportType='SVG',
                    fileLike=fh,
                )
        except AttributeError:
            # If freecad_impl is not available (beacuse cadquery based on
            # PythonOCC is being uses), fall back onto an alternative export method
            from cadquery import exporters
            with open(filename, "w") as fh:
                exporters.exportShape(shape, exporters.ExportTypes.SVG, fh)
Esempio n. 15
0
    def export_svg(self, filename: str) -> str:
        """Exports an svg file for the Shape.solid. If the provided filename
        doesn't end with .svg it will be added.

        Args:
            filename (str): the filename of the svg file to be exported
        """

        path_filename = Path(filename)

        if path_filename.suffix != ".svg":
            path_filename = path_filename.with_suffix(".svg")

        path_filename.parents[0].mkdir(parents=True, exist_ok=True)

        with open(path_filename, "w") as out_file:
            exporters.exportShape(self.solid, "SVG", out_file)
        print("Saved file as ", path_filename)

        return str(path_filename)
Esempio n. 16
0
    def export_svg(self, filename):
        """Exports an svg file for the Shape.solid.
        If the provided filename doesn't end with .svg it will be added

        :param filename: the filename of the svg
        :type filename: str
        """

        Pfilename = Path(filename)

        if Pfilename.suffix != ".svg":
            Pfilename = Pfilename.with_suffix(".svg")

        Pfilename.parents[0].mkdir(parents=True, exist_ok=True)

        with open(Pfilename, "w") as f:
            exporters.exportShape(self.solid, "SVG", f)
        print("Saved file as ", Pfilename)

        return str(Pfilename)
Esempio n. 17
0
    def export_stl(self, filename, tolerance=0.001):
        """Exports an stl file for the Shape.solid. If the provided filename
            doesn't end with .stl it will be added

        Args:
            filename (str): the filename of the stl file to be exported
            tolerance (float): the precision of the faceting
        """

        Pfilename = Path(filename)

        if Pfilename.suffix != ".stl":
            Pfilename = Pfilename.with_suffix(".stl")

        Pfilename.parents[0].mkdir(parents=True, exist_ok=True)

        with open(Pfilename, "w") as f:
            exporters.exportShape(self.solid, "STL", f, tolerance)
        print("Saved file as ", Pfilename)

        return str(Pfilename)
Esempio n. 18
0
    def _exportBox(self,eType,stringsToFind):
        """
            Exports a test object, and then looks for
            all of the supplied strings to be in the result
            returns the result in case the case wants to do more checks also
        """
        p = Workplane("XY").box(1,2,3)

        if eType == exporters.ExportTypes.AMF:
            s = io.BytesIO()
            exporters.exportShape(p,eType,s,0.1)
            result = s.getvalue()
            for q in stringsToFind:
                self.assertTrue(result.decode().find(q) > -1 )
        else:
            s = io.StringIO()
            exporters.exportShape(p,eType,s,0.1)
            result = s.getvalue()
            for q in stringsToFind:
                self.assertTrue(q in result)

        return result
Esempio n. 19
0
user_script = """
base_cube = cq.Workplane('XY').rect(1.0,1.0).extrude(1.0)
top_of_cube_plane = base_cube.faces(">Z").workplane()
debug(top_of_cube_plane, { 'color': 'yellow', } )
debug(top_of_cube_plane.center, { 'color' : 'blue' } )

circle=top_of_cube_plane.circle(0.5)
debug(circle, { 'color': 'red' } )

show_object( circle.extrude(1.0) )
"""

user_script = """
result = cq.Workplane("front").box(2.0, 2.0, 0.5); show_object(result)
"""

# must fix the time.clock() call in the cqgi https://github.com/jmwright/cadquery-freecad-module/issues/147
from cadquery import cqgi, exporters
import io

parsed_script = cqgi.parse(user_script)
build_result = parsed_script.build(build_parameters={}, build_options={})
if build_result.results:
    b = build_result.results[0]
    s = io.StringIO()
    exporters.exportShape(b.shape, "STL", s, 0.01)
    res = s.getvalue()
else:
    res = str(build_result.exception)
print(res)
Esempio n. 20
0
 def write_shapes(self,shape_list):
     #f = open('/tmp/cqtemp','w')
     #with suppress_stdout_stderr():
     exporters.exportShape(shape_list[0].shape,self.shape_format,sys.stdout)
Esempio n. 21
0
def cqdisplay(result, color='#708090', scale=1.0):
    'display CQ object in a ThreeJS Webgl context'
    # Open stream
    output = StringIO.StringIO()

    # cadquery will stream a ThreeJS JSON (using old v3 schema, which is deprecated)
    exporters.exportShape(result.shape.findSolid().scale(scale), 'TJS', output)

    # store stream to a variable
    contents = output.getvalue()

    # Close stream
    output.close()

    # Overwrite the JSON color portion with user defined color. Disallows NAMED colors
    col = list(matplotlib.colors.hex2color(color))
    old_col_str = '"colorDiffuse" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746]'
    new_col_str = '"colorDiffuse" : ' + str(col)
    new_contents = contents.replace(old_col_str, new_col_str)

    # Take the string and create a proper json object
    contents = json.loads(contents)

    # Vertices and Faces are both flat lists, but the pythreejs module requires list of lists
    old_v = contents['vertices']
    old_f = contents['faces']

    # Splits the list up in 3s, to produce a list of lists representing the vertices
    vertices = [old_v[i:i+3] for i in range(0, len(old_v), 3)]

    # JSON Schema has first position in the face's list reserved to indicate type.
    # Cadquery returns Triangle mesh, so we know that we must split list into lists of length 4
    # 1st entry to indicate triangle, next 3 to specify vertices
    three_faces = [old_f[i:i+4] for i in range(0, len(old_f), 4)]
    faces = []

    # Drop the first entry in the face list
    for entry in three_faces:
        entry.pop(0)
        faces.append(entry)

    # Cadquery does not supply face normals in the JSON,
    # and we cannot use THREE.JS built in 'computefaceNormals'
    # (at least, not easily)
    # Instead, we just calculate the face normals ourselves.
    # It is just the cross product of 2 vectors in the triangle.
    # TODO: see if there is a better way to achieve this result
    face_normals = []

    for entry in faces:
        v_a = np.asarray(vertices[entry[0]])
        v_b = np.asarray(vertices[entry[1]])
        v_c = np.asarray(vertices[entry[2]])

        vec_a = v_b - v_a
        vec_b = v_c - v_a

        cross = np.cross(vec_a, vec_b)

        face_normals.append([cross[0], cross[1], cross[2]])

    # set up geometry
    geom = pythreejs.PlainGeometry(vertices=vertices, faces=faces, faceNormals=face_normals)
    mtl = pythreejs.LambertMaterial(color=color, shading='FlatShading')
    obj = pythreejs.Mesh(geometry=geom, material=mtl)

    # set up scene and camera
    cam_dist = 50
    fov = 35
    cam = pythreejs.PerspectiveCamera(
        position=[cam_dist, cam_dist, cam_dist], fov=fov,
        children=[pythreejs.DirectionalLight(color='#ffffff', position=[-3, 5, 1], intensity=0.45)])
    scn_chld = [
        obj,
        pythreejs.AmbientLight(color='#dddddd')
    ]
    scn = pythreejs.Scene(children=scn_chld)

    render = pythreejs.Renderer(
        width='830'.decode('utf-8'),
        height='553'.decode('utf-8'),
        camera=cam,
        scene=scn,
        controls=[pythreejs.OrbitControls(controlling=cam)]
        )

    return render
Esempio n. 22
0
 def write_shapes(self, shape_list):
     #f = open('/tmp/cqtemp','w')
     #with suppress_stdout_stderr():
     exporters.exportShape(shape_list[0].shape, self.shape_format,
                           sys.stdout)
Esempio n. 23
0
# Example cadquery script
# Usage: test.py output.stl

import cadquery as cq
from cadquery import exporters
import sys

result = cq.Workplane("XY").box(3, 3, 0.5).edges("|Z").fillet(0.125)

with open(sys.argv[1], 'w') as f:
    exporters.exportShape(result, exporters.ExportTypes.STL, f)