July 10, 2019

Look for exact property value and more

When using the search() function of the Viewer, you can only look for strings that at least partially match a given value. That will include other values as well: e.g. you may look for "Window1", but the search will also return items like "Window12". Having lots of false positives could slow things down.

In v6.5.0 a new function was introduced called executeUserFunction() that can help us out here: https://forge.autodesk.com/en/docs/viewer/v6/change_history/changelog_v6/
You can find samples for it here: https://forge.autodesk.com/en/docs/viewer/v6/tutorials/propdb-queries/

One difficulty is with passing parameters to our userFunction() because it's executed on a worker thread - so not even global variables will be reachable from it.

You can work around it by "baking in" your variable's value into the userFunction()'s implementation. Since executeUserFunction() accepts a string as well that contains the source code of our function, therefore the simplest solution might be to write our function as normal (so we have access to intelli-sense), and once done, just turn it into a template literal by surrounding it with back-tick ` characters. Then we can use inside it ${} placeholders to inject our variable's value into it.

async function autoSelect(viewer, tag) {
    let res = await viewer.model.getPropertyDb().executeUserFunction(`function userFunction(pdb) {
        console.log('${tag}');
        var dbIds = [];

        pdb.enumObjects(dbId => {
            let p = pdb.getObjectProperties(dbId);
            let pv = p && p.properties;
            if (!pv) return;

            if (p.name === '${tag}') {
                dbIds.push(dbId);
                return true;
            }
        });
        
        return dbIds;  
    }`);
    
    let dbId = res[0];
    console.log(`dbId with tag ${tag} => ${dbId}`);
    viewer.select([dbId]);
    viewer.fitToView([dbId]);
}

Now we can call it e.g. in the browser console to see the result - see above picture.

   

Related Posts