新しい Forge Viewer チュートリアル ~ その1

GitHub logo featuring a cartoon octopus character with cat-like ears and a tail, sitting on a blue shape with the text 'GitHub' next to it.

初期の View and Data API の提供停止 にともなって、過去にご案内した Forge Viewer チュートリアル も新しく生まれ変わっています。このブログ記事では、新しいチュートリアルとなる https://github.com/Autodesk-Forge/viewer-nodejs-tutorial リポジトリに記載された viewer-nodejs-tutorial サンプルの利用方法をご紹介するものです。


  1. GitHub アカウントをお持ちでない場合や、GitHub Desktop と Node.js、Postman をインストールされていない場合には、Forge の開発環境 の内容をご確認の上、アカウント取得とインストールを完了させてください。実際の開発に GitHub アカウントや GitHub Desktop は必須ではありませんが、GirHub 上で公開されている Forge サンプルを参照する場合に便利です。
  2. Forge を利用するために必要な Client ID と Client Secret(別名 Consumer Key と Consumer Secret)を取得していない場合には、Forge API を利用するアプリの登録とキーの取得 の内容に沿って、キーを取得してください。
  3. チュートリアルの環境をセットアップしてきます。 https://github.com/Autodesk-Forge/viewer-nodejs-tutorial リポジトリ ページを表示して、右上の Sign in から GitHub アカウントでサインインします。
  4. Git Shell 上の git コマンドを使って素材となるソースコード一式をクライアント コンピュータにコピーします。まずは、コピー対象の URL をページ上で確認します。
  5. Git Shell を起動して、git clone コマンドで確認した URL をパラメータに指定して、リポジトリ をクライアント コンピュータにコピーします。具体的には、git clone https://github.com/Autodesk-Forge/viewer-nodejs-tutorial.git と入力してください。リポジトリのコピーが始まるはずです。
    もし、Git Shell を利用せずにサンプルをダウンロードしたい場合には、隣にある [Download ZIP] ボタンを使って、任意に ZIP 圧縮されたソースコードを入手することも可能です。
  6. コピーされたリポジトリが、C:Users<Windows ユーザ名>DocumentsGitHub フォルダ直下の viewer-nodejs-tutorial フォルダにあることを確認してください。
  7. Node.js を利用した Web サーバーをローカル コンピュータ上に構築していきます。コピーしたリポジトリ内のサンプル コードが利用している Node Package を、npm(Node Package Manager)コマンドを使ってインストールしていきます。Node.js command prompt を起動してローカル リポジトリのディレクトリに移動したら、npm install と入力してください。インストールが開始されて、expressrequestserve-favicon の 3つの Node Package がインストールされるはずです。
  8. 同じ viewer-nodejs-tutorial フォルダ内で、copy コマンドを使って credentials_.js ファイルを credentials.js の名前でコピーします。
  9. コピーした credentials.js ファイルを Adobe Brackets で開いて、 Developer Portal サイトで取得済の Client ID と Client Secret の値に置き換えて上書き保存します。<replace with your client id> を Client ID で、<replace with your client secret> を Client Secret で書き換えて、ファイルを上書き保存してください。
  10. Adobe Brackets で viewer-nodejs-tutorial フォルダ直下の Server.js を開き、コード部分のコメント記号 // を削除します。
var favicon = require('serve-favicon');
var oauth = require('./routes/oauth');
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use('/', express.static(__dirname + '/www'));
app.use(favicon(__dirname + '/www/images/favicon.ico'));
// /////////////////////////////////////////////////////////////////////////////////
// //
// // Use this route for proxying access token requests
// //
// /////////////////////////////////////////////////////////////////////////////////
app.use('/oauth', oauth);
var server = app.listen(app.get('port'), function () {
    console.log('Server listening on port ' + server.address().port);
});
  1. 同様に Adobe Brackets で routes フォルダ直下の oauth.js を開いて、コード部分のコメント記号 // を削除します。
/////////////////////////////////////////////////////////////////////////////////
//
// Obtaining our Token 
//
/////////////////////////////////////////////////////////////////////////////////
var express = require('express');
var request = require('request');
var router = express.Router();
var credentials = (require('fs').existsSync(__dirname + '/../credentials.js') ?
    require(__dirname + '/../credentials')
    : (console.log('No credentials.js file present, assuming using FORGE_CLIENT_ID & FORGE_CLIENT_SECRET system variables.'),
        require(__dirname + '/../credentials_')));
router.get('/token', function (req, res) {
    request.post(
        credentials.Authentication,
        { form: credentials.credentials },
        function (error, response, body) {
            if (!error && response.statusCode == 200)
                res.send(body);
        });
});
module.exports = router;
  1. 更に www フォルダ下の js フォルダ内から index.js ファイルを開いて、コード部のコメント記号 // を削除し、<YOUR_URN_ID> 箇所に Postman による Viewer 利用手順の理解 – 2 legged 認証 で紹介した手順で取得した Base64 エンコード済みの値で置き換えます。この際、’urn:<YOUR_URN_ID>’ の urn: は削除しないでください。
/////////////////////////////////////////////////////////////////////////////////
//
// Use this call to get back an object json of your token
//
/////////////////////////////////////////////////////////////////////////////////
var tokenurl = window.location.protocol + '//' + window.location.host + '/api/token';
function tokenAjax() {
    return $.ajax({
        url: tokenurl,
        dataType: 'json'
    });
}
/////////////////////////////////////////////////////////////////////////////////
//
// Initialize function to the Viewer inside of Async Promise
//
/////////////////////////////////////////////////////////////////////////////////
var viewer;
var options = {};
var documentId = 'urn:<YOUR_URN_ID>';
var promise = tokenAjax();
promise.success(function (data) {
    options = {
        env: 'AutodeskProduction',
        accessToken: data.access_token
    };
    Autodesk.Viewing.Initializer(options, function onInitialized() {
        Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
    });
})

/**
* Autodesk.Viewing.Document.load() success callback.
* Proceeds with model initialization.
*/
function onDocumentLoadSuccess(doc) {
    // A document contains references to 3D and 2D viewables.
    var viewables = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), { 'type': 'geometry' }, true);
    if (viewables.length === 0) {
        console.error('Document contains no viewables.');
        return;
    }
    // Choose any of the avialble viewables
    var initialViewable = viewables[0];
    var svfUrl = doc.getViewablePath(initialViewable);
    var modelOptions = {
        sharedPropertyDbPath: doc.getPropertyDbPath()
    };
    var viewerDiv = document.getElementById('viewerDiv');
    ///////////////USE ONLY ONE OPTION AT A TIME/////////////////////////
    /////////////////////// Headless Viewer ///////////////////////////// 
    viewer = new Autodesk.Viewing.Viewer3D(viewerDiv);
    //////////////////Viewer with Autodesk Toolbar///////////////////////
    viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);
    //////////////////////////////////////////////////////////////////////
    // viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
}
/**
* Autodesk.Viewing.Document.load() failuire callback.
*/
function onDocumentLoadFailure(viewerErrorCode) {
    console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
/**
* viewer.loadModel() success callback.
* Invoked after the model's SVF has been initially loaded.
* It may trigger before any geometry has been downloaded and displayed on-screen.
*/
function onLoadModelSuccess(model) {
    console.log('onLoadModelSuccess()!');
    console.log('Validate model loaded: ' + (viewer.model === model));
    console.log(model);
}
/**
* viewer.loadModel() failure callback.
* Invoked when there's an error fetching the SVF file.
*/
function onLoadModelError(viewerErrorCode) {
    console.error('onLoadModelError() - errorCode:' + viewerErrorCode);
}
  1. Node.js command prompt 上で カレント  ディレクトリが viewer-nodejs-tutorial フォルダであることを確認したら、npm start または node server.js と入力して Node サーバーを起動します。
  2. Google Chrome か、他の WebGL がサポートされる Web ブラウザを起動して、URL に localhost:3000 と入力してください。指定したドキュメントが表示されるはずです。

次回 は、各種 Extension をロードさせたり、背景を変更するなどして、Viewer の状態を拡張します。

By Toshiaki Isezaki

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading