#
tokens: 40404/50000 4/82 files (page 3/7)
lines: off (toggle) GitHub
raw markdown copy
This is page 3 of 7. Use http://codebase.md/jingcheng-chen/rhinomcp?lines=false&page={x} to view the full context.

# Directory Structure

```
├── .github
│   └── workflows
│       ├── mcp-server-publish.yml
│       └── rhino-plugin-publish.yml
├── .gitignore
├── assets
│   ├── claude_enable_instruction.jpg
│   ├── cursor_enable_instruction.jpg
│   ├── cursor_usage_instruction.jpg
│   ├── demo1.jpg
│   ├── demo2.jpg
│   ├── rhino_plugin_instruction.jpg
│   └── rhinomcp_logo.svg
├── demo_chats
│   ├── create_6x6x6_boxes.txt
│   └── create_rhinoceros_lego_blocks.txt
├── LICENSE
├── README.md
├── rhino_mcp_plugin
│   ├── .gitignore
│   ├── Commands
│   │   ├── MCPStartCommand.cs
│   │   ├── MCPStopCommand.cs
│   │   └── MCPVersionCommand.cs
│   ├── EmbeddedResources
│   │   └── plugin-utility.ico
│   ├── Functions
│   │   ├── _utils.cs
│   │   ├── CreateLayer.cs
│   │   ├── CreateObject.cs
│   │   ├── CreateObjects.cs
│   │   ├── DeleteLayer.cs
│   │   ├── DeleteObject.cs
│   │   ├── ExecuteRhinoscript.cs
│   │   ├── GetDocumentInfo.cs
│   │   ├── GetObjectInfo.cs
│   │   ├── GetOrSetCurrentLayer.cs
│   │   ├── GetSelectedObjectsInfo.cs
│   │   ├── ModifyObject.cs
│   │   ├── ModifyObjects.cs
│   │   └── SelectObjects.cs
│   ├── manifest.yml
│   ├── Properties
│   │   ├── AssemblyInfo.cs
│   │   └── launchSettings.json
│   ├── rhinomcp.csproj
│   ├── rhinomcp.sln
│   ├── RhinoMCPPlugin.cs
│   ├── RhinoMCPServer.cs
│   ├── RhinoMCPServerController.cs
│   └── Serializers
│       └── Serializer.cs
└── rhino_mcp_server
    ├── .gitignore
    ├── dev.sh
    ├── main.py
    ├── pyproject.toml
    ├── README.md
    ├── src
    │   └── rhinomcp
    │       ├── __init__.py
    │       ├── prompts
    │       │   └── assert_general_strategy.py
    │       ├── server.py
    │       ├── static
    │       │   └── rhinoscriptsyntax.py
    │       └── tools
    │           ├── create_layer.py
    │           ├── create_object.py
    │           ├── create_objects.py
    │           ├── delete_layer.py
    │           ├── delete_object.py
    │           ├── execute_rhinoscript_python_code.py
    │           ├── get_document_info.py
    │           ├── get_object_info.py
    │           ├── get_or_set_current_layer.py
    │           ├── get_rhinoscript_python_code_guide.py
    │           ├── get_rhinoscript_python_function_names.py
    │           ├── get_selected_objects_info.py
    │           ├── modify_object.py
    │           ├── modify_objects.py
    │           └── select_objects.py
    ├── static
    │   ├── application.py
    │   ├── block.py
    │   ├── compat.py
    │   ├── curve.py
    │   ├── dimension.py
    │   ├── document.py
    │   ├── geometry.py
    │   ├── grips.py
    │   ├── group.py
    │   ├── hatch.py
    │   ├── layer.py
    │   ├── light.py
    │   ├── line.py
    │   ├── linetype.py
    │   ├── material.py
    │   ├── mesh.py
    │   ├── object.py
    │   ├── plane.py
    │   ├── pointvector.py
    │   ├── selection.py
    │   ├── surface.py
    │   ├── toolbar.py
    │   ├── transformation.py
    │   ├── userdata.py
    │   ├── userinterface.py
    │   ├── utility.py
    │   └── view.py
    └── uv.lock
```

# Files

--------------------------------------------------------------------------------
/rhino_mcp_server/static/utility.py:
--------------------------------------------------------------------------------

```python
import time
import math
import string
import numbers
from operator import attrgetter

import System
import System.Drawing
import System.Windows.Forms

import Rhino

import rhinocompat as compat
import scriptcontext


def ContextIsRhino():
    """Return True if the script is being executed in the context of Rhino
    Returns:
      bool: True if the script is being executed in the context of Rhino
    Example:
      import rhinoscriptsyntax as  rs
      print(rs.ContextIsRhino())
    See Also:
      ContextIsGrasshopper
    """
    return scriptcontext.id == 1


def ContextIsGrasshopper():
    """Return True if the script is being executed in a grasshopper component
    Returns:
      bool: True if the script is being executed in a grasshopper component
    Example:
      import rhinoscriptsyntax as  rs
      print(rs.ContextIsGrasshopper())
    See Also:
      ContextIsRhino
    """
    return scriptcontext.id == 2


def Angle(point1, point2, plane=True):
    """Measures the angle between two points
    Parameters:
      point1, point2 (point): the input points
      plane (bool, optional): 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(tuple(number, number), number, number, number, number): 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
    Example:
      import rhinoscriptsyntax as  rs
      point1 = rs.GetPoint("First  point")
      if point1:
          point2  = rs.GetPoint("Second point")
          if point2:
              angle  = rs.Angle(point1, point2)
              if  angle: print("Angle: {}".format(angle[0]))
    See Also:
      Angle2
      Distance
    """
    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 Angle2(line1, line2):
    """Measures the angle between two lines
    Parameters:
      line1 (line): List of 6 numbers or 2 Point3d.
      line2 (line): List of 6 numbers or 2 Point3d.
    Returns:
      tuple(number, number): 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: {}".format(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


def ClipboardText(text=None):
    """Returns or sets a text string to the Windows clipboard
    Parameters:
      text (str, optional): text to set
    Returns:
      str: if text is not specified, the current text in the clipboard
      str: if text is specified, the previous text in the clipboard
      None: if not successful
    Example:
      import rhinoscriptsyntax as rs
      txt = rs.ClipboardText("Hello Rhino!")
      if txt: rs.MessageBox(txt, 0, "Clipboard Text")
    See Also:
      
    """
    rc = None
    if System.Windows.Forms.Clipboard.ContainsText():
        rc = System.Windows.Forms.Clipboard.GetText()
    if text:
        if not isinstance(text, str): text = str(text)
        System.Windows.Forms.Clipboard.SetText(text)
    return rc


def ColorAdjustLuma(rgb, luma, scale=False):
    """Changes the luminance of a red-green-blue value. Hue and saturation are
    not affected
    Parameters:
      rgb (color): initial rgb value
      luma (number): The luminance in units of 0.1 percent of the total range. A
          value of luma = 50 corresponds to 5 percent of the maximum luminance
      scale (bool, optional): if True, luma specifies how much to increment or decrement the
          current luminance. If False, luma specified the absolute luminance.
    Returns:
      color: modified rgb value if successful
    Example:
      import rhinoscriptsyntax as rs
      rgb = rs.ColorAdjustLuma((128, 128, 128), 50)
      print("Red = {}".format(rs.ColorRedValue(rgb)))
      print("Green = {}".format(rs.ColorGreenValue(rgb)))
      print("Blue = {}".format(rs.ColorBlueValue(rgb)))
    See Also:
      ColorHLSToRGB
      ColorRGBToHLS
    """
    rgb = coercecolor(rgb, True)
    hsl = Rhino.Display.ColorHSL(rgb)
    luma = luma / 1000.0
    if scale: luma = hsl.L + luma
    hsl.L = luma
    return hsl.ToArgbColor()


def ColorBlueValue(rgb):
    """Retrieves intensity value for the blue component of an RGB color
    Parameters:
      rgb (color): the RGB color value
    Returns:
      number: The blue component if successful, otherwise None
    Example:
      import rhinoscriptsyntax as rs
      rgb = rs.LayerColor("Default")
      print("Red = {}".format(rs.ColorRedValue(rgb)))
      print("Green = {}".format(rs.ColorGreenValue(rgb)))
      print("Blue = {}".format(rs.ColorBlueValue(rgb)))
    See Also:
      ColorGreenValue
      ColorRedValue
    """
    return coercecolor(rgb, True).B


def ColorGreenValue(rgb):
    """Retrieves intensity value for the green component of an RGB color
    Parameters:
      rgb (color): the RGB color value
    Returns:
      number: The green component if successful, otherwise None
    Example:
      import rhinoscriptsyntax as rs
      rgb = rs.LayerColor("Default")
      print("Red = {}".format(rs.ColorRedValue(rgb)))
      print("Green = {}".format(rs.ColorGreenValue(rgb)))
      print("Blue = {}".format(rs.ColorBlueValue(rgb)))
    See Also:
      ColorBlueValue
      ColorRedValue
    """
    return coercecolor(rgb, True).G


def ColorHLSToRGB(hls):
    """Converts colors from hue-lumanence-saturation to RGB
    Parameters:
      hls (color): the HLS color value
    Returns:
      color: The RGB color value if successful, otherwise False
    Example:
      import rhinoscriptsyntax as rs
      rgb = rs.ColorHLSToRGB( (160, 120, 0) )
      print("Red = {}".format(rs.ColorRedValue(rgb)))
      print("Green = {}".format(rs.ColorGreenValue(rgb)))
      print("Blue = {}".format(rs.ColorBlueValue(rgb)))
    See Also:
      ColorAdjustLuma
      ColorRGBToHLS
    """
    if len(hls)==3:
        hls = Rhino.Display.ColorHSL(hls[0]/240.0, hls[2]/240.0, hls[1]/240.0)
    elif len(hls)==4:
        hls = Rhino.Display.ColorHSL(hls[3]/240.0, hls[0]/240.0, hls[2]/240.0, hls[1]/240.0)
    return hls.ToArgbColor()


def ColorRedValue(rgb):
    """Retrieves intensity value for the red component of an RGB color
    Parameters:
      hls (color): the HLS color value
    Returns:
      color: The red color value if successful, otherwise False
    Example:
      import rhinoscriptsyntax as rs
      rgb = rs.LayerColor("Default")
      print("Red = {}".format(rs.ColorRedValue(rgb)))
      print("Green = {}".format(rs.ColorGreenValue(rgb)))
      print("Blue = {}".format(rs.ColorBlueValue(rgb)))
    See Also:
      ColorBlueValue
      ColorGreenValue
    """
    return coercecolor(rgb, True).R


def ColorRGBToHLS(rgb):
    """Convert colors from RGB to HLS
    Parameters:
      rgb (color): the RGB color value
    Returns:
      color: The HLS color value if successful, otherwise False
    Example:
      import rhinoscriptsyntax as rs
      hls = rs.ColorRGBToHLS((128, 128, 128))
      print("Hue = {}".format(hls[0]))
      print("Luminance = {}".format(hls[1]))
      print("Saturation = {}".format(hls[2]))
    See Also:
      ColorAdjustLuma
      ColorHLSToRGB
    """
    rgb = coercecolor(rgb, True)
    hsl = Rhino.Display.ColorHSL(rgb)
    return hsl.H, hsl.S, hsl.L


def CullDuplicateNumbers(numbers, tolerance=None):
    """Removes duplicates from an array of numbers.
    Parameters:
      numbers ([number, ...]): list or tuple
      tolerance (number, optional): The minimum distance between numbers.  Numbers that fall within this tolerance will be discarded.  If omitted, Rhino's internal zero tolerance is used.
    Returns:
      list(number, ...): numbers with duplicates removed if successful.
    Example:
      import rhinoscriptsyntax as rs
      arr = [1,1,2,2,3,3,4,4,5,5]
      arr = rs.CullDuplicateNumbers(arr)
      for n in arr: print(n)
    See Also:
      CullDuplicatePoints
    """
    count = len(numbers)
    if count < 2: return numbers
    if tolerance is None: tolerance = scriptcontext.doc.ModelAbsoluteTolerance
    numbers = sorted(numbers)
    d = numbers[0]
    index = 1
    for step in range(1,count):
        test_value = numbers[index]
        if math.fabs(d-test_value)<=tolerance:
            numbers.pop(index)
        else:
            d = test_value
            index += 1
    return numbers


def CullDuplicatePoints(points, tolerance=-1):
    """Removes duplicates from a list of 3D points.
    Parameters:
      points ([point, ...]): A list of 3D points.
      tolerance (number): Minimum distance between points. Points within this
        tolerance will be discarded. If omitted, Rhino's internal zero tolerance
        is used.
    Returns:
      list(point, ...): of 3D points with duplicates removed if successful.
      None: if not successful
    Example:
      import rhinoscriptsyntax as rs
      points = rs.GetPoints(,,"First point", "Next point")
      if points:
          points= rs.CullDuplicatePoints(points)
          for p in points: print(p)
    See Also:
      CullDuplicateNumbers
    """
    points = coerce3dpointlist(points, True)
    if tolerance is None or tolerance < 0:
        tolerance = Rhino.RhinoMath.ZeroTolerance
    return list(Rhino.Geometry.Point3d.CullDuplicates(points, tolerance))


def Distance(point1, point2):
    """Measures distance between two 3D points, or between a 3D point and
    an array of 3D points.
    Parameters:
      point1 (point): The first 3D point.
      point2 (point): The second 3D point or list of 3-D points.
    Returns:
      point: If point2 is a 3D point then the distance if successful.
      point: If point2 is a list of points, then an list of distances if successful.
      None: if not successful
    Example:
      import rhinoscriptsyntax as rs
      point1 = rs.GetPoint("First point")
      if point1:
          point2 = rs.GetPoint("Second point")
          if point2:
              print("Distance: {}".format(rs.Distance(point1, point2)))
    See Also:
      Angle
      Angle2
    """
    from_pt = coerce3dpoint(point1, True)
    to_pt = coerce3dpoint(point2)
    if to_pt: return (to_pt - from_pt).Length
    # check if we have a list of points
    to_pt = coerce3dpointlist(point2, True)
    distances = [(point - from_pt).Length for point in to_pt]
    if distances: return distances


def GetSettings(filename, section=None, entry=None):
    """Returns string from a specified section in a initialization file.
    Parameters:
      filename (str): name of the initialization file
      section (str, optional): section containing the entry
      entry (str, optional): entry whose associated string is to be returned
    Returns:
      list(str, ...): If section is not specified, a list containing all section names
      list:(str, ...): If entry is not specified, a list containing all entry names for a given section
      str: If section and entry are specified, a value for entry
      None: if not successful
    Example:
      import rhinoscriptsyntax as rs
      filename = rs.OpenFileName("Open", "Initialization Files (*.ini)|*.ini||")
      if filename:
          sections = rs.GetSettings(filename)
          if sections:
              section = rs.ListBox(sections, "Select a section", filename)
              if section:
                  entries = rs.GetSettings(filename, section)
                  if entries:
                      entry = rs.ListBox(entries, "Select an entry", section)
                      if entry:
                          value = rs.GetSettings(filename, section, entry)
                          if value: rs.MessageBox( value, 0, entry )
    See Also:
      
    """
    CP = compat.GET_IMPORT_CONFIG_PARSER()
    try:
        cp = CP.ConfigParser()
        cp.read(filename)
        if not section: return cp.sections()
        section = string.lower(section)
        if not entry: return cp.options(section)
        entry = string.lower(entry)
        return cp.get(section, entry)
    except IOError:
        return scriptcontext.errorhander()
    return scriptcontext.errorhandler()


def Polar(point, angle_degrees, distance, plane=None):
    """Returns 3D point that is a specified angle and distance from a 3D point
    Parameters:
      point (point): the point to transform
      plane (plane, optional): plane to base the transformation. If omitted, the world
        x-y plane is used
    Returns:
      point: resulting point is successful
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      point = (1.0, 1.0, 0.0)
      result = rs.Polar(point, 45.0, 1.414214)
      print(result)
    See Also:
      PointAdd
      PointCompare
      PointDivide
      PointScale
      PointSubtract
    """
    point = coerce3dpoint(point, True)
    angle = math.radians(angle_degrees)
    if plane: plane = coerceplane(plane)
    else: plane = Rhino.Geometry.Plane.WorldXY
    offset = plane.XAxis
    offset.Unitize()
    offset *= distance
    rc = point+offset
    xform = Rhino.Geometry.Transform.Rotation(angle, plane.ZAxis, point)
    rc.Transform(xform)
    return rc


def SimplifyArray(points):
    """Flattens an array of 3-D points into a one-dimensional list of real numbers. For example, if you had an array containing three 3-D points, this method would return a one-dimensional array containing nine real numbers.
    Parameters:
      points ([point, ...]): Points to flatten
    Returns:
      list(number, ...): A one-dimensional list containing real numbers, if successful, otherwise None
    Example:
      import rhinoscriptsyntax as rs
      points = rs.GetPoints()
      if points:
          numbers = rs.SimplifyArray(points)
          for n in numbers: print(n)
    See Also:
      
    """
    rc = []
    for point in points:
        point = coerce3dpoint(point, True)
        rc.append(point.X)
        rc.append(point.Y)
        rc.append(point.Z)
    return rc


def Sleep(milliseconds):
    """Suspends execution of a running script for the specified interval
    Parameters:
      milliseconds (number): thousands of a second
    Returns:
      None
    Example:
      import rhinoscriptsyntax as rs
      print("This")
      rs.Sleep(2000)
      print("is")
      rs.Sleep(2000)
      print("a")
      rs.Sleep(2000)
      print("slow")
      rs.Sleep(2000)
      print("message!")
    See Also:
      
    """
    time.sleep( milliseconds / 1000.0 )
    Rhino.RhinoApp.Wait() #keep the message pump alive

def SortPointList(points, tolerance=None):
    """Sorts list of points so they will be connected in a "reasonable" polyline order
    Parameters:
      points ({point, ...])the points to sort
      tolerance (number, optional): minimum distance between points. Points that fall within this tolerance
        will be discarded. If omitted, Rhino's internal zero tolerance is used.
    Returns:
      list(point, ...): of sorted 3D points if successful
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      points = rs.GetPointCoordinates()
      if points:
          sorted = rs.SortPointList(points)
          rs.AddPolyline(sorted)
    See Also:
      SortPoints
    """
    points = coerce3dpointlist(points, True)
    if tolerance is None: tolerance = Rhino.RhinoMath.ZeroTolerance
    return list(Rhino.Geometry.Point3d.SortAndCullPointList(points, tolerance))


def SortPoints(points, ascending=True, order=0):
    """Sorts the components of an array of 3D points
    Parameters:
      points ([point, ...]): points to sort
      ascending (bool, optional: ascending if omitted (True) or True, descending if False.
      order (number, optional): the component sort order
        Value       Component Sort Order
        0 (default) X, Y, Z
        1           X, Z, Y
        2           Y, X, Z
        3           Y, Z, X
        4           Z, X, Y
        5           Z, Y, X
    Returns:
      list(point, ...): sorted 3-D points if successful
      None: if not successful
    Example:
      import rhinoscriptsyntax as rs
      points = rs.GetPoints()
      if points:
          points = rs.SortPoints(points)
          for p in points: print(p)
    See Also:
      
    """
    __attrXYZ = attrgetter('X', 'Y', 'Z')
    __attrXZY = attrgetter('X', 'Z', 'Y')
    __attrYXZ = attrgetter('Y', 'X', 'Z')
    __attrYZX = attrgetter('Y', 'Z', 'X')
    __attrZXY = attrgetter('Z', 'X', 'Y')
    __attrZYX = attrgetter('Z', 'Y', 'X')
    __attrgetter = (__attrXYZ, __attrXZY, __attrYXZ, __attrYZX, __attrZXY, __attrZYX)[order]
    return sorted(points, key=__attrgetter, reverse=not ascending)


def Str2Pt(point):
    """convert a formatted string value into a 3D point value
    Parameters:
      point (str): A string that contains a delimited point like "1,2,3".
    Returns:
      point: Point structure from the input string.
      None: error on invalid format
    Example:
      import rhinoscriptsyntax as rs
      point = rs.Str2Pt("1,2,3")
      if point: rs.AddPoint( point )
    See Also:
      
    """
    return coerce3dpoint(point, True)


def clamp(lowvalue, highvalue, value):
    if lowvalue>=highvalue: raise Exception("lowvalue must be less than highvalue")
    if value<lowvalue: return lowvalue
    if value>highvalue: return highvalue
    return value


def fxrange(start, stop, step):
    "float version of the xrange function"
    if step==0: raise ValueError("step must not equal 0")
    x = start
    if start<stop:
        if step<0: raise ValueError("step must be greater than 0")
        while x<=stop:
            yield x
            x+=step
    else:
        if step>0: raise ValueError("step must be less than 0")
        while x>=stop:
            yield x
            x+=step


def frange(start, stop, step):
    "float version of the range function"
    return [x for x in fxrange(start, stop, step)]


def coerce3dpoint(point, raise_on_error=False):
    """Converts input into a Rhino.Geometry.Point3d if possible.
    Parameters:
      point = Point3d, Vector3d, Point3f, Vector3f, str, uuid
      raise_on_error [opt] = True or False
    Returns:
      a Rhino.Geometry.Point3d
    Example:
    See Also:
    """
    if type(point) is Rhino.Geometry.Point3d: return point
    enumerable = compat.GET_HOST().Coerce3dPointFromEnumerables(point)
    if enumerable is not None: return enumerable
    if type(point) is System.Guid:
        found, pt = scriptcontext.doc.Objects.TryFindPoint(point)
        if found: return pt
    if hasattr(point, "__len__") and len(point)==3 and hasattr(point, "__getitem__"):
        try:
            return Rhino.Geometry.Point3d(float(point[0]), float(point[1]), float(point[2]))
        except:
            if raise_on_error: raise
    if type(point) is Rhino.Geometry.Vector3d or type(point) is Rhino.Geometry.Point3f or type(point) is Rhino.Geometry.Vector3f:
        return Rhino.Geometry.Point3d(point.X, point.Y, point.Z)
    if type(point) is str:
        point = point.split(',')
        return Rhino.Geometry.Point3d( float(point[0]), float(point[1]), float(point[2]) )
    if hasattr(point, "__len__") and len(point)==2 and hasattr(point, "__getitem__"):
        try:
            return Rhino.Geometry.Point3d(float(point[0]), float(point[1]), 0.0)
        except:
            if raise_on_error: raise
    if raise_on_error: raise ValueError("Could not convert %s to a Point3d" % point)


def CreatePoint(point, y=None, z=None):
    """Converts 'point' into a Rhino.Geometry.Point3d if possible.
    If the provided object is already a point, it value is copied.
    In case the conversion fails, an error is raised.
    Alternatively, you can also pass two coordinates singularly for a
    point on the XY plane, or three for a 3D point.
    Parameters:
      point (Point3d|Vector3d|Point3f|Vector3f|str|guid|[number, number, number])
    Returns:
      point: a Rhino.Geometry.Point3d. This can be seen as an object with three indices:
        [0]  X coordinate
        [1]  Y coordinate
        [2]  Z coordinate.
    Example:
    See Also:
    """
    if y is not None: return Rhino.Geometry.Point3d(float(point), float(y), float(z or 0.0))
    if type(point) is System.Drawing.Color: return Rhino.Geometry.Point3d(point)
    return coerce3dpoint(point, True)


def coerce2dpoint(point, raise_on_error=False):
    """Convert input into a Rhino.Geometry.Point2d if possible.
    Parameters:
      point = Point2d, list, tuple, Vector3d, Point3d, str
      raise_on_error [opt] = True or False
    Returns:
      a Rhino.Geometry.Point2d
    Example:
    See Also:
    """
    if type(point) is Rhino.Geometry.Point2d: return point
    if type(point) is list or type(point) is tuple:
        length = len(point)
        if length==2 and type(point[0]) is not list and type(point[0]) is not Rhino.Geometry.Point2d:
            return Rhino.Geometry.Point2d(point[0], point[1])
    if type(point) is Rhino.Geometry.Vector3d or type(point) is Rhino.Geometry.Point3d:
        return Rhino.Geometry.Point2d(point.X, point.Y)
    if type(point) is str:
        point = point.split(',')
        return Rhino.Geometry.Point2d( float(point[0]), float(point[1]) )
    if raise_on_error: raise ValueError("Could not convert %s to a Point2d" % point)


def coerce3dvector(vector, raise_on_error=False):
    """Convert input into a Rhino.Geometry.Vector3d if possible.
    Parameters:
      vector = Vector3d, Point3d, list, Point3f, Vector3f, str, uuid
      raise_on_error [opt] = True or False
    Returns:
      a Rhino.Geometry.Vector3d
    Example:
    See Also:
    """
    if type(vector) is Rhino.Geometry.Vector3d: return vector
    point = coerce3dpoint(vector, False)
    if point: return Rhino.Geometry.Vector3d(point.X, point.Y, point.Z)
    if raise_on_error: raise ValueError("Could not convert %s to a Vector3d" % vector)


def CreateVector(vector, y=None, z=None):
    """Converts 'vector' into a Rhino.Geometry.Vector3d if possible.
    If the provided object is already a vector, it value is copied.
    If the conversion fails, an error is raised.
    Alternatively, you can also pass two coordinates singularly for a
    vector on the XY plane, or three for a 3D vector.
    Parameters:
      vector (Vector3d|Point3d|Point3f|Vector3f\str|guid|[number, number, number])
      raise_on_error (bool, optionals): True or False
    Returns:
      a Rhino.Geometry.Vector3d. This can be seen as an object with three indices:
      result[0]: X component, result[1]: Y component, and result[2] Z component.
    Example:
    See Also:
    """
    if y is not None: return Rhino.Geometry.Vector3d(float(vector), float(y), float(z or 0.0))
    if type(vector) is Rhino.Geometry.Vector3d: return Rhino.Geometry.Vector3d(vector)
    return coerce3dvector(vector, True)


def coerce3dpointlist(points, raise_on_error=False):
    if isinstance(points, System.Array[Rhino.Geometry.Point3d]):
        return list(points)
    if isinstance(points, Rhino.Collections.Point3dList): return list(points)
    if type(points) is list or type(points) is tuple:
        count = len(points)
        if count>10 and type(points[0]) is Rhino.Geometry.Point3d: return points
        if count>0 and (coerce3dpoint(points[0]) is not None):
            return [coerce3dpoint(points[i], raise_on_error) for i in compat.RANGE(count)]
        elif count>2 and type(points[0]) is not list:
            point_count = count/3
            rc = []
            for i in compat.RANGE(point_count):
                pt = Rhino.Geometry.Point3d(points[i*3], points[i*3+1], points[i*3+2])
                rc.append(pt)
            return rc
    if hasattr(points, '__iter__'):
        return [coerce3dpoint(pt, raise_on_error) for pt in points]
    if raise_on_error: raise ValueError("Could not convert %s to a list of points" % points)


def coerce2dpointlist(points):
    if points is None or isinstance(points, System.Array[Rhino.Geometry.Point2d]):
        return points
    if type(points) is list or type(points) is tuple:
        count = len(points)
        if count>0 and type(points[0]) is Rhino.Geometry.Point2d:
            rc = System.Array.CreateInstance(Rhino.Geometry.Point2d, count)
            for i in compat.RANGE(count): rc[i] = points[i]
            return rc
        elif count>1 and type(points[0]) is not list:
            point_count = count/2
            rc = System.Array.CreateInstance(Rhino.Geometry.Point2d,point_count)
            for i in compat.RANGE(point_count):
                rc[i] = Rhino.Geometry.Point2d(points[i*2], points[i*2+1])
            return rc
        elif count>0 and type(points[0]) is list:
            point_count = count
            rc = System.Array.CreateInstance(Rhino.Geometry.Point2d,point_count)
            for i in compat.RANGE(point_count):
                pt = points[i]
                rc[i] = Rhino.Geometry.Point2d(pt[0],pt[1])
            return rc
        return None
    return None


def coerceplane(plane, raise_on_bad_input=False):
    """Convert input into a Rhino.Geometry.Plane if possible.
    Parameters:
      plane = Plane, list, tuple
    Returns:
      a Rhino.Geometry.Plane
    Example:
    See Also:
    """
    if type(plane) is Rhino.Geometry.Plane: return plane
    if type(plane) is list or type(plane) is tuple:
        length = len(plane)
        if length == 1:
            point = coerce3dpoint(plane, False)
            if point: plane = point; length = 3
            elif plane[0] is list or plane[0] is tuple: return coerceplane(plane[0])
        if length==3 and type(plane[0]) is not list:
            rc = Rhino.Geometry.Plane.WorldXY
            rc.Origin = Rhino.Geometry.Point3d(plane[0],plane[1],plane[2])
            return rc
        if length==9 and type(plane[0]) is not list:
            origin = Rhino.Geometry.Point3d(plane[0],plane[1],plane[2])
            xpoint = Rhino.Geometry.Point3d(plane[3],plane[4],plane[5])
            ypoint = Rhino.Geometry.Point3d(plane[6],plane[7],plane[8])
            rc     = Rhino.Geometry.Plane(origin, xpoint, ypoint)
            return rc
        if (length==3 or length==4) and (type(plane[0]) is list or type(plane[0]) is tuple):
            origin = Rhino.Geometry.Point3d(plane[0][0],plane[0][1],plane[0][2])
            xpoint = Rhino.Geometry.Point3d(plane[1][0],plane[1][1],plane[1][2])
            ypoint = Rhino.Geometry.Point3d(plane[2][0],plane[2][1],plane[2][2])
            rc     = Rhino.Geometry.Plane(origin, xpoint, ypoint)
            return rc
    if raise_on_bad_input: raise TypeError("%s can not be converted to a Plane"%plane)


def CreatePlane(plane_or_origin, x_axis=None, y_axis=None, ignored=None):
    """Converts input into a Rhino.Geometry.Plane object if possible.
    If the provided object is already a plane, its value is copied.
    The returned data is accessible by indexing[origin, X axis, Y axis, Z axis], and that is the suggested method to interact with the type.
    The Z axis is in any case computed from the X and Y axes, so providing it is possible but not required.
    If the conversion fails, an error is raised.
    Parameters:
      plane (plane|point|point, vector, vector|[point, vector, vector])
    Returns:
      plane: A Rhino.Geometry.plane.
    Example:
    See Also:
    """
    if type(plane_or_origin) is Rhino.Geometry.Plane: return plane_or_origin.Clone()
    if x_axis != None:
        if y_axis == None: raise Exception("A value for the Y axis is expected if the X axis is specified.")
        origin = coerce3dpoint(plane_or_origin, True)
        x_axis = coerce3dvector(x_axis, True)
        y_axis = coerce3dvector(y_axis, True)
        return Rhino.Geometry.Plane(origin, x_axis, y_axis)
    return coerceplane(plane_or_origin, True)


def coercexform(xform, raise_on_bad_input=False):
    """Convert input into a Rhino.Transform if possible.
    Parameters:
      xform = the xform
      raise_on_bad_input [opt] = True or False
    Example:
    See Also:
    """
    t = type(xform)
    if t is Rhino.Geometry.Transform: return xform
    if( (t is list or t is tuple) and len(xform)==4 and len(xform[0])==4):
        xf = Rhino.Geometry.Transform()
        for i in range(4):
            for j in range(4):
                xf[i,j] = xform[i][j]
        return xf
    if raise_on_bad_input: raise TypeError("%s can not be converted to a Transform"%xform)


def CreateXform(xform):
    """Converts input into a Rhino.Geometry.Transform object if possible.
    If the provided object is already a transform, its value is copied.
    The returned data is accessible by indexing[row, column], and that is the suggested method to interact with the type.
    If the conversion fails, an error is raised.
    Parameters:
      xform (list): the transform. This can be seen as a 4x4 matrix, given as nested lists or tuples.
    Returns:
      transform: A Rhino.Geometry.Transform. result[0,3] gives access to the first row, last column.
    Example:
    See Also:
    """
    if type(xform) is Rhino.Geometry.Transform: return xform.Clone()
    return coercexform(xform, True)


def coerceguid(id, raise_exception=False):
    if type(id) is System.Guid: return id
    if type(id) is str and len(id)>30:
        try:
            id = System.Guid(id)
            return id
        except:
            pass
    if (type(id) is list or type(id) is tuple) and len(id)==1:
        return coerceguid(id[0], raise_exception)
    if type(id) is Rhino.DocObjects.ObjRef: return id.ObjectId
    if isinstance(id,Rhino.DocObjects.RhinoObject): return id.Id
    if raise_exception: raise TypeError("Parameter must be a Guid or string representing a Guid")


def coerceguidlist(ids):
    if ids is None: return None
    rc = []
    if( type(ids) is list or type(ids) is tuple ): pass
    else: ids = [ids]
    for id in ids:
        id = coerceguid(id)
        if id: rc.append(id)
    if rc: return rc


def coerceboundingbox(bbox, raise_on_bad_input=False):
    if type(bbox) is Rhino.Geometry.BoundingBox: return bbox
    points = coerce3dpointlist(bbox)
    if points: return Rhino.Geometry.BoundingBox(points)
    if raise_on_bad_input: raise TypeError("%s can not be converted to a BoundingBox"%bbox)


def coercecolor(c, raise_if_bad_input=False):
    if type(c) is System.Drawing.Color: return c
    if type(c) is list or type(c) is tuple:
        if len(c)==3: return System.Drawing.Color.FromArgb(c[0], c[1], c[2])
        elif len(c)==4: return System.Drawing.Color.FromArgb(c[3], c[0], c[1], c[2])
    if type(c)==type(1): return System.Drawing.Color.FromArgb(c)
    if raise_if_bad_input: raise TypeError("%s can not be converted to a Color"%c)


def CreateColor(color, g=None, b=None, a=None):
    """Converts 'color' into a native color object if possible.
    The returned data is accessible by indexing, and that is the suggested method to interact with the type.
    Red index is [0], Green index is [1], Blue index is [2] and Alpha index is [3].
    If the provided object is already a color, its value is copied.
    Alternatively, you can also pass three coordinates singularly for an RGB color, or four
    for an RGBA color point.
    Parameters:
      color ([number, number, number]): list or 3 or 4 items. Also, a single int can be passed and it will be bitwise-parsed.
    Returns:
      color: An object that can be indexed for red, green, blu, alpha. Item[0] is red.
    Example:
    See Also:
    """
    if g is not None and b is not None: return System.Drawing.Color.FromArgb(int(a or 255), int(color), int(g), int(b))
    if type(color) is System.Drawing.Color: return System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B)
    return coercecolor(color, True)


def coerceline(line, raise_if_bad_input=False):
    if type(line) is Rhino.Geometry.Line: return line
    guid = coerceguid(line, False)
    if guid: line = scriptcontext.doc.Objects.Find(guid).Geometry
    if isinstance(line, Rhino.Geometry.Curve) and line.IsLinear:
        return Rhino.Geometry.Line(line.PointAtStart, line.PointAtEnd)
    points = coerce3dpointlist(line, raise_if_bad_input)
    if points and len(points)>1: return Rhino.Geometry.Line(points[0], points[1])
    if raise_if_bad_input: raise TypeError("%s can not be converted to a Line"%line)


def coercegeometry(id, raise_if_missing=False):
    """attempt to get GeometryBase class from given input
    Parameters:
      id = geometry identifier
      raise_if_missing [opt] = True or False
    Example:
    See Also:
    """
    if isinstance(id, Rhino.Geometry.GeometryBase): return id
    if type(id) is Rhino.DocObjects.ObjRef: return id.Geometry()
    if isinstance(id, Rhino.DocObjects.RhinoObject): return id.Geometry
    id = coerceguid(id, raise_if_missing)
    if id:
        rhobj = scriptcontext.doc.Objects.Find(id)
        if rhobj: return rhobj.Geometry
    if raise_if_missing: raise ValueError("unable to convert %s into geometry"%id)


def coercebrep(id, raise_if_missing=False):
    """attempt to get polysurface geometry from the document with a given id
    Parameters:
      id = id to be coerced into a brep
      raise_if_missing [opt] = True or False
    Returns:
      a Rhino.Geometry.Brep
    Example:
    See Also:
    """
    geom = coercegeometry(id, False)
    if isinstance(geom, Rhino.Geometry.Brep): return geom
    if isinstance(geom, Rhino.Geometry.Extrusion): return geom.ToBrep(True)
    if raise_if_missing: raise ValueError("unable to convert %s into Brep geometry"%id)


def coercecurve(id, segment_index=-1, raise_if_missing=False):
    """attempt to get curve geometry from the document with a given id
    Parameters:
      id = id to be coerced into a curve
      segment_index [opt] = index of segment to retrieve
      raise_if_missing [opt] = True or False
    Example:
    See Also:
    """
    if isinstance(id, Rhino.Geometry.Curve): return id
    if type(id) is Rhino.DocObjects.ObjRef: return id.Curve()
    id = coerceguid(id, True)
    crvObj = scriptcontext.doc.Objects.Find(id)
    if crvObj:
        curve = crvObj.Geometry
        if curve and segment_index>=0 and type(curve) is Rhino.Geometry.PolyCurve:
            curve = curve.SegmentCurve(segment_index)
        if isinstance(curve, Rhino.Geometry.Curve): return curve
    if raise_if_missing: raise ValueError("unable to convert %s into Curve geometry"%id)


def coercesurface(object_id, raise_if_missing=False):
    """attempt to get surface geometry from the document with a given id
    Parameters:
      object_id = the object's identifier
      raise_if_missing [opt] = True or False
    Returns:
      a Rhino.Geometry.Surface
    Example:
    See Also:
    """
    if isinstance(object_id, Rhino.Geometry.Surface): return object_id
    if isinstance(object_id, Rhino.Geometry.Brep) and object_id.Faces.Count==1: return object_id.Faces[0]
    if type(object_id) is Rhino.DocObjects.ObjRef: return object_id.Face()
    object_id = coerceguid(object_id, True)
    srfObj = scriptcontext.doc.Objects.Find(object_id)
    if srfObj:
        srf = srfObj.Geometry
        if isinstance(srf, Rhino.Geometry.Surface): return srf
        #single face breps are considered surfaces in the context of scripts
        if isinstance(srf, Rhino.Geometry.Brep) and srf.Faces.Count==1:
            return srf.Faces[0]
    if raise_if_missing: raise ValueError("unable to convert %s into Surface geometry"%object_id)


def coercemesh(object_id, raise_if_missing=False):
    """attempt to get mesh geometry from the document with a given id
    Parameters:
      object_id = object identifier
      raise_if_missing [opt] = True or False
    Returns:
      a Rhino.Geometry.Mesh
    Example:
    See Also:
    """
    if type(object_id) is Rhino.DocObjects.ObjRef: return object_id.Mesh()
    if isinstance(object_id, Rhino.Geometry.Mesh): return object_id
    object_id = coerceguid(object_id, raise_if_missing)
    if object_id: 
        meshObj = scriptcontext.doc.Objects.Find(object_id)
        if meshObj:
            mesh = meshObj.Geometry
            if isinstance(mesh, Rhino.Geometry.Mesh): return mesh
    if raise_if_missing: raise ValueError("unable to convert %s into Mesh geometry"%object_id)


def coercerhinoobject(object_id, raise_if_bad_input=False, raise_if_missing=False):
    """attempt to get RhinoObject from the document with a given id
    Parameters:
        object_id = object's identifier
        raise_if_bad_input [opt] = True or False
        raise_if_missing [opt] = True or False
    Returns:
      a RhinoObject
    Example:
    See Also:
    """
    if isinstance(object_id, Rhino.DocObjects.RhinoObject): return object_id
    object_id = coerceguid(object_id, raise_if_bad_input)
    if object_id is None: return None
    rc = scriptcontext.doc.Objects.Find(object_id)
    if not rc and raise_if_missing: raise ValueError("%s does not exist in ObjectTable" % object_id)
    return rc

def CreateInterval(interval, y=None):
    """Converts 'interval' into a Rhino.Geometry.Interval.
    If the provided object is already an interval, its value is copied.
    In case the conversion fails, an error is raised.
    In case a single number is provided, it will be translated to an increasing interval that includes
    the provided input and 0. If two values are provided, they will be used instead.
    Parameters:
      interval ([number, number]): or any item that can be accessed at index 0 and 1; an Interval
    Returns:
      interval: a Rhino.Geometry.Interval. This can be seen as an object made of two items:
        [0] start of interval
        [1] end of interval
    Example:
    See Also:
    """
    if y is not None: return Rhino.Geometry.Interval(float(interval), float(y))
    if isinstance(interval, numbers.Number):
        return Rhino.Geometry.Interval(interval if interval < 0 else 0, interval if interval > 0 else 0)
    try:
        return Rhino.Geometry.Interval(interval[0], interval[1])
    except:
        raise ValueError("unable to convert %s into an Interval: it cannot be indexed."%interval)

```

--------------------------------------------------------------------------------
/rhino_mcp_server/static/document.py:
--------------------------------------------------------------------------------

```python
import math

import System
import System.Drawing
import System.IO

import Rhino

import scriptcontext

from rhinoscript import utility as rhutil


def _SetRenderMeshAndUpdateStyle(current):
    scriptcontext.doc.SetCustomMeshingParameters(current)
    scriptcontext.doc.MeshingParameterStyle = Rhino.Geometry.MeshingParameterStyle.Custom


def CreatePreviewImage(filename, view=None, size=None, flags=0, wireframe=False):
    """Create a bitmap preview image of the current model
    Parameters:
      filename (str): name of the bitmap file to create
      view (str, optional): title of the view. If omitted, the active view is used
      size (number, optional): two integers that specify width and height of the bitmap
      flags (number, optional): Bitmap creation flags. Can be the combination of:
          1 = honor object highlighting
          2 = draw construction plane
          4 = use ghosted shading
      wireframe (bool, optional): If True then a wireframe preview image. If False,
          a rendered image will be created
    Returns:
      bool: True or False indicating success or failure
    Example:
      import rhinoscriptsyntax as  rs
      result = rs.CreatePreviewImage("test.jpg")
      if result:
          print( "test.jpg created successfully.")
      else:
          print( "Unable to create preview image.")
    See Also:
      ExtractPreviewImage
    """
    rhview = scriptcontext.doc.Views.ActiveView
    if view is not None:
        rhview = scriptcontext.doc.Views.Find(view, False)
        if rhview is None: return False
    rhsize = rhview.ClientRectangle.Size
    if size: rhsize = System.Drawing.Size(size[0], size[1])
    ignore_highlights = (flags&1)!=1
    drawcplane = (flags&2)==2
    useghostedshading = (flags&4)==4
    if wireframe:
        return rhview.CreateWireframePreviewImage(filename, rhsize, ignore_highlights, drawcplane)
    else:
        return rhview.CreateShadedPreviewImage(filename, rhsize, ignore_highlights, drawcplane, useghostedshading)


def DocumentModified(modified=None):
    """Returns or sets the document's modified flag. This flag indicates whether
    or not any changes to the current document have been made. NOTE: setting the
    document modified flag to False will prevent the "Do you want to save this
    file..." from displaying when you close Rhino.
    Parameters:
      modified (bool): the modified state, either True or False
    Returns:
      bool: if no modified state is specified, the current modified state
      bool: if a modified state is specified, the previous modified state
    Example:
      import rhinoscriptsyntax as rs
      modified = rs.IsDocumentModified()
      if not modified: rs.DocumentModified(True)
    See Also:
      IsDocumentModified
    """
    oldstate = scriptcontext.doc.Modified
    if modified is not None and modified!=oldstate:
        scriptcontext.doc.Modified = modified
    return oldstate


def DocumentName():
    """Returns the name of the currently loaded Rhino document (3DM file)
    Returns:
      str: the name of the currently loaded Rhino document (3DM file)
    Example:
      import rhinoscriptsyntax as rs
      name = rs.DocumentName()
      print(name)
    See Also:
      DocumentPath
    """
    return scriptcontext.doc.Name or None


def DocumentPath():
    """Returns path of the currently loaded Rhino document (3DM file)
    Returns:
      str: the path of the currently loaded Rhino document (3DM file)
    Example:
      import rhinoscriptsyntax as rs
      path = rs.DocumentPath()
      print(path)
    See Also:
      DocumentName
    """
    # GetDirectoryName throws an exception if an empty string is passed hence the 'or None'
    path = System.IO.Path.GetDirectoryName(scriptcontext.doc.Path or None)
    # add \ or / at the end to be consistent with RhinoScript
    if path and not path.endswith(str(System.IO.Path.DirectorySeparatorChar)):
      path += System.IO.Path.DirectorySeparatorChar
    return path


def EnableRedraw(enable=True):
    """Enables or disables screen redrawing
    Parameters:
      enable (bool, optional): True to enable, False to disable
    Returns: 
      bool: previous screen redrawing state
    Example:
      import rhinoscriptsyntax as rs
      redraw = rs.EnableRedraw(True)
    See Also:
      Redraw
    """
    old = scriptcontext.doc.Views.RedrawEnabled
    if old!=enable: scriptcontext.doc.Views.RedrawEnabled = enable
    return old


def ExtractPreviewImage(filename, modelname=None):
    """Extracts the bitmap preview image from the specified model (.3dm)
    Parameters:
      filename (str): name of the bitmap file to create. The extension of
         the filename controls the format of the bitmap file created.
         (.bmp, .tga, .jpg, .jpeg, .pcx, .png, .tif, .tiff)
      modelname (str, optional): The model (.3dm) from which to extract the
         preview image. If omitted, the currently loaded model is used.
    Returns:
      bool: True or False indicating success or failure
    Example:
      import rhinoscriptsyntax as rs
      result = rs.ExtractPreviewImage("test.jpg")
      if result:
          print("Test.jpg created successfully.")
      else:
          print("Unable to extract preview image.")
    See Also:
      CreatePreviewImage
    """
    return scriptcontext.doc.ExtractPreviewImage(filename, modelname)


def IsDocumentModified():
    """Verifies that the current document has been modified in some way
    Returns:
      bool: True or False. None on error
    Example:
      import rhinoscriptsyntax as rs
      modified = rs.IsDocumentModified()
      if not modified: rs.DocumentModified(True)
    See Also:
      DocumentModified
    """
    return scriptcontext.doc.Modified


def Notes(newnotes=None):
    """Returns or sets the document's notes. Notes are generally created
    using Rhino's Notes command
    Parameters:
      newnotes (str): new notes to set
    Returns:
      str: if `newnotes` is omitted, the current notes if successful
      str: if `newnotes` is specified, the previous notes if successful
    Example:
      import rhinoscriptsyntax as rs
      notes = rs.Notes()
      if notes: rs.MessageBox(notes)
    See Also:
      
    """
    old = scriptcontext.doc.Notes
    if newnotes is not None: scriptcontext.doc.Notes = newnotes
    return old


def ReadFileVersion():
    """Returns the file version of the current document. Use this function to
    determine which version of Rhino last saved the document. Note, this
    function will not return values from referenced or merged files.
    Returns:
      str: the file version of the current document
    Example:
      import rhinoscriptsyntax as rs
      print("ReadFileVersion = {}".format(rs.ReadFileVersion()))
    See Also:
      DocumentName
      DocumentPath
    """
    return scriptcontext.doc.ReadFileVersion()


def Redraw():
    """Redraws all views
    Returns:
      None 
    Example:
      import rhinoscriptsyntax as rs
      rs.Redraw()
    See Also:
      EnableRedraw
    """
    old = scriptcontext.doc.Views.RedrawEnabled
    scriptcontext.doc.Views.RedrawEnabled = True
    scriptcontext.doc.Views.Redraw()
    Rhino.RhinoApp.Wait()
    scriptcontext.doc.Views.RedrawEnabled = old


def RenderAntialias(style=None):
    """Returns or sets render antialiasing style
    Parameters:
      style (number, optional): level of antialiasing (0=none, 1=normal, 2=best)
    Returns:
      number: if style is not specified, the current antialiasing style
      number: if style is specified, the previous antialiasing style
    Example:
      import rhinoscriptsyntax as rs
      rs.RenderAntialias(1)
    See Also:
      RenderColor
      RenderResolution
      RenderSettings
    """
    rc = scriptcontext.doc.RenderSettings.AntialiasLevel
    if style==0 or style==1 or style==2:
        settings = scriptcontext.doc.RenderSettings
        settings.AntialiasLevel = style
        scriptcontext.doc.RenderSettings = settings
    return rc


def RenderColor(item, color=None):
    """Returns or sets the render ambient light or background color
    Parameters:
      item (number): 0=ambient light color, 1=background color
      color (color, optional): the new color value. If omitted, the current item color is returned
    Returns:
      color: if color is not specified, the current item color
      color: if color is specified, the previous item color
    Example:
      import rhinoscriptsyntax as rs
      render_background_color = 1
      rs.RenderColor( render_background_color, (0,0,255) )
    See Also:
      RenderAntialias
      RenderResolution
      RenderSettings
    """
    if item!=0 and item!=1: raise ValueError("item must be 0 or 1")
    if item==0: rc = scriptcontext.doc.RenderSettings.AmbientLight
    else: rc = scriptcontext.doc.RenderSettings.BackgroundColorTop
    if color is not None:
        color = rhutil.coercecolor(color, True)
        settings = scriptcontext.doc.RenderSettings
        if item==0: settings.AmbientLight = color
        else: settings.BackgroundColorTop = color
        scriptcontext.doc.RenderSettings = settings
        scriptcontext.doc.Views.Redraw()
    return rc


def RenderResolution(resolution=None):
    """Returns or sets the render resolution
    Parameters:
      resolution ([number, number], optional): width and height of render
    Returns:
      tuple(number, number): if resolution is not specified, the current resolution width,height
      tuple(number, number): if resolution is specified, the previous resolution width, height
    Example:
      import rhinoscriptsyntax as rs
      sizex, sizey = rs.Viewsize()
      resolution = sizex/2 , sizey/2
      rs.RenderResolution( resolution )
    See Also:
      RenderAntialias
      RenderColor
      RenderSettings
    """
    rc = scriptcontext.doc.RenderSettings.ImageSize
    if resolution:
        settings = scriptcontext.doc.RenderSettings
        settings.ImageSize = System.Drawing.Size(resolution[0], resolution[1])
        scriptcontext.doc.RenderSettings = settings
    return rc.Width, rc.Height


def RenderMeshDensity(density=None):
    """Returns or sets the render mesh density property of the active document.
        For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
    Parameters:
      density (number, optional): the new render mesh density, which is a number between 0.0 and 1.0.
    Returns:
      number: if density is not specified, the current render mesh density if successful.
      number: if density is specified, the previous render mesh density if successful.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = current.RelativeTolerance
    if density is not None:
        if Rhino.RhinoMath.Clamp(density, 0.0, 1.0) != density: return None
        current.RelativeTolerance = density
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshMaxAngle(angle_degrees=None):
    """Returns or sets the render mesh maximum angle property of the active document.  
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
    Parameters:
      angle_degrees (number, optional): the new maximum angle, which is a positive number in degrees.
    Returns:
      number: if angle_degrees is not specified, the current maximum angle if successful.
      number: if angle_degrees is specified, the previous maximum angle if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = math.degrees(current.RefineAngle)
    if angle_degrees is not None:
        if angle_degrees < 0: return None
        current.RefineAngle = math.radians(angle_degrees)
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshMaxAspectRatio(ratio=None):
    """Returns or sets the render mesh maximum aspect ratio property of the active document.
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
     Parameters:
      ratio (number, optional): the render mesh maximum aspect ratio.  The suggested range, when not zero, is from 1 to 100.
    Returns:
      number: if ratio is not specified, the current render mesh maximum aspect ratio if successful.
      number: if ratio is specified, the previous render mesh maximum aspect ratio if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = current.GridAspectRatio
    if ratio is not None:
        current.GridAspectRatio = ratio
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshMaxDistEdgeToSrf(distance=None):
    """Returns or sets the render mesh maximum distance, edge to surface parameter of the active document.
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
    Parameters:
      distance (number, optional): the render mesh maximum distance, edge to surface.
    Returns:
      number: if distance is not specified, the current render mesh maximum distance, edge to surface if successful.
      number: if distance is specified, the previous render mesh maximum distance, edge to surface if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = current.Tolerance
    if distance is not None:
        current.Tolerance = distance
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshMaxEdgeLength(distance=None):
    """Returns or sets the render mesh maximum edge length parameter of the active document.
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
    Parameters:
      distance (number, optional): the render mesh maximum edge length.
    Returns:
      number: if distance is not specified, the current render mesh maximum edge length if successful.
      number: if distance is specified, the previous render mesh maximum edge length if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = current.MaximumEdgeLength
    if distance is not None:
        current.MaximumEdgeLength = distance
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshMinEdgeLength(distance=None):
    """Returns or sets the render mesh minimum edge length parameter of the active document.
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
        Parameters:
      distance (number, optional): the render mesh minimum edge length.
    Returns:
      number: if distance is not specified, the current render mesh minimum edge length if successful.
      number: if distance is specified, the previous render mesh minimum edge length if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = current.MinimumEdgeLength
    if distance is not None:
        current.MinimumEdgeLength = distance
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshMinInitialGridQuads(quads=None):
    """Returns or sets the render mesh minimum initial grid quads parameter of the active document.
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
    Parameters:
      quads (number, optional): the render mesh minimum initial grid quads. The suggested range is from 0 to 10000.
    Returns:
      number: if quads is not specified, the current render mesh minimum initial grid quads if successful.
      number: if quads is specified, the previous render mesh minimum initial grid quads if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = current.GridMinCount
    if quads is not None:
        current.GridMinCount = quads
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderMeshQuality(quality=None):
    """Returns or sets the render mesh quality of the active document.
        For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
      Parameters:
      quality (number, optional): the render mesh quality, either:
        0: Jagged and faster.  Objects may look jagged, but they should shade and render relatively quickly.
        1: Smooth and slower.  Objects should look smooth, but they may take a very long time to shade and render.
        2: Custom.
    Returns:
      number: if quality is not specified, the current render mesh quality if successful.
      number: if quality is specified, the previous render mesh quality if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.MeshingParameterStyle
    if current == Rhino.Geometry.MeshingParameterStyle.Fast:
        rc = 0
    elif current == Rhino.Geometry.MeshingParameterStyle.Quality:
        rc = 1
    elif current == Rhino.Geometry.MeshingParameterStyle.Custom:
        rc = 2
    else:
        rc = None
    if quality is not None:
        if quality == 0:
            new_value = Rhino.Geometry.MeshingParameterStyle.Fast
        elif quality == 1:
            new_value = Rhino.Geometry.MeshingParameterStyle.Quality
        elif quality == 2:
            new_value = Rhino.Geometry.MeshingParameterStyle.Custom
        else:
            return None
        scriptcontext.doc.MeshingParameterStyle = new_value
    return rc


def RenderMeshSettings(settings=None):
    """Returns or sets the render mesh settings of the active document.
      For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.
    Parameters:
      settings (number, optional): the render mesh settings, which is a bit-coded number that allows or disallows certain features.
      The bits can be added together in any combination to form a value between 0 and 7.  The bit values are as follows:
        0: No settings enabled.
        1: Refine mesh enabled.
        2: Jagged seams enabled.
        4: Simple planes enabled.
        8: Texture is packed, scaled and normalized; otherwise unpacked, unscaled and normalized.
    Returns:
      number: if settings is not specified, the current render mesh settings if successful.
      number: if settings is specified, the previous render mesh settings if successful.
      None: if not successful, or on error.
    Example:
      import rhinoscriptsyntax as  rs
      print("Quality: %s" % rs.RenderMeshQuality())
      print("Mesh density: %s" % rs.RenderMeshDensity())
      print("Maximum angle: %s" % rs.RenderMeshMaxAngle())
      print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio())
      print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength())
      print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength())
      print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf())
      print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads())
      print("Other settings: %s" % rs.RenderMeshSettings())
    See Also:
      RenderMeshDensity
      RenderMeshMaxAngle
      RenderMeshMaxAspectRatio
      RenderMeshMaxDistEdgeToSrf
      RenderMeshMaxEdgeLength
      RenderMeshMinEdgeLength
      RenderMeshMinInitialGridQuads
      RenderMeshQuality
      RenderMeshSettings
    """
    current = scriptcontext.doc.GetCurrentMeshingParameters()
    rc = 0
    if current.RefineGrid: rc += 1
    if current.JaggedSeams: rc += 2
    if current.SimplePlanes: rc += 4
    if current.TextureRange == Rhino.Geometry.MeshingParameterTextureRange.PackedScaledNormalized: rc += 8
    if settings is not None:
        current.RefineGrid = (settings & 1)
        current.JaggedSeams = (settings & 2)
        current.SimplePlanes = (settings & 4)
        current.TextureRange = Rhino.Geometry.MeshingParameterTextureRange.PackedScaledNormalized if (settings & 8) else Rhino.Geometry.MeshingParameterTextureRange.UnpackedUnscaledNormalized
        _SetRenderMeshAndUpdateStyle(current)
    return rc


def RenderSettings(settings=None):
    """Returns or sets render settings
    Parameters:
      settings (number, optional): bit-coded flags of render settings to modify.
        0=none,
        1=create shadows,
        2=use lights on layers that are off,
        4=render curves and isocurves,
        8=render dimensions and text
    Returns:
      number: if settings are not specified, the current render settings in bit-coded flags
      number: if settings are specified, the previous render settings in bit-coded flags
    Example:
      import rhinoscriptsyntax as rs
      render_annotations = 8
      settings = rs.RenderSettings()
      if settings & render_annotations:
          settings = settings - render_annotations
          rs.RenderSettings( settings )
    See Also:
      RenderAntialias
      RenderColor
      RenderResolution
    """
    rc = 0
    rendersettings = scriptcontext.doc.RenderSettings
    if rendersettings.ShadowmapLevel: rc+=1
    if rendersettings.UseHiddenLights: rc+=2
    if rendersettings.RenderCurves: rc+=4
    if rendersettings.RenderAnnotations: rc+=8
    if settings is not None:
        rendersettings.ShadowmapLevel = (settings & 1)
        rendersettings.UseHiddenLights = (settings & 2)==2
        rendersettings.RenderCurves = (settings & 4)==4
        rendersettings.RenderAnnotations = (settings & 8)==8
        scriptcontext.doc.RenderSettings = rendersettings
    return rc


def UnitAbsoluteTolerance(tolerance=None, in_model_units=True):
    """Resturns or sets the document's absolute tolerance. Absolute tolerance
    is measured in drawing units. See Rhino's document properties command
    (Units and Page Units Window) for details
    Parameters:
      tolerance (number, optional): the absolute tolerance to set
      in_model_units (bool, optional): Return or modify the document's model units (True)
                            or the document's page units (False)
    Returns:
      number: if tolerance is not specified, the current absolute tolerance
      number: if tolerance is specified, the previous absolute tolerance
    Example:
      import rhinoscriptsyntax as rs
      tol = rs.UnitAbsoluteTolerance()
      if tol<0.01:
          rs.UnitAbsoluteTolerance( 0.01 )
    See Also:
      UnitAngleTolerance
      UnitDistanceDisplayPrecision
      UnitRelativeTolerance
      UnitSystem
    """
    if in_model_units:
        rc = scriptcontext.doc.ModelAbsoluteTolerance
        if tolerance is not None:
            scriptcontext.doc.ModelAbsoluteTolerance = tolerance
    else:
        rc = scriptcontext.doc.PageAbsoluteTolerance
        if tolerance is not None:
            scriptcontext.doc.PageAbsoluteTolerance = tolerance
    return rc


def UnitAngleTolerance(angle_tolerance_degrees=None, in_model_units=True):
    """Return or set the document's angle tolerance. Angle tolerance is
    measured in degrees. See Rhino's DocumentProperties command
    (Units and Page Units Window) for details
    Parameters:
      angle_tolerance_degrees (number, optional): the angle tolerance to set
      in_model_units (number, optional): Return or modify the document's model units (True)
                             or the document's page units (False)
    Returns:
      number: if angle_tolerance_degrees is not specified, the current angle tolerance
      number: if angle_tolerance_degrees is specified, the previous angle tolerance
    Example:
      import rhinoscriptsyntax as rs
      tol = rs.UnitAngleTolerance()
      if tol<3.0:
          rs.UnitAngleTolerance(3.0)
    See Also:
      UnitAbsoluteTolerance
      UnitDistanceDisplayPrecision
      UnitRelativeTolerance
      UnitSystem
    """
    if in_model_units:
        rc = scriptcontext.doc.ModelAngleToleranceDegrees
        if angle_tolerance_degrees is not None:
            scriptcontext.doc.ModelAngleToleranceDegrees = angle_tolerance_degrees
    else:
        rc = scriptcontext.doc.PageAngleToleranceDegrees
        if angle_tolerance_degrees is not None:
            scriptcontext.doc.PageAngleToleranceDegrees = angle_tolerance_degrees
    return rc


def UnitDistanceDisplayPrecision(precision=None, model_units=True):
    """Return or set the document's distance display precision
    Parameters:
      precision (number, optional): The distance display precision.  If the current distance display mode is Decimal, then precision is the number of decimal places.
                                    If the current distance display mode is Fractional (including Feet and Inches), then the denominator = (1/2)^precision.
                                    Use UnitDistanceDisplayMode to get the current distance display mode.
      model_units (bool, optional): Return or modify the document's model units (True) or the document's page units (False). The default is True.
    Returns:
     number: If precision is not specified, the current distance display precision if successful. If precision is specified, the previous distance display precision if successful. If not successful, or on error.
    Example:
      import rhinoscriptsyntax as rs
      precision = 3
      rs.UnitDistanceDisplayPrecision( precision )
    See Also:
      UnitAbsoluteTolerance
      UnitAngleTolerance
      UnitRelativeTolerance
      UnitSystem
    """
    if model_units:
        rc = scriptcontext.doc.ModelDistanceDisplayPrecision
        if precision: scriptcontext.doc.ModelDistanceDisplayPrecision = precision
        return rc
    rc = scriptcontext.doc.PageDistanceDisplayPrecision
    if precision: scriptcontext.doc.PageDistanceDisplayPrecision = precision
    return rc


def UnitRelativeTolerance(relative_tolerance=None, in_model_units=True):
    """Return or set the document's relative tolerance. Relative tolerance
    is measured in percent. See Rhino's DocumentProperties command
    (Units and Page Units Window) for details
    Parameters:
      relative_tolerance (number, optional) the relative tolerance in percent
      in_model_units (bool, optional): Return or modify the document's model units (True)
                             or the document's page units (False)
    Returns:
      number: if relative_tolerance is not specified, the current tolerance in percent
      number: if relative_tolerance is specified, the previous tolerance in percent
    Example:
      import rhinoscriptsyntax as rs
      tol = rs.UnitRelativeTolerance()
      if tol<1.0:
          rs.UnitRelativeTolerance(1.0)
    See Also:
      UnitAbsoluteTolerance
      UnitAngleTolerance
      UnitDistanceDisplayPrecision
      UnitSystem
    """
    if in_model_units:
        rc = scriptcontext.doc.ModelRelativeTolerance
        if relative_tolerance is not None:
            scriptcontext.doc.ModelRelativeTolerance = relative_tolerance
    else:
        rc = scriptcontext.doc.PageRelativeTolerance
        if relative_tolerance is not None:
            scriptcontext.doc.PageRelativeTolerance = relative_tolerance
    return rc


def UnitScale(to_system, from_system=None):
  """Return the scale factor for changing between unit systems.
  Parameters:
    to_system (number): The unit system to convert to. The unit systems are are:
       0 - No unit system
       1 - Microns (1.0e-6 meters)
       2 - Millimeters (1.0e-3 meters)
       3 - Centimeters (1.0e-2 meters)
       4 - Meters
       5 - Kilometers (1.0e+3 meters)
       6 - Microinches (2.54e-8 meters, 1.0e-6 inches)
       7 - Mils (2.54e-5 meters, 0.001 inches)
       8 - Inches (0.0254 meters)
       9 - Feet (0.3408 meters, 12 inches)
      10 - Miles (1609.344 meters, 5280 feet)
      11 - *Reserved for custom Unit System*
      12 - Angstroms (1.0e-10 meters)
      13 - Nanometers (1.0e-9 meters)
      14 - Decimeters (1.0e-1 meters)
      15 - Dekameters (1.0e+1 meters)
      16 - Hectometers (1.0e+2 meters)
      17 - Megameters (1.0e+6 meters)
      18 - Gigameters (1.0e+9 meters)
      19 - Yards (0.9144  meters, 36 inches)
      20 - Printer point (1/72 inches, computer points)
      21 - Printer pica (1/6 inches, (computer picas)
      22 - Nautical mile (1852 meters)
      23 - Astronomical (1.4959787e+11)
      24 - Lightyears (9.46073e+15 meters)
      25 - Parsecs (3.08567758e+16)
    from_system (number, optional): the unit system to convert from (see above). If omitted,
        the document's current unit system is used
  Returns:
    number: scale factor for changing between unit systems
  Example:
      import rhinoscriptsyntax as rs
      print(rs.UnitScale(3, 4)) # 100.0
      print(rs.UnitScale(3, 8)) # 2.54
      print(rs.UnitScale(8, 9)) # 12.0
    See Also:
    UnitSystem
    UnitSystemName
  """
  if from_system is None:
      from_system = scriptcontext.doc.ModelUnitSystem
  if type(from_system) is int:
      from_system = System.Enum.ToObject(Rhino.UnitSystem, from_system)
  if type(to_system) is int:
      to_system = System.Enum.ToObject(Rhino.UnitSystem, to_system)
  return Rhino.RhinoMath.UnitScale(from_system, to_system)


def UnitSystem(unit_system=None, scale=False, in_model_units=True):
    """Return or set the document's unit system. See Rhino's DocumentProperties
    command (Units and Page Units Window) for details
    Parameters:
      unit_system (number, optional): The unit system to set the document to. The unit systems are:
         0 - No unit system
         1 - Microns (1.0e-6 meters)
         2 - Millimeters (1.0e-3 meters)
         3 - Centimeters (1.0e-2 meters)
         4 - Meters
         5 - Kilometers (1.0e+3 meters)
         6 - Microinches (2.54e-8 meters, 1.0e-6 inches)
         7 - Mils (2.54e-5 meters, 0.001 inches)
         8 - Inches (0.0254 meters)
         9 - Feet (0.3048 meters, 12 inches)
        10 - Miles (1609.344 meters, 5280 feet)
        11 - *Reserved for custom Unit System*
        12 - Angstroms (1.0e-10 meters)
        13 - Nanometers (1.0e-9 meters)
        14 - Decimeters (1.0e-1 meters)
        15 - Dekameters (1.0e+1 meters)
        16 - Hectometers (1.0e+2 meters)
        17 - Megameters (1.0e+6 meters)
        18 - Gigameters (1.0e+9 meters)
        19 - Yards (0.9144  meters, 36 inches)
        20 - Printer point (1/72 inches, computer points)
        21 - Printer pica (1/6 inches, (computer picas)
        22 - Nautical mile (1852 meters)
        23 - Astronomical (1.4959787e+11)
        24 - Lightyears (9.46073e+15 meters)
        25 - Parsecs (3.08567758e+16)
      scale (bool, optional): Scale existing geometry based on the new unit system.
          If not specified, any existing geometry is not scaled (False)
      in_model_units (number, optional): Return or modify the document's model units (True)
          or the document's page units (False). The default is True.
    Returns:
      number: if unit_system is not specified, the current unit system
      number: if unit_system is specified, the previous unit system
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      rhUnitMillimeters = 2
      rhUnitInches = 8
      current_system = rs.UnitSystem()
      if current_system==rhUnitMillimeters:
          rs.UnitSystem(rhUnitInches, True)
    See Also:
      UnitAbsoluteTolerance
      UnitAngleTolerance
      UnitDistanceDisplayPrecision
      UnitRelativeTolerance
    """
    if (unit_system is not None and (unit_system<1 or unit_system>25)):
        raise ValueError("unit_system value of %s is not valid"%unit_system)
    if in_model_units:
        rc = int(scriptcontext.doc.ModelUnitSystem)
        if unit_system is not None:
            unit_system = System.Enum.ToObject(Rhino.UnitSystem, unit_system)
            scriptcontext.doc.AdjustModelUnitSystem(unit_system, scale)
    else:
        rc = int(scriptcontext.doc.PageUnitSystem)
        if unit_system is not None:
            unit_system = System.Enum.ToObject(Rhino.UnitSystem, unit_system)
            scriptcontext.doc.AdjustPageUnitSystem(unit_system, scale)
    return rc


def UnitSystemName(capitalize=False, singular=True, abbreviate=False, model_units=True):
    """Returns the name of the current unit system
    Parameters:
      capitalize (bool, optional): Capitalize the first character of the units system name (e.g. return "Millimeter" instead of "millimeter"). The default is not to capitalize the first character (false).
      singular (bool, optional): Return the singular form of the units system name (e.g. "millimeter" instead of "millimeters"). The default is to return the singular form of the name (true).
      abbreviate (bool, optional): Abbreviate the name of the units system (e.g. return "mm" instead of "millimeter"). The default is not to abbreviate the name (false).
      model_units (bool, optional): Return the document's model units (True) or the document's page units (False). The default is True.
    Returns:
      str: The name of the current units system if successful.
    Example:
      import rhinoscriptsyntax as rs
      system = rs.UnitSystemName(False, False, False)
      print("The units system is set to{}".format(system))
    See Also:
      UnitSystem
    """
    return scriptcontext.doc.GetUnitSystemName(model_units, capitalize, singular, abbreviate)

```

--------------------------------------------------------------------------------
/rhino_mcp_server/static/dimension.py:
--------------------------------------------------------------------------------

```python
import System

import Rhino

import scriptcontext

from rhinoscript import utility as rhutil
from rhinoscript.view import __viewhelper, ViewCPlane


def __coerceannotation(object_id):
    annotation_object = rhutil.coercerhinoobject(object_id, True)
    if not isinstance(annotation_object, Rhino.DocObjects.AnnotationObjectBase):
        raise ValueError("object_id does not refer to an Annotation")
    return annotation_object


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 (point): first point of dimension
      end_point (point): second point of dimension
      point_on_dimension_line (point): location point of dimension line
      style (str, optional): name of dimension style
    Returns:
      guid: identifier of new dimension on success
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      origin = 1, 1, 0
      offset = 11, 5, 0
      point = 1, 3, 0
      rs.AddAlignedDimension( origin, offset, point )
    See Also:
      IsAlignedDimension
    """
    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)
    if not plane.IsValid:
      # usually when points passed to ctor are colinear
      plane = ViewCPlane()
    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.FindName(style)
        if ds is None: return scriptcontext.errorhandler()
        ldim.DimensionStyleId = ds.Id
    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


def AddDimStyle(dimstyle_name=None):
    """Adds a new dimension style to the document. The new dimension style will
    be initialized with the current default dimension style properties.
    Parameters:
      dimstyle_name (str, optional): name of the new dimension style. If omitted, Rhino automatically generates the dimension style name
    Returns:
      str: name of the new dimension style on success
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      print("New dimension style: {}".format(rs.AddDimStyle()))
      print("New dimension style: {}".format(rs.AddDimStyle("MyDimStyle")))
    See Also:
      CurrentDimStyle
      DeleteDimStyle
      IsDimStyle
      RenameDimStyle
    """
    index = scriptcontext.doc.DimStyles.Add(dimstyle_name)
    if index<0: return scriptcontext.errorhandler()
    ds = scriptcontext.doc.DimStyles[index]
    return ds.Name


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 ([point, point, ....])list of (at least 2) 3D points
      view_or_plane (str, optional): If a view name 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 (str, optional): leader's text string
    Returns:
      guid: 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 AddLinearDimension(plane, start_point, end_point, point_on_dimension_line):
    """Adds a linear dimension to the document
    Parameters:
      plane (plane): The plane on which the dimension will lie.
      start_point (point): The origin, or first point of the dimension.
      end_point (point): The offset, or second point of the dimension.
      point_on_dimension_line (point): A point that lies on the dimension line.
    Returns:
      guid: identifier of the new object on success
      None: on error
    Example:
      import rhinoscriptsyntax as  rs
      points = rs.GetPoints(True,  False, "Select 3 dimension points")
      if points and len(points)>2:
          rs.AddLinearDimension(rs.WorldXYPlane(),  points[0], points[1], points[2] )
    See Also:
      IsLeader
      LeaderText
    """
    if not plane: 
      plane = ViewCPlane()
    else:
      plane = rhutil.coerceplane(plane, True)
    start = rhutil.coerce3dpoint(start_point, True)
    plane.Origin = start
    end = rhutil.coerce3dpoint(end_point, True)
    onpoint = rhutil.coerce3dpoint(point_on_dimension_line, True)
    # Calculate 2d dimension points
    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)    
    # Add the dimension
    ldim = Rhino.Geometry.LinearDimension(plane, 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


def CurrentDimStyle(dimstyle_name=None):
    """Returns or changes the current default dimension style
    Parameters:
      dimstyle_name (str, optional): name of an existing dimension style to make current
    Returns:
      str: if dimstyle_name is not specified, name of the current dimension style
      str: if dimstyle_name is specified, name of the previous dimension style
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      rs.AddDimStyle("MyDimStyle")
      rs.CurrentDimStyle("MyDimStyle")
    See Also:
      AddDimStyle
      DeleteDimStyle
      IsDimStyle
      RenameDimStyle
    """
    rc = scriptcontext.doc.DimStyles.Current.Name
    if dimstyle_name:
        ds = scriptcontext.doc.DimStyles.FindName(dimstyle_name)
        if ds is None: return scriptcontext.errorhandler()
        scriptcontext.doc.DimStyles.SetCurrent(ds.Index, False)
    return rc


def DeleteDimStyle(dimstyle_name):
    """Removes an existing dimension style from the document. The dimension style
    to be removed cannot be referenced by any dimension objects.
    Parameters:
      dimstyle_name (str): the name of an unreferenced dimension style
    Returns:
      str: The name of the deleted dimension style if successful
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.GetString("Dimension style to remove")
      if dimstyle: rs.DeleteDimStyle(dimstyle)
    See Also:
      AddDimStyle
      CurrentDimStyle
      IsDimStyle
      RenameDimStyle
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle_name)
    if ds and scriptcontext.doc.DimStyles.DeleteDimensionStyle(ds.Index, True):
        return dimstyle_name
    return scriptcontext.errorhandler()


def DimensionStyle(object_id, dimstyle_name=None):
    """Returns or modifies the dimension style of a dimension object
    Parameters:
      object_id (guid): identifier of the object
      dimstyle_name (str, optional): the name of an existing dimension style
    Returns:
      str: if dimstyle_name is not specified, the object's current dimension style name
      str: if dimstyle_name is specified, the object's previous dimension style name
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsDimension(obj): rs.DimensionStyle(obj, "Default")
    See Also:
      DimStyleNames
      IsDimStyle
    """
    annotation_object = __coerceannotation(object_id)
    ds = annotation_object.AnnotationGeometry.ParentDimensionStyle
    rc = ds.Name
    if dimstyle_name:
        ds = scriptcontext.doc.DimStyles.FindName(dimstyle_name)
        if not ds: return scriptcontext.errorhandler()
        annotation = annotation_object.Geometry
        annotation.DimensionStyleId = ds.Id
        annotation_object.CommitChanges()
    return rc


def DimensionText(object_id):
    """Returns the text displayed by a dimension object
    Parameters:
      object_id (guid): identifier of the object
    Returns:
      str: the text displayed by a dimension object
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsDimension(obj):
          print(rs.DimensionText(obj))
    See Also:
      DimensionUserText
      DimensionValue
      IsDimension
    """
    annotation_object = __coerceannotation(object_id)
    return annotation_object.DisplayText


def DimensionUserText(object_id, usertext=None):
    """Returns of modifies the user text string of a dimension object. The user
    text is the string that gets printed when the dimension is defined
    Parameters:
      object_id (guid): identifier of the object
      usertext (str, optional): the new user text string value
    Returns:
      str: if usertext is not specified, the current usertext string
      str: if usertext is specified, the previous usertext string
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsDimension(obj):
          usertext = "!= " + chr(177) + str(rs.UnitAbsoluteTolerance())
          rs.DimensionUserText( obj, usertext )
    See Also:
      DimensionText
      DimensionValue
      IsDimension
    """
    annotation_object = __coerceannotation(object_id)
    rc = annotation_object.Geometry.Text
    if usertext is not None:
        annotation_object.Geometry.Text = usertext
        annotation_object.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc


def DimensionValue(object_id):
    """Returns the value of a dimension object
    Parameters:
      object_id (guid): identifier of the object
    Returns:
      number: numeric value of the dimension if successful
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsDimension(obj):
          print(rs.DimensionValue(obj))
    See Also:
      DimensionText
      DimensionUserText
      IsDimension
    """
    annotation_object = __coerceannotation(object_id)
    return annotation_object.Geometry.NumericValue


def DimStyleAnglePrecision(dimstyle, precision=None):
    """Returns or changes the angle display precision of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      precision (number, optional): the new angle precision value. If omitted, the current angle
        precision is returned
    Returns:
      number: If a precision is not specified, the current angle precision
      number: If a precision is specified, the previous angle precision
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      precision = rs.DimStyleAnglePrecision(dimstyle)
      if precision>2:
          rs.DimStyleAnglePrecision( dimstyle, 2 )
    See Also:
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.AngleResolution
    if precision is not None:
        ds.AngleResolution = precision
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleArrowSize(dimstyle, size=None):
    """Returns or changes the arrow size of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      size (number, optional): the new arrow size. If omitted, the current arrow size is returned
    Returns:
      number: If size is not specified, the current arrow size
      number: If size is specified, the previous arrow size
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      size = rs.DimStyleArrowSize(dimstyle)
      if size>1.0: rs.DimStyleArrowSize( dimstyle, 1.0 )
    See Also:
      DimStyleAnglePrecision
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.ArrowLength
    if size is not None:
        ds.ArrowLength = size
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleCount():
    """Returns the number of dimension styles in the document
    Returns:
      number: the number of dimension styles in the document
    Example:
      import rhinoscriptsyntax as rs
      count = rs.DimStyleCount()
      print("There are", count, "dimension styles.")
    See Also:
      DimStyleNames
      IsDimStyle
    """
    return scriptcontext.doc.DimStyles.Count


def DimStyleExtension(dimstyle, extension=None):
    """Returns or changes the extension line extension of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      extension (number, optional): the new extension line extension
    Returns:
      number: if extension is not specified, the current extension line extension
      number: if extension is specified, the previous extension line extension
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      extension = rs.DimStyleExtension(dimstyle)
      if extension>0.5: rs.DimStyleExtension( dimstyle, 0.5 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.ExtensionLineExtension
    if extension is not None:
        ds.ExtensionLineExtension = extension
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleFont(dimstyle, font=None):
    """Returns or changes the font used by a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      font (str, optional): the new font face name
    Returns:
      str: if font is not specified, the current font if successful
      str: if font is specified, the previous font if successful
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      font = rs.DimStyleFont(dimstyle)
      if font!="Arial": rs.DimStyleFont( dimstyle, "Arial" )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.Font.FaceName
    if font:
        newindex = scriptcontext.doc.Fonts.FindOrCreate(font, False, False)
        ds.Font = scriptcontext.doc.Fonts[newindex]
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleLeaderArrowSize(dimstyle, size=None):
    """Returns or changes the leader arrow size of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      size (number, optional) the new leader arrow size
    Returns:
      number: if size is not specified, the current leader arrow size
      number: if size is specified, the previous leader arrow size
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      size = rs.DimStyleLeaderArrowSize(dimstyle)
      if size>1.0: rs.DimStyleLeaderArrowSize( dimstyle, 1.0 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.LeaderArrowLength
    if size is not None:
        ds.LeaderArrowLength = size
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleLengthFactor(dimstyle, factor=None):
    """Returns or changes the length factor of a dimension style. Length factor
    is the conversion between Rhino units and dimension units
    Parameters:
      dimstyle (str): the name of an existing dimension style
      factor (number, optional): the new length factor
    Returns:
      number: if factor is not defined, the current length factor
      number: if factor is defined, the previous length factor
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      factor = rs.DimStyleLengthFactor(dimstyle)
      if factor>1.0: rs.DimStyleLengthFactor( dimstyle, 1.0 )
    See Also:
      DimStylePrefix
      DimStyleSuffix
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.LengthFactor
    if factor is not None:
        ds.LengthFactor = factor
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleLinearPrecision(dimstyle, precision=None):
    """Returns or changes the linear display precision of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      precision (number, optional): the new linear precision value
    Returns:
      number: if precision is not specified, the current linear precision value
      number: if precision is specified, the previous linear precision value
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      precision = rs.DimStyleLinearPrecision(dimstyle)
      if precision>2: rs.DimStyleLinearPrecision( dimstyle, 2 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.LengthResolution
    if precision is not None:
        ds.LengthResolution = precision
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleNames(sort=False):
    """Returns the names of all dimension styles in the document
    Parameters:
      sort (bool): sort the list if True, not sorting is the default (False)
    Returns:
      list(str, ...): the names of all dimension styles in the document
    Example:
      import rhinoscriptsyntax as rs
      dimstyles = rs.DimStyleNames()
      if dimstyles:
          for dimstyle in dimstyles: print(dimstyle)
    See Also:
      DimStyleCount
      IsDimStyle
    """
    rc = [ds.Name for ds in scriptcontext.doc.DimStyles]
    if sort: rc.sort()
    return rc


def DimStyleNumberFormat(dimstyle, format=None):
    """Returns or changes the number display format of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      format (number, optional) the new number format
         0 = Decimal
         1 = Fractional
         2 = Feet and inches
    Returns:
      number: if format is not specified, the current display format
      number: if format is specified, the previous display format
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      format = rs.DimStyleNumberFormat(dimstyle)
      if format>0: rs.DimStyleNumberFormat( dimstyle, 0 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = int(ds.LengthFormat)
    if format is not None:
        if format==0: ds.LengthFormat = Rhino.DocObjects.DistanceDisplayMode.Decimal
        if format==1: ds.LengthFormat = Rhino.DocObjects.DistanceDisplayMode.Feet
        if format==2: ds.LengthFormat = Rhino.DocObjects.DistanceDisplayMode.FeetAndInches
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleOffset(dimstyle, offset=None):
    """Returns or changes the extension line offset of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      offset (number, optional): the new extension line offset
    Returns:
      number: if offset is not specified, the current extension line offset
      number: if offset is specified, the previous extension line offset
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      offset = rs.DimStyleOffset(dimstyle)
      if offset>0.5: rs.DimStyleOffset( dimstyle, 0.5 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.ExtensionLineOffset
    if offset is not None:
        ds.ExtensionLineOffset = offset
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStylePrefix(dimstyle, prefix=None):
    """Returns or changes the prefix of a dimension style - the text to
    prefix to the dimension text.
    Parameters:
      dimstyle (str): the name of an existing dimstyle
      prefix (str, optional): the new prefix
    Returns:
      str: if prefix is not specified, the current prefix
      str: if prefix is specified, the previous prefix
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      rs.DimStylePrefix( dimstyle, "[" )
    See Also:
      DimStyleLengthFactor
      DimStyleSuffix
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.Prefix
    if prefix is not None:
        ds.Prefix = prefix
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleScale(dimstyle, scale=None):
    """Returns or modifies the scale of a dimension style.
    Parameters:
      dimstyle (str): the name of an existing dimstyle
      scale (number, optional): the new scale value
    Returns:
      number: if scale is not specified, the current scale
      number: if scale is specified, the previous scale
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      from scriptcontext import doc
      dimstyle = doc.DimStyles.Current
      scale = rs.DimStyleScale(dimstyle)
      rs.DimStyleScale(dimstyle, scale*2.0)
    See Also:
      DimStyleTextHeight
      DimStyleOffset
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.DimensionScale
    if scale is not None:
        ds.DimensionScale = scale
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleSuffix(dimstyle, suffix=None):
    """Returns or changes the suffix of a dimension style - the text to
    append to the dimension text.
    Parameters:
      dimstyle (str): the name of an existing dimstyle
      suffix (str, optional): the new suffix
    Returns:
      str: if suffix is not specified, the current suffix
      str: if suffix is specified, the previous suffix
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      rs.DimStyleSuffix( dimstyle, "}" )
    See Also:
      DimStyleLengthFactor
      DimStylePrefix
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.Suffix
    if suffix is not None:
        ds.Suffix = suffix
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleTextAlignment(dimstyle, alignment=None):
    """Returns or changes the text alignment mode of a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      alignment (number, optional): the new text alignment
          0 = Normal (same as 2)
          1 = Horizontal to view
          2 = Above the dimension line
          3 = In the dimension line
    Returns:
      number: if alignment is not specified, the current text alignment
      number: if alignment is specified, the previous text alignment
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      alignment = rs.DimStyleTextAlignment(dimstyle)
      if alignment!=2: rs.DimStyleTextAlignment( dimstyle, 2 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    # NOTE:
    # this function is about text alignment so return alignment value
    rc = int(ds.DimTextLocation)
    if alignment is not None:
        # NOTE:
        # for backward compatibility, lets set the "horizontal to view" if
        # alignment value is '1' - eirannejad 2025-03-17 (RH-86539)
        if alignment==1: ds.DimTextOrientation = Rhino.DocObjects.TextOrientation.InView

        # set dim text location
        if alignment==3: ds.DimTextLocation = Rhino.DocObjects.DimensionStyle.TextLocation.InDimLine
        if alignment==0 or alignment==2:
          ds.DimTextLocation = Rhino.DocObjects.DimensionStyle.TextLocation.AboveDimLine  # default

        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleTextGap(dimstyle, gap=None):
    """Returns or changes the text gap used by a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      gap (number, optional): the new text gap
    Returns:
      number: if gap is not specified, the current text gap
      number: if gap is specified, the previous text gap
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      gap = rs.DimStyleTextGap(dimstyle)
      if gap>0.25: rs.DimStyleTextGap( dimstyle, 0.25 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
      DimStyleTextHeight
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.TextGap
    if gap is not None:
        ds.TextGap = gap
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def DimStyleTextHeight(dimstyle, height=None):
    """Returns or changes the text height used by a dimension style
    Parameters:
      dimstyle (str): the name of an existing dimension style
      height (number, optional): the new text height
    Returns:
      number: if height is not specified, the current text height
      number: if height is specified, the previous text height
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.CurrentDimStyle()
      height = rs.DimStyleTextHeight(dimstyle)
      if offset>1.0: rs.DimStyleTextHeight( dimstyle, 1.0 )
    See Also:
      DimStyleAnglePrecision
      DimStyleArrowSize
      DimStyleExtension
      DimStyleFont
      DimStyleLinearPrecision
      DimStyleNumberFormat
      DimStyleOffset
      DimStyleTextAlignment
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    rc = ds.TextHeight
    if height:
        ds.TextHeight = height
        scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False)
        scriptcontext.doc.Views.Redraw()
    return rc


def IsAlignedDimension(object_id):
    """Verifies an object is an aligned dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.  None on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsAlignedDimension(obj):
          print("The object is an aligned dimension.")
      else:
          print("The object is not an aligned dimension.")
    See Also:
      IsAngularDimension
      IsDiameterDimension
      IsDimension
      IsLinearDimension
      IsOrdinateDimension
      IsRadialDimension
    """
    annotation_object = __coerceannotation(object_id)
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    if isinstance(geom, Rhino.Geometry.LinearDimension): return geom.Aligned
    return False


def IsAngularDimension(object_id):
    """Verifies an object is an angular dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsAngularDimension(obj):
          print("The object is an angular dimension.")
      else:
          print("The object is not an angular dimension.")
    See Also:
      IsAlignedDimension
      IsDiameterDimension
      IsDimension
      IsLinearDimension
      IsOrdinateDimension
      IsRadialDimension
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    return isinstance(geom, Rhino.Geometry.AngularDimension)


def IsDiameterDimension(object_id):
    """Verifies an object is a diameter dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsDiameterDimension(obj):
          print("The object is a diameter dimension.")
      else:
          print("The object is not a diameter dimension.")
    See Also:
      IsAlignedDimension
      IsAngularDimension
      IsDimension
      IsLinearDimension
      IsOrdinateDimension
      IsRadialDimension
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    if isinstance(geom, Rhino.Geometry.RadialDimension):
        return geom.IsDiameterDimension
    return False


def IsDimension(object_id):
    """Verifies an object is a dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsDimension(obj):
          print("The object is a dimension.")
      else:
          print("The object is not a dimension.")
    See Also:
      IsAlignedDimension
      IsAngularDimension
      IsDiameterDimension
      IsLinearDimension
      IsOrdinateDimension
      IsRadialDimension
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    return isinstance(geom, Rhino.Geometry.AnnotationBase)


def IsDimStyle(dimstyle):
    """Verifies the existance of a dimension style in the document
    Parameters:
      dimstyle (str): the name of a dimstyle to test for
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.GetString("Dimension style to test")
      if rs.IsDimStyle(dimstyle):
          if rs.IsDimStyleReference(dimstyle):
              print("The dimension style is from a reference file.")
          else:
              print("The dimension style is not from a reference file.")
      else:
          print("The dimension style does not exist.")
    See Also:
      IsDimStyleReference
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    return ds is not None


def IsDimStyleReference(dimstyle):
    """Verifies that an existing dimension style is from a reference file
    Parameters:
      dimstyle (str): the name of an existing dimension style
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      dimstyle = rs.GetString("Dimension style to test")
      if rs.IsDimStyle(dimstyle):
          if rs.IsDimStyleReference(dimstyle):
              print("The dimension style is from a reference file.")
          else:
              print("The dimension style is not from a reference file.")
      else:
          print("The dimension style does not exist.")
    See Also:
      IsDimStyle
    """
    ds = scriptcontext.doc.DimStyles.FindName(dimstyle)
    if ds is None: return scriptcontext.errorhandler()
    return ds.IsReference


def IsLeader(object_id):
    """Verifies an object is a dimension leader object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a leader")
      if rs.IsLeader(obj):
          print("The object is a leader.")
      else:
          print("The object is not a leader.")
    See Also:
      AddLeader
      LeaderText
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    return isinstance(geom, Rhino.Geometry.Leader)


def IsLinearDimension(object_id):
    """Verifies an object is a linear dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsLinearDimension(obj):
          print("The object is a linear dimension.")
      else:
          print("The object is not a linear dimension.")
    See Also:
      IsAlignedDimension
      IsAngularDimension
      IsDiameterDimension
      IsDimension
      IsOrdinateDimension
      IsRadialDimension
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    return isinstance(geom, Rhino.Geometry.LinearDimension)


def IsOrdinateDimension(object_id):
    """Verifies an object is an ordinate dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsOrdinateDimension(obj):
          print("The object is an ordinate dimension.")
      else:
          print("The object is not an ordinate dimension.")
    See Also:
      IsAlignedDimension
      IsAngularDimension
      IsDiameterDimension
      IsDimension
      IsLinearDimension
      IsRadialDimension
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    return isinstance(geom, Rhino.Geometry.OrdinateDimension)


def IsRadialDimension(object_id):
    """Verifies an object is a radial dimension object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True or False.
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a dimension")
      if rs.IsRadialDimension(obj):
          print("The object is a radial dimension.")
      else:
          print("The object is not a radial dimension.")
    See Also:
      IsAlignedDimension
      IsAngularDimension
      IsDiameterDimension
      IsDimension
      IsLinearDimension
      IsOrdinateDimension
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    return isinstance(geom, Rhino.Geometry.RadialDimension)


def LeaderText(object_id, text=None):
    """Returns or modifies the text string of a dimension leader object
    Parameters:
      object_id (guid): the object's identifier
      text (string, optional): the new text string
    Returns:
      str: if text is not specified, the current text string
      str: if text is specified, the previous text string
      None on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a leader")
      if rs.IsLeader(obj): print(rs.LeaderText(obj))
    See Also:
      AddLeader
      IsLeader
    """
    id = rhutil.coerceguid(object_id, True)
    annotation_object = scriptcontext.doc.Objects.Find(id)
    geom = annotation_object.Geometry
    if not isinstance(geom, Rhino.Geometry.Leader):
        return scriptcontext.errorhandler()
    rc = annotation_object.DisplayText
    if text is not None:
        geom.RichText = text
        annotation_object.CommitChanges()
        scriptcontext.doc.Views.Redraw()
    return rc


def RenameDimStyle(oldstyle, newstyle):
    """Renames an existing dimension style
    Parameters:
      oldstyle (str): the name of an existing dimension style
      newstyle (str): the new dimension style name
    Returns:
      str: the new dimension style name if successful
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      oldstyle = rs.GetString("Old dimension style name")
      if oldstyle:
          newstyle = rs.GetString("New dimension style name")
          if newstyle: rs.RenameDimStyle( oldstyle, newstyle )
    See Also:
      AddDimStyle
      CurrentDimStyle
      DeleteDimStyle
      IsDimStyle
    """
    ds = scriptcontext.doc.DimStyles.FindName(oldstyle)
    if not ds: return scriptcontext.errorhandler()
    ds.Name = newstyle
    if scriptcontext.doc.DimStyles.Modify(ds, ds.Id, False): return newstyle
    return None

```

--------------------------------------------------------------------------------
/rhino_mcp_server/static/geometry.py:
--------------------------------------------------------------------------------

```python
import System

import Rhino

import scriptcontext

from rhinoscript import utility as rhutil


def __simplify_PointCloudKNeighbors(result, amount):
    if amount == 1:
        return [item[0] for item in result]
    else:
        return [list(item) for item in result]


def __simplify_PointCloudClosestPoints(result):
    return [list(item) for item in result]


def AddClippingPlane(plane, u_magnitude, v_magnitude, views=None):
    """Create a clipping plane for visibly clipping away geometry in a specific
    view. Note, clipping planes are infinite
    Parameters:
      plane (plane): the plane
      u_magnitude, v_magnitude (number): size of the plane
      views ([str|guid, ...]): Titles or ids the the view(s) to clip. If omitted, the active
        view is used.
    Returns:
      guid: object identifier on success
      None: on failure
    Example:
      import rhinoscriptsyntax as rs
      rs.AddClippingPlane( rs.WorldXYPlane(), 5.0, 3.0 )
    See Also:
      IsClippingPlane
    """
    viewlist = []
    if views:
        if type(views) is System.Guid:
            viewlist.append(views)
        elif type(views) is str:
            modelviews = scriptcontext.doc.Views.GetViewList(True, False)
            rc = None
            for item in modelviews:
                if item.ActiveViewport.Name == views:
                    id = item.ActiveViewportID
                    rc = AddClippingPlane(plane, u_magnitude, v_magnitude, id)
                    break
            return rc
        else:
            if type(views[0]) is System.Guid:
                viewlist = views
            elif( type(views[0]) is str ):
                modelviews = scriptcontext.doc.Views.GetViewList(True,False)
                for viewname in views:
                    for item in modelviews:
                        if item.ActiveViewport.Name==viewname:
                            viewlist.append(item.ActiveViewportID)
                            break
    else:
        viewlist.append(scriptcontext.doc.Views.ActiveView.ActiveViewportID)
    if not viewlist: return scriptcontext.errorhandler()
    rc = scriptcontext.doc.Objects.AddClippingPlane(plane, u_magnitude, v_magnitude, viewlist)
    if rc==System.Guid.Empty: raise Exception("unable to add clipping plane to document")
    scriptcontext.doc.Views.Redraw()
    return rc


def AddPictureFrame(plane, filename, width=0.0, height=0.0, self_illumination=True, embed=False, use_alpha=False, make_mesh=False):
  """Creates a picture frame and adds it to the document.
  Parameters:
    plane (plane): The plane in which the PictureFrame will be created.  The bottom-left corner of picture will be at plane's origin. The width will be in the plane's X axis direction, and the height will be in the plane's Y axis direction.
    filename (str): The path to a bitmap or image file.
    width (number, optional): If both dblWidth and dblHeight = 0, then the width and height of the PictureFrame will be the width and height of the image. If dblWidth = 0 and dblHeight is > 0, or if dblWidth > 0 and dblHeight = 0, then the non-zero value is assumed to be an aspect ratio of the image's width or height, which ever one is = 0. If both dblWidth and dblHeight are > 0, then these are assumed to be the width and height of in the current unit system.
    height (number, optional):  If both dblWidth and dblHeight = 0, then the width and height of the PictureFrame will be the width and height of the image. If dblWidth = 0 and dblHeight is > 0, or if dblWidth > 0 and dblHeight = 0, then the non-zero value is assumed to be an aspect ratio of the image's width or height, which ever one is = 0. If both dblWidth and dblHeight are > 0, then these are assumed to be the width and height of in the current unit system.
    self_illumination (bool, optional): If True, then the image mapped to the picture frame plane always displays at full intensity and is not affected by light or shadow.
    embed (bool, optional): If True, then the function adds the image to Rhino's internal bitmap table, thus making the document self-contained.
    use_alpha (bool, optional): If False, the picture frame is created without any transparency texture.  If True, a transparency texture is created with a "mask texture" set to alpha, and an instance of the diffuse texture in the source texture slot.
    make_mesh (bool, optional): If True, the function will make a PictureFrame object from a mesh rather than a plane surface.
  Returns:
    guid: object identifier on success
    None: on failure
  Example:
    
  See Also:
    
  """
  plane = rhutil.coerceplane(plane, True)
  if not isinstance(filename, (str, System.String)) or not System.IO.File.Exists(filename): raise Exception('\"{0}\" does not exist or is not a file name'.format(filename))
  rc = scriptcontext.doc.Objects.AddPictureFrame(plane, filename, make_mesh, width, height, self_illumination, embed) 
  if rc==System.Guid.Empty: raise Exception("unable to add picture frame to document")
  scriptcontext.doc.Views.Redraw()
  return rc


def AddPoint(point, y=None, z=None):
    """Adds point object to the document.
    Parameters:
      point (point): a point3d or list(x,y,z) location of point to add
    Returns:
      guid: identifier for the object that was added to the doc
    Example:
      import rhinoscriptsyntax as rs
      rs.AddPoint( (1,2,3) )
    See Also:
      IsPoint
      PointCoordinates
    """
    if y is not None: point = Rhino.Geometry.Point3d(point, y, z or 0.0)
    point = rhutil.coerce3dpoint(point, True)
    rc = scriptcontext.doc.Objects.AddPoint(point)
    if rc==System.Guid.Empty: raise Exception("unable to add point to document")
    scriptcontext.doc.Views.Redraw()
    return rc


def AddPointCloud(points, colors=None):
    """Adds point cloud object to the document
    Parameters:
      points ([point, ....]): list of values where every multiple of three represents a point
      colors ([color, ...]): list of colors to apply to each point
    Returns:
      guid: identifier of point cloud on success
    Example:
      import rhinoscriptsyntax as rs
      points = (0,0,0), (1,1,1), (2,2,2), (3,3,3)
      rs.AddPointCloud(points)
    See Also:
      IsPointCloud
      PointCloudCount
      PointCloudPoints
    """
    points = rhutil.coerce3dpointlist(points, True)
    if colors and len(colors)==len(points):
        pc = Rhino.Geometry.PointCloud()
        for i in range(len(points)):
            color = rhutil.coercecolor(colors[i],True)
            pc.Add(points[i],color)
        points = pc
    rc = scriptcontext.doc.Objects.AddPointCloud(points)
    if rc==System.Guid.Empty: raise Exception("unable to add point cloud to document")
    scriptcontext.doc.Views.Redraw()
    return rc


def AddPoints(points):
    """Adds one or more point objects to the document
    Parameters:
      points ([point, ...]): list of points
    Returns:
      list(guid, ...): identifiers of the new objects on success
    Example:
      import rhinoscriptsyntax as rs
      points = rs.GetPoints(True, True, "Select points")
      if points: rs.AddPoints(points)
    See Also:
      AddPoint
      AddPointCloud
    """
    points = rhutil.coerce3dpointlist(points, True)
    rc = [scriptcontext.doc.Objects.AddPoint(point) for point in points]
    scriptcontext.doc.Views.Redraw()
    return rc


def AddText(text, point_or_plane, height=1.0, font=None, font_style=0, justification=None):
    """Adds a text string to the document
    Parameters:
      text (str): the text to display
      point_or_plane (point|plane): a 3-D point or the plane on which the text will lie.
          The origin of the plane will be the origin point of the text
      height (number, optional): the text height
      font (str, optional): the text font
      font_style (number, optional): any of the following flags
         0 = normal
         1 = bold
         2 = italic
         3 = bold and italic
      justification (number, optional): text justification. Values may be added to create combinations.
         1 = Left
         2 = Center (horizontal)
         4 = Right
         65536 = Bottom
         131072 = Middle (vertical)
         262144 = Top
    Returns:
      guid: identifier for the object that was added to the doc on success
      None: on failure
    Example:
      import rhinoscriptsyntax as rs
      point = rs.GetPoint("Pick point")
      if point: rs.AddText("Hello Rhino!", point)
    See Also:
      IsText
    """
    if not text: raise ValueError("text invalid")
    if not isinstance(text, str): text = str(text)
    point = rhutil.coerce3dpoint(point_or_plane)
    plane = None
    if not point: plane = rhutil.coerceplane(point_or_plane, True)
    if not plane:
        plane = scriptcontext.doc.Views.ActiveView.ActiveViewport.ConstructionPlane()
        plane.Origin = point
    if font != None and type(font) != str:
      raise ValueError("font needs to be a quartet name")
    bold = (1==font_style or 3==font_style)
    italic = (2==font_style or 3==font_style)

    ds = scriptcontext.doc.DimStyles.Current
    if font == None:
      qn = ds.Font.QuartetName
      quartetBoldProp = ds.Font.Bold
      quartetItalicProp = ds.Font.Italic
    else:
      qn = font
      quartetBoldProp = False
      quartetItalicProp = False

    f = Rhino.DocObjects.Font.FromQuartetProperties(qn, quartetBoldProp, quartetItalicProp)
    if f == None:
        print("font error: there is a problem with the font {} and cannot be used to create a text entity".format(font))
        return scriptcontext.errorhandler()

    te = Rhino.Geometry.TextEntity.Create(text, plane, ds, False, 0, 0)
    te.TextHeight = height

    if font != None:
      te.Font = f

    if bold != quartetBoldProp:
        if Rhino.DocObjects.Font.FromQuartetProperties(qn, bold, False) == None:
          print("'{}' does not have a 'bold' property so it will not be set.".format(qn))
        else:
          te.SetBold(bold)
    if italic != quartetItalicProp:
        if Rhino.DocObjects.Font.FromQuartetProperties(qn, False, italic) == None:
          print("'{}' does not have an 'italic' property so it will not be set.".format(qn))
        else:
          te.SetItalic(italic)

    if justification is not None:
        h_map = [(1,0), (2,1), (4,2)]
        v_map = [(65536,5), (131072,3), (262144,0)]

        def getOneAlignFromMap(j, m, e):
            lst = []
            for k, v in m:
                if int(j) & k:
                    lst.append(v)
            return System.Enum.ToObject(e, lst[0]) if lst else None

        h = getOneAlignFromMap(justification, h_map, Rhino.DocObjects.TextHorizontalAlignment)
        if h != None:
            te.TextHorizontalAlignment = h
        v = getOneAlignFromMap(justification, v_map, Rhino.DocObjects.TextVerticalAlignment)
        if v != None:
            te.TextVerticalAlignment = v

    id = scriptcontext.doc.Objects.Add(te);
    if id==System.Guid.Empty: raise ValueError("unable to add text to document")
    scriptcontext.doc.Views.Redraw()
    return id


def AddTextDot(text, point):
    """Add a text dot to the document.
    Parameters:
      text (str): string in dot
      point (point): A 3D point identifying the origin point.
    Returns:
      guid: The identifier of the new object if successful
    Example:
      import rhinoscriptsyntax as rs
      rs.AddTextDot("howdy",(1,2,3))
    See Also:
      IsTextDot
    """
    point = rhutil.coerce3dpoint(point, True)
    if not isinstance(text, str): text = str(text)
    rc = scriptcontext.doc.Objects.AddTextDot(text, point)
    if rc==System.Guid.Empty: raise ValueError("unable to add text dot to document")
    scriptcontext.doc.Views.Redraw()
    return rc


def Area(object_id):
    """Compute the area of a closed curve, hatch, surface, polysurface, or mesh
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      number: area if successful
      None: on error
    Example:
      import rhinoscriptsyntax as  rs
      a = rs.Area('a9e34aa8-226c-4e17-9e11-b74bf2cf581b')
    See Also:
      IsPoint
      PointCoordinates
    """
    rhobj = rhutil.coercerhinoobject(object_id, True, True)
    mp = Rhino.Geometry.AreaMassProperties.Compute(rhobj.Geometry)
    if mp is None: raise Exception("unable to compute area mass properties")
    return mp.Area


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 ([guid, ...]): The identifiers of the objects
      view_or_plane (str|guid): 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 (bool, optional): return the bounding box as world coordinates or
          construction plane coordinates. Note, this option does not apply to
          world axis-aligned bounding boxes.
    Returns:
      list(point, point, point, point, point, point, point, point): 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:
      import rhinoscriptsyntax as rs
      object = rs.GetObject("Select object")
      if object:
          box = rs.BoundingBox(object)
          if box:
              for i, point in enumerate(box):
                  rs.AddTextDot( i, point )
    See Also:
      
    """
    def __objectbbox(object, xform):
        geom = rhutil.coercegeometry(object, False)
        if not geom:
            pt = rhutil.coerce3dpoint(object, True)
            if xform: pt = xform * pt
            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 CompareGeometry(first, second):
    """Compares two objects to determine if they are geometrically identical.
    Parameters:
      first (guid|geometry): The identifier of the first object to compare.
      second (guid|geometry): The identifier of the second object to compare.
    Returns:
      True if the objects are geometrically identical, otherwise False.
    Example:
      import rhinoscriptsyntax as rs
      object1 = rs.GetObject("Select first object")
      object2 = rs.GetObject("Select second object")
      if object:
      print("Objects are identical" if rs.CompareGeometry(object1, object2) else "Objects differ")
    See Also:
      
    """
    first_g = rhutil.coercegeometry(first, True)
    second_g = rhutil.coercegeometry(second, True)

    return Rhino.Geometry.GeometryBase.GeometryEquals(first_g, second_g)


def ExplodeText(text_id, delete=False):
    """Creates outline curves for a given text entity
    Parameters:
      text_id (guid): identifier of Text object to explode
      delete (bool, optional): delete the text object after the curves have been created
    Returns:
      list(guid): of outline curves
    Example:
      import rhinoscriptsyntax as rs
      text = rs.AddText("abcd", rs.WorldXYPlane())
      rs.ExplodeText(text, True)
    See Also:
      IsHatch
      HatchPattern
      HatchRotation
      HatchScale
    """
    rhobj = rhutil.coercerhinoobject(text_id, True, True)
    curves = rhobj.Geometry.Explode()
    attr = rhobj.Attributes
    rc = [scriptcontext.doc.Objects.AddCurve(curve,attr) for curve in curves]
    if delete: scriptcontext.doc.Objects.Delete(rhobj,True)
    scriptcontext.doc.Views.Redraw()
    return rc


def IsClippingPlane(object_id):
    """Verifies that an object is a clipping plane object
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True if the object with a given id is a clipping plane
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a clipping plane")
      if rs.IsClippingPlane(id):
          print("The object is a clipping plane.")
      else:
          print("The object is not a clipping plane.")
    See Also:
      AddClippingPlane
    """
    cp = rhutil.coercegeometry(object_id)
    return isinstance(cp, Rhino.Geometry.ClippingPlaneSurface)


def IsPoint(object_id):
    """Verifies an object is a point object.
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True if the object with a given id is a point
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a point")
      if rs.IsPoint(id):
          print("The object is a point.")
      else:
          print("The object is not a point.")
    See Also:
      AddPoint
      PointCoordinates
    """
    p = rhutil.coercegeometry(object_id)
    return isinstance(p, Rhino.Geometry.Point)


def IsPointCloud(object_id):
    """Verifies an object is a point cloud object.
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True if the object with a given id is a point cloud
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a point cloud")
      if rs.IsPointCloud(id):
          print("The object is a point cloud.")
      else:
          print("The object is not a point cloud.")
    See Also:
      AddPointCloud
      PointCloudCount
      PointCloudPoints
    """
    pc = rhutil.coercegeometry(object_id)
    return isinstance(pc, Rhino.Geometry.PointCloud)


def IsText(object_id):
    """Verifies an object is a text object.
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True if the object with a given id is a text object
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a text object")
      if rs.IsText(id):
          print("The object is a text object.")
      else:
          print("The object is not a text object.")
    See Also:
      AddText
    """
    text = rhutil.coercegeometry(object_id)
    return isinstance(text, Rhino.Geometry.TextEntity)


def IsTextDot(object_id):
    """Verifies an object is a text dot object.
    Parameters:
      object_id (guid): the object's identifier
    Returns:
      bool: True if the object with a given id is a text dot object
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select a text dot object")
      if rs.IsTextDot(id):
          print("The object is a text dot object.")
      else:
          print("The object is not a text dot object.")
    See Also:
      AddTextDot
    """
    td = rhutil.coercegeometry(object_id)
    return isinstance(td, Rhino.Geometry.TextDot)


def PointCloudCount(object_id):
    """Returns the point count of a point cloud object
    Parameters:
      object_id (guid): the point cloud object's identifier
    Returns:
      number: number of points if successful
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select point cloud", rs.filter.pointcloud)
      print("Point count:{}".format(rs.PointCloudCount(id)))
    See Also:
      AddPointCloud
      IsPointCloud
      PointCloudPoints
    """
    pc = rhutil.coercegeometry(object_id, True)
    if isinstance(pc, Rhino.Geometry.PointCloud): return pc.Count


def PointCloudHasHiddenPoints(object_id):
    """Verifies that a point cloud has hidden points
    Parameters:
      object_id (guid): the point cloud object's identifier
    Returns:
      bool: True if cloud has hidden points, otherwise False
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a point cloud", rs.filter.pointcloud)
      if rs.PointCloudHasHiddenPoints(obj):
          print("The point cloud has hidden points.")
      else:
          print("The point cloud has no hidden points.")
    See Also:
      PointCloudHasPointColors
      PointCloudHidePoints
      PointCloudPointColors
    """
    pc = rhutil.coercegeometry(object_id, True)
    if isinstance(pc, Rhino.Geometry.PointCloud): return pc.HiddenPointCount>0


def PointCloudHasPointColors(object_id):
    """Verifies that a point cloud has point colors
    Parameters:
      object_id (guid): the point cloud object's identifier
    Returns:
      bool: True if cloud has point colors, otherwise False
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select a point cloud", rs.filter.pointcloud)
      if rs.PointCloudHasPointColors(obj):
          print("The point cloud has point colors.")
      else:
          print("The point cloud has no point colors.")
    See Also:
      PointCloudHasPointColors
      PointCloudHidePoints
      PointCloudPointColors
    """
    pc = rhutil.coercegeometry(object_id, True)
    if isinstance(pc, Rhino.Geometry.PointCloud): return pc.ContainsColors


def PointCloudHidePoints(object_id, hidden=[]):
    """Returns or modifies the hidden points of a point cloud object
    Parameters:
      object_id (guid): the point cloud object's identifier
      hidden ([bool, ....]): list of booleans matched to the index of points to be hidden
    Returns:
      list(bool, ....): List of point cloud hidden states
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select point cloud", rs.filter.pointcloud)
      if obj:
          hidden = [True] * rs.PointCloudCount(obj)
          for i in range(len(hidden)):
              hidden[i] = (i%2==0)
          rs.PointCloudHidePoints(obj, hidden)
    See Also:
      PointCloudHasPointColors
      PointCloudPointColors
    """
    rhobj = rhutil.coercerhinoobject(object_id)
    if rhobj: pc = rhobj.Geometry
    else: pc = rhutil.coercegeometry(object_id, True)
    if isinstance(pc, Rhino.Geometry.PointCloud):
        rc = None
        if pc.ContainsHiddenFlags: rc = [item.Hidden for item in pc]
        if hidden is None:
            pc.ClearHiddenFlags()
        elif len(hidden)==pc.Count:
            for i in range(pc.Count): pc[i].Hidden = hidden[i]
        if rhobj:
            rhobj.CommitChanges()
            scriptcontext.doc.Views.Redraw()
        return rc


def PointCloudPointColors(object_id, colors=[]):
    """Returns or modifies the point colors of a point cloud object
    Parameters:
      object_id (guid): the point cloud object's identifier
      colors ([color, ...]) list of color values if you want to adjust colors
    Returns:
      list(color, ...): List of point cloud colors
    Example:
      import rhinoscriptsyntax as rs
      import random
       
      def RandomColor():
          red = random.randint(0,255)
          green = random.randint(0,255)
          blue = random.randint(0,255)
          return rs.coercecolor((red,green,blue))
       
      obj = rs.GetObject("Select point cloud", rs.filter.pointcloud)
      if obj:
          colors = [RandomColor() for i in range(rs.PointCloudCount(obj))]
          rs.PointCloudColors(obj, colors)
    See Also:
      PointCloudHasHiddenPoints
      PointCloudHasPointColors
      PointCloudHidePoints
    """
    rhobj = rhutil.coercerhinoobject(object_id)
    if rhobj: pc = rhobj.Geometry
    else: pc = rhutil.coercegeometry(object_id, True)
    if isinstance(pc, Rhino.Geometry.PointCloud):
        rc = None
        if pc.ContainsColors: rc = [item.Color for item in pc]
        if colors is None:
            pc.ClearColors()
        elif len(colors)==pc.Count:
            for i in range(pc.Count): pc[i].Color = rhutil.coercecolor(colors[i])
        if rhobj:
            rhobj.CommitChanges()
            scriptcontext.doc.Views.Redraw()
        return rc


def PointCloudPoints(object_id):
    """Returns the points of a point cloud object
    Parameters:
      object_id (guid): the point cloud object's identifier
    Returns:
      list(guid, ...): list of points if successful
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select point cloud", rs.filter.pointcloud)
      points = rs.PointCloudPoints(id)
      if points: for point in points: print(point)
    See Also:
      AddPointCloud
      IsPointCloud
      PointCloudCount
    """
    pc = rhutil.coercegeometry(object_id, True)
    if isinstance(pc, Rhino.Geometry.PointCloud): return pc.GetPoints()


def PointCloudKNeighbors(pt_cloud, needle_points, amount=1):
    """Returns amount indices of points in a point cloud that are near needle_points.
    Parameters:
      pt_cloud (guid|[point, ...]): the point cloud to be searched, or the "hay stack". This can also be a list of points.
      needle_points (guid|[point, ...]): a list of points to search in the point_cloud. This can also be specified as a point cloud.
      amount (int, optional): the amount of required closest points. Defaults to 1.
    Returns:
      [int, int,...]: a list of indices of the found points, if amount equals 1.
      [[int, ...], ...]: nested lists with amount items within a list, with the indices of the found points.
    Example:
import rhinoscriptsyntax as rs
id = rs.GetObject("Select point cloud", rs.filter.pointcloud)
if id:
    result = rs.PointCloudKNeighbors(id, [(0,0,0)])
    if result:
        print("The closest point to origin has index : %s." % result[0])
    See Also:
      AddPointCloud
      IsPointCloud
      PointCloudPoints
    """
    needles = rhutil.coercegeometry(needle_points, False)
    if isinstance(needles, Rhino.Geometry.PointCloud): needles = needles.AsReadOnlyListOfPoints()
    else: needles = rhutil.coerce3dpointlist(needle_points, True)

    pc_geom = rhutil.coercegeometry(pt_cloud, False)
    if isinstance(pc_geom, Rhino.Geometry.PointCloud):
        if len(needles) > 100:
            search = Rhino.Geometry.RTree.PointCloudKNeighbors
        else:
            search = Rhino.Collections.RhinoList.PointCloudKNeighbors

        return __simplify_PointCloudKNeighbors(search(pc_geom, needles, amount), amount)

    if len(needles) > 100:
        search = Rhino.Geometry.RTree.Point3dKNeighbors
    else:
        search = Rhino.Collections.RhinoList.Point3dKNeighbors

    if isinstance(pt_cloud, System.Collections.Generic.IEnumerable[Rhino.Geometry.Point3d]):
        return __simplify_PointCloudKNeighbors(search(pt_cloud, needles, amount), amount)
    pts = rhutil.coerce3dpointlist(pt_cloud, True)
    return __simplify_PointCloudKNeighbors(search(pts, needles, amount), amount)


def PointCloudClosestPoints(pt_cloud, needle_points, distance):
    """Returns a list of lists of point indices in a point cloud that are
    closest to needle_points. Each inner list references all points within or on the surface of a sphere of distance radius.
    Parameters:
      pt_cloud (guid|[point, ...]): the point cloud to be searched, or the "hay stack". This can also be a list of points.
      needle_points (guid|[point, ...]): a list of points to search in the point_cloud. This can also be specified as a point cloud.
      distance (float): the included limit for listing points.
    Returns:
      [[int, ...], ...]: a list of lists with the indices of the found points.
    Example:
import rhinoscriptsyntax as rs
id = rs.GetObject("Select point cloud", rs.filter.pointcloud)
if id:
    result = rs.PointCloudClosestPoints(id, [[0,0,0]], 1.0)
    if result and result[0]:
        print("The first point next to origin within a 1.0 unit radius is: %s." % result[0][0])
    else:
        print("There is no point in the point cloud within a 1.0 unit radius sphere from origin.")
    See Also:
      AddPointCloud
      IsPointCloud
      PointCloudPoints
    """
    needles = rhutil.coercegeometry(needle_points, False)
    if isinstance(needles, Rhino.Geometry.PointCloud): needles = needles.AsReadOnlyListOfPoints()
    else: needles = rhutil.coerce3dpointlist(needle_points, True)
    pc_geom = rhutil.coercegeometry(pt_cloud, False)
    if isinstance(pc_geom, Rhino.Geometry.PointCloud):
        return __simplify_PointCloudClosestPoints(Rhino.Geometry.RTree.PointCloudClosestPoints(pc_geom, needles, distance))
    if isinstance(pt_cloud, System.Collections.Generic.IEnumerable[Rhino.Geometry.Point3d]):
        return __simplify_PointCloudClosestPoints(Rhino.Geometry.RTree.Point3dClosestPoints(pt_cloud, needles, distance))
    pts = rhutil.coerce3dpointlist(pt_cloud, True)
    return __simplify_PointCloudClosestPoints(Rhino.Geometry.RTree.Point3dClosestPoints(pts, needles, distance))


def PointCoordinates(object_id, point=None):
    """Returns or modifies the X, Y, and Z coordinates of a point object
    Parameters:
      object_id (guid): The identifier of a point object
      point (point, optional): A new 3D point location.
    Returns:
      point: If point is not specified, the current 3-D point location
      point: If point is specified, the previous 3-D point location
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select point", rs.filter.point)
      point = rs.PointCoordinates(id)
      if point: print(point)
    See Also:
      AddPoint
      IsPoint
    """
    point_geometry = rhutil.coercegeometry(object_id, True)
    if isinstance(point_geometry, Rhino.Geometry.Point):
        rc = point_geometry.Location
        if point:
            point = rhutil.coerce3dpoint(point, True)
            id = rhutil.coerceguid(object_id, True)
            scriptcontext.doc.Objects.Replace(id, point)
            scriptcontext.doc.Views.Redraw()
        return rc


def TextDotFont(object_id, fontface=None):
    """Returns or modified the font of a text dot
    Parameters:
      object_id (guid): identifier of a text dot object
      fontface (str, optional): new font face name
    Returns:
      str: If font is not specified, the current text dot font
      str: If font is specified, the previous text dot font
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text dot")
      if rs.IsTextDot(obj): rs.TextDotFont( obj, "Arial" )
    See Also:
      AddTextDot
      IsTextDot
      TextDotHeight
      TextDotPoint
      TextDotText
    """
    textdot = rhutil.coercegeometry(object_id, True)
    if isinstance(textdot, Rhino.Geometry.TextDot):
        rc = textdot.FontFace
        if fontface:
            textdot.FontFace = fontface
            id = rhutil.coerceguid(object_id, True)
            scriptcontext.doc.Objects.Replace(id, textdot)
            scriptcontext.doc.Views.Redraw()
        return rc


def TextDotHeight(object_id, height=None):
    """Returns or modified the font height of a text dot
    Parameters:
      object_id (guid): identifier of a text dot object
      height (number, optional) new font height
    Returns:
      number: If height is not specified, the current text dot height
      number: If height is specified, the previous text dot height
      None: on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text dot")
      if rs.IsTextDot(obj): rs.TextDotHeight(obj, 10.0)
    See Also:
      AddTextDot
      IsTextDot
      TextDotFont
      TextDotPoint
      TextDotText
    """
    textdot = rhutil.coercegeometry(object_id, True)
    if isinstance(textdot, Rhino.Geometry.TextDot):
        rc = textdot.FontHeight
        if height and height>0:
            textdot.FontHeight = height
            id = rhutil.coerceguid(object_id, True)
            scriptcontext.doc.Objects.Replace(id, textdot)
            scriptcontext.doc.Views.Redraw()
        return rc


def TextDotPoint(object_id, point=None):
    """Returns or modifies the location, or insertion point, on a text dot object
    Parameters:
      object_id (guid): identifier of a text dot object
      point (point, optional): A new 3D point location.
    Returns:
      point: If point is not specified, the current 3-D text dot location
      point: If point is specified, the previous 3-D text dot location
      None: if not successful, or on error
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select text dot")
      if rs.IsTextDot(id):
          point = rs.TestDotPoint(id)
          rs.AddPoint( point )
          rs.TextDotPoint(id, [0,0,0])
    See Also:
      AddTextDot
      IsTextDot
      TextDotText
    """
    textdot = rhutil.coercegeometry(object_id, True)
    if isinstance(textdot, Rhino.Geometry.TextDot):
        rc = textdot.Point
        if point:
            textdot.Point = rhutil.coerce3dpoint(point, True)
            id = rhutil.coerceguid(object_id, True)
            scriptcontext.doc.Objects.Replace(id, textdot)
            scriptcontext.doc.Views.Redraw()
        return rc


def TextDotText(object_id, text=None):
    """Returns or modifies the text on a text dot object
    Parameters:
      object_id (guid): The identifier of a text dot object
      text (str, optional): a new string for the dot
    Returns:
      str: If text is not specified, the current text dot text
      str: If text is specified, the previous text dot text
      None: if not successful, or on error
    Example:
      import rhinoscriptsyntax as rs
      id = rs.GetObject("Select text dot")
      if rs.IsTextDot(id):
          rs.TextDotText( id, "Rhino")
    See Also:
      AddTextDot
      IsTextDot
      TextDotPoint
    """
    textdot = rhutil.coercegeometry(object_id, True)
    if isinstance(textdot, Rhino.Geometry.TextDot):
        rc = textdot.Text
        if text is not None:
            if not isinstance(text, str): text = str(text)
            textdot.Text = text
            id = rhutil.coerceguid(object_id, True)
            scriptcontext.doc.Objects.Replace(id, textdot)
            scriptcontext.doc.Views.Redraw()
        return rc


def TextObjectFont(object_id, font=None):
    """Returns of modifies the font used by a text object
    Parameters:
      object_id (guid): the identifier of a text object
      font (str): the new font face name
    Returns:
      str: if a font is not specified, the current font face name
      str: 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 = annotation.Font
    rc = fontdata.QuartetName
    if font:
        def q2f(qn, b, i):
            return Rhino.DocObjects.Font.FromQuartetProperties(qn, b, i)
        # normally calls will not go further than q2f(font, False, False)
        # but there are a few rare fonts that don't have a regular font
        f = q2f(font, fontdata.Bold, fontdata.Italic)\
            or q2f(font, False, False)\
            or q2f(font, True, False)\
            or q2f(font, False, True)\
            or q2f(font, True, True)
        if f is None:
              return scriptcontext.errorhandler()
        annotation.Font = f
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc


def TextObjectHeight(object_id, height=None):
    """Returns or modifies the height of a text object
    Parameters:
      object_id (guid): the identifier of a text object
      height (number, optional): the new text height.
    Returns:
      number: if height is not specified, the current text height
      number: if height is specified, the previous text height
      None: if not successful, or on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text")
      if rs.IsText(obj):
          rs.TextObjectHeight( obj, 1.0 )
    See Also:
      AddText
      IsText
      TextObjectFont
      TextObjectPlane
      TextObjectPoint
      TextObjectStyle
      TextObjectText
    """
    annotation = rhutil.coercegeometry(object_id, True)
    if not isinstance(annotation, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    rc = annotation.TextHeight
    if height:
        annotation.TextHeight = height
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc


def TextObjectPlane(object_id, plane=None):
    """Returns or modifies the plane used by a text object
    Parameters:
      object_id (guid): the identifier of a text object
      plane (plane): the new text object plane
    Returns:
      plane: if a plane is not specified, the current plane if successful
      plane: if a plane is specified, the previous plane if successful
      None: if not successful, or on Error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text")
      if rs.IsText(obj):
          plane = rs.ViewCPlane("Top")
          rs.TextObjectPlane( obj, plane )
    See Also:
      AddText
      IsText
      TextObjectFont
      TextObjectHeight
      TextObjectPoint
      TextObjectStyle
      TextObjectText
    """
    annotation = rhutil.coercegeometry(object_id, True)
    if not isinstance(annotation, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    rc = annotation.Plane
    if plane:
        annotation.Plane = rhutil.coerceplane(plane, True)
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc


def TextObjectPoint(object_id, point=None):
    """Returns or modifies the location of a text object
    Parameters:
      object_id (guid): the identifier of a text object
      point (point, optional) the new text object location
    Returns:
      point: if point is not specified, the 3D point identifying the current location
      point: if point is specified, the 3D point identifying the previous location
      None: if not successful, or on Error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text")
      if rs.IsText(obj):
          rs.TextObjectPoint( obj, [0,0,0] )
    See Also:
      AddText
      IsText
      TextObjectFont
      TextObjectHeight
      TextObjectPlane
      TextObjectStyle
      TextObjectText
    """
    text = rhutil.coercegeometry(object_id, True)
    if not isinstance(text, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    plane = text.Plane
    rc = plane.Origin
    if point:
        plane.Origin = rhutil.coerce3dpoint(point, True)
        text.Plane = plane
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, text)
        scriptcontext.doc.Views.Redraw()
    return rc


def TextObjectStyle(object_id, style=None):
    """Returns or modifies the font style of a text object
    Parameters:
      object_id (guid) the identifier of a text object
      style (number, optional) the font style. Can be any of the following flags
         0 = Normal
         1 = Bold
         2 = Italic
    Returns:
      number: if style is not specified, the current font style
      number: if style is specified, the previous font style
      None: if not successful, or on Error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text")
      if rs.IsText(obj):
          rs.TextObjectStyle( obj, 3 )
    See Also:
      AddText
      IsText
      TextObjectFont
      TextObjectHeight
      TextObjectPlane
      TextObjectPoint
      TextObjectText
    """
    annotation = rhutil.coercegeometry(object_id, True)
    if not isinstance(annotation, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    fontdata = annotation.Font
    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.Font = scriptcontext.doc.Fonts[index]
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc


def TextObjectText(object_id, text=None):
    """Returns or modifies the text string of a text object.
    Parameters:
      object_id (guid): the identifier of a text object
      text (str, optional): a new text string
    Returns:
      str: if text is not specified, the current string value if successful
      str: if text is specified, the previous string value if successful
      None: if not successful, or on error
    Example:
      import rhinoscriptsyntax as rs
      obj = rs.GetObject("Select text")
      if rs.IsText(obj): rs.TextObjectText(obj, "Rhino")
    See Also:
      AddText
      IsText
      TextObjectFont
      TextObjectHeight
      TextObjectPlane
      TextObjectPoint
      TextObjectStyle
    """
    annotation = rhutil.coercegeometry(object_id, True)
    if not isinstance(annotation, Rhino.Geometry.TextEntity):
        return scriptcontext.errorhandler()
    rc = annotation.Text
    if text:
        if not isinstance(text, str): text = str(text)
        isBold = annotation.IsAllBold()
        isItalic = annotation.IsAllItalic()
        isUnderlined = annotation.IsAllUnderlined()
        annotation.Text = text
        if isBold: annotation.SetBold(True)
        if isItalic: annotation.SetItalic(True)
        if isUnderlined: annotation.SetUnderline(True)
        id = rhutil.coerceguid(object_id, True)
        scriptcontext.doc.Objects.Replace(id, annotation)
        scriptcontext.doc.Views.Redraw()
    return rc

```
Page 3/7FirstPrevNextLast