You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Autodesk Forge API统计Inventor文件零件节点并过滤装配体

解决Autodesk Forge中Inventor装配体零件统计与节点筛选问题

1. 统计装配体中的零件总数(排除装配体/子装配体)

原方法getAllLeafIdsOfParentId会将无下级子节点的装配体也计入统计,需通过节点属性+子节点存在性双重判断来筛选零件:

// 递归遍历所有节点,筛选出零件ID
function getAllPartIds(rootId) {
    const instanceTree = viewer.model.getData().instanceTree;
    const partIds = [];
    const traverseNode = (nodeId) => {
        // 判断节点是否有子节点
        const hasChildren = instanceTree.getChildCount(nodeId) > 0;
        // 获取节点属性,判断是否为零件(需匹配Inventor导出的实际属性)
        const props = viewer.model.getPropertyDb().getProperties(nodeId);
        const isPart = props.some(prop => prop.displayName === "Type" && prop.displayValue === "Part");
        
        // 仅收集无子女的零件节点
        if (!hasChildren && isPart) {
            partIds.push(nodeId);
        } else if (hasChildren) {
            // 递归遍历子节点
            instanceTree.enumNodeChildren(nodeId, (childId) => traverseNode(childId));
        }
    };
    traverseNode(rootId);
    return partIds;
}

// 调用获取零件总数
const rootId = viewer.model.getData().instanceTree.getRootId();
const totalParts = getAllPartIds(rootId).length;

注:若Inventor导出的属性中"Type"字段名称或值不同,需根据实际返回的属性调整判断条件,比如部分场景下用"Document Type"区分。

2. 仅允许零件节点加入指定数组,阻止装配体

在节点选择或手动添加逻辑中加入判断,拒绝装配体节点:

场景1:监听用户选择事件

const selectedParts = [];

viewer.addEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, (event) => {
    event.dbIdArray.forEach(dbId => {
        const instanceTree = viewer.model.getData().instanceTree;
        const hasChildren = instanceTree.getChildCount(dbId) > 0;
        const props = viewer.model.getPropertyDb().getProperties(dbId);
        const isPart = props.some(prop => prop.displayName === "Type" && prop.displayValue === "Part");
        
        if (isPart && !hasChildren) {
            // 验证通过,加入数组(避免重复)
            if (!selectedParts.includes(dbId)) {
                selectedParts.push(dbId);
            }
        } else {
            // 阻止装配体加入,可提示用户
            console.log("仅支持选择零件节点,请重新选择");
            // 可选:恢复之前的零件选择状态
            viewer.select(selectedParts);
        }
    });
});

场景2:手动添加节点的函数

const selectedParts = [];

function addNodeToPartArray(dbId) {
    const instanceTree = viewer.model.getData().instanceTree;
    const hasChildren = instanceTree.getChildCount(dbId) > 0;
    const props = viewer.model.getPropertyDb().getProperties(dbId);
    const isPart = props.some(prop => prop.displayName === "Type" && prop.displayValue === "Part");
    
    if (isPart && !hasChildren) {
        selectedParts.push(dbId);
    } else {
        console.error("无法添加装配体节点,仅支持零件");
    }
}

内容的提问来源于stack exchange,提问作者kaushik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 18:52:59