How do I make a Path out of User Command selected SketchCurve?

How do I make a Path out of User Command selected SketchCurve?

adminTCYL2
Enthusiast Enthusiast
421 Views
3 Replies
Message 1 of 4

How do I make a Path out of User Command selected SketchCurve?

adminTCYL2
Enthusiast
Enthusiast

I try to write a skript that leads a Rope or a telephone-cable (coil) along a path. The path should be drawn and selected by the user. But creating the path the script tells me it is empty. So I give out a messageBox to see that there is a selection: 

adminTCYL2_0-1627468885630.png

If I go OK the script runns further on from line 27 to line 29 and tells me the path is empty (see # Path does not work) : 

adminTCYL2_1-1627469044950.png

But why? What is wrong?

 

import adsk.core, adsk.fusion, adsk.cam, traceback, os 
# Global variables to keep them referenced for the duration of the command
_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)
_handlers = []
_dropdownInput3 = adsk.core.DropDownCommandInput.cast(None)
_inputs = adsk.core.CommandInputs.cast(None)

def makeIt(execute): 
    try:
        # Here is my code that is done with every change in User-Selections:

        # Get UserCommand-Values
        curve = _inputs.itemById('selection')
        broadness = _inputs.itemById('broadness').value/2
        thickness = _inputs.itemById('thickness').value/2
        rotations = _inputs.itemById('rotations').value
        shape = _dropdownInput3.selectedItem.name

        design = _app.activeProduct
        rootComp = design.rootComponent
        # create new component
        newOcc1 = rootComp.occurrences.addNewComponent(adsk.core.Matrix3D.create())
        root_comp = newOcc1.component
        root_comp.name = 'Windings'

        _ui.messageBox("Your selected Curve is: " + str(curve))
# Path does not work
        path = root_comp.features.createPath(curve)
        planes = root_comp.constructionPlanes
        planeInput = planes.createInput()
        planeInput.setByDistanceOnPath(path, adsk.core.ValueInput.createByReal(0))
        plane = planes.add(planeInput)
        sketches = root_comp.sketches
        sketch = sketches.add(plane)

        # Define lines for linear profiles
        point1a = sketch.sketchPoints.add(adsk.core.Point3D.create(broadness, 0, 0))
        point1b = sketch.sketchPoints.add(adsk.core.Point3D.create(-broadness,0, 0))
        point2a = sketch.sketchPoints.add(adsk.core.Point3D.create(0, broadness, 0))
        point2b = sketch.sketchPoints.add(adsk.core.Point3D.create(0,-broadness, 0))
        line1 = sketch.sketchCurves.sketchLines.addByTwoPoints(point1a, point1b)
        line2 = sketch.sketchCurves.sketchLines.addByTwoPoints(point2a, point2b)


        if execute:
            # Here is my code that is additionaly done when User presses OK:
            _ui.messageBox("you selected: "+shape + " and Thickness: "+ str(thickness)+" and Rotations: "+ str(rotations))

    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the inputChanged event.
class MyInputChangedHandler(adsk.core.InputChangedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.InputChangedEventArgs.cast(args)
            changedInput = eventArgs.input
            execute = False
            makeIt(execute)
        except:
            if _ui:
                _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the execute event.
class MyExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.InputChangedEventArgs.cast(args)
            execute=True
            makeIt(execute)
        except:
            if _ui:
                _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the destroy event.
class MyDestroyHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        adsk.terminate()

# Event handler for the commandCreated event.
# Here you create your UserCommands
class MyCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            global _inputs
            _inputs = adsk.core.CommandInputs.cast(eventArgs.command.commandInputs)

            message = '<div align="center">See also my <a href="http:picsandpixels.at/windings">windings-AddIn</a></div>'
            _inputs.addTextBoxCommandInput('fullWidth_textBox', '', message, 1, True)  

            selInput = _inputs.addSelectionInput('selection', 'Sketch', 'SketchCurves')
            selInput.addSelectionFilter('SketchCurves')

            _inputs.addValueInput('broadness', 'Broadness', 'mm', adsk.core.ValueInput.createByReal(0.22))
            _inputs.addValueInput('thickness', 'Thickness', 'mm', adsk.core.ValueInput.createByReal(0.11))
            _inputs.addIntegerSpinnerCommandInput('rotations', 'Rotations', 0, 20, 1, 5)

            global _dropdownInput3     
            _dropdownInput3 = _inputs.addDropDownCommandInput('dropdown3', 'shape', adsk.core.DropDownStyles.LabeledIconDropDownStyle)
            _dropdownInput3.listItems.add('Cord', True, '')
            _dropdownInput3.listItems.add('Rope', False, '')
            _dropdownInput3.listItems.add('Coil', False, '')

            # Connect to command execute.
            onExecute = MyExecuteHandler()
            eventArgs.command.execute.add(onExecute)
            _handlers.append(onExecute)

            # Connect to input changed.
            onInputChanged = MyInputChangedHandler()
            eventArgs.command.inputChanged.add(onInputChanged)
            _handlers.append(onInputChanged)
            
            # Connect to the command terminate.
            onDestroy = MyDestroyHandler()
            eventArgs.command.destroy.add(onDestroy)
            _handlers.append(onDestroy)      
        except:
            if _ui:
                _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
        
def run(context):  
    try:
        global _app, _ui
        _app = adsk.core.Application.get()
        _ui  = _app.userInterface
        
        # Create a command.
        cmd = _ui.commandDefinitions.itemById('tableTest')
        if cmd:
            cmd.deleteMe()
# Rename the script in the following line:
        cmd = _ui.commandDefinitions.addButtonDefinition('tableTest', 'Cord, Rope, Coil -Maker', 'Table Test', '')
        onCommandCreated = MyCommandCreatedHandler()
        cmd.commandCreated.add(onCommandCreated)
        _handlers.append(onCommandCreated)

        cmd.execute()
        # Set this so the script continues to run.
        adsk.autoTerminate(False)
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

 



0 Likes
422 Views
3 Replies
Replies (3)
Message 2 of 4

adminTCYL2
Enthusiast
Enthusiast

Can it be, that the selected curve is in an ObjectCollection, because the user might have the oppinion to select many curves? Then I have to get it out of the collection before I define a path. So I write  instead of  line 29 the following code: 

 

 

 

 

 

 

# This was the old code: path = root_comp.features.createPath(curve)
# Here comes the new:
        paths = adsk.core.ObjectCollection.create()
        for thisEntity in range(curve.selectionCount):
            paths.add(curve.selection(thisEntity).entity)
        for thisPath in paths:
            path = root_comp.features.createPath(thisPath)

 

 

 

 

 

 

But now I get a refferenced bevore assignment-Error. Normaly easy to solve... but here I am confused:

adminTCYL2_1-1627472606831.png

 

Please, is there someone who can help me?

0 Likes
Message 3 of 4

adminTCYL2
Enthusiast
Enthusiast

Ok, curve.selectionCount is 0 because there is no curve.selection().entity
Maybe the Idea was wrong, that the selected curve is an object-collection. 
But whatever it is, it is not "none". I can print data, but path stays empty. So the question is: How do I change the Data of the selected curve so that it gets a path?

 

0 Likes
Message 4 of 4

adminTCYL2
Enthusiast
Enthusiast

I found an answer by myself with the line:

curve = _inputs.itemById('selection').selection(0).entity

, but now I have the problem, that the ok-button deactivates as soon as line 27 is done and a plane is created on the end of the selected path. You see it in the picture :  OK is grey. But why?

 

adminTCYL2_0-1627487075111.png

 

 

 

import adsk.core, adsk.fusion, adsk.cam, traceback, os 
# Global variables to keep them referenced for the duration of the command
_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)
_handlers = []
_dropdownInput3 = adsk.core.DropDownCommandInput.cast(None)
_inputs = adsk.core.CommandInputs.cast(None)

def makeIt(execute): # Here comes your Code
    try:
        curve = _inputs.itemById('selection').selection(0).entity
        broadness = _inputs.itemById('broadness').value
        thickness = _inputs.itemById('thickness').value
        rotations = _inputs.itemById('rotations').value
        shape = _dropdownInput3.selectedItem.name
        design = _app.activeProduct
        root_comp = design.rootComponent
        path = adsk.fusion.Path.create(curve,1) 
        # https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-1728AD08-743F-4ABB-AA10-C2B2C53A0757
        # this also works: path = root_comp.features.createPath(curve)
        planes = root_comp.constructionPlanes
        planeInput = planes.createInput()
        distance = adsk.core.ValueInput.createByReal(0)
        planeInput.setByDistanceOnPath(path, distance)
        plane = planes.add(planeInput)
        #sketches = root_comp.sketches
        #sketch = sketches.add(plane)
        #circle = sketch.sketchCurves.sketchCircles.addByCenterRadius(adsk.core.Point3D.create(0,0,0), broadness)
        

        if execute:
            #code that is done when User presses OK:
            _ui.messageBox("you selected: "+shape + " and Thickness: "+ str(thickness)+" and Rotations: "+ str(rotations))

    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the inputChanged event.
class MyInputChangedHandler(adsk.core.InputChangedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.InputChangedEventArgs.cast(args)
            changedInput = eventArgs.input
            execute = False
            makeIt(execute)
        except:
            if _ui:
                _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the execute event.
class MyExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.InputChangedEventArgs.cast(args)
            execute=True
            makeIt(execute)
        except:
            if _ui:
                _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the destroy event.
class MyDestroyHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        adsk.terminate()

# Event handler for the commandCreated event.
# Here you create your UserCommands
class MyCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            global _inputs
            _inputs = adsk.core.CommandInputs.cast(eventArgs.command.commandInputs)

            message = '<div align="center">See also my <a href="http:picsandpixels.at/windings">windings-AddIn</a></div>'
            _inputs.addTextBoxCommandInput('fullWidth_textBox', '', message, 1, True)  

            selInput = _inputs.addSelectionInput('selection', 'Sketch', 'SketchCurves')
            selInput.addSelectionFilter('SketchCurves')

            _inputs.addValueInput('broadness', 'Broadness', 'mm', adsk.core.ValueInput.createByReal(0.22))
            _inputs.addValueInput('thickness', 'Thickness', 'mm', adsk.core.ValueInput.createByReal(0.11))
            _inputs.addIntegerSpinnerCommandInput('rotations', 'Rotations', 0, 20, 1, 5)

            global _dropdownInput3     
            _dropdownInput3 = _inputs.addDropDownCommandInput('dropdown3', 'shape', adsk.core.DropDownStyles.LabeledIconDropDownStyle)
            _dropdownInput3.listItems.add('Cord', True, '')
            _dropdownInput3.listItems.add('Rope', False, '')
            _dropdownInput3.listItems.add('Coil', False, '')

            # Connect to command execute.
            onExecute = MyExecuteHandler()
            eventArgs.command.execute.add(onExecute)
            _handlers.append(onExecute)

            # Connect to input changed.
            onInputChanged = MyInputChangedHandler()
            eventArgs.command.inputChanged.add(onInputChanged)
            _handlers.append(onInputChanged)
            
            # Connect to the command terminate.
            onDestroy = MyDestroyHandler()
            eventArgs.command.destroy.add(onDestroy)
            _handlers.append(onDestroy)      
        except:
            if _ui:
                _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
        
def run(context):  
    try:
        global _app, _ui
        _app = adsk.core.Application.get()
        _ui  = _app.userInterface
        
        # Create a command.
        cmd = _ui.commandDefinitions.itemById('tableTest')
        if cmd:
            cmd.deleteMe()
# Rename the script in the following line:
        cmd = _ui.commandDefinitions.addButtonDefinition('tableTest', 'User selection test', 'Table Test', '')
        onCommandCreated = MyCommandCreatedHandler()
        cmd.commandCreated.add(onCommandCreated)
        _handlers.append(onCommandCreated)

        cmd.execute()
        # Set this so the script continues to run.
        adsk.autoTerminate(False)
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

 

 

0 Likes