Exemple #1
0
def AddHatches(curve_ids, hatch_pattern=None, scale=1.0, rotation=0.0):
    """Creates one or more new hatch objects a list of closed planar curves
    Parameters:
      curve_ids = identifiers of the closed planar curves that defines the
          boundary of the hatch objects
      hatch_pattern[opt] = name of the hatch pattern to be used by the hatch
          object. If omitted, the current hatch pattern will be used
      scale[opt] = hatch pattern scale factor
      rotation[opt] = hatch pattern rotation angle in degrees.
    Returns:
      identifiers of the newly created hatch on success
      None on error
    """
    id = rhutil.coerceguid(curve_ids, False)
    if id: curve_ids = [id]
    index = scriptcontext.doc.HatchPatterns.CurrentHatchPatternIndex
    if hatch_pattern and hatch_pattern!=index:
        if isinstance(hatch_pattern, int):
            index = hatch_pattern
        else:
            index = scriptcontext.doc.HatchPatterns.Find(hatch_pattern, True)
        if index<0: return scriptcontext.errorhandler()
    curves = [rhutil.coercecurve(id, -1, True) for id in curve_ids]
    rotation = Rhino.RhinoMath.ToRadians(rotation)
    hatches = Rhino.Geometry.Hatch.Create(curves, index, rotation, scale)
    if not hatches: return scriptcontext.errorhandler()
    ids = []
    for hatch in hatches:
        id = scriptcontext.doc.Objects.AddHatch(hatch)
        if id==System.Guid.Empty: continue
        ids.append(id)
    if not ids: return scriptcontext.errorhandler()
    scriptcontext.doc.Views.Redraw()
    return ids
Exemple #2
0
def TextObjectStyle(object_id, style=None):
    """Returns or modifies the font style of a text object
    Parameters:
      object_id = the identifier of a text object
      style [opt] = the font style. Can be any of the following flags
         0 = Normal
         1 = Bold
         2 = Italic
    Returns:
      if style is not specified, the current font style
      if style is specified, the previous font style
      None if not successful, or on Error
    """
    annotation = rhutil.coercegeometry(object_id, True)
    if not isinstance(annotation, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    fontdata = scriptcontext.doc.Fonts[annotation.FontIndex]
    if fontdata is None: return scriptcontext.errorhandler()
    rc = 0
    if fontdata.Bold: rc += 1
    if fontdata.Italic: rc += 2
    if style is not None and style!=rc:
        index = scriptcontext.doc.Fonts.FindOrCreate( fontdata.FaceName, (style&1)==1, (style&2)==2 )
        annotation.FontIndex = index
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #3
0
def SpotLightShadowIntensity(object_id, intensity=None):
    """Returns or changes the shadow intensity of a spot light.
    Parameters:
      object_id = the light object's identifier
      intensity[opt] = the light's new intensity
    Returns:
      if intensity is not specified, the current intensity
      if intensity is specified, the previous intensity
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a light", rs.filter.light)
      if id: rs.SpotLightShadowIntensity(id, 0.75)
    See Also:
      AddSpotLight
      IsSpotLight
      SpotLightHardness
      SpotLightRadius
    """
    light = __coercelight(object_id, True)
    if light.LightStyle!=Rhino.Geometry.LightStyle.WorldSpot:
        return scriptcontext.errorhandler()
    rc = light.SpotLightShadowIntensity
    if intensity and intensity!=rc:
        light.SpotLightShadowIntensity = intensity
        id = rhutil.coerceguid(object_id, True)
        if not scriptcontext.doc.Lights.Modify(id, light):
            return scriptcontext.errorhandler()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #4
0
def TextObjectFont(object_id, font=None):
    """Returns of modifies the font used by a text object
    Parameters:
      object_id = the identifier of a text object
      font [opt] = the new font face name
    Returns:
      if a font is not specified, the current font face name
      if a font is specified, the previous font face name
      None if not successful, or on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text")
      if rs.IsText(obj): rs.TextObjectFont(obj, "Arial")
    See Also:
      AddText
      IsText
      TextObjectHeight
      TextObjectPlane
      TextObjectPoint
      TextObjectStyle
      TextObjectText
    """
    annotation = rhutil.coercegeometry(object_id, True)
    if not isinstance(annotation, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    fontdata = scriptcontext.doc.Fonts[annotation.FontIndex]
    if fontdata is None: return scriptcontext.errorhandler()
    rc = fontdata.FaceName
    if font:
        index = scriptcontext.doc.Fonts.FindOrCreate( font, fontdata.Bold, fontdata.Italic )
        annotation.FontIndex = index
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #5
0
def ObjectGripLocation(object_id, index, point=None):
    """Returns or modifies the location of an object's grip
    Parameters:
      object_id = identifier of the object
      index = index of the grip to either query or modify
      point [opt] = 3D point defining new location of the grip
    Returns:
      if point is not specified, the current location of the grip referenced by index
      if point is specified, the previous location of the grip referenced by index
      None on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select curve", rs.filter.curve)
      if obj:
      rs.EnableObjectGrips(obj)
      point = rs.ObjectGripLocation(obj, 0)
      rs.ObjectGripLocation(obj, 0, point)
      rs.EnableObjectGrips(obj, False)
    See Also:
      EnableObjectGrips
      ObjectGripLocations
    """
    rhobj = rhutil.coercerhinoobject(object_id, True, True)
    if not rhobj.GripsOn: return scriptcontext.errorhandler()
    grips = rhobj.GetGrips()
    if not grips or index<0 or index>=grips.Length:
        return scriptcontext.errorhandler()
    grip = grips[index]
    rc = grip.CurrentLocation
    if point:
        grip.CurrentLocation = rhutil.coerce3dpoint(point, True)
        scriptcontext.doc.Objects.GripUpdate(rhobj, True)
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #6
0
def UnselectObjectGrips(object_id):
    """Unselects an object's grips. Note, the grips will not be turned off.
    Parameters:
      object_id = identifier of the object
    Returns:
      Number of grips unselected on success
      None on failure
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select object")
      if rs.ObjectGripsSelected(obj): rs.UnselectObjectGrips(obj)
    See Also:
      EnableObjectGrips
      ObjectGripCount
      UnselectObjectGrip
    """
    rhobj = rhutil.coercerhinoobject(object_id, True, True)
    if not rhobj.GripsOn: return scriptcontext.errorhandler()
    grips = rhobj.GetGrips()
    if grips is None: return scriptcontext.errorhandler()
    count = 0
    for grip in grips:
        if grip.Select(False)==0: count += 1
    if count>0:
        scriptcontext.doc.Views.Redraw()
        return count
    return scriptcontext.errorhandler()
Exemple #7
0
def RenameGroup(old_name, new_name):
    """Renames an existing group
    Parameters:
      old_name = the name of an existing group
      new_name = the new group name
    Returns:
      the new group name if successful
      None on error
    Example:
      import rhinoscriptsyntax as rs
      strOldGroup = rs.GetString("Old group name")
      if strOldGroup:
      strNewGroup = rs.GetString("New group name")
      if strNewName: rs.RenameGroup(strOldGroup, strNewGroup)
    See Also:
      AddGroup
      DeleteGroup
      GroupCount
      GroupNames
      IsGroup
    """
    if not isinstance(old_name, str): old_name = str(old_name)
    index = scriptcontext.doc.Groups.Find(old_name, True)
    if index<0: return scriptcontext.errorhandler()
    if not isinstance(new_name, str): new_name = str(new_name)
    if scriptcontext.doc.Groups.ChangeGroupName(index, new_name):
        return new_name
    return scriptcontext.errorhandler()
Exemple #8
0
def AddAlignedDimension(start_point, end_point, point_on_dimension_line, style=None):
    """Adds an aligned dimension object to the document. An aligned dimension
    is a linear dimension lined up with two points
    Parameters:
      start_point: first point of dimension
      end_point: second point of dimension
      point_on_dimension_line: location point of dimension line
      style[opt]: name of dimension style
    Returns:
      identifier of new dimension on success
      None on error
    """
    start = rhutil.coerce3dpoint(start_point, True)
    end = rhutil.coerce3dpoint(end_point, True)
    onpoint = rhutil.coerce3dpoint(point_on_dimension_line, True)
    plane = Rhino.Geometry.Plane(start, end, onpoint)
    success, s, t = plane.ClosestParameter(start)
    start = Rhino.Geometry.Point2d(s,t)
    success, s, t = plane.ClosestParameter(end)
    end = Rhino.Geometry.Point2d(s,t)
    success, s, t = plane.ClosestParameter(onpoint)
    onpoint = Rhino.Geometry.Point2d(s,t)
    ldim = Rhino.Geometry.LinearDimension(plane, start, end, onpoint)
    if not ldim: return scriptcontext.errorhandler()
    ldim.Aligned = True
    if style:
        ds = scriptcontext.doc.DimStyles.Find(style, True)
        if ds is None: return scriptcontext.errorhandler()
        ldim.DimensionStyleIndex = ds.Index
    rc = scriptcontext.doc.Objects.AddLinearDimension(ldim)
    if rc==System.Guid.Empty: raise Exception("unable to add dimension to document")
    scriptcontext.doc.Views.Redraw()
    return rc
Exemple #9
0
def HatchPattern(hatch_id, hatch_pattern=None):
    """Returns or changes a hatch object's hatch pattern
    Parameters:
      hatch_id = identifier of a hatch object
      hatch_pattern[opt] = name of an existing hatch pattern to replace the
          current hatch pattern
    Returns:
      if hatch_pattern is not specified, the current hatch pattern
      if hatch_pattern is specified, the previous hatch pattern
      None on error
    Example:
      import rhinoscriptsyntax as rs
      objects = rs.AllObjects()
      if objects is not None:
      for obj in objects:
      if rs.IsHatch(obj) and rs.HatchPattern(obj)=="Solid":
      rs.SelectObject(obj)
    See Also:
      AddHatch
      AddHatches
      HatchRotation
      HatchScale
      IsHatch
    """
    hatchobj = rhutil.coercerhinoobject(hatch_id, True, True)
    if not isinstance(hatchobj, Rhino.DocObjects.HatchObject):
        return scriptcontext.errorhandler()
    old_index = hatchobj.HatchGeometry.PatternIndex
    if hatch_pattern:
        new_index = scriptcontext.doc.HatchPatterns.Find(hatch_pattern, True)
        if new_index<0: return scriptcontext.errorhandler()
        hatchobj.HatchGeometry.PatternIndex = new_index
        hatchobj.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return scriptcontext.doc.HatchPatterns[old_index].Name
Exemple #10
0
def ExplodeHatch(hatch_id, delete=False):
    """Explodes a hatch object into its component objects. The exploded objects
    will be added to the document. If the hatch object uses a solid pattern,
    then planar face Brep objects will be created. Otherwise, line curve objects
    will be created
    Parameters:
      hatch_id = identifier of a hatch object
      delete[opt] = delete the hatch object
    Returns:
      list of identifiers for the newly created objects
      None on error
    """
    rhobj = rhutil.coercerhinoobject(hatch_id, True, True)
    if not isinstance(rhobj, Rhino.DocObjects.HatchObject):
        return scriptcontext.errorhandler()
    pieces = rhobj.HatchGeometry.Explode()
    if not pieces: return scriptcontext.errorhandler()
    attr = rhobj.Attributes
    rc = []
    for piece in pieces:
        id = None
        if isinstance(piece, Rhino.Geometry.Curve):
            id = scriptcontext.doc.Objects.AddCurve(piece, attr)
        elif isinstance(piece, Rhino.Geometry.Brep):
            id = scriptcontext.doc.Objects.AddBrep(piece, attr)
        if id: rc.append(id)
    return rc
Exemple #11
0
def AddHatchPatterns(filename, replace=False):
    """Adds hatch patterns to the document by importing hatch pattern definitions
    from a pattern file.
    Parameters:
      filename = name of the hatch pattern file
      replace[opt] = If hatch pattern names already in the document match hatch
          pattern names in the pattern definition file, then the existing hatch
          patterns will be redefined
    Returns:
      Names of the newly added hatch patterns if successful
      None on error
    Example:
      import rhinoscriptsyntax as rs
      filename = rs.OpenFileName("Import", "Pattern Files (*.pat)|*.pat||")
      if filename:
      patterns = rs.AddHatchPatterns(filename)
      if patterns:
      for pattern in patterns: print pattern
    See Also:
      HatchPatternCount
      HatchPatternNames
    """
    patterns = Rhino.DocObjects.HatchPattern.ReadFromFile(filename, True)
    if not patterns: return scriptcontext.errorhandler()
    rc = []
    for pattern in patterns:
         index = scriptcontext.doc.HatchPatterns.Add(pattern)
         if index>=0:
             pattern = scriptcontext.doc.HatchPatterns[index]
             rc.append(pattern.Name)
    if not rc: return scriptcontext.errorhandler()
    return rc
Exemple #12
0
def SpotLightRadius(object_id, radius=None):
    """Returns or changes the radius of a spot light.
    Parameters:
      object_id = the light object's identifier
      radius[opt] = the light's new radius
    Returns:
      if radius is not specified, the current radius
      if radius is specified, the previous radius
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a light", rs.filter.light)
      if id: rs.SpotLightRadius(id, 5.0)
    See Also:
      AddSpotLight
      IsSpotLight
      SpotLightHardness
      SpotLightShadowIntensity
    """
    light = __coercelight(object_id, True)
    if light.LightStyle!=Rhino.Geometry.LightStyle.WorldSpot:
        return scriptcontext.errorhandler()
    radians = light.SpotAngleRadians
    rc = light.Direction.Length * math.tan(radians)
    if radius and radius!=rc:
        radians = math.atan(radius/light.Direction.Length)
        light.SpotAngleRadians = radians
        id = rhutil.coerceguid(object_id, True)
        if not scriptcontext.doc.Lights.Modify(id, light):
            return scriptcontext.errorhandler()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #13
0
def ObjectGripLocations(object_id, points=None):
    """Returns or modifies the location of all grips owned by an object. The
    locations of the grips are returned in a list of Point3d with each position
    in the list corresponding to that grip's index. To modify the locations of
    the grips, you must provide a list of points that contain the same number
    of points at grips
    Parameters:
      object_id = identifier of the object
      points [opt] = list of 3D points identifying the new grip locations
    Returns:
      if points is not specified, the current location of all grips
      if points is specified, the previous location of all grips
      None if not successful
    """
    rhobj = rhutil.coercerhinoobject(object_id, True, True)
    if not rhobj.GripsOn: return scriptcontext.errorhandler()
    grips = rhobj.GetGrips()
    if grips is None: return scriptcontext.errorhandler()
    rc = [grip.CurrentLocation for grip in grips]
    if points and len(points)==len(grips):
        points = rhutil.coerce3dpointlist(points, True)
        for i, grip in enumerate(grips):
            point = points[i]
            grip.CurrentLocation = point
        scriptcontext.doc.Objects.GripUpdate(rhobj, True)
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #14
0
def RenameView(old_title, new_title):
    """Changes the title of the specified view
    Parameters:
      old_title: the title or identifier of the view to rename
      new_title: the new title of the view
    Returns:
      the view's previous title if successful
      None on error
    """
    if not old_title or not new_title: return scriptcontext.errorhandler()
    old_id = rhutil.coerceguid(old_title)
    foundview = None
    allviews = scriptcontext.doc.Views.GetViewList(True, True)
    for view in allviews:
        if old_id:
            if view.MainViewport.Id==old_id:
                foundview = view
                break
        elif view.MainViewport.Name==old_title:
            foundview = view
            break
    if foundview is None: return scriptcontext.errorhandler()
    old_title = foundview.MainViewport.Name
    foundview.MainViewport.Name = new_title
    return old_title
Exemple #15
0
def SpotLightHardness(object_id, hardness=None):
    """Returns or changes the hardness of a spot light. Spotlight hardness
    controls the fully illuminated region.
    Parameters:
      object_id = the light object's identifier
      hardness[opt] = the light's new hardness
    Returns:
      if hardness is not specified, the current hardness
      if hardness is specified, the previous hardness
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a light", rs.filter.light)
      if id: rs.SpotLightHardness(id, 0.75)
    See Also:
      AddSpotLight
      IsSpotLight
      SpotLightRadius
      SpotLightShadowIntensity
    """
    light = __coercelight(object_id, True)
    if light.LightStyle!=Rhino.Geometry.LightStyle.WorldSpot:
        return scriptcontext.errorhandler()
    rc = light.HotSpot
    if hardness and hardness!=rc:
        light.HotSpot = hardness
        id = rhutil.coerceguid(object_id, True)
        if not scriptcontext.doc.Lights.Modify(id, light):
            return scriptcontext.errorhandler()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #16
0
def BoundingBox(objects, view_or_plane=None, in_world_coords=True):
    """Returns either world axis-aligned or a construction plane axis-aligned
    bounding box of an object or of several objects
    Parameters:
      objects = The identifiers of the objects
      view_or_plane[opt] = Title or id of the view that contains the
          construction plane to which the bounding box should be aligned -or-
          user defined plane. If omitted, a world axis-aligned bounding box
          will be calculated
      in_world_coords[opt] = return the bounding box as world coordinates or
          construction plane coordinates. Note, this option does not apply to
          world axis-aligned bounding boxes.
    Returns:
      Eight 3D points that define the bounding box. Points returned in counter-
      clockwise order starting with the bottom rectangle of the box.
      None on error
    """
    def __objectbbox(object, xform):
        geom = rhutil.coercegeometry(object, False)
        if not geom:
            pt = rhutil.coerce3dpoint(object, True)
            return Rhino.Geometry.BoundingBox(pt,pt)
        if xform: return geom.GetBoundingBox(xform)
        return geom.GetBoundingBox(True)

    xform = None
    plane = rhutil.coerceplane(view_or_plane)
    if plane is None and view_or_plane:
        view = view_or_plane
        modelviews = scriptcontext.doc.Views.GetStandardRhinoViews()
        for item in modelviews:
            viewport = item.MainViewport
            if type(view) is str and viewport.Name==view:
                plane = viewport.ConstructionPlane()
                break
            elif type(view) is System.Guid and viewport.Id==view:
                plane = viewport.ConstructionPlane()
                break
        if plane is None: return scriptcontext.errorhandler()
    if plane:
        xform = Rhino.Geometry.Transform.ChangeBasis(Rhino.Geometry.Plane.WorldXY, plane)
    bbox = Rhino.Geometry.BoundingBox.Empty
    if type(objects) is list or type(objects) is tuple:
        for object in objects:
            objectbbox = __objectbbox(object, xform)
            bbox = Rhino.Geometry.BoundingBox.Union(bbox,objectbbox)
    else:
        objectbbox = __objectbbox(objects, xform)
        bbox = Rhino.Geometry.BoundingBox.Union(bbox,objectbbox)
    if not bbox.IsValid: return scriptcontext.errorhandler()

    corners = list(bbox.GetCorners())
    if in_world_coords and plane is not None:
        plane_to_world = Rhino.Geometry.Transform.ChangeBasis(plane, Rhino.Geometry.Plane.WorldXY)
        for pt in corners: pt.Transform(plane_to_world)
    return corners
def AddMaterialToObject(object_id, attr):
    # Assigns Texture to geometry
    object_id = rhutil.coerceguid(object_id)
    if( object_id==None ): return scriptcontext.errorhandler()
    
    objref = Rhino.DocObjects.ObjRef(object_id)
    rhino_object = objref.Object()
    objref.Dispose()
    if( rhino_object==None ): return scriptcontext.errorhandler()

    scriptcontext.doc.Objects.ModifyAttributes(rhino_object, attr, True)
    scriptcontext.doc.Views.Redraw();
Exemple #18
0
def ViewTitle(view_id):
    """Returns the name, or title, of a given view's identifier
    Parameters:
      view_id: String or Guid. The identifier of the view
    Returns:
      name or title of the view on success
      None on error
    """
    view_id = rhutil.coerceguid(view_id)
    if view_id is None: return scriptcontext.errorhandler()
    view = scriptcontext.doc.Views.Find(view_id)
    if view is None: return scriptcontext.errorhandler()
    return view.MainViewport.Name
Exemple #19
0
def ObjectGripCount(object_id):
    """Returns number of grips owned by an object
    Parameters:
      object_id = identifier of the object
    Returns:
      number of grips if successful
      None on error  
    """
    rhobj = rhutil.coercerhinoobject(object_id, True, True)
    if not rhobj.GripsOn: return scriptcontext.errorhandler()
    grips = rhobj.GetGrips()
    if not grips: return scriptcontext.errorhandler()
    return grips.Length
Exemple #20
0
def AddLeader(points, view_or_plane=None, text=None):
    """Adds a leader to the document. Leader objects are planar.
    The 3D points passed to this function should be co-planar
    Parameters:
      points = list of (at least 2) 3D points
      view_or_plane [opt] = If a view is specified, points will be constrained
        to the view's construction plane. If a view is not specified, points
        will be constrained to a plane fit through the list of points
      text [opt] = leader's text string
    Returns:
      identifier of the new leader on success
      None on error
    Example:
      import rhinoscriptsyntax as rs
      points = rs.GetPoints(True, False, "Select leader points")
      if points: rs.AddLeader( points )
    See Also:
      IsLeader
      LeaderText
    """
    points = rhutil.coerce3dpointlist(points)
    if points is None or len(points)<2: raise ValueError("points must have at least two items")
    rc = System.Guid.Empty
    view = None
    if text and not isinstance(text, str): 
        text = str(text)

    if not view_or_plane:
        if len(points) == 2:
            plane = scriptcontext.doc.Views.ActiveView.ActiveViewport.ConstructionPlane()
            rc = scriptcontext.doc.Objects.AddLeader(text, plane, [Rhino.Geometry.Point2d(p.X, p.Y) for p in points])
        else:
            rc = scriptcontext.doc.Objects.AddLeader(text, points)
    else:
        plane = rhutil.coerceplane(view_or_plane)
        if not plane:
            view = __viewhelper(view_or_plane)
            plane = view.ActiveViewport.ConstructionPlane()
        points2d = []
        for point in points:
            cprc, s, t = plane.ClosestParameter( point )
            if not cprc: return scriptcontext.errorhandler()
            points2d.append( Rhino.Geometry.Point2d(s,t) )
        if text is None:
            rc = scriptcontext.doc.Objects.AddLeader(plane, points2d)
        else:
            if not isinstance(text, str): text = str(text)
            rc = scriptcontext.doc.Objects.AddLeader(text, plane, points2d)
    if rc==System.Guid.Empty: return scriptcontext.errorhandler()
    scriptcontext.doc.Views.Redraw()
    return rc
def PointArrayBoundingBox(points, view_or_plane=None, in_world_coords=True):
    """Returns either a world axis-aligned or a construction plane axis-aligned 
    bounding box of an array of 3-D point locations.
    Parameters:
      points = A list of 3-D points
      view_or_plane[opt] = Title or id of the view that contains the
          construction plane to which the bounding box should be aligned -or-
          user defined plane. If omitted, a world axis-aligned bounding box
          will be calculated
      in_world_coords[opt] = return the bounding box as world coordinates or
          construction plane coordinates. Note, this option does not apply to
          world axis-aligned bounding boxes.
    Returns:
      Eight 3D points that define the bounding box. Points returned in counter-
      clockwise order starting with the bottom rectangle of the box.
      None on error
    Example:
      
    See Also:
      BoundingBox
    """
    points = rhutil.coerce3dpointlist(points)
    if not points:
      return None
    bbox = Rhino.Geometry.BoundingBox(points)

    xform = None
    plane = rhutil.coerceplane(view_or_plane)
    if plane is None and view_or_plane:
        view = view_or_plane
        modelviews = scriptcontext.doc.Views.GetStandardRhinoViews()
        for item in modelviews:
            viewport = item.MainViewport
            if type(view) is str and viewport.Name==view:
                plane = viewport.ConstructionPlane()
                break
            elif type(view) is System.Guid and viewport.Id==view:
                plane = viewport.ConstructionPlane()
                break
        if plane is None: return scriptcontext.errorhandler()
    if plane:
        xform = Rhino.Geometry.Transform.ChangeBasis(Rhino.Geometry.Plane.WorldXY, plane)
        bbox = xform.TransformBoundingBox(bbox)
    if not bbox.IsValid: return scriptcontext.errorhandler()

    corners = list(bbox.GetCorners())
    if in_world_coords and plane is not None:
        plane_to_world = Rhino.Geometry.Transform.ChangeBasis(plane, Rhino.Geometry.Plane.WorldXY)
        for pt in corners: pt.Transform(plane_to_world)
    return corners
Exemple #22
0
def CurrentDetail(layout, detail=None, return_name=True):
    """Returns or changes the current detail view in a page layout view
    Parameters:
      layout = title or identifier of an existing page layout view
      detail[opt] = title or identifier the the detail view to set
      return_name[opt] = return title if True, else return identifier
    Returns:
      if detail is not specified, the title or id of the current detail view
      if detail is specified, the title or id of the previous detail view
      None on error
    """
    layout_id = rhutil.coerceguid(layout)
    page = None
    if layout_id is None: page = scriptcontext.doc.Views.Find(layout, False)
    else: page = scriptcontext.doc.Views.Find(layout_id)
    if page is None: return scriptcontext.errorhandler()
    rc = None
    active_viewport = page.ActiveViewport
    if return_name: rc = active_viewport.Name
    else: rc = active_viewport.Id
    if detail:
        id = rhutil.coerceguid(detail)
        if( (id and id==page.MainViewport.Id) or (id is None and detail==page.MainViewport.Name) ):
            page.SetPageAsActive()
        else:
            if id: page.SetActiveDetail(id)
            else: page.SetActiveDetail(detail, False)
    scriptcontext.doc.Views.Redraw()
    return rc
Exemple #23
0
def GetPoint(message=None, base_point=None, distance=None, in_plane=False):
    """Pauses for user input of a point.
    Parameters:
      message [opt] = A prompt or message.
      base_point [opt] = list of 3 numbers or Point3d identifying a starting, or base point
      distance  [opt] = constraining distance. If distance is specified, basePoint must also
                        be sepcified.
      in_plane [opt] = constrains the point selections to the active construction plane.
    Returns:
      point on success
      None if no point picked or user canceled
    """
    gp = Rhino.Input.Custom.GetPoint()
    if message: gp.SetCommandPrompt(message)
    base_point = rhutil.coerce3dpoint(base_point)
    if base_point:
        gp.DrawLineFromPoint(base_point,True)
        gp.EnableDrawLineFromPoint(True)
        if distance: gp.ConstrainDistanceFromBasePoint(distance)
    if in_plane: gp.ConstrainToConstructionPlane(True)
    gp.Get()
    if gp.CommandResult()!=Rhino.Commands.Result.Success:
        return scriptcontext.errorhandler()
    pt = gp.Point()
    gp.Dispose()
    return pt
Exemple #24
0
def AddMaterialToLayer(layer):
    """Add material to a layer and returns the new material's index. If the
    layer already has a material, then the layer's current material index is
    returned
    Parameters:
      layer = name of an existing layer.
    Returns:
      Material index of the layer if successful
      None if not successful or on error
    Example:
      import rhinoscriptsyntax as rs
      layer = rs.CurrentLayer()
      index = rs.LayerMaterialIndex(layer)
    See Also:
      LayerMaterialIndex
      IsMaterialDefault
    """
    layer = __getlayer(layer, True)
    if layer.RenderMaterialIndex>-1: return layer.RenderMaterialIndex
    material_index = scriptcontext.doc.Materials.Add()
    layer.RenderMaterialIndex = material_index
    if scriptcontext.doc.Layers.Modify( layer, layer.LayerIndex, True):
        scriptcontext.doc.Views.Redraw()
        return material_index
    return scriptcontext.errorhandler()
Exemple #25
0
def GetPointOnSurface(surface_id, message=None):
    """Pauses for user input of a point constrained to a surface or polysurface
    object
    Parameters:
      surface_id = identifier of the surface to get a point on
      message [opt] = a prompt or message
    Returns:
      3d point if successful
      None on error
    """
    surfOrBrep = rhutil.coercesurface(surface_id)
    if not surfOrBrep:
        surfOrBrep = rhutil.coercebrep(surface_id, True)
    gp = Rhino.Input.Custom.GetPoint()
    if message: gp.SetCommandPrompt(message)
    if isinstance(surfOrBrep,Rhino.Geometry.Surface):
        gp.Constrain(surfOrBrep,False)
    else:
        gp.Constrain(surfOrBrep, -1, -1, False)
    gp.Get()
    if gp.CommandResult()!=Rhino.Commands.Result.Success:
        return scriptcontext.errorhandler()
    pt = gp.Point()
    gp.Dispose()
    return pt
Exemple #26
0
def Angle2(line1, line2):
    """Measures the angle between two lines
    Parameters:
      line1 = List of 6 numbers or 2 Point3d.
      line2 = List of 6 numbers or 2 Point3d.
    Returns:
      A tuple containing the following elements if successful.
        0 The angle in degrees.
        1 The reflex angle in degrees.
        None If not successful, or on error.
    Example:
      import rhinoscriptsyntax as rs
      point1 = rs.GetPoint("Start of first line")
      point2 = rs.GetPoint("End of first line", point1)
      point3 = rs.GetPoint("Start of second line")
      point4 = rs.GetPoint("End of second line", point3)
      angle = rs.Angle2( (point1, point2), (point3, point4))
      if angle: print "Angle: ", angle
    See Also:
      Angle
      Distance
    """
    line1 = coerceline(line1, True)
    line2 = coerceline(line2, True)
    vec0 = line1.To - line1.From
    vec1 = line2.To - line2.From
    if not vec0.Unitize() or not vec1.Unitize(): return scriptcontext.errorhandler()
    dot = vec0 * vec1
    dot = clamp(-1,1,dot)
    angle = math.acos(dot)
    reflex_angle = 2.0*math.pi - angle
    angle = math.degrees(angle)
    reflex_angle = math.degrees(reflex_angle)
    return angle, reflex_angle
Exemple #27
0
def ViewRadius(view=None, radius=None, mode=False):
    """Returns or sets the radius of a parallel-projected view. Useful
    when you need an absolute zoom factor for a parallel-projected view
    Parameters:
      view:[opt] title or id of the view. If omitted, current active view is used
      radius:[opt] the view radius
      mode: [opt] perform a "dolly" magnification by moving the camera 
        towards/away from the target so that the amount of the screen 
        subtended by an object changes.  true = perform a "zoom" 
        magnification by adjusting the "lens" angle
    Returns:
      if radius is not specified, the current view radius for the specified view
      if radius is specified, the previous view radius for the specified view
    """
    view = __viewhelper(view)
    viewport = view.ActiveViewport
    if not viewport.IsParallelProjection: return scriptcontext.errorhandler()
    fr = viewport.GetFrustum()
    frus_right = fr[2]
    frus_top = fr[4]
    old_radius = min(frus_top, frus_right)
    if radius is None: return old_radius
    magnification_factor = radius / old_radius
    d = 1.0 / magnification_factor
    viewport.Magnify(d, mode)
    view.Redraw()
    return old_radius
Exemple #28
0
def AddDetail(layout_id, corner1, corner2, title=None, projection=1):
    """Add new detail view to an existing layout view
    Parameters:
      layout_id = identifier of an existing layout
      corner1, corner2 = 2d corners of the detail in the layout's unit system
      title[opt] = title of the new detail
      projection[opt] = type of initial view projection for the detail
          1 = parallel top view
          2 = parallel bottom view
          3 = parallel left view
          4 = parallel right view
          5 = parallel front view
          6 = parallel back view
          7 = perspective view
    Returns:
      identifier of the newly created detial on success
      None on error
    """
    layout_id = rhutil.coerceguid(layout_id, True)
    corner1 = rhutil.coerce2dpoint(corner1, True)
    corner2 = rhutil.coerce2dpoint(corner2, True)
    if projection<1 or projection>7: raise ValueError("projection must be a value between 1-7")
    layout = scriptcontext.doc.Views.Find(layout_id)
    if not layout: raise ValueError("no layout found for given layout_id")
    projection = System.Enum.ToObject(Rhino.Display.DefinedViewportProjection, projection)
    detail = layout.AddDetailView(title, corner1, corner2, projection)
    if not detail: return scriptcontext.errorhandler()
    scriptcontext.doc.Views.Redraw()
    return detail.Id
Exemple #29
0
def ObjectLayer(object_id, layer=None):
    """Returns or modifies the layer of an object
    Parameters:
      object_id = the identifier of the object(s)
      layer[opt] = name of an existing layer
    Returns:
      If a layer is not specified, the object's current layer
      If a layer is specified, the object's previous layer
      If object_id is a list or tuple, the number of objects modified
    """
    if type(object_id) is not str and hasattr(object_id, "__len__"):
        layer = __getlayer(layer, True)
        index = layer.LayerIndex
        for id in object_id:
            obj = rhutil.coercerhinoobject(id, True, True)
            obj.Attributes.LayerIndex = index
            obj.CommitChanges()
        scriptcontext.doc.Views.Redraw()
        return len(object_id)
    obj = rhutil.coercerhinoobject(object_id, True, True)
    if obj is None: return scriptcontext.errorhandler()
    index = obj.Attributes.LayerIndex
    rc = scriptcontext.doc.Layers[index].FullPath
    if layer:
        layer = __getlayer(layer, True)
        index = layer.LayerIndex
        obj.Attributes.LayerIndex = index
        obj.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #30
0
def IsDetail(layout, detail):
    """Verifies that a detail view exists on a page layout view
    Parameters:
      layout: title or identifier of an existing page layout
      detail: title or identifier of an existing detail view
    Returns:
      True if detail is a detail view
      False if detail is not a detail view
      None on error
    """
    layout_id = rhutil.coerceguid(layout)
    views = scriptcontext.doc.Views.GetViewList(False, True)
    found_layout = None
    for view in views:
        if layout_id:
            if view.MainViewport.Id==layout_id:
                found_layout = view
                break
        elif view.MainViewport.Name==layout:
            found_layout = view
            break
    # if we couldn't find a layout, this is an error
    if found_layout is None: return scriptcontext.errorhandler()
    detail_id = rhutil.coerceguid(detail)
    details = view.GetDetailViews()
    if not details: return False
    for detail_view in details:
        if detail_id:
            if detail_view.Id==detail_id: return True
        else:
            if detail_view.Name==detail: return True
    return False
Exemple #31
0
def AddPlanarMesh(object_id, delete_input=False):
    """Creates a planar mesh from a closed, planar curve
    Parameters:
      object_id = identifier of a closed, planar curve
      delete_input[opt] = if True, delete the input curve defined by object_id
    Returns:
      id of the new mesh on success
      None on error
    """
    curve = rhutil.coercecurve(object_id, -1, True)
    mesh = Rhino.Geometry.Mesh.CreateFromPlanarBoundary(curve, Rhino.Geometry.MeshingParameters.Default)
    if not mesh: return scriptcontext.errorhandler()
    rc = scriptcontext.doc.Objects.AddMesh(mesh)
    if rc==System.Guid.Empty: raise Exception("unable to add mesh to document")
    scriptcontext.doc.Views.Redraw()
    return rc
Exemple #32
0
def AddNamedView(name, view=None):
    """Adds a new named view to the document
    Parameters:
      name: the name of the new named view
      view: [opt] the title or identifier of the view to save. If omitted, the current
            active view is saved
    Returns:
      name fo the newly created named view if successful
      None on error
    """
    view = __viewhelper(view)
    if not name: raise ValueError("name is empty")
    viewportId = view.MainViewport.Id
    index = scriptcontext.doc.NamedViews.Add(name, viewportId)
    if index < 0: return scriptcontext.errorhandler()
    return name
def XformRotation3(start_direction, end_direction, center_point):
    """Calculate the minimal transformation that rotates start_direction to
    end_direction while fixing center_point
    Parameters:
      start_direction, end_direction = 3d vectors
      center_point = the rotation center
    Returns:
      The 4x4 transformation matrix.
      None on error.
    """
    start = rhutil.coerce3dvector(start_direction, True)
    end = rhutil.coerce3dvector(end_direction, True)
    center = rhutil.coerce3dpoint(center_point, True)
    xform = Rhino.Geometry.Transform.Rotation(start, end, center)
    if not xform.IsValid: return scriptcontext.errorhandler()
    return xform
Exemple #34
0
def AddLinearDimension(start_point, end_point, point_on_dimension_line):
    """Adds a linear dimension to the document
    Returns:
      identifier of the new object on success
      None on error
    """
    start = rhutil.coerce3dpoint(start_point, True)
    end = rhutil.coerce3dpoint(end_point, True)
    onpoint = rhutil.coerce3dpoint(point_on_dimension_line, True)
    ldim = Rhino.Geometry.LinearDimension.FromPoints(start, end, onpoint)
    if not ldim: return scriptcontext.errorhandler()
    rc = scriptcontext.doc.Objects.AddLinearDimension(ldim)
    if rc == System.Guid.Empty:
        raise Exception("unable to add dimension to document")
    scriptcontext.doc.Views.Redraw()
    return rc
Exemple #35
0
def RotatePlane(plane, angle_degrees, axis):
    """Rotates a plane
    Parameters:
      plane = OnPlane or On3dmConstructionPlane
      angle_degrees = rotation angle in degrees
      axis = On3dVector or list of three numbers
    Returns:
      rotated plane on success
      None on error
    """
    plane = rhutil.coerceplane(plane, True)
    axis = rhutil.coerce3dvector(axis, True)
    angle_radians = math.radians(angle_degrees)
    rc = Rhino.Geometry.Plane(plane)
    if rc.Rotate(angle_radians, axis): return rc
    return scriptcontext.errorhandler()
Exemple #36
0
def AddNamedCPlane(cplane_name, view=None):
    """Adds new named construction plane to the document
    Parameters:
      cplane_name: the name of the new named construction plane
      view:[opt] string or Guid. Title or identifier of the view from which to save
               the construction plane. If omitted, the current active view is used.
    Returns:
      name of the newly created construction plane if successful
      None on error
    """
    view = __viewhelper(view)
    if not cplane_name: raise ValueError("cplane_name is empty")
    plane = view.MainViewport.ConstructionPlane()
    index = scriptcontext.doc.NamedConstructionPlanes.Add(cplane_name, plane)
    if index < 0: return scriptcontext.errorhandler()
    return cplane_name
Exemple #37
0
def AddHatch(curve_id, hatch_pattern=None, scale=1.0, rotation=0.0):
    """Creates a new hatch object from a closed planar curve object
    Parameters:
      curve_id = identifier of the closed planar curve that defines the
          boundary of the hatch object
      hatch_pattern[opt] = name of the hatch pattern to be used by the hatch
          object. If omitted, the current hatch pattern will be used
      scale[opt] = hatch pattern scale factor
      rotation[opt] = hatch pattern rotation angle in degrees.
    Returns:
      identifier of the newly created hatch on success
      None on error
    """
    rc = AddHatches(curve_id, hatch_pattern, scale, rotation)
    if rc: return rc[0]
    return scriptcontext.errorhandler()
Exemple #38
0
def Angle(point1, point2, plane=True):
    """Measures the angle between two points
    Parameters:
      point1, point2: the input points
      plane[opt] = Boolean or Plane
        If True, angle calculation is based on the world coordinate system.
        If False, angle calculation is based on the active construction plane
        If a plane is provided, angle calculation is with respect to this plane
    Returns:
      tuple containing the following elements if successful
        element 0 = the X,Y angle in degrees
        element 1 = the elevation
        element 2 = delta in the X direction
        element 3 = delta in the Y direction
        element 4 = delta in the Z direction
      None if not successful
    """
    pt1 = coerce3dpoint(point1)
    if pt1 is None:
        pt1 = coercerhinoobject(point1)
        if isinstance(pt1, Rhino.DocObjects.PointObject): pt1 = pt1.Geometry.Location
        else: pt1=None
    pt2 = coerce3dpoint(point2)
    if pt2 is None:
        pt2 = coercerhinoobject(point2)
        if isinstance(pt2, Rhino.DocObjects.PointObject): pt2 = pt2.Geometry.Location
        else: pt2=None
    point1 = pt1
    point2 = pt2
    if point1 is None or point2 is None: return scriptcontext.errorhandler()
    vector = point2 - point1
    x = vector.X
    y = vector.Y
    z = vector.Z
    if plane!=True:
        plane = coerceplane(plane)
        if plane is None:
            plane = scriptcontext.doc.Views.ActiveView.ActiveViewport.ConstructionPlane()
        vfrom = point1 - plane.Origin
        vto = point2 - plane.Origin
        x = vto * plane.XAxis - vfrom * plane.XAxis
        y = vto * plane.YAxis - vfrom * plane.YAxis
        z = vto * plane.ZAxis - vfrom * plane.ZAxis
    h = math.sqrt( x * x + y * y)
    angle_xy = math.degrees( math.atan2( y, x ) )
    elevation = math.degrees( math.atan2( z, h ) )
    return angle_xy, elevation, x, y, z
def XformRotation1(initial_plane, final_plane):
    """Returns a rotation transformation that maps initial_plane to final_plane.
    The planes should be right hand orthonormal planes.
    Parameters:
      initial_plane (plane): plane to rotate from
      final_plane (plane): plane to rotate to
    Returns:
      transform: The 4x4 transformation matrix.
      None: on error.
    Example:
    See Also:
    """
    initial_plane = rhutil.coerceplane(initial_plane, True)
    final_plane = rhutil.coerceplane(final_plane, True)
    xform = Rhino.Geometry.Transform.PlaneToPlane(initial_plane, final_plane)
    if not xform.IsValid: return scriptcontext.errorhandler()
    return xform
Exemple #40
0
def MeshOffset(mesh_id, distance):
    """Makes a new mesh with vertices offset at a distance in the opposite
    direction of the existing vertex normals
    Parameters:
      mesh_id = identifier of a mesh object
      distance = the distance to offset
    Returns:
      id of the new mesh object if successful
      None on error
    """
    mesh = rhutil.coercemesh(mesh_id, True)
    offsetmesh = mesh.Offset(distance)
    if offsetmesh is None: return scriptcontext.errorhandler()
    rc = scriptcontext.doc.Objects.AddMesh(offsetmesh)
    if rc==System.Guid.Empty: raise Exception("unable to add mesh to document")
    scriptcontext.doc.Views.Redraw()
    return rc
Exemple #41
0
def RestoreNamedCPlane(cplane_name, view=None):
    """Restores a named construction plane to the specified view.
    Parameters:
      cplane_name: name of the construction plane to restore
      view: [opt] the title or identifier of the view. If omitted, the current
            active view is used
    Returns:
      name of the restored named construction plane if successful
      None on error
    """
    view = __viewhelper(view)
    index = scriptcontext.doc.NamedConstructionPlanes.Find(cplane_name)
    if index < 0: return scriptcontext.errorhandler()
    cplane = scriptcontext.doc.NamedConstructionPlanes[index]
    view.MainViewport.PushConstructionPlane(cplane)
    view.Redraw()
    return cplane_name
Exemple #42
0
def CurrentDimStyle(dimstyle_name=None):
    """
    Returns or changes the current default dimension style
    Parameters:
      dimstyle_name[opt] = name of an existing dimension style to make current
    Returns:
      if dimstyle_name is not specified, name of the current dimension style
      if dimstyle_name is specified, name of the previous dimension style
      None on error
    """
    rc = scriptcontext.doc.DimStyles.CurrentDimensionStyle.Name
    if dimstyle_name:
        ds = scriptcontext.doc.DimStyles.Find(dimstyle_name, True)
        if ds is None: return scriptcontext.errorhandler()
        scriptcontext.doc.DimStyles.SetCurrentDimensionStyleIndex(
            ds.Index, False)
    return rc
Exemple #43
0
def ViewNames(return_names=True, view_type=0):
    """Return the names, titles, or identifiers of all views in the document
    Parameters:
      return_names: [opt] if True then the names of the views are returned.
        If False, then the identifiers of the views are returned
      view_type: [opt] the type of view to return
                       0 = standard model views
                       1 = page layout views
                       2 = both standard and page layout views
    Returns:
      list of the view names or identifiers on success
      None on error
    """
    views = scriptcontext.doc.Views.GetViewList(view_type != 1, view_type > 0)
    if views is None: return scriptcontext.errorhandler()
    if return_names: return [view.MainViewport.Name for view in views]
    return [view.MainViewport.Id for view in views]
Exemple #44
0
def MaterialName(material_index, name=None):
    """Returns or modifies a material's user defined name
    Parameters:
      material_index = zero based material index
      name[opt] = the new name
    Returns:
      if name is not specified, the current material name
      if name is specified, the previous material name
      None on error
    """
    mat = scriptcontext.doc.Materials[material_index]
    if mat is None: return scriptcontext.errorhandler()
    rc = mat.Name
    if name:
        mat.Name = name
        mat.CommitChanges()
    return rc
Exemple #45
0
def RectangularLightPlane(object_id):
    """Returns the plane of a rectangular light object
    Parameters:
      object_id = the light object's identifier
    Returns:
      the plane if successful
      None on error
    """
    light = __coercelight(object_id, True)
    if light.LightStyle != Rhino.Geometry.LightStyle.WorldRectangular:
        return scriptcontext.errorhandler()
    location = light.Location
    length = light.Length
    width = light.Width
    direction = light.Direction
    plane = Rhino.Geometry.Plane(location, length, width)
    return plane, (length.Length, width.Length)
Exemple #46
0
def GetSurfaceObject(message="select surface", preselect=False, select=False):
    """Prompts the user to select a single surface
    Parameters:
      message[opt] = prompt displayed
      preselect[opt] = allow for preselected objects
      select[opt] = select the picked object
    Returns:
      tuple of information on success
        element 0 = identifier of the surface
        element 1 = True if the surface was preselected, otherwise False
        element 2 = selection method ( see help )
        element 3 = selection point
        element 4 = u,v surface parameter of the selection point
        element 5 = name of the view in which the selection was made
      None on error
    """
    if not preselect:
        scriptcontext.doc.Objects.UnselectAll()
        scriptcontext.doc.Views.Redraw()
    go = Rhino.Input.Custom.GetObject()
    go.SetCommandPrompt(message)
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Surface
    go.SubObjectSelect = False
    go.GroupSelect = False
    go.AcceptNothing(True)
    if go.Get() != Rhino.Input.GetResult.Object:
        return scriptcontext.errorhandler()
    objref = go.Object(0)
    rhobj = objref.Object()
    rhobj.Select(select)
    scriptcontext.doc.Views.Redraw()

    id = rhobj.Id
    prepicked = go.ObjectsWerePreselected
    selmethod = objref.SelectionMethod()
    point = objref.SelectionPoint()
    surf, u, v = objref.SurfaceParameter()
    uv = (u, v)
    if not point.IsValid:
        point = None
        uv = None
    view = go.View()
    name = view.ActiveViewport.Name
    go.Dispose()
    return id, prepicked, selmethod, point, uv, name
Exemple #47
0
def GetBoolean(message, items, defaults):
    """Pauses for user input of one or more boolean values. Boolean values are
    displayed as click-able command line option toggles
    Parameters:
      message (str): a prompt
      items ([str, str, str], ...): list or tuple of options. Each option is a tuple of three strings
        [n][1]    description of the boolean value. Must only consist of letters
                  and numbers. (no characters like space, period, or dash
        [n][2]    string identifying the false value
        [n][3]    string identifying the true value
      defaults ([bool, ...]): list of boolean values used as default or starting values
    Returns:
      list(bool, ...): a list of values that represent the boolean values if successful
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      results = rs.GetBoolean("Boolean options", items, (True, True, True) )
      if results:
      for val in results: print val
    See Also:
      GetString
    """
    go = Rhino.Input.Custom.GetOption()
    go.AcceptNothing(True)
    go.SetCommandPrompt( message )
    if type(defaults) is list or type(defaults) is tuple: pass
    else: defaults = [defaults]
    # special case for single list. Wrap items into a list
    if len(items)==3 and len(defaults)==1: items = [items]
    count = len(items)
    if count<1 or count!=len(defaults): return scriptcontext.errorhandler()
    toggles = []
    for i in range(count):
        initial = defaults[i]
        item = items[i]
        offVal = item[1]
        t = Rhino.Input.Custom.OptionToggle( initial, item[1], item[2] )
        toggles.append(t)
        go.AddOptionToggle(item[0], t)
    while True:
        getrc = go.Get()
        if getrc==Rhino.Input.GetResult.Option: continue
        if getrc!=Rhino.Input.GetResult.Nothing: return None
        break
    return [t.CurrentValue for t in toggles]
def XformRotation4(x0, y0, z0, x1, y1, z1):
    """Returns a rotation transformation.
    Paramters:
      x0,y0,z0 = Vectors defining the initial orthonormal frame
      x1,y1,z1 = Vectors defining the final orthonormal frame
    Returns:
      The 4x4 transformation matrix.
      None on error.
    """
    x0 = rhutil.coerce3dveector(x0, True)
    y0 = rhutil.coerce3dveector(y0, True)
    z0 = rhutil.coerce3dveector(z0, True)
    x1 = rhutil.coerce3dveector(x1, True)
    y1 = rhutil.coerce3dveector(y1, True)
    z1 = rhutil.coerce3dveector(z1, True)
    xform = Rhino.Geometry.Transform.Rotation(x0, y0, z0, x1, y1, z1)
    if not xform.IsValid: return scriptcontext.errorhandler()
    return xform
Exemple #49
0
def DetailLock(detail_id, lock=None):
    """Returns or modifies the projection locked state of a detail
    Parameters:
      detail_id = identifier of a detail object
      lock[opt] = the new lock state
    Returns:
      if lock==None, the current detail projection locked state
      if lock is True or False, the previous detail projection locked state
      None on error
    """
    detail_id = rhutil.coerceguid(detail_id, True)
    detail = scriptcontext.doc.Objects.Find(detail_id)
    if not detail: return scriptcontext.errorhandler()
    rc = detail.DetailGeometry.IsProjectionLocked
    if lock is not None and lock != rc:
        detail.DetailGeometry.IsProjectionLocked = lock
        detail.CommitChanges()
    return rc
Exemple #50
0
def DimStyleTextGap(dimstyle, gap=None):
    """Returns or changes the text gap used by a dimension style
    Parameters:
      dimstyle = the name of an existing dimension style
      gap[opt] = the new text gap
    Returns:
      if gap is not specified, the current text gap
      if gap is specified, the previous text gap
      None on error
    """
    ds = scriptcontext.doc.DimStyles.Find(dimstyle, True)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.TextGap
    if gap is not None:
        ds.TextGap = gap
        ds.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #51
0
def AddGroup(group_name=None):
    """Adds a new empty group to the document
    Parameters:
      group_name[opt] = name of the new group. If omitted, rhino automatically
          generates the group name
    Returns:
      name of the new group if successful
      None is not successful or on error
    """
    index = -1
    if group_name is None:
        index = scriptcontext.doc.Groups.Add()
    else:
        if not isinstance(group_name, str): group_name = str(group_name)
        index = scriptcontext.doc.Groups.Add(group_name)
    rc = scriptcontext.doc.Groups.GroupName(index)
    if rc is None: return scriptcontext.errorhandler()
    return rc
Exemple #52
0
def DimStyleLeaderArrowSize(dimstyle, size=None):
    """Returns or changes the leader arrow size of a dimension style
    Parameters:
      dimstyle = the name of an existing dimension style
      size[opt] = the new leader arrow size
    Returns:
      if size is not specified, the current leader arrow size
      if size is specified, the previous leader arrow size
      None on error
    """
    ds = scriptcontext.doc.DimStyles.Find(dimstyle, True)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.LeaderArrowLength
    if size is not None:
        ds.LeaderArrowLength = size
        ds.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #53
0
def DimStyleTextHeight(dimstyle, height=None):
    """Returns or changes the text height used by a dimension style
    Parameters:
      dimstyle = the name of an existing dimension style
      height[opt] = the new text height
    Returns:
      if height is not specified, the current text height
      if height is specified, the previous text height
      None on error
    """
    ds = scriptcontext.doc.DimStyles.Find(dimstyle, True)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.TextHeight
    if height:
        ds.TextHeight = height
        ds.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #54
0
def CheckListBox(items, message=None, title=None):
    """Displays a list of items in a checkable-style list dialog box
    Parameters:
      items = a list of tuples containing a string and a boolean check state
      message[opt] = a prompt or message
      title[opt] = a dialog box title
    Returns:
      A list of tuples containing the input string in items along with their
      new boolean check value
      None on error      
    """
    checkstates = [item[1] for item in items]
    itemstrs = [str(item[0]) for item in items]
    newcheckstates = Rhino.UI.Dialogs.ShowCheckListBox(title, message, itemstrs, checkstates)
    if newcheckstates:
        rc = zip(itemstrs, newcheckstates)
        return rc
    return scriptcontext.errorhandler()
Exemple #55
0
def DimStyleAnglePrecision(dimstyle, precision=None):
    """Returns or changes the angle display precision of a dimension style
    Parameters:
      dimstyle = the name of an existing dimension style
      precision[opt] = the new angle precision value. If omitted, the current angle
        precision is returned
    Returns:
      If a precision is not specified, the current angle precision
      If a precision is specified, the previous angle precision
    """
    ds = scriptcontext.doc.DimStyles.Find(dimstyle, True)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.AngleResolution
    if precision is not None:
        ds.AngleResolution = precision
        ds.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #56
0
def DimStyleOffset(dimstyle, offset=None):
    """Returns or changes the extension line offset of a dimension style
    Parameters:
      dimstyle = the name of an existing dimension style
      offset[opt] = the new extension line offset
    Returns:
      if offset is not specified, the current extension line offset
      if offset is specified, the previous extension line offset
      None on error
    """
    ds = scriptcontext.doc.DimStyles.Find(dimstyle, True)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.ExtensionLineOffset
    if offset is not None:
        ds.ExtensionLineOffset = offset
        ds.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #57
0
def AddMaterialToLayer(layer):
    """Add material to a layer and returns the new material's index. If the
    layer already has a material, then the layer's current material index is
    returned
    Parameters:
      layer = name of an existing layer.
    Returns:
      Material index of the layer if successful
      None if not successful or on error
    """
    layer = __getlayer(layer, True)
    if layer.RenderMaterialIndex > -1: return layer.RenderMaterialIndex
    material_index = scriptcontext.doc.Materials.Add()
    layer.RenderMaterialIndex = material_index
    if scriptcontext.doc.Layers.Modify(layer, layer.LayerIndex, True):
        scriptcontext.doc.Views.Redraw()
        return material_index
    return scriptcontext.errorhandler()
def XformRotation2(angle_degrees, rotation_axis, center_point):
    """Returns a rotation transformation around an axis
    Parameters:
      angle_degrees (number): rotation angle in degrees
      rotation_axis (vector): rotation axis
      center_point (point): rotation center
    Returns:
      transform: The 4x4 transformation matrix.
      None: on error.
    Example:
    See Also:
    """
    axis = rhutil.coerce3dvector(rotation_axis, True)
    center = rhutil.coerce3dpoint(center_point, True)
    angle_rad = math.radians(angle_degrees)
    xform = Rhino.Geometry.Transform.Rotation(angle_rad, axis, center)
    if not xform.IsValid: return scriptcontext.errorhandler()
    return xform
Exemple #59
0
def LightName(object_id, name=None):
    """Returns or changes the name of a light object
    Parameters:
      object_id = the light object's identifier
      name[opt] = the light's new name
    Returns:
      if name is not specified, the current name
      if name is specified, the previous name
    """
    light = __coercelight(object_id, True)
    rc = light.Name
    if name and name != rc:
        light.Name = name
        id = rhutil.coerceguid(object_id, True)
        if not scriptcontext.doc.Lights.Modify(id, light):
            return scriptcontext.errorhandler()
        scriptcontext.doc.Views.Redraw()
    return rc
Exemple #60
0
def DimStyleLinearPrecision(dimstyle, precision=None):
    """Returns or changes the linear display precision of a dimension style
    Parameters:
      dimstyle = the name of an existing dimension style
      precision[opt] = the new linear precision value
    Returns:
      if precision is not specified, the current linear precision value
      if precision is specified, the previous linear precision value
      None on error
    """
    ds = scriptcontext.doc.DimStyles.Find(dimstyle, True)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.LengthResolution
    if precision is not None:
        ds.LengthResolution = precision
        ds.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc