Automating text input

Automating text input

dames123
Advocate Advocate
550 Views
5 Replies
Message 1 of 6

Automating text input

dames123
Advocate
Advocate

Hello,

 

In the following script, I'm trying to create text in numerical order. I have two issues.

 

1. the text height is not accurate, if I enter .06 I get .0236.

2. the text location is not accurate. It comes out like this:

 

dames123_0-1738775317368.png

as opposed to this:

 

dames123_1-1738775354361.png

 

Any help would be appreciated.

 

import adsk.core, adsk.fusion, adsk.cam, traceback

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        design = app.activeProduct
        rootComp = design.rootComponent

        # Create a new sketch on the selected face
        def create_sketch(face, name):
            sketches = rootComp.sketches
            sketch = sketches.add(face)
            sketch.name = name
            return sketch

        # Create text on the sketch
        def create_text(sketch, text, height, position, angle, flip):
            textInput = sketch.sketchTexts.createInput(str(text), height, position)
            textInput.angle = angle
            textInput.fontName = 'Romans.shx'
            textInput.isHorizontalFlip = flip
            sketchText = sketch.sketchTexts.add(textInput)
            return sketchText

        # Get user inputs
        range_input = ui.inputBox('Enter the range of numbers (e.g., 1-10):', 'Range Input', '1-10')
        if isinstance(range_input, list):
            range_input = range_input[0]
        start, end = map(int, range_input.split('-'))
        numbers = range(start, end + 1)
        height_input = ui.inputBox('Enter the height:', 'Height Input', '0.060')
        height = float(height_input[0]) if isinstance(height_input, list) else float(height_input)
        angle_input = ui.inputBox('Enter the orientation angle (in degrees):', 'Orientation Input', '0.0')
        angle = float(angle_input[0]) if isinstance(angle_input, list) else float(angle_input)
        flip = ui.messageBox('Flip the text horizontally?', 'Flip Input', adsk.core.MessageBoxButtonTypes.YesNoButtonType) == adsk.core.DialogResults.DialogYes

        # Select the face
        face_selection = ui.selectEntity('Select the face to place the numbers on:', 'Faces')
        if not face_selection:
            ui.messageBox('No face selected. Please select a face to place the numbers on.')
            return
        face = face_selection.entity

        # Select the joint origin to place the sketches
        joint_origin_selection = ui.selectEntity('Select the joint origin to place the numbers:', 'JointOrigins')
        if not joint_origin_selection:
            ui.messageBox('No joint origin selected. Please select a joint origin to place the numbers.')
            return
        joint_origin = joint_origin_selection.entity
        base_position = joint_origin.geometry.origin

        # Create separate sketches and add text
        for number in numbers:
            sketch = create_sketch(face, str(number))
            position = adsk.core.Point3D.create(base_position.x, base_position.y, base_position.z)
            sketchText = create_text(sketch, number, height, position, angle, flip)
            
            # Calculate the width and height of the text
            textWidth = sketchText.boundingBox.maxPoint.x - sketchText.boundingBox.minPoint.x
            textHeight = sketchText.boundingBox.maxPoint.y - sketchText.boundingBox.minPoint.y


            # Adjust the position to center the text
            centered_position = adsk.core.Point3D.create(base_position.x - textWidth / 2, base_position.y - height / 2, base_position.z)
            sketchText.position = centered_position

        ui.messageBox('Script completed successfully.')

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
0 Likes
Accepted solutions (1)
551 Views
5 Replies
Replies (5)
Message 2 of 6

BrianEkins
Mentor
Mentor

Here's a modified version of your program that I think might do what you want. Here are a few things that I found.

  1. You're using an old API for creating text. It should still work, but you don't have the same capabilities as what you see in the command. I switched it to use the new API.
  2. When using the API lengths are always in centimeters and angles are always in radians. I added conversions from inch to cm and degrees to radians to the code.
  3. A sketch has its own coordinate system, and is positioned within the model. The sketch coordinate system is also 3D, although most sketch geometry lies on the X-Y plane of the and is planar, but that's not a requirement. The geometry in a sketch is relative to the sketch coordinate system. I added a couple of conversions to go from model to sketch space, although I'm not sure that what I did is what you want.
def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        design = app.activeProduct
        rootComp = design.rootComponent

        # Create a new sketch on the selected face
        def create_sketch(face, name):
            sketches = rootComp.sketches
            sketch = sketches.add(face)
            sketch.name = name
            return sketch

        # Create text on the sketch
        def create_text(sketch: adsk.fusion.Sketch, text, height, position: adsk.core.Point3D, flip):
            textInput = sketch.sketchTexts.createInput2(str(text), height)
            position = sketch.modelToSketchSpace(position)
            corner1 = position.copy()
            corner1.translateBy(adsk.core.Vector3D.create(-1, -1, 0))
            corner2 = position.copy()
            corner2.translateBy(adsk.core.Vector3D.create(1, 1, 0))
            textInput.setAsMultiLine(corner1, corner2, 
                                     adsk.core.HorizontalAlignments.CenterHorizontalAlignment,
                                     adsk.core.VerticalAlignments.MiddleVerticalAlignment, 0)
            textInput.fontName = 'Romans.shx'
            textInput.isHorizontalFlip = flip
            sketchText = sketch.sketchTexts.add(textInput)
            return sketchText

        # Get user inputs
        range_input = ui.inputBox('Enter the range of numbers (e.g., 1-10):', 'Range Input', '1-10')
        if isinstance(range_input, list):
            range_input = range_input[0]
        start, end = map(int, range_input.split('-'))
        numbers = range(start, end + 1)
        height_input = ui.inputBox('Enter the height:', 'Height Input', '0.060')
        height = float(height_input[0]) if isinstance(height_input, list) else float(height_input)
        height = height * 2.54
        angle_input = ui.inputBox('Enter the orientation angle (in degrees):', 'Orientation Input', '0.0')
        angle = float(angle_input[0]) if isinstance(angle_input, list) else float(angle_input)
        angle = math.radians(angle)
        flip = ui.messageBox('Flip the text horizontally?', 'Flip Input', adsk.core.MessageBoxButtonTypes.YesNoButtonType) == adsk.core.DialogResults.DialogYes

        # Select the face
        face_selection = ui.selectEntity('Select the face to place the numbers on:', 'Faces')
        if not face_selection:
            ui.messageBox('No face selected. Please select a face to place the numbers on.')
            return
        face = face_selection.entity

        # Select the joint origin to place the sketches
        joint_origin_selection = ui.selectEntity('Select the joint origin to place the numbers:', 'JointOrigins')
        if not joint_origin_selection:
            ui.messageBox('No joint origin selected. Please select a joint origin to place the numbers.')
            return
        joint_origin = joint_origin_selection.entity
        base_position = joint_origin.geometry.origin

        # Create separate sketches and add text
        for number in numbers:
            sketch = create_sketch(face, str(number))
            position = adsk.core.Point3D.create(base_position.x, base_position.y, base_position.z)
            sketchText = create_text(sketch, number, height, position, flip)
            
            # # Calculate the width and height of the text
            # textWidth = sketchText.boundingBox.maxPoint.x - sketchText.boundingBox.minPoint.x
            # textHeight = sketchText.boundingBox.maxPoint.y - sketchText.boundingBox.minPoint.y

            # Adjust the position to center the text
            # centered_position = adsk.core.Point3D.create(base_position.x - textWidth / 2, base_position.y - height / 2, base_position.z)
            # sketchText.position = centered_position

        ui.messageBox('Script completed successfully.')

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))    
---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
0 Likes
Message 3 of 6

dames123
Advocate
Advocate

Hi @BrianEkins ,

 

Thanks for your help. I get the following error when trying to run the code.

 

Failed:

Traceback (most recent call last):

File "M:/Programming/DelCam/Fusion 360/Scripts/CavID/CavID.py", line 45, in run

angle = math.radians(angle)

^^^^

NameError: name 'math' is not defined. Did you forget to import 'math'

0 Likes
Message 4 of 6

dames123
Advocate
Advocate

Sorry, right in front of my face.

 

"NameError: name 'math' is not defined. Did you forget to import 'math'"

 

It works now. although it seems to add a sketch to the surrounding edges of the surface I pick. In addition to the numbers.

 

 

dames123_0-1738853111171.png

 

0 Likes
Message 5 of 6

BrianEkins
Mentor
Mentor
Accepted solution

When I copied and pasted the code I missed the import statements. As you already found, you need "import math".

 

For the second problem with the sketches containing the extra geometry of the edges of the face, in your create_sketch function you can change the call to create the sketch to use the addWithoutEdges instead of the add method.

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
0 Likes
Message 6 of 6

dames123
Advocate
Advocate

Perfect. Thank you so much!

0 Likes