宏忽略参数更改

问题描述

给定一个 FreeCAD model 组成的

  • 带有别名为“radius”和值为 50 的单元格的电子表格“参数”
  • 具有 Radius=parameters.radius 的二十面体(来自 Pyramids-and-polyhedrons 宏)
  • 一些对这个问题来说不重要的 facebinder,

下面的python脚本打开这个模型,将Spreadsheet中的radius单元格改为15,在电子表格上调用recompute(),在二十面体上调用touch(),在文档上调用recompute(),最后对二十面体进行镶嵌.镶嵌网格中索引 11 处顶点的 z 坐标恰好等于二十面体的半径。根据参数更改,我预计它会更改为 15。但它仍然保持原来的值 50。我做错了什么?

据我所知,应该在重新计算文档期间调用宏的 execute method

当我用 pudb 跟踪 Document.recompute() 时,我只看到它在执行 Facebinder.execute() 而不是 Icosahedron.execute()。从 Document.recompute() 到 Facebinder.execute() 方法的路径在 pudb 中是不可见的;它立即停止在 Facebinder.execute() 中。

FREECAdpath = '/usr/local/lib' # path to your FreeCAD.so or FreeCAD.dll polyHEDRONS_PATH = '/home/user/.FreeCAD/Mod/Pyramids-and-polyhedrons'
import sys
sys.path.append(FREECAdpath)
sys.path.append(polyHEDRONS_PATH)
import FreeCAD

filename = 'icosahedron.FCStd'
newRadius = 15

doc = FreeCAD.open(filename)
sheet = doc.Spreadsheet
sheet.set('radius',str(newRadius))
sheet.recompute()
print('radius = ' + str(sheet.get('radius')))

icosahedron = doc.getobjectsByLabel('Icosahedron')[0]
print('icosahedron.Radius = '+str(icosahedron.Radius))
icosahedron.touch()
doc.recompute()
print('icosahedron.Radius = '+str(icosahedron.Radius))

(vertices,faces) = icosahedron.Shape.tessellate(1)
z11 = vertices[11][2]
print('z11 = ' + str(z11))
FreeCAD.closeDocument(doc.Name)

解决方法

我想通了。原因是 Pyramids-and-Polyhedrons 毕竟没有被导入。 第一个问题是 Pyramids-and-Polyhedrons 导入 FreeCADGui(为了安装它的工作台),它依赖于在运行脚本之前需要添加到 LD_LIBRARY_PATH 的某些本地库:

export LD_LIBRARY_PATH=$(echo $(find /usr/local/lib/python3.7/site-packages -maxdepth 2 -mindepth 2 -type f -name *.so* | sed -r 's|/[^/]+$||' | sort -u) | sed -E 's/ /:/g')

现在可以导入 FreeCADGui,但缺少 addCommand 调用所需的 Pyramids-and-Polyhedrons 方法。我发现 FreeCADGui 只有在调用 FreeCADGui.showMainWindow() 后才会完全初始化。但是,这需要显示,并且我想将脚本作为 Docker 容器中无头工具链的一部分运行。因此我在图像中添加了 Xvfb。我在运行更新后的脚本之前在后台启动它,DISPLAY 指向 Xvfb:

FREECADPATH = '/usr/local/lib' # path to your FreeCAD.so or FreeCAD.dll file
POLYHEDRONS_PATH = '/home/user/.FreeCAD/Mod/Pyramids-and-Polyhedrons'
import sys
sys.path.append(FREECADPATH)
sys.path.append(POLYHEDRONS_PATH)
import FreeCAD
import FreeCADGui
FreeCADGui.showMainWindow()

import polyhedrons

filename = 'icosahedron.FCStd'
newRadius = 15

doc = FreeCAD.open(filename)
sheet = doc.Spreadsheet
sheet.set('radius',str(newRadius))
sheet.recompute()
print('radius = ' + str(sheet.get('radius')))

icosahedron = doc.getObjectsByLabel('Icosahedron')[0]
print('icosahedron.Radius = '+str(icosahedron.Radius))
breakpoint()
icosahedron.touch()
doc.recompute()
print('icosahedron.Radius = '+str(icosahedron.Radius))

(vertices,faces) = icosahedron.Shape.tessellate(1)
z11 = vertices[11][2]
print('z11 = ' + str(z11))
FreeCAD.closeDocument(doc.Name)

现在输出是

...
z11 = 15.0

正如预期的那样。