Esempio n. 1
0
def vrep_pose_from_plane(plane):
    """Creates a vrep-compatible transformation matrix from a Rhino/Grasshopper
    plane.

    This function might need rework as the source of the 90-deg Y rotation
    need is not entirely clear to me (related to the RFL model mismatch).
    """
    translation_matrix = rs.XformTranslation(((plane[0][0]), (plane[0][1]), plane[0][2]))
    plane_start = rs.PlaneFromFrame(rs.AddPoint(0, 0, 0), rs.AddPoint(1, 0, 0), rs.AddPoint(0, 1, 0))
    plane_end = rs.PlaneFromFrame(rs.AddPoint(0, 0, 0), rs.AddPoint(plane[1][0], (plane[1][1]), plane[1][2]), rs.AddPoint(plane[2][0], plane[2][1], plane[2][2]))
    rotation_matrix = rs.XformRotation1(plane_start, plane_end)
    matrix = rs.XformMultiply(translation_matrix, rotation_matrix)
    return [matrix.M00, matrix.M01, matrix.M02, matrix.M03,
            matrix.M10, matrix.M11, matrix.M12, matrix.M13,
            matrix.M20, matrix.M21, matrix.M22, matrix.M23]
Esempio n. 2
0
def load_printpoints(path, folder_name, json_name):
    """ Loads a dict of compas_slicer printpoints. """
    data = load_json_file(path, folder_name, json_name)

    # geometry data
    points = []
    frames = []
    layer_heights = []
    up_vectors = []
    mesh_normals = []
    closest_support = []

    # fabrication related data
    velocities = []
    wait_times = []
    blend_radiuses = []
    extruder_toggles = []

    if data:
        for i in range(len(data)):
            data_point = data[str(i)]

            # geometry related data
            point = rg.Point3d(data_point["point"][0], data_point["point"][1],
                               data_point["point"][2])
            points.append(point)

            compas_frame = Frame.from_data(data_point["frame"])
            pt, x_axis, y_axis = compas_frame.point, compas_frame.xaxis, compas_frame.yaxis
            frame = rs.PlaneFromFrame(pt, x_axis, y_axis)
            frames.append(frame)

            layer_heights.append(data_point["layer_height"])

            v = data_point["up_vector"]
            up_vector = rg.Vector3d(v[0], v[1], v[2])
            up_vectors.append(up_vector)

            v = data_point["mesh_normal"]
            mesh_normal = rg.Vector3d(v[0], v[1], v[2])
            mesh_normals.append(mesh_normal)

            cp = data_point["closest_support_pt"]
            if cp:
                cp_pt = rg.Point3d(cp[0], cp[1], cp[2])
                closest_support.append(cp_pt)
            else:
                closest_support.append(
                    point
                )  # in order to have the same number of points everywhere

            # fabrication related data
            velocities.append(data_point["velocity"])
            wait_times.append(data_point["wait_time"])
            blend_radiuses.append(data_point["blend_radius"])
            extruder_toggles.append(data_point["extruder_toggle"])

    return points, frames, layer_heights, up_vectors, mesh_normals, closest_support, velocities, wait_times, \
        blend_radiuses, extruder_toggles
Esempio n. 3
0
def RunCommand(is_interactive):
    global params

    pitch_line = rs.GetObject(message="Select pitch line",
                              filter=rs.filter.curve,
                              preselect=True)
    if pitch_line is None:
        return 1  # Cancel

    if not rs.IsLine(pitch_line):
        print "Selected curve is not a line!"
        return 1  # Cancel

    rs.SelectObjects(pitch_line)

    m = rs.GetReal(message="Rack module", number=params["m"])
    pa = rs.GetReal(message="Pressure angle",
                    number=params["pa"],
                    minimum=0,
                    maximum=45)

    if m is None or pa is None:
        return 1  # Cancel

    params["m"] = m
    params["pa"] = pa

    pitch_line_center = rs.CurveMidPoint(pitch_line)
    pitch_line_start = rs.CurveStartPoint(pitch_line)
    pitch_line_end = rs.CurveEndPoint(pitch_line)
    angle, reflex_angle = rs.Angle2(line1=((0, 0, 0), (1, 0, 0)),
                                    line2=(pitch_line_start, pitch_line_end))

    x_vector = rs.VectorCreate(pitch_line_end, pitch_line_start)
    y_vector = rs.VectorRotate(x_vector, 90.0, [0, 0, 1])
    cplane = rs.PlaneFromFrame(origin=pitch_line_center,
                               x_axis=x_vector,
                               y_axis=y_vector)

    xform = rs.XformChangeBasis(cplane, rs.WorldXYPlane())

    rs.EnableRedraw(False)
    old_plane = rs.ViewCPlane(plane=rs.WorldXYPlane())

    rack = draw_rack(length=rs.CurveLength(pitch_line),
                     module=params["m"],
                     pressure_angle=params["pa"])

    rs.ViewCPlane(plane=old_plane)
    rs.TransformObjects(rack, xform)

    rs.EnableRedraw(True)
    rs.UnselectAllObjects()
    rs.SelectObjects(rack)

    return 0  # Success
Esempio n. 4
0
def create_cut_sht_targets(stockOutline, array, margin, partSpacing):
    """returns a list of target planes to evenly space parts on a given stock"""
    numParts = len(array)
    stockDimensions = dimension_boundingBox(stockOutline)
    partDimensions = dimension_boundingBox(array[0])
    stockHeight = stockDimensions[0]
    stockWidth = stockDimensions[1]
    partHeight = partDimensions[0]
    partWidth = partDimensions[1]

    yStartPt = partWidth / 2.0 + margin
    xStartPt = partHeight / 2.0 + margin
    ySpacing = partWidth + partSpacing
    xSpacing = partHeight + partSpacing
    rowWidth = stockWidth - (2 * margin)
    columnHeight = stockHeight - (2 * margin)

    currentX = xStartPt
    currentY = yStartPt
    locationPts = []
    targetPlanes = []

    for i in range(len(array)):
        xLimit = currentX + (partWidth / 2.0)
        yLimit = currentY + (partHeight / 2.0)
        if yLimit > columnHeight:
            print "parts do not fit on stock"
            return None
        elif xLimit > rowWidth:
            currentY += ySpacing
            currentX = xStartPt
            partCenterPt = rs.AddPoint(currentX, currentY, 0)
            locationPts.append(partCenterPt)
            targetPlane = rs.PlaneFromFrame(partCenterPt, [1, 0, 0], [0, 1, 0])
            targetPlanes.append(targetPlane)
            currentX += xSpacing
        else:
            partCenterPt = rs.AddPoint(currentX, currentY, 0)
            locationPts.append(partCenterPt)
            targetPlane = rs.PlaneFromFrame(partCenterPt, [1, 0, 0], [0, 1, 0])
            targetPlanes.append(targetPlane)
            currentX += xSpacing
    return targetPlanes
Esempio n. 5
0
 def cross_section_plane_curvature(self, curvature, prev_normal, prev_perp):
     crvPoint = curvature[0]
     crvTangent = curvature[1]
     crvPerp = rs.VectorUnitize(curvature[4])
     crvNormal = rs.VectorCrossProduct(crvTangent, crvPerp)
     if prev_normal:
         crvNormal = self.reverse_if_needed(crvNormal, prev_normal)
     if prev_perp:
         crvPerp = self.reverse_if_needed(crvPerp, prev_perp)
     return rs.PlaneFromFrame(crvPoint, crvPerp, crvNormal)
Esempio n. 6
0
def flatWorm():
    curveObject = rs.GetObject("pick a backbone curve", 4, True, False)
    samples = rs.GetInteger("# of crosssections", 100, 5)
    bend_radius = rs.GetReal("bend radius", 0.5, 0.001)  # r1
    perp_radius = rs.GetReal("ribbon plan radius", 2.0, 0.001)  #r2
    crvDom = rs.CurveDomain(
        curveObject
    )  # domain != length // why do we use domains? == "The domain is the set of all possible input values to the function that defines the curve or surface."

    crossSections = []  # empty array to store sections
    t_step = (crvDom[1] -
              crvDom[0]) / samples  # this is starting to be a pattern!
    t = crvDom[0]  # start pt for loop at the start of the line

    for t in rs.frange(crvDom[0], crvDom[1],
                       t_step):  # loop thru entire domain w/ floats
        crvCurvature = rs.CurveCurvature(
            curveObject, t
        )  # evaluate curve with a circle - gives 3d normals & gives radius info
        crossSecPlane = None
        if not crvCurvature:
            crvPoint = rs.EvaluateCurve(curveObject, t)
            crvTan = rs.CurveTangent(curveObject, t)  # get tangent vector
            crvPerp = (0, 0, 1)
            crvNorm = rs.VectorCrossProduct(crvTan,
                                            crvPerp)  # = product of 2 vectors
            crossSecPlane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNorm)
        else:
            crvPoint = crvCurvature[0]
            crvTan = crvCurvature[1]
            crvPerp = rs.VectorUnitize(crvCurvature[4])
            crvNorm = rs.VectorCrossProduct(crvTan, crvPerp)  # look up
            crossSecPlane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNorm)
        if crossSecPlane:
            csec = rs.AddEllipse(
                crossSecPlane, bend_radius, perp_radius
            )  # draw ellipse at tan/normal to point along curve with radii
            crossSections.append(csec)  # add ellipses to an array
        t += t_step  # step through domain

    rs.AddLoftSrf(crossSections)  # loft list of curves
    rs.DeleteObjects(
        crossSections)  # delete original list of curves as cleanup
Esempio n. 7
0
def FlatWorm():
    curve_object = rs.GetObject("Pick a backbone curve", 4, True, False)
    if not curve_object: return

    samples = rs.GetInteger("Number of cross sections", 100, 5)
    if not samples: return

    bend_radius = rs.GetReal("Bend plane radius", 0.5, 0.001)
    if not bend_radius: return

    perp_radius = rs.GetReal("Ribbon plane radius", 2.0, 0.001)
    if not perp_radius: return

    crvdomain = rs.CurveDomain(curve_object)

    crosssections = []
    t_step = (crvdomain[1]-crvdomain[0])/samples
    t = crvdomain[0]
    while t<=crvdomain[1]:
        crvcurvature = rs.CurveCurvature(curve_object, t)
        crosssectionplane = None
        if not crvcurvature:
            crvPoint = rs.EvaluateCurve(curve_object, t)
            crvTangent = rs.CurveTangent(curve_object, t)
            crvPerp = (0,0,1)
            crvNormal = rs.VectorCrossProduct(crvTangent, crvPerp)
            crosssectionplane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNormal)
        else:
            crvPoint = crvcurvature[0]
            crvTangent = crvcurvature[1]
            crvPerp = rs.VectorUnitize(crvcurvature[4])
            crvNormal = rs.VectorCrossProduct(crvTangent, crvPerp)
            crosssectionplane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNormal)

        if crosssectionplane:
            csec = rs.AddEllipse(crosssectionplane, bend_radius, perp_radius)
            crosssections.append(csec)
        t += t_step

    if not crosssections: return
    rs.AddLoftSrf(crosssections)
    rs.DeleteObjects(crosssections)
Esempio n. 8
0
 def cross_section_plane_no_curvature(self,
                                      t,
                                      prev_normal=None,
                                      prev_perp=None):
     crvPoint = rs.EvaluateCurve(self.curve_object, t)
     crvTangent = rs.CurveTangent(self.curve_object, t)
     crvPerp = (0, 0, 1)
     crvNormal = rs.VectorCrossProduct(crvTangent, crvPerp)
     if prev_normal:
         crvNormal = self.reverse_if_needed(crvNormal, prev_normal)
     if prev_perp:
         crvPerp = self.reverse_if_needed(crvPerp, prev_perp)
     return rs.PlaneFromFrame(crvPoint, crvPerp, crvNormal)
Esempio n. 9
0
 def offset_vector(self, point, cross_section_index, point_index):
     modulo = len(self.point_lists[cross_section_index - 1])
     prev_point_1 = self.point_lists[cross_section_index - 1][
         (point_index - 2) %
         modulo] if cross_section_index % 2 == 0 else self.point_lists[
             cross_section_index - 1][(point_index - 1) % modulo]
     prev_point_2 = self.point_lists[cross_section_index - 1][
         (point_index - 1) %
         modulo] if cross_section_index % 2 == 0 else self.point_lists[
             cross_section_index - 1][point_index]
     in_between_vector = rs.VectorAdd(rs.VectorCreate(prev_point_1, point),
                                      rs.VectorCreate(prev_point_2, point))
     normal_vector = rs.SurfaceNormal(
         self.brep, rs.SurfaceClosestPoint(self.brep, point))
     plane = rs.PlaneFromFrame(point, in_between_vector, normal_vector)
     vector = rs.SurfaceNormal(rs.AddPlaneSurface(plane, 1, 1), [0, 0])
     unit_vector = rs.VectorUnitize(vector)
     return [rs.VectorScale(unit_vector, 2), in_between_vector]
Esempio n. 10
0
    x = r * ma.sin(beta) * ma.cos(theta) * (ma.e**(theta / ma.tan(alpha)))
    y = r * ma.sin(beta) * ma.sin(theta) * (ma.e**(theta / ma.tan(alpha)))
    return (x, y)  #对数螺旋线基本方程。


crvdomain = rs.CurveDomain(curve_object)
sections = []
t_step = (crvdomain[1] - crvdomain[0]) / sample
t = crvdomain[0]
a_step = 20 * pi / sample
a = 0
for t in rs.frange(crvdomain[0], crvdomain[1], t_step):
    a = a + a_step
    curvecurvature = rs.CurveCurvature(curve_object, t)
    sectionplane = None
    curvept = curvecurvature[0]
    curvetangent = curvecurvature[1]
    curveperp = (0, 0, 1)
    curvenormal = rs.VectorCrossProduct(curveperp, curvetangent)
    sectionplane = rs.PlaneFromFrame(curvept, curveperp, curvenormal)
    if sectionplane:
        coor = coorxy(a, al, be, r)
        x = coor[0]
        y = coor[1]
        x1 = rs.VectorUnitize(curveperp)
        y1 = rs.VectorUnitize(curvenormal)
        pt = rs.VectorAdd(x * x1, y * y1)
        secptvec = pt + curvept
        secpt = rs.AddPoint(secptvec)
        sections.append(secpt)
    curve = rs.AddInterpCurve(sections)
Esempio n. 11
0
def makeFireStair(rect, landingLevels):
    #HARD VARIABLES
    minStairWidth = 1.118
    minHeadroom = 2.032
    maxRunRise = 3.658
    minNumRisers = 3
    minGapSize = .2
    minTread = .280
    maxTread = .400
    minRiser = .100
    maxRiser = .180
    thickness = .25
    maxRisersInRun = 16
    maxWidth = 2.4
    scissorStair = False
    hdrlHeight = .900
    #hdrlTopExtension = .305
    #hdrlBtmExtension = 1*treadDepth
    #hdrlMaxProjection = .114

    #(1)Determine Run Direction
    rs.SimplifyCurve(rect)
    rectSegments = rs.ExplodeCurves(rect)
    edge1 = rectSegments[0]
    edge3 = rectSegments[1]
    if rs.CurveLength(edge1) > rs.CurveLength(edge3):
        longEdge = edge1
        shortEdge = edge3
    else:
        longEdge = edge3
        shortEdge = edge1
    longVec = rs.VectorCreate(rs.CurveStartPoint(longEdge),
                              rs.CurveEndPoint(longEdge))
    longVecRev = rs.VectorReverse(longVec)
    shortVec = rs.VectorCreate(rs.CurveStartPoint(shortEdge),
                               rs.CurveEndPoint(shortEdge))
    shortVecRev = rs.VectorReverse(shortVec)

    #(2)Stair Width
    stairWidth = (rs.CurveLength(shortEdge) - minGapSize) / 2
    if stairWidth < .6:
        print "ERROR: Stair is ridiculously too narrow."
        return

    #(3)Run Length
    runLength = rs.CurveLength(longEdge) - (stairWidth * 2)
    if runLength < 1:
        print "ERROR: Stair is ridiculously too short."
        return

    #LandingRect
    landing1Plane = rs.PlaneFromFrame(rs.CurveStartPoint(shortEdge),
                                      shortVecRev, longVecRev)
    landing1 = rs.AddRectangle(landing1Plane, rs.CurveLength(shortEdge),
                               stairWidth)
    landing2Plane = rs.PlaneFromFrame(rs.CurveEndPoint(longEdge), shortVec,
                                      longVec)
    landing2 = rs.AddRectangle(landing2Plane, rs.CurveLength(shortEdge),
                               stairWidth)

    #RunRects
    run1Plane = rs.PlaneFromFrame(
        rs.CurveEditPoints(landing1)[3], shortVecRev, longVecRev)
    run1Rect = rs.AddRectangle(run1Plane, stairWidth, runLength)
    run2Plane = rs.PlaneFromFrame(
        rs.CurveEditPoints(landing2)[3], shortVec, longVec)
    run2Rect = rs.AddRectangle(run2Plane, stairWidth, runLength)

    #(4)Num Flights between Landings
    numLevels = len(landingLevels)
    deltaLevels = []
    runsPerLevel = []
    mostRisersInRun = math.floor(runLength / minTread)
    if mostRisersInRun > maxRisersInRun:
        mostRisersInRun = maxRisersInRun
    numRuns = 0

    for i in range(0, numLevels - 1):
        deltaLevels.append(landingLevels[i + 1] - landingLevels[i])
        minNumRisers = math.ceil(deltaLevels[i] / maxRiser)
        runsPerLevel.append(math.ceil(minNumRisers / mostRisersInRun))
        numRuns = numRuns + int(runsPerLevel[i])

    #(5) Which flights
    listOfRuns = []
    for i in range(0, numRuns):
        if i % 2:  #if even
            listOfRuns.append(rs.CopyObject(run1Rect))
        else:
            listOfRuns.append(rs.CopyObject(run2Rect))

    #(6) Num Treads per run
    runsDeltaHeight = []
    for i in range(0, numLevels - 1):
        for j in range(0, int(runsPerLevel[i])):
            runsDeltaHeight.append(deltaLevels[i] / runsPerLevel[i])

    numRisersPerRun = []
    for i in range(0, numRuns):
        numRisersPerRun.append(math.ceil(runsDeltaHeight[i] / maxRiser))

    #(7) Move Runs
    elevation = 0
    landings = []
    for i in range(0, numRuns):
        elevation = elevation + runsDeltaHeight[i]
        translation = rs.VectorCreate([0, 0, elevation], [0, 0, 0])
        rs.MoveObject(listOfRuns[i], translation)
        if i % 2:
            landings.append(rs.MoveObject(rs.CopyObject(landing2),
                                          translation))
        else:
            landings.append(rs.MoveObject(rs.CopyObject(landing1),
                                          translation))

    #(8) Make Landings
    stairGeo = []
    for i in range(0, numRuns):
        dir = rs.VectorCreate([0, 0, 0], [0, 0, runsDeltaHeight[i]])
        #rs.MoveObject(landings[i], dir)
        path = rs.AddLine([0, 0, 0], [0, 0, -thickness])
        geo = rs.ExtrudeCurve(landings[i], path)
        rs.CapPlanarHoles(geo)
        stairGeo.append(geo)
        rs.DeleteObject(path)
    rs.DeleteObjects(landings)

    #(9) Draw Stairs
    runs = []
    for i in range(0, numRuns):
        runs.append(
            Run(listOfRuns[i], runsDeltaHeight[i], numRisersPerRun[i],
                thickness, i, maxTread))
        stairGeo.append(runs[i].make())
        runs[i].makeHandrail(hdrlHeight, minGapSize)
        runs[i].printStats()
        runs[i].cleanup()

    finalGeo = rs.BooleanUnion(stairGeo, delete_input=True)

    #(10) Scissor Stairs
    if scissorStair:
        pt0 = rs.CurveMidPoint(rectSegments[0])
        pt1 = rs.CurveMidPoint(rectSegments[1])
        pt2 = rs.CurveMidPoint(rectSegments[2])
        pt3 = rs.CurveMidPoint(rectSegments[3])
        mir1 = rs.MirrorObject(finalGeo, pt0, pt2, copy=True)
        mirroredStair = rs.MirrorObject(mir1, pt1, pt3, copy=False)

    #(11)Label
    rs.SetUserText(finalGeo, "Brew", "Hot Coffee")
    if scissorStair:
        rs.SetUserText(mirroredStair, "Brew", "Hot Coffee")

    #Cleanup
    rs.DeleteObjects(listOfRuns)
    rs.DeleteObjects(rectSegments)
    rs.DeleteObject(landing1)
    rs.DeleteObject(landing2)
    rs.DeleteObject(run1Rect)
    rs.DeleteObject(run2Rect)
    print "done"
    return None
import rhinoscriptsyntax as rs
all = rs.AllObjects()
rs.DeleteObjects(all)

plane1 = rs.PlaneFromFrame([0, 0, 0], [0, 1, 0], [0, 0, 1])
plane2 = rs.PlaneFromFrame([20, 10, 10], [0, 0, 1], [0, 1, 0])
plane3 = rs.PlaneFromFrame([20, -10, 10], [0, 0, 1], [0, 1, 0])
plane4 = rs.PlaneFromFrame([40, 0, 0], [0, 0, 1], [0, 1, 0])
plane5 = rs.PlaneFromFrame([-12, 15, 35], [1, 0, .50], [0, 1, -.4])
plane6 = rs.PlaneFromFrame([0, 5, 17], [1, 0, .50], [0, 1, -.4])
#plane2 = rs.AddPlaneSurface (plane1, 50, 50)

x = rs.AddPoint(-11, 15, 35)
y = rs.AddPoint(1, 0, .50)
z = rs.AddPoint(0, 1, -.4)
j = 0
plane11 = rs.RotatePlane(plane1, 0, [0, 1, 0])
#for i in range(50):

#plane11 = rs.RotatePlane(plane1, j, [0,1,0])
#j=j+10
#rs.AddRectangle( plane11, 25.0, 25.0 )
#rs.AddCircle( plane11, 25.0 )
#rs.AddSphere ( plane11, 25.0 )

#plane11 = rs.RotatePlane(plane1, j, [0,0,1])
#j=j+10
#rs.AddRectangle( plane11, 25.0, 25.0 )

#rs.AddSphere ( plane11, 50.0 )\
head = rs.AddSphere(plane11, 25.0)
                arrBoxPoints = [[offsetX, offsetY, offsetZ],[offsetX + panelData[i][0].GetPanelProperty("PanelWidth"), offsetY, offsetZ],\
                    [offsetX, offsetY, offsetZ+panelData[i][0].GetPanelProperty("PanelHeight")],\
                    [offsetX + panelData[i][0].GetPanelProperty("PanelWidth"), offsetY, offsetZ+panelData[i][0].GetPanelProperty("PanelHeight")]]

                blockCount = len(
                    panelData[i][0].GetPanelProperty("BlockInstances"))
                panelCounter += blockCount
                #create text info
                if drawGeometry:
                    panelName = panelName.replace(" ", "\n\r", 1)
                    prevLayer = rs.CurrentLayer()
                    if not rs.IsLayer("GEO::_Canvas"):
                        rs.AddLayer("GEO::_Canvas")
                    rs.CurrentLayer("GEO::_Canvas")
                    txtPlane = rs.PlaneFromFrame(
                        rs.PointSubtract(arrBoxPoints[0],
                                         [0, 0, rowSeparation / 2]), (1, 0, 0),
                        (0, 0, 1))
                    textTypes.append(
                        rs.AddText(panelName + "\n\rCount: " + str(blockCount),
                                   txtPlane,
                                   fontHeight,
                                   font_style=fontStyle))
                    rs.CurrentLayer(prevLayer)
                #create panel copy
                Mockup_Bay.append(SGLibPanel())
                Mockup_Bay[len(Mockup_Bay) - 1].Copy(panelData[i][0])
                panelPoints = Mockup_Bay[len(Mockup_Bay) - 1].GetPanelProperty(
                    "PanelCornerPoints")
                alignXform = rc.Geometry.Transform.Translation(
                    -min(panelPoints[0].X, panelPoints[2].X), 0, 0)
                tmpBoxPts = rs.PointArrayTransform(arrBoxPoints, alignXform)
Esempio n. 14
0
def ImportNearMaps():
    try:

        def scale():
            system = rs.UnitSystem()
            if system == 2 or system == 3 or system == 4:
                scaleFactorDict = {2: 1000, 3: 100, 4: 1}
                scaleFactor = scaleFactorDict[system]
                return scaleFactor

            if system != 2 or system != 3 or system != 4:
                return None

        def get_image_size(fname):
            '''Determine the image type of fhandle and return its size.
            from draco'''
            with open(fname, 'rb') as fhandle:
                head = fhandle.read(24)
                if len(head) != 24:
                    return
                if imghdr.what(fname) == 'png':
                    check = struct.unpack('>i', head[4:8])[0]
                    if check != 0x0d0a1a0a:
                        return
                    width, height = struct.unpack('>ii', head[16:24])
                elif imghdr.what(fname) == 'gif':
                    width, height = struct.unpack('<HH', head[6:10])
                elif imghdr.what(fname) == 'jpeg':
                    try:
                        fhandle.seek(0)  # Read 0xff next
                        size = 2
                        ftype = 0
                        while not 0xc0 <= ftype <= 0xcf:
                            fhandle.seek(size, 1)
                            byte = fhandle.read(1)
                            while ord(byte) == 0xff:
                                byte = fhandle.read(1)
                            ftype = ord(byte)
                            size = struct.unpack('>H', fhandle.read(2))[0] - 2
                        # We are at a SOFn block
                        fhandle.seek(1, 1)  # Skip `precision' byte.
                        height, width = struct.unpack('>HH', fhandle.read(4))
                    except Exception:  # IGNORE:W0703
                        return
                else:
                    return
                return width, height

        if scale() == None:
            rs.MessageBox(
                "This tool is can only be used in mm, cm or m model units")
            return None

        factor = scale()

        # Find and open jgw file, extract scalefactor and x and y coordinates

        jgw = rs.OpenFileName(title='Select .JGW file',
                              filter="JGW Files (*.JGW)|*.JGW||")

        with open(jgw, 'rt') as f:
            numslist = f.read().splitlines()

        scaleFactor01 = numslist[0]

        worldx = float(numslist[4]) * int(factor)
        worldy = float(numslist[5]) * int(factor)

        # Find and open jpg file, extract pixel size

        jpg = rs.OpenFileName(title='Select .JPG image File',
                              filter="JPG Files (*.JPG)|*.JPG||")

        size = get_image_size(jpg)

        scaleFactor02 = (float(size[0]) * int(factor))
        scaleFactor03 = (float(size[1]) * int(factor))

        # Calculate scale factor

        scaleFactorWidth = (float(scaleFactor01)) * (float(scaleFactor02))
        scaleFactorHeight = (float(scaleFactor01)) * (float(scaleFactor03))

        origin = (float(worldx), (float(worldy) - float(scaleFactorHeight)), 0)

        picturePlane = rs.PlaneFromFrame(origin, (1, 0, 0), (0, 1, 0))

        rs.AddPictureFrame(picturePlane,
                           jpg,
                           width=(float(scaleFactorWidth)),
                           height=(float(scaleFactorHeight)))

    except:
        print("Failed to execute")
        rs.EnableRedraw(True)
        return
Esempio n. 15
0
def RedrawNetwork(path):
    # open text file
    m = open(path, 'r')
    # read first line of text file; length of the domain
    l = m.readline()
    # convert length to float
    length = float(l)
    # read the second line of the domain; shape of the fracture
    shape = m.readline().split()
    #corners = ([(0,0,0),(length,0,0),(length,length,0),(0,length,0),(0,0,length),(length,0,length),(length,length,length),(0,length,length)])
    #rs.AddBox(corners)
    # create the domain
    dom = Domain.Domain(length)
    # display the domain
    dom.Show()
    if shape[0] != 'polygon':
        # a list to store GUIDs of regenerated fractures
        frac_list = []
        # list to store the x_axis of the fracture plane
        x_axis = []
        # list to store the y_axis of the fracture plane
        y_axis = []
        # list to store the origin of the fracture location
        origin = []
        # list to store the size of fracture
        size = []
        # read file line by line
        for line in m:
            # split line by comma
            words = line.split(",")
            #if words[0] != 'circle':
            # append the origin, x_axis and y_axis values in each line
            origin.append(float(words[0]))
            origin.append(float(words[1]))
            origin.append(float(words[2]))
            x_axis.append(float(words[3]))
            x_axis.append(float(words[4]))
            x_axis.append(float(words[5]))
            y_axis.append(float(words[6]))
            y_axis.append(float(words[7]))
            y_axis.append(float(words[8]))
            size.append(float((words[9])))
            # if the shape is ellipse, we have two radii, so append the second radius
            if shape[0] == 'ellipse':
                size.append(float((words[10])))
        # close file
        m.close()
        # display fractures if they are circles/disks
        if shape[0] == 'circle':
            n = 0
            # go through the lists of origin, x_axis and y_axis
            # we divide by 3, because the list contains 3 consecutive values
            # representing a single origin, x_axis or y_axis
            for i in range(int(len(origin) / 3)):
                # lists to store the origin, x_axis and y_axis of each fracture
                o = []
                x = []
                y = []
                # append the origin, x_axis and y_axis of each fracture
                for j in range(3):
                    o.append(origin[n + j])
                    x.append(x_axis[n + j])
                    y.append(y_axis[n + j])
                # convert the origin, x_axis and y_axis to a plane
                plane = rs.PlaneFromFrame(o, x, y)
                # name the current layer
                # we are creating layers so that we can trim out of bounds fractures
                # the function that does this makes use of the layer names
                layer_name = "FRACTURE_" + str(i + 1)
                # give the layer a color
                rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
                # make layer the current layer
                rs.CurrentLayer(layer_name)
                # draw fracture
                my_disk = rs.AddCircle(plane, size[i])
                # convert to a surface
                surf = rs.AddPlanarSrf(my_disk)
                #delete initial fracture drawn which is a curve
                rs.DeleteObject(my_disk)
                # append fracture
                frac_list.append(surf)
                # increment n used for parsing
                n += 3
            # trim out of bounds fractures
            # the function all creates new fractures at the locations of all
            # exixting fractures
            dom.RemoveSurfacesOutsideOfBox(length)
            # delete all old fractures
            for frac in frac_list:
                rs.DeleteObject(frac)
            dom_frac = dom.my_fractures  #get the fractures in the domain
            #print(dom_frac)
            #swap old guids with new ones and put new guids in old frac layers
            #new_frac_guids = Frac.NewFracturesGuids(dom_frac,frac_list)

        # display fractures if they are ellipse
        if shape[0] == 'ellipse':
            # lists to store the origin, x_axis and y_axis of each fracture
            n = 0
            p = 0
            q = 1
            # go through the lists of origin, x_axis and y_axis
            # we divide by 3, because the list contains 3 consecutive values
            # representing a single origin, x_axis or y_axis
            for i in range(int(len(origin) / 3)):
                o = []
                x = []
                y = []
                # append the origin, x_axis and y_axis of each fracture
                for j in range(3):
                    o.append(origin[n + j])
                    x.append(x_axis[n + j])
                    y.append(y_axis[n + j])
                # convert the origin, x_axis and y_axis to a plane
                plane = rs.PlaneFromFrame(o, x, y)
                # name the current layer
                # we are creating layers so that we can trim out of bounds fractures
                # the function that does this makes use of the layer names
                layer_name = "FRACTURE_" + str(i + 1)
                # give the layer a color
                rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
                # make layer current layer
                rs.CurrentLayer(layer_name)
                # draw fracture
                my_frac = rs.AddEllipse(plane, size[i + p], size[i + q])
                # convert to a surface from curve
                surf = rs.AddPlanarSrf(my_frac)
                # delete initial fracture drawn which is a curve
                rs.DeleteObject(my_frac)
                # append fracture
                frac_list.append(surf)
                # increment varaiables used for parsing
                n += 3
                p += 1
                q += 1
            # trim out of bounds fractures
            dom.RemoveSurfacesOutsideOfBox(length)
            # delete old fractures
            for frac in frac_list:
                rs.DeleteObject(frac)
            dom_frac = dom.my_fractures

    if shape[0] == 'polygon':
        # list to store origin
        origin = []
        # list to store number of sides of each polygon
        size = []
        # list to store number of angle of deviation of each polygon
        angle = []
        # list to store fractures
        frac_list = []
        # list to store points
        points = []
        for line in m:
            # split each line by comma
            words = line.split(",")
            # store the number of sides of the polygon
            size.append(float(words[-1]))
            # store the angle of deviation
            angle.append(float(words[-2]))
            # stpre the origin
            origin.extend(
                (float(words[-5]), float(words[-4]), float(words[-3])))
            # length of all points on the line
            # this will ensure we capture lines with disparate points when
            # generating polygon of different sides
            ex = int(3 * (size[-1] + 1))
            # store all points on the line
            points.extend((words[:ex]))
        # close file
        m.close()

        # variables to use for parsing
        n = 0
        m = 0
        # iterate for the number of fractures generated
        for i in range(len(size)):
            # list to store points and origin
            o = []
            p = []
            # get the origin of the fracture
            for j in range(3):
                o.append(origin[n + j])
            # variable for parsing
            r = 0
            # get the points of fracture edges
            for k in range(int(size[i]) + 1):
                p.append([])
                for l in range(3):
                    p[k].append(float(points[m + l + r]))
                # increment r
                r += 3
            # increment parsing variables
            m += ((int(size[i]) + 1) * 3)
            n += 3
            # name the current layer
            # we are creating layers so that we can trim out of bounds fractures
            # the function that does this makes use of the layer names
            layer_name = "FRACTURE_" + str(i + 1)
            # give the layer a color
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            # make layer the current layer
            rs.CurrentLayer(layer_name)
            # joing the points
            poly = rs.AddPolyline(p)
            # roatate the fracture
            frac = rs.RotateObject(poly, o, angle[i], [0, 1, 0])
            # convert to a surface
            surf = rs.AddPlanarSrf(frac)
            #delete initial fracture drawn which is a curve
            rs.DeleteObject(frac)
            frac_list.append(surf)
        # trim out of bounds fractures
        # the function all creates new fractures at the locations of all
        # exixting fractures
        dom.RemoveSurfacesOutsideOfBox(length)
        # delete all old fractures
        for fr in frac_list:
            rs.DeleteObject(fr)
        dom_frac = dom.my_fractures
    return dom_frac
Esempio n. 16
0
# Load the Optitrack CSV file parser module.
import optitrack.csv_reader as csv
from optitrack.geometry import *

# Find the path to the test data file located alongside the script.
filename = os.path.join( os.path.abspath(os.path.dirname(__file__)), "sample_optitrack_take.csv")

# Read the file.
take = csv.Take().readCSV(filename)

# Print out some statistics
print "Found rigid bodies:", take.rigid_bodies.keys()

# Process the first rigid body into a set of planes.
bodies = take.rigid_bodies.values()

# for now:
xaxis = [1,0,0]
yaxis = [0,1,0]

if len(bodies) > 0:
    body = bodies[0]
    for pos,rot in zip(body.positions, body.rotations):
        if pos is not None and rot is not None:
            xaxis, yaxis = quaternion_to_xaxis_yaxis(rot)
            plane = rs.PlaneFromFrame(pos, xaxis, yaxis)

            # create a visible plane, assuming units are in meters
            rs.AddPlaneSurface( plane, 0.1, 0.1 )
Esempio n. 17
0
depth = 2.133

currentl = rs.CurrentLayer("Heel_0")

copy0 = rs.CopyObject(hull)
rs.ObjectLayer(copy0, "Heel_0")

rs.LayerVisible("Default", False)

#####################################################
####                                             ####
#### Creating DWL and obtaining submerged volume ####
####                                             ####
#####################################################

aux_plane = rs.PlaneFromFrame( [-5,-50,draft], [1,0,0], [0,1,0] )
dwl = rs.AddPlaneSurface(aux_plane, 100, 100)

inter = rs.BooleanIntersection(copy0, dwl, False)

Nabla = rs.SurfaceVolumeCentroid(inter)
if Nabla:
    cb = rs.AddPoint(Nabla[0])

Volume0 = rs.SurfaceVolume(inter)
Initial_Volume = Volume0[0]

####################################
####                            ####
#### Heeled volume calculations ####
####                            ####
Esempio n. 18
0
        def makeFireStair(rect, landingLevels):
            #HARD VARIABLES
            minGapSize = .2
            minTread = .260
            maxRiser = .180
            thickness = .15

            #(1)Determine Run Direction
            rs.SimplifyCurve(rect)
            rectSegments = rs.ExplodeCurves(rect)
            edge1 = rectSegments[0]
            edge3 = rectSegments[1]
            rs.DeleteObject(rectSegments[2])
            rs.DeleteObject(rectSegments[3])
            if rs.CurveLength(edge1) > rs.CurveLength(edge3):
                longEdge = edge1
                shortEdge = edge3
            else:
                longEdge = edge3
                shortEdge = edge1
            longVec = rs.VectorCreate(rs.CurveStartPoint(longEdge),
                                      rs.CurveEndPoint(longEdge))
            longVecRev = rs.VectorReverse(longVec)
            shortVec = rs.VectorCreate(rs.CurveStartPoint(shortEdge),
                                       rs.CurveEndPoint(shortEdge))
            shortVecRev = rs.VectorReverse(shortVec)
            rs.CurveArrows(longEdge, 2)
            rs.CurveArrows(shortEdge, 2)

            #(2)Stair Width
            stairWidth = (rs.CurveLength(shortEdge) - minGapSize) / 2

            #LandingRect
            landing1Plane = rs.PlaneFromFrame(rs.CurveStartPoint(shortEdge),
                                              shortVecRev, longVecRev)
            landing1 = rs.AddRectangle(landing1Plane,
                                       rs.CurveLength(shortEdge), stairWidth)
            landing2Plane = rs.PlaneFromFrame(rs.CurveEndPoint(longEdge),
                                              shortVec, longVec)
            landing2 = rs.AddRectangle(landing2Plane,
                                       rs.CurveLength(shortEdge), stairWidth)

            #(3)Run Length
            runLength = rs.CurveLength(longEdge) - (stairWidth * 2)

            #RunRects
            run1Plane = rs.PlaneFromFrame(
                rs.CurveEditPoints(landing1)[3], shortVecRev, longVecRev)
            run1Rect = rs.AddRectangle(run1Plane, stairWidth, runLength)
            run2Plane = rs.PlaneFromFrame(
                rs.CurveEditPoints(landing2)[3], shortVec, longVec)
            run2Rect = rs.AddRectangle(run2Plane, stairWidth, runLength)

            #(4)Num Flights between Landings
            numLevels = len(landingLevels)
            deltaLevels = []
            runsPerLevel = []
            maxRisersPerRun = math.floor(runLength / minTread)
            numRuns = 0

            for i in range(0, numLevels - 1):
                deltaLevels.append(landingLevels[i + 1] - landingLevels[i])
                minNumRisers = math.ceil(deltaLevels[i] / maxRiser)
                runsPerLevel.append(math.ceil(minNumRisers / maxRisersPerRun))
                numRuns = numRuns + int(runsPerLevel[i])

            #(5) Which flights

            listOfRuns = []
            for i in range(0, numRuns):
                if i % 2:  #if even
                    listOfRuns.append(rs.CopyObject(run1Rect))
                else:
                    listOfRuns.append(rs.CopyObject(run2Rect))

            #(6) Num Treads per run
            runsDeltaHeight = []
            for i in range(0, numLevels - 1):
                for j in range(0, int(runsPerLevel[i])):
                    runsDeltaHeight.append(deltaLevels[i] / runsPerLevel[i])

            numRisersPerRun = []
            for i in range(0, numRuns):
                numRisersPerRun.append(math.ceil(runsDeltaHeight[i] /
                                                 maxRiser))

            #(7) Move Runs
            elevation = 0
            landings = []
            for i in range(0, numRuns):
                elevation = elevation + runsDeltaHeight[i]
                translation = rs.VectorCreate([0, 0, elevation], [0, 0, 0])
                rs.MoveObject(listOfRuns[i], translation)
                if i % 2:
                    landings.append(
                        rs.MoveObject(rs.CopyObject(landing2), translation))
                else:
                    landings.append(
                        rs.MoveObject(rs.CopyObject(landing1), translation))

            #(8) Make Landings
            stairGeo = []
            for i in range(0, numRuns):
                dir = rs.VectorCreate([0, 0, 0], [0, 0, runsDeltaHeight[i]])
                #rs.MoveObject(landings[i], dir)
                path = rs.AddLine([0, 0, 0], [0, 0, -thickness])
                geo = rs.ExtrudeCurve(landings[i], path)
                rs.CapPlanarHoles(geo)
                stairGeo.append(geo)
                rs.DeleteObject(path)
            rs.DeleteObjects(landings)

            #(9) Draw Stairs
            runs = []
            for i in range(0, numRuns):
                runs.append(
                    Run(listOfRuns[i], runsDeltaHeight[i], numRisersPerRun[i]))
                stairGeo.append(runs[i].make())

            finalGeo = rs.BooleanUnion(stairGeo, delete_input=True)
            #Cleanup
            rs.DeleteObjects(listOfRuns)
            rs.DeleteObjects(rectSegments)
            rs.DeleteObject(landing1)
            rs.DeleteObject(landing2)
            rs.DeleteObject(run1Rect)
            rs.DeleteObject(run2Rect)
            print "done"
            return finalGeo
    def outbox(self, gap):
        #DEFINE BASE SLICE------------>
        rec_lr = rs.AddRectangle(rs.WorldYZPlane(), self.data[0], self.data[1])
        srf_lr = rs.AddPlanarSrf(rec_lr)
        rec_lr = rs.MoveObject(
            rec_lr, rs.VectorCreate(ZERO,
                                    rs.SurfaceAreaCentroid(srf_lr)[0]))
        rs.DeleteObject(srf_lr)
        rec_lr = cutrec(2, rec_lr, gap)
        srf_lr = rs.AddPlanarSrf(rec_lr)
        rs.DeleteObjects(rec_lr)
        ### CANNOT USE WORLDZX()---------->
        xz = rs.PlaneFromFrame([0, 0, 0], [1, 0, 0], [0, 0, 1])
        rec_fk = rs.AddRectangle(xz, self.data[2], self.data[3])
        ###<-------------
        srf_fk = rs.AddPlanarSrf(rec_fk)
        rec_fk = rs.MoveObject(
            rec_fk, rs.VectorCreate(ZERO,
                                    rs.SurfaceAreaCentroid(srf_fk)[0]))
        rs.DeleteObject(srf_fk)
        rec_fk = cutrec(2, rec_fk, gap)
        srf_fk = rs.AddPlanarSrf(rec_fk)
        rs.DeleteObjects(rec_fk)
        rec_tb = rs.AddRectangle(rs.WorldXYPlane(), self.data[5], self.data[4])
        srf_tb = rs.AddPlanarSrf(rec_tb)
        rec_tb = rs.MoveObject(
            rec_tb, rs.VectorCreate(ZERO,
                                    rs.SurfaceAreaCentroid(srf_tb)[0]))
        rs.DeleteObject(srf_tb)
        rec_tb = cutrec(1, rec_tb, 0)
        srf_tb = rs.AddPlanarSrf(rec_tb)
        rs.DeleteObject(rec_tb)

        #CONSTRUCT THE BOX-------------------->
        srfs = []
        srfs.append(rs.CopyObject(srf_tb, [0, 0, self.data[3] / 2.0]))
        srfs.append(rs.CopyObject(srf_tb, [0, 0, self.data[3] / (-2.0)]))
        srfs.append(rs.CopyObject(srf_fk, [0, self.data[0] / 2.0, 0]))
        srfs.append(
            rs.MirrorObject(
                rs.CopyObject(srf_fk, [0, self.data[0] / (-2.0), 0]),
                [0, 1, 0], [0, 0, 1]))
        srfs.append(rs.CopyObject(srf_lr, [self.data[5] / (-2.0), 0, 0]))
        srfs.append(
            rs.MirrorObject(
                rs.CopyObject(srf_lr, [self.data[5] / (2.0), 0, 0]), [1, 0, 0],
                [0, 0, 1]))

        bele = []
        for srf in srfs:
            extvec = rs.VectorCreate(ZERO, rs.SurfaceAreaCentroid(srf)[0])
            max, sign, loc = 0, -1, 0
            for i in range(len(extvec)):
                if abs(extvec[i]) > max:
                    max = abs(extvec[i])
                    sign = extvec[i]
                    loc = i
            if loc == 0:
                line = rs.AddLine(
                    ZERO, rs.VectorScale(rs.VectorUnitize([sign, 0, 0]), cut2))
                bele.append(rs.ExtrudeSurface(srf, line))
            elif loc == 1:
                line = rs.AddLine(
                    ZERO, rs.VectorScale(rs.VectorUnitize([0, sign, 0]), cut2))
                bele.append(rs.ExtrudeSurface(srf, line))
            elif loc == 2:
                line = rs.AddLine(
                    ZERO, rs.VectorScale(rs.VectorUnitize([0, 0, sign]), cut2))
                bele.append(rs.ExtrudeSurface(srf, line))
            rs.DeleteObject(line)
        rs.DeleteObjects(srfs)
        rs.DeleteObjects([srf_lr, srf_fk, srf_tb])
        return bele
import rhinoscriptsyntax as rs
all = rs.AllObjects()
rs.DeleteObjects(all)

plane1 = rs.PlaneFromFrame([0, 0, 0], [0, 1, 0], [1, 0, 0])
plane2 = rs.PlaneFromFrame([0, 0, 6], [0, 1, 0], [1, 0, 0])
plane3 = rs.PlaneFromFrame([0, 0, 40], [0, 1, 0], [1, 0, 0])

nose = rs.AddCone(plane2, 6, 20, cap=True)
nose2 = rs.AddCone(plane3, 24, 5, cap=True)
hat1 = rs.AddCylinder(plane1, 110, 20, cap=True)
hat2 = rs.AddCylinder(plane1, -6, 10, cap=True)
hat3 = rs.AddCylinder(plane2, -10, 12, cap=True)
##neck=rs.AddCylinder ((0,0,-35), 10, 5, cap=True)