Использование расширения Forge Javascript в приложении Angular - PullRequest
0 голосов
/ 18 марта 2020

Как использовать расширение на основе Jasvscript, например IconMarkupExtension из https://forge.autodesk.com/blog/placing-custom-markup-dbid в моем Angular приложение Я попробовал следующее:

Импортировать файл Javascript:

import IconMarkupExtension from './IconMarkupExtension';

, используя расширение, определив в viewerConfig:

constructor(private router: Router, private auth: AuthService, private api: ApiService, private messageService: MessageService) {
this.viewerOptions3d = {
  initializerOptions: {
    env: 'AutodeskProduction',
    getAccessToken: (async (onGetAccessToken) => {
      const authToken: AuthToken = await this.api.get2LToken();
      this.auth.currentUserValue.twolegggedToken = authToken.access_token;
      onGetAccessToken(this.auth.currentUserValue.twolegggedToken, 30 * 60);
    }),
    api: 'derivativeV2',
  },
  viewerConfig: {
    extensions: ['IconMarkupExtension'], // [GetParameterExtension.extensionName],
    theme: 'dark-theme',
  },
  onViewerScriptsLoaded: this.scriptsLoaded,
  onViewerInitialized: (async (args: ViewerInitializedEvent) => {
    if (this.platform.currentProject.encodedmodelurn) {
      args.viewerComponent.DocumentId = this.platform.currentProject.encodedmodelurn;
      this.loadCustomToolbar();
      // this.loadIconMarkupExtension();
    }
    else {
      // Graphische Anpassung
      $('#forge-viewer').hide();
      // args.viewerComponent.viewer.uninitialize();
      this.messageService.clear();
      this.messageService.add({ key: 'noModel', sticky: true, severity: 'warn', summary: 'NOT AVAILABLE', detail: 'Do you want to add a Model' });
      this.platform.app.openOverlay();
    }
  }),
  // Muss true sein
  showFirstViewable: true,
  // Ist falsch gesetzt => GuiViewer3D => Buttons asugeblendet in CSS
  headlessViewer: false,
};

}

и, наконец, зарегистрируйтесь после onViewerScriptsLoaded

public scriptsLoaded() {
// Extension.registerExtension(GetParameterExtension.extensionName, GetParameterExtension);
Extension.registerExtension('IconMarkupExtension', IconMarkupExtension);

}

Проблема, с которой я сталкиваюсь, - причина ошибки

class IconMarkupExtension extends Autodesk.Viewing.Extension {

Autodesk не определен

Спасибо

Ответы [ 2 ]

0 голосов
/ 22 марта 2020

Решением было переписать расширение, затем как обычно зарегистрировать и загрузить расширение.

/// <reference types="forge-viewer" />

   import { Extension } from '../../viewer/extensions/extension';

   declare const THREE: any;

export class IconMarkupExtension extends Extension {
    // Extension must have a name
    public static extensionName: string = 'IconMarkupExtension';
    public _group;
    public _button: Autodesk.Viewing.UI.Button;
    public _icons;
    public _inputs;
    public _enabled;
    public _frags;
    public onClick;

constructor(viewer, options) {
    super(viewer, options);
    this._group = null;
    this._button = null;
    this._enabled = false;
    this._icons = options.icons || [];
    this._inputs = options.inputs || [];
    this.onClick = (id) => {
        this.viewer.select(id);
        this.viewer.fitToView([id], this.viewer.model, false);
    };
}

public load() {
    const updateIconsCallback = () => {
        if (this._enabled) {
            this.updateIcons();
        }
    };
    this.viewer.addEventListener(Autodesk.Viewing.CAMERA_CHANGE_EVENT, updateIconsCallback);
    this.viewer.addEventListener(Autodesk.Viewing.ISOLATE_EVENT, updateIconsCallback);
    this.viewer.addEventListener(Autodesk.Viewing.HIDE_EVENT, updateIconsCallback);
    this.viewer.addEventListener(Autodesk.Viewing.SHOW_EVENT, updateIconsCallback);
    return true;
}

unload() {
    // Clean our UI elements if we added any
    if (this._group) {
        this._group.removeControl(this._button);
        if (this._group.getNumberOfControls() === 0) {
            this.viewer.toolbar.removeControl(this._group);
        }
    }
    return true;
}

onToolbarCreated() {
    // Create a new toolbar group if it doesn't exist
    this._group = this.viewer.toolbar.getControl('customExtensions');
    if (!this._group) {
        this._group = new Autodesk.Viewing.UI.ControlGroup('customExtensions');
        this.viewer.toolbar.addControl(this._group);
    }

    // Add a new button to the toolbar group
    this._button = new Autodesk.Viewing.UI.Button('IconExtension');
    this._button.onClick = (ev) => {
        this._enabled = !this._enabled;
        this.showIcons(this._enabled);
        this._button.setState(this._enabled ? 0 : 1);

    };
    // this._button.setToolTip(this.options.button.tooltip);
    this._button.setToolTip('Showing Panel Information');
    // @ts-ignore
    this._button.container.children[0].classList.add('fas', 'fa-cogs');
    this._group.addControl(this._button);

    // Iterate through _inputs
    this._inputs.forEach(input => {
        var name = '';
        if (input.objectPath.indexOf('/')) {
            name = input.objectPath.split('/')[input.objectPath.split('/').length - 1];
        }
        else {
            name = input.objectPath;
        }
        this.viewer.search(name, (idArray) => {
            if (idArray.length === 1) {
                // console.log(idArray);
                this._icons.push({ dbId: idArray[0], label: name, css: 'fas fa-question-circle' });
            }
            else if (idArray.length !== 1) {
                console.log('idArray.length !== 1 getMarkups!!');
            }
        }, (err) => {
            console.log('Something with GETTING MARKUPS went wrong');
        }, ['name']);
    });
}

showIcons(show) {
    console.log(this.viewer);
    console.log(this._icons);
    // @ts-ignore
    const $viewer = $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer');

    // remove previous...
    // @ts-ignore
    $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer label.markup').remove();
    if (!show) return;

    // do we have anything to show?
    if (this._icons === undefined || this._icons === null) return;

    // do we have access to the instance tree?
    const tree = this.viewer.model.getInstanceTree();

    if (tree === undefined) { console.log('Loading tree...'); return; }

    const onClick = (e) => {
        this.onClick($(e.currentTarget).data('id'));
    };

    this._frags = {};

    for (var i = 0; i < this._icons.length; i++) {
        // we need to collect all the fragIds for a given dbId
        const icon = this._icons[i];
        this._frags['dbId' + icon.dbId] = [];

        // create the label for the dbId
        const $label = $(`
        <label class="markup update" data-id="${icon.dbId}">
            <span class="${icon.css}"> ${icon.label || ''}</span>
        </label>
        `);
        $label.css('display', this.viewer.isNodeVisible(icon.dbId) ? 'block' : 'none');
        $label.on('click', onClick);

        $viewer.append($label);
        // now collect the fragIds
        const _this = this;
        tree.enumNodeFragments(icon.dbId, (fragId) => {
            _this._frags['dbId' + icon.dbId].push(fragId);
            _this.updateIcons(); // re-position of each fragId found
        });
    }
}

getModifiedWorldBoundingBox(dbId) {
    var fragList = this.viewer.model.getFragmentList();
    const nodebBox = new THREE.Box3();

    // for each fragId on the list, get the bounding box
    for (const fragId of this._frags['dbId' + dbId]) {
        const fragbBox = new THREE.Box3();
        fragList.getWorldBounds(fragId, fragbBox);
        nodebBox.union(fragbBox); // create a unifed bounding box
    }

    return nodebBox;
}

updateIcons() {
    // @ts-ignore
    // const label = $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer .update')[0];
    // const $label = $(label);
    // @ts-ignore
    // @ts-ignore
    $(() => {
        // @ts-ignore
        const labels = Array.from($('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer .update'));
        for (const label of labels) {
            const $label = $(label);
            const id = $label.data('id');
            // get the center of the dbId(based on its fragIds bounding boxes)
            const pos = this.viewer.worldToClient(this.getModifiedWorldBoundingBox(id).center());
            // position the label center to it
            $label.css('left', Math.floor(pos.x - $label[0].offsetWidth / 2) + 'px');
            $label.css('top', Math.floor(pos.y - $label[0].offsetHeight / 2) + 'px');
            $label.css('display', this.viewer.isNodeVisible(id) ? 'block' : 'none');
        }
    });

    // for (const label of $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer .update')) {
    //     const $label = $(label);
    //     const id = $label.data('id');

    //     // @ts-ignore
    //     // const $label = $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer .update')[0];
    //     // const id = $label.data('id');

    //     // get the center of the dbId (based on its fragIds bounding boxes)
    //     const pos = this.viewer.worldToClient(this.getModifiedWorldBoundingBox(id).center());
    //     // console.log(pos);

    //     // position the label center to it
    //     $label.css('left', Math.floor(pos.x - $label[0].offsetWidth / 2) + 'px');
    //     $label.css('top', Math.floor(pos.y - $label[0].offsetHeight / 2) + 'px');
    //     $label.css('display', this.viewer.isNodeVisible(id) ? 'block' : 'none');
    // }
}
}
0 голосов
/ 19 марта 2020

Используйте определения Typescript средства просмотра - см. здесь для установки и настройки.

Вот также пара примеров, если вам нужен рабочий код:

...