Я пытаюсь придать предоставленному Inventor_sample_file.ipt другой цвет. У меня есть SFC ниже. Часть кода взята из другого SO вопроса.
<template>
<div class = "viewer-container">
<div id = "forge-viewer" />
</div>
</template>
<script>
export default {
props: {
object: {
type: Object,
required: true,
},
},
mounted()
{
this.initializeViewer();
},
data()
{
return {
viewer: null,
access_token: <some token>, // No, it is not hardcoded
options: {
env: 'AutodeskProduction2',
api: 'streamingV2_EU', // for models uploaded to EMEA change this option to 'streamingV2_EU'
getAccessToken: onTokenReady => {
let token = this.access_token;
let timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
}
}
},
methods: {
initializeViewer()
{
this.$loadScript('https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js')
.then(() => {
Autodesk.Viewing.Initializer(this.options, () => {
this.viewer = new Autodesk.Viewing.GuiViewer3D(
document.getElementById('forge-viewer'),
);
let startedCode = this.viewer.start();
if ( startedCode > 0 )
{
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
this.loadModel(<base64 encoded this.object.object_id>);
});
}).catch((error) => {
console.warn('Autodesk not loaded', error);
});
},
onDocumentLoadedSuccess(viewer_document)
{
let viewerapp = viewer_document.getRoot();
let default_model = viewerapp.getDefaultGeometry();
let viewables = viewerapp.search({'type':'geometry'});
if (viewables.length === 0)
{
console.error('Document contains no viewables.');
return;
}
this.viewer.loadDocumentNode(viewer_document, default_model);
this.viewer.loadExtension('Autodesk.PDF').then( () => {
this.viewer.loadExtension("Autodesk.Viewing.MarkupsCore")
this.viewer.loadExtension("Autodesk.Viewing.MarkupsGui")
});
console.info(new THREE.Vector4(1, 0, 0, 0.5));
this.viewer.setThemingColor(4, new THREE.Vector4(1, 0, 0, 0.5), null, true);
},
onDocumentLoadedFailure()
{
console.error('Failed fetching Forge manifest');
},
loadModel(urn)
{
const documentId = `urn:${urn}`;
Autodesk.Viewing.Document.load(
documentId,
viewer_document => this.onDocumentLoadedSuccess(viewer_document),
() => this.onDocumentLoadedFailure
);
},
}
}
</script>
<style scoped>
@import 'https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.min.css';
#forge-viewer {
width: 100%;
height: 100%;
margin: 0;
background-color: #F0F8FF;
}
.viewer-container {
display: block;
position: relative;
width: 100%;
height: 100%;
}
</style>
Модель загружается во вьювере, но теперь выдает следующую ошибку:
Viewer3D.js: 4872 Uncaught TypeError: невозможно прочитать свойства неопределенного (чтение 'setThemingColor')
Эта ошибка ссылается на следующее:
Viewer3D.prototype.setThemingColor = function(dbId, color, model, recursive) {
// use default RenderModel by default
model = model || this.model;
model.setThemingColor(dbId, color, recursive); // this line gives the error
// we changed the scene to apply theming => trigger re-render
this.impl.invalidate(true);
};
И я не удивлен, так как здесь за модель дается null
this.viewer.setThemingColor(4, new THREE.Vector4(1, 0, 0, 0.5), null, true);
. Хотя это не должно быть проблемой, если установлено this.model
, но, видимо, это не так.
Я надеюсь, что кто-то может указать мне правильное направление, как раскрасить модель.
Я добавил следующее, как было предложено:
this.viewer.loadDocumentNode(viewer_document, default_model).then(model => {
console.info('model', model, 'color', new THREE.Vector4(1, 0, 0, 0.5));
this.viewer.setThemingColor(4, new THREE.Vector4(1, 0, 0, 0.5), model, true);
});
Это дает журнал, как показано ниже. Ошибка исчезла. Но это все еще не меняет цвет модели.
Насколько я понимаю, это потому, что вы запускаете setThemingColor до завершения loadDocumentNode.
Можете ли вы попробовать поместить viewer.setThemingColor(...)
в функцию обратного вызова loadDocumentNode()? просто чтобы убедиться, что вы установили цвет после полной загрузки модели.
так :
this.viewer.loadDocumentNode(viewer_document, default_model)
.then(() => {
//when document node loaded, do...
this.viewer.setThemingColor(4, new THREE.Vector4(1, 0, 0, 0.5), this.model, true);
})
Мне также пришлось изменить dbId, который все еще был неправильным. После этого модель окончательно сменила цвет. Спасибо!
Обновили вопрос. Мне пришлось использовать параметр
model
, чтобы получить модель такой, какойthis.model
былаundefined