What's new

Script Release: Send Part Model View to DXF

NateLiquidGravity

Alibre Super User
Send Part Model View to DXF

A few notes though:
* The part file must be saved or the view can't be made and if the saved part file is obsolete so will be the DXF made from it.
* It worked fine when I open the part in its own session - but did not work if the part is opened from an assembly session.
* Since it is projected into the drawing any edge not parallel to the plane of view will not be true length. In this picture the overall scale is off only due to zoom, but since most of those lines are not parallel to the view they will not be true length measure in the DXF either.

Here is my AlibreScript code for that:
Python:
from __future__ import division # This fixes division with integers. For example the 1 / 2 = 0.5 instead of 0
import clr
import os
import _winreg

Root = Global.Root
Win = Windows()

def getalibrepath():
    try:
        keystring = r'SOFTWARE\Alibre, Inc.\Alibre Design' + '\\' + str(Global.Root.Version).split(' ')[1].replace(',', '.')
        # printpass(keystring)
        hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keystring)
        result = _winreg.QueryValueEx(hKey, 'HomeDirectory')
        # printpass(result[0])
        return result[0]
    except Exception, e:
        print(e)
        try:
            hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'Software\\Alibre, Inc.\\Alibre Design')
            result = _winreg.QueryValueEx(hKey, 'HomeDirectory')
            return result[0]
        except Exception, e:
            print(e)
            return ''
    return ''  # technically unreachable

ADPath = os.path.join(getalibrepath(), 'Program')
sys.path.append(ADPath)
clr.AddReference('AlibreX.dll')
from AlibreX import ADUnits, ADDrawingViewType, ADDetailingOption, ADViewOrientation, IAD2DPoint, IADTransformation

prt = CurrentPart()
AD_prt = prt._Part

trans = AD_prt.ViewTransform

my_drawing = Root.CreateEmptyDrawing(str(prt.Name))
point_orgin = my_drawing.GeometryFactory.Create2DPoint(0.0,0.0)
test_sheet = my_drawing.Sheets.CreateBlankSheet('Exported From Model Space', 1.0, 1.0, ADUnits.AD_CENTIMETERS, 1.0, 1.0)
test_sheet.CreateStandardViews(str(prt.FileName), ADDrawingViewType.AD_STANDARD, ADDetailingOption.AD_TANGENT_EDGES, 1.0, 1.0, ADViewOrientation.AD_FRONT, point_orgin, trans)

savePath = Win.SaveFileDialog('Save the DXF', 'DXF Files|*.DXF', '.DXF')
if savePath:
    my_drawing.ExportDXF(savePath)
    print('Saved')
else:
    print('Canceled')
my_drawing.Close(0)
 

Cator

Senior Member
Hi Nate,
sometimes I get this kind of error from your script

Traceback (most recent call last):
File "<string>", line 45, in <module>
EnvironmentError: System.Runtime.InteropServices.COMException (0x8002000D): Memoria bloccata. (Eccezione da HRESULT: 0x8002000D (DISP_E_ARRAYISLOCKED))
in com.alibre.automation.ExceptionMap.handleException(Exception inputException)
in com.alibre.automation.AlibreDrawingSession.ExportDXF(String targetFilename)
in Microsoft.Scripting.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
in Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
in Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
in System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
in Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
in Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
in Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
in IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
in Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
in AlibreScript.UI.IronTextBoxControl.#9Gb(Object #FI)
>>>
 

NateLiquidGravity

Alibre Super User
Since the script gets all the way to the ExportDXF function then I assume that everything else worked fine. I suspect it is a problem with either the file path you or file name you tried to save it as or an internal problem to Alibre Design. It doesn't have any error checking of the user input file name so perhaps you gave it a name or a symbol it couldn't handle?
 

stepalibre

Alibre Super User
Same here:

Code:
Traceback (most recent call last):
  File "<string>", line 45, in <module>
EnvironmentError: System.Runtime.InteropServices.COMException (0x8002000D): Memory is locked. (Exception from HRESULT: 0x8002000D (DISP_E_ARRAYISLOCKED))
   at com.alibre.automation.ExceptionMap.handleException(Exception inputException)
   at com.alibre.automation.AlibreDrawingSession.ExportDXF(String targetFilename)
   at Microsoft.Scripting.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at AlibreScript.UI.IronTextBoxControl.#9Gb(Object #FI)
 

stepalibre

Alibre Super User
Same here:

Code:
Traceback (most recent call last):
  File "<string>", line 45, in <module>
EnvironmentError: System.Runtime.InteropServices.COMException (0x8002000D): Memory is locked. (Exception from HRESULT: 0x8002000D (DISP_E_ARRAYISLOCKED))
   at com.alibre.automation.ExceptionMap.handleException(Exception inputException)
   at com.alibre.automation.AlibreDrawingSession.ExportDXF(String targetFilename)
   at Microsoft.Scripting.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at AlibreScript.UI.IronTextBoxControl.#9Gb(Object #FI)
index.php

The AD_DRW is created successfully, but not ExportDXF.
 

stepalibre

Alibre Super User
This script works fine in Python but not .NET:


I think it's Alibre APP/API, not your code. View related code is unreliable and CreateStandardViews is flaky at best. It is all unfinished. poorly documented and something as simple as export views to a file doesn't work. This is a simple method call in any and every other CAD API. This is why I use QCAD API. I'm avoiding all these unfinished Alibre features and APIs. I want to use Alibre for more stuff but it's not production grade.
 

NateLiquidGravity

Alibre Super User
Yeah, there isn't really much I can mess up in that function. And was is only happening sometimes for you too? Does it happen more on more complex parts? Perhaps another case of needing to wait for Alibre Design to finish something even though it has already returned from a previous function? I think I was testing it on v27. I'll try v28 later and I'll try more complex parts.
 

Cator

Senior Member
Nate, from what I have been able to test, the problem almost always occurs with the more complex parts. Example the FanCover posted a few days ago here on the forum. If you create a part from new, whatever the complexity, the script works, but if you use a complex one it creates problems. I used the TooTallToby templates as a test but I was afraid of the hyphens in the names(24-08-09 BRACKET) created exceptions, but this is not the case. If it can help you after the failure, if I try to close the part it tells me to save it even if the save icon is still off.... It really seems like he's missing some step, I'd like to fill it with time.sleep but if we identify the cause it would be Better....
 

stepalibre

Alibre Super User
Nate, from what I have been able to test, the problem almost always occurs with the more complex parts. Example the FanCover posted a few days ago here on the forum. If you create a part from new, whatever the complexity, the script works, but if you use a complex one it creates problems. I used the TooTallToby templates as a test but I was afraid of the hyphens in the names(24-08-09 BRACKET) created exceptions, but this is not the case. If it can help you after the failure, if I try to close the part it tells me to save it even if the save icon is still off.... It really seems like he's missing some step, I'd like to fill it with time.sleep but if we identify the cause it would be Better....

Thanks for posting this! There is something about the file that causes this "Memory is locked" crash. We'll have to figure out why.

I tried another file and it worked!

1722745166459.png

But as I said the other DXF view script is working, so what's the difference between "Export Part Views as DXF" and "Send Part Model View to DXF"?
 

Cator

Senior Member
Further tests allowed me to understand that the complexity of the sketches to be produced affects the occurrence of the exception...
 

NateLiquidGravity

Alibre Super User
Most likely then the view isn't finished generating before it is trying to export. I'll attempt to add some kinda checking or if all else fails the Python way of try/except.
 

stepalibre

Alibre Super User
I don't think that's the problem. Other scripts generate more views and work fine. The views aren't complex either. The crash happens at ExportDXF. Maybe something is named or has a character in the part is the cause.
 

Cator

Senior Member
I made many attempts, including using try/except but nullq was successful this way. The view always creates perfectly, ExportDXF fails. I solved it by embedding the function in a Win.UtilityDialog as you did in the other script and everything works divinely. I even imported subprocess and I open it in my favorite CAM in less than three seconds. But again my question is, how come even the delays have no effect while the stopping of the dialogue boxes work?
 

Cator

Senior Member
PS :
I don't know if written elsewhere, but if this is used Win.SaveFileDialog('Save the DXF', 'DXF Files|*.DXF', '.DXF') The export will take place in R14. You can decide the export version by writing it in the line, that is: Win.SaveFileDialog(Save the DXF', 'AutoCAD® 2018|*.dxf','.dxf'). I hope I have given useful information!


I'm crossing out the comment so as not to leave incorrect information!
 
Last edited:

NateLiquidGravity

Alibre Super User
PS :
I don't know if written elsewhere, but if this is used Win.SaveFileDialog('Save the DXF', 'DXF Files|*.DXF', '.DXF') The export will take place in R14. You can decide the export version by writing it in the line, that is: Win.SaveFileDialog(Save the DXF', 'AutoCAD® 2018|*.dxf','.dxf'). I hope I have given useful information!
That has no effect on what format is saved and is only a dialog to ask the user where and what name to save it.
 

NateLiquidGravity

Alibre Super User
I made many attempts, including using try/except but nullq was successful this way. The view always creates perfectly, ExportDXF fails. I solved it by embedding the function in a Win.UtilityDialog as you did in the other script and everything works divinely. I even imported subprocess and I open it in my favorite CAM in less than three seconds. But again my question is, how come even the delays have no effect while the stopping of the dialogue boxes work?
Depending on how the delays are done they may be uninterruptible by the thread. Meaning the delay holds the thread hostage until the time is up. Forms are often on their own thread so that could explain it.
 

Cator

Senior Member
Depending on how the delays are done they may be uninterruptible by the thread. Meaning the delay holds the thread hostage until the time is up. Forms are often on their own thread so that could explain it.
I understand, it's beyond my skills but I understand the meaning. I'm happy to have solved my communication problem of simple outlines with CAM. Thank you for your work!
 

stepalibre

Alibre Super User
Depending on how the delays are done they may be uninterruptible by the thread. Meaning the delay holds the thread hostage until the time is up. Forms are often on their own thread so that could explain it.
If this is true, then the issue is AD and the AlibreScript addon. These are details Alibre should address. We shouldn't need to worry about threading in an embedded scripting tool. IronPython is stable and many applications embed it without these issues.
 

Cator

Senior Member
Send Part Model View to DXF

A few notes though:
* The part file must be saved or the view can't be made and if the saved part file is obsolete so will be the DXF made from it.
* It worked fine when I open the part in its own session - but did not work if the part is opened from an assembly session.
* Since it is projected into the drawing any edge not parallel to the plane of view will not be true length. In this picture the overall scale is off only due to zoom, but since most of those lines are not parallel to the view they will not be true length measure in the DXF either.

Here is my AlibreScript code for that:
Python:
from __future__ import division # This fixes division with integers. For example the 1 / 2 = 0.5 instead of 0
import clr
import os
import _winreg

Root = Global.Root
Win = Windows()

def getalibrepath():
    try:
        keystring = r'SOFTWARE\Alibre, Inc.\Alibre Design' + '\\' + str(Global.Root.Version).split(' ')[1].replace(',', '.')
        # printpass(keystring)
        hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keystring)
        result = _winreg.QueryValueEx(hKey, 'HomeDirectory')
        # printpass(result[0])
        return result[0]
    except Exception, e:
        print(e)
        try:
            hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'Software\\Alibre, Inc.\\Alibre Design')
            result = _winreg.QueryValueEx(hKey, 'HomeDirectory')
            return result[0]
        except Exception, e:
            print(e)
            return ''
    return ''  # technically unreachable

ADPath = os.path.join(getalibrepath(), 'Program')
sys.path.append(ADPath)
clr.AddReference('AlibreX.dll')
from AlibreX import ADUnits, ADDrawingViewType, ADDetailingOption, ADViewOrientation, IAD2DPoint, IADTransformation

prt = CurrentPart()
AD_prt = prt._Part

trans = AD_prt.ViewTransform

my_drawing = Root.CreateEmptyDrawing(str(prt.Name))
point_orgin = my_drawing.GeometryFactory.Create2DPoint(0.0,0.0)
test_sheet = my_drawing.Sheets.CreateBlankSheet('Exported From Model Space', 1.0, 1.0, ADUnits.AD_CENTIMETERS, 1.0, 1.0)
test_sheet.CreateStandardViews(str(prt.FileName), ADDrawingViewType.AD_STANDARD, ADDetailingOption.AD_TANGENT_EDGES, 1.0, 1.0, ADViewOrientation.AD_FRONT, point_orgin, trans)

savePath = Win.SaveFileDialog('Save the DXF', 'DXF Files|*.DXF', '.DXF')
if savePath:
    my_drawing.ExportDXF(savePath)
    print('Saved')
else:
    print('Canceled')
my_drawing.Close(0)
Good morning @NateLiquidGravity ,
I saw that this script does not work with files saved in Alibre PDM. It gives me a window as "empty value" like when I don't save the file whose view I want to export. Is it a programmatic control or should I report it as possible bug?
Thank you
Francesco
 

NateLiquidGravity

Alibre Super User
Alibre PDM is in beta and I haven't tested it yet. There is no public API for it yet. I'm assuming that AlibreScript will need to be updated to work with it at some point but who knows. I've got no ability to make it work at this point so I would suggest reporting for the Beta.
 
Top