Files
web3d/WebGl/draw/webgl_draw.js
T
2023-10-19 09:49:21 +02:00

663 lines
23 KiB
JavaScript

import * as THREE from '../threeJsLib/three.module.js';
import { OrbitControls } from '../jsm/controls/OrbitControls.js';
import { ThreeMFLoader } from '../jsm/loaders/3MFLoader.js';
import { Rhino3dmLoader } from '../jsm/addons/loaders/3DMLoader.js';
// VARIABILI DI CONTROLLO
// *** div dimensions ***
var m_divStartDimX = 500;
var m_divStartDimY = 400;
var fName = "Cubo.3mf";
//var fileType = "3MF";
// *** camera settings ***
var m_bZoom = true;
var m_bPan = true;
var m_bRot = true;
var m_nCamPos = 0;
var m_nCameraStartPos = 8 ;
var m_bIsOrtographic = true ;
// *** index blender ***
var m_nStartL = 0;
var m_nEndL = 0;
// *** frame settings ***
var m_bShowFrame = true ;
var m_lFrameLen = 100 ;
var m_dFrameFat = 2; // raggio del cilindro
var m_bFrameType = 2 ;
var m_bAutoRot = false;
// *** grid settings ***
var m_bShowGrid = true ;
var m_bInfGrid = true ;
// *** Direction Arrows ***
var m_bShowPrintDir = true ;
//var useInSlider = false;
var counter = 0;
let activeCamera, scene, renderer, controls, ORIG, perspectiveCamera, orthographicCamera;
var layer_list = [];
const GLBox3D = new THREE.Box3(); // Box3D globale delle geometrie
//init();
class webgl_original {
async initcall({ _dimX, _dimY, _fileName, _showInfiniteGrid, _fileType}) {
m_divStartDimX = _dimX;
m_divStartDimY = _dimY;
fName = _fileName;
m_bInfGrid = _showInfiniteGrid;
//console.log(fName)
setLoaders();
if(_fileType.toUpperCase() == '3MF')
{
await init3mf();
}
else if(_fileType.toUpperCase() == '3DM')
{
await init3dm();
}
else
{
console.log('File type not supported')
}
}
setCameraType(){
toggleCamera( perspectiveCamera, orthographicCamera);
}
refreshcall(nStart, nEnd) {
refreshElement(nStart, nEnd);
}
resetCamera() {
SetCameraPos( m_nCameraStartPos, ORIG) ;
}
}
export { webgl_original }
function toggleCamera( perspectiveCamera, orthographicCamera) { // <-----------------
var cameraPosition = activeCamera.position.clone() ;
var cameraMatrix = activeCamera.matrix.clone() ;
var ControlsTarget = controls.target.clone() ;
var ControlsPosition = controls.position0.clone() ;
if ( m_bIsOrtographic == true) {
m_bIsOrtographic = false ;
activeCamera = perspectiveCamera ;
activeCamera.position.copy( cameraPosition) ;
activeCamera.matrix.copy( cameraMatrix) ;
} else {
m_bIsOrtographic = true ;
activeCamera = orthographicCamera ;
activeCamera.position.copy( cameraPosition) ;
activeCamera.matrix.copy( cameraMatrix) ;
}
activeCamera.updateProjectionMatrix() ;
controls.object = activeCamera ;
controls.target = ControlsTarget ;
controls.position0 = ControlsPosition ;
controls.update() ;
render() ;
}
function setLoaders() {
//<input type="range" class="form-range" id="customRange1">
const mother = document.getElementById('WebGL-3mfExport');
const spinContainer = document.createElement('div');
const sliderInput = document.createElement('input');
const elParent = document.createElement('div');
const elChild1 = document.createElement('div');
const elChild2 = document.createElement('div');
const elChild3 = document.createElement('div');
const elChild4 = document.createElement('div');
const elChild5 = document.createElement('div');
const elChild6 = document.createElement('div');
const loadTxt = document.createElement('div');
//if (useInSlider) {
mother.appendChild(sliderInput);
sliderInput.setAttribute('id', 'refre_slider');
sliderInput.setAttribute('hidden', true);
sliderInput.type = 'range';
sliderInput.min = '0';
//}
mother.appendChild(spinContainer);
//document.body.appendChild(spinContainer);
spinContainer.appendChild(elParent);
spinContainer.appendChild(loadTxt);
elParent.appendChild(elChild1);
elParent.appendChild(elChild2);
elParent.appendChild(elChild3);
elParent.appendChild(elChild4);
elParent.appendChild(elChild5);
elParent.appendChild(elChild6);
loadTxt.setAttribute('id', 'loadTxt');
spinContainer.setAttribute('id', 'spinContainer');
var st = 'height: ' + m_divStartDimY + 'px ; width: ' + m_divStartDimX + 'px ; background-color: #a0a0a0';
spinContainer.setAttribute("style", st);
elParent.setAttribute('id', 'sp');
elParent.classList.add('spinner');
loadTxt.style.padding = '30px 0 0 0'
loadTxt.innerText = 'Loading...';
loadTxt.style.fontSize = '50px';
loadTxt.style.fontFamily = 'Helvetica';
spinContainer.style.display = 'flex';
spinContainer.style.alignItems = 'center';
spinContainer.style.justifyContent = 'center';
spinContainer.style.flexDirection = 'column';
elParent.style.width = '70.4px';
elParent.style.height = '70.4px';
elParent.style.setProperty('--clr', 'rgb(247, 197, 159)');
elParent.style.setProperty('--clr-alpha', 'rgb(247, 197, 159,.1)');
elParent.style.transformStyle = 'preserve-3d';
elParent.animate([
// key frames
{ transform: 'rotate(45deg) rotateX(-25deg) rotateY(25deg)' },
{ transform: 'rotate(45deg) rotateX(-385deg) rotateY(25deg)' },
{ transform: 'rotate(45deg) rotateX(-385deg) rotateY(385deg)' }
], {
// sync options
duration: 2600,
iterations: Infinity,
easing: 'ease',
rangeStart: "cover 0%",
rangeEnd: "cover 100%"
});
var cDiv = elParent.children;
for (var i = 0; i < cDiv.length; i++) {
if (cDiv[i].tagName == "DIV") { //or use toUpperCase()
cDiv[i].style.height = '100%';
cDiv[i].style.position = 'absolute';
cDiv[i].style.width = '100%';
cDiv[i].style.border = '#afc5d6';
cDiv[i].style.backgroundSize = 'contain';
cDiv[i].style.backgroundImage = 'url(./styles/LogoClassic_NoText.png)'
}
}
elChild1.style.transform = 'translateZ(-35.2px) rotateY(180deg)';
elChild2.style.transform = 'rotateY(-270deg) translateX(50%)';
elChild2.style.transformOrigin = 'top right';
elChild3.style.transform = 'rotateY(270deg) translateX(-50%)';
elChild3.style.transformOrigin = 'center left';
elChild4.style.transform = 'rotateX(90deg) translateY(-50%)';
elChild4.style.transformOrigin = 'top center';
elChild5.style.transform = 'rotateX(-90deg) translateY(50%)';
elChild5.style.transformOrigin = 'bottom center';
elChild6.style.transform = 'translateZ(35.2px)';
}
function init3mf() {
const manager = new THREE.LoadingManager();
const loader = new ThreeMFLoader(manager);
let startTime = performance.now();
return new Promise(() => {
setTimeout(() => {
loader.load('./models/3mf/' + fName, function (object) {
object.rotation.set(-Math.PI / 2, 0, 0);
object.traverse(function (child) {
child.castShadow = true;
});
for (var i = 0; i < object.children.length; ++i) {
var child = object.children[i];
child.rotation.set(-Math.PI / 2, 0, 0);
layer_list.push(child);
}
//console.log(layer_list);
AdaptSeceneToContest();
// Adapting Scene to contest
let endTime = performance.now();
let timeElapsed = endTime - startTime;
console.log('init3mf in : ' + timeElapsed)
});
}, 0);
});
}
function init3dm(){
return new Promise(() => {
setTimeout(() => {
loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/rhino3dm@7.15.0/' ) ;
loader.load( './models/3dm/Ex' + FileNumber + '.3dm', m_nApproxIndex, function ( object ) {
object.traverse( function( child) {
child.castShadow = true ;
}) ;
// Ref systems
const Mat_GlobToLoc = new THREE.Matrix4() ; //<---- rotations for XY plane from Extrusion
const Mat_LocToGlob = new THREE.Matrix4() ; //<---- rotations for Extrusion from XY plane
const Mat_ThreeJs_Frame = new THREE.Matrix4() ; // <----- rotations from XYZ ref system to ThreeJS system
Mat_ThreeJs_Frame.set( 1, 0, 0, 0,
0, 0, 1, 0,
0, -1, 0, 0,
0, 0, 0, 1) ;
var Mat_ToScene = new THREE.Matrix4() ;
// Extrusion settings for curves
const extrudeSettings = {
steps: 1,
depth: 0,
bevelEnabled: false,
bevelThickness: 1,
bevelSize: 1,
bevelOffset: 0,
bevelSegments: 1
} ;
// loading entities...
for ( var i = 0 ; i < object.children.length ; ++ i) {
// getting i-th object
var child = object.children[i] ;
//console.log( child);
// READING A POINT TYPE -----------------------------------------------------------------
if ( child.type == 'Points') {
try {
if ( child.name != 'Orig') {
console.log( 'Not a valid origin') ;
return false ;
}
// start layer
nStartLayer = parseInt( child.userData.attributes.layerIndex) ;
// ORIGIN ------------------------
var coord = child.userData.attributes.geometry.location ;
var orig_x = parseFloat( coord[0]) ;
var orig_y = parseFloat( coord[2]) ;
var orig_z = - parseFloat( coord[1]) ;
ORIG = new THREE.Vector3( orig_x, orig_y, orig_z) ;
// EXTRUSION ---------------------
var bOk_ext = false ;
if ( child.userData.attributes.userStrings[1][0] == 'SlicingDir') {
var sExtr = child.userData.attributes.userStrings[1][1] ;
if ( sExtr != "" ) {
let sExtr_arr = sExtr.split(',') ;
if ( sExtr_arr.length == 3) {
var dExtr_x = parseFloat( sExtr_arr[0]) ;
var dExtr_y = parseFloat( sExtr_arr[1]) ;
var dExtr_z = parseFloat( sExtr_arr[2]) ;
vtExtr = new THREE.Vector3( dExtr_x, dExtr_y, dExtr_z) ;
bOk_ext = true ;
}
}
}
if ( ! bOk_ext) {
console.log( ' Not a valid Extrusion') ;
return false ;
}
var Z_AX = new THREE.Vector3( vtExtr.x, vtExtr.y, vtExtr.z) ;
var X_AX = new THREE.Vector3() ;
var Y_AX = new THREE.Vector3() ;
if ( ! Z_AX.equals( new THREE.Vector3( 0, 0, 1))) {
X_AX.crossVectors( new THREE.Vector3( 0, 0, 1), Z_AX) ;
Y_AX.crossVectors( Z_AX, X_AX) ;
}
else {
X_AX = new THREE.Vector3( 1, 0, 0) ;
Y_AX = new THREE.Vector3( 0, 1, 0) ;
}
Mat_GlobToLoc.set( X_AX.x, X_AX.y, X_AX.z, 0,
Y_AX.x, Y_AX.y, Y_AX.z, 0,
Z_AX.x, Z_AX.y, Z_AX.z, 0,
0, 0, 0, 1) ;
Mat_LocToGlob.copy( Mat_GlobToLoc) ;
Mat_LocToGlob.invert() ;
Mat_ToScene.multiplyMatrices( Mat_ThreeJs_Frame, Mat_LocToGlob) ;
// STRAND -------------------------
if ( child.userData.attributes.userStrings[0][0] == 'StrandH') {
dStrand = - parseFloat( child.userData.attributes.userStrings[0][1]) ;
extrudeSettings.depth = dStrand ;
}
else {
console.log( ' Not a valid Strand') ;
return false ;
}
}
catch( error) {
console.log( 'Orig, Extrusion or Strand missing or not implemented') ;
return false ;
}
}
// READING A LINE -----------------------------------------------------------------------
else if ( child.type == 'Line') {
// Parsing the extrusion and the Layer of the curve
try {
var nLayer = parseInt( child.userData.attributes.layerIndex) - nStartLayer ;
if ( nLayer < 0)
return false ;
var points_array = child.geometry.attributes.position.array ;
//var ptPrec ;
const shape = new THREE.Shape() ;
for ( var v = 0 ; v < points_array.length ; v += 3) {
var Zact ;
var vtCoord = new THREE.Vector4( points_array[v], points_array[v+1], points_array[v+2], 1) ;
vtCoord.applyMatrix4( Mat_GlobToLoc) ;
//if ( v != 0 && v < points_array.length - 3 &&
// (( vtCoord.x - ptPrec.x) * ( vtCoord.x - ptPrec.x) +
// ( vtCoord.y - ptPrec.y) * ( vtCoord.y - ptPrec.y) +
// ( vtCoord.z - ptPrec.z) * ( vtCoord.z - ptPrec.z)) < 10)
// continue ;
if ( v == 0) {
shape.moveTo( vtCoord.x, vtCoord.y) ;
Zact = vtCoord.z ;
}
else
shape.lineTo( vtCoord.x, vtCoord.y) ;
//ptPrec = new THREE.Vector4( vtCoord.x, vtCoord.y, vtCoord.z, 1) ;
}
var cCol = child.material.color.clone() ;
if ( nLayer%2 == 0) {
cCol.lerp( new THREE.Color( 0x000000 ), 0.25) ;
}
const geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings) ;
const material = new THREE.MeshLambertMaterial({ color: cCol,
wireframe : false,
shadowSide : THREE.DoubleSide}) ;
const mesh = new THREE.Mesh( geometry, material) ;
mesh.translateZ( Zact) ;
//mesh.applyMatrix4( Mat_LocToGlob) ;
//mesh.applyMatrix4( Mat_ThreeJs_Frame) ;
mesh.applyMatrix4( Mat_ToScene) ;
mesh.nLayer = nLayer ;
mesh.isArrow = false ;
layer_list.push( mesh) ;
} catch( err) {
console.log( ' Not a valid Layer for paths') ;
return false ;
}
}
// READING ARROW'S MESH
else if ( child.type == 'Mesh') {
try {
if ( child.name != 'Arrow') {
//console.log( 'Not a valid Arrow direction') ;
//return false ;
child.nLayer = 1 ;
layer_list.push( child) ;
continue ;
}
var nLayer = parseInt( child.userData.attributes.layerIndex) - nStartLayer ;
if ( nLayer < 0)
return false ;
child.isArrow = true ;
child.applyMatrix4( Mat_ThreeJs_Frame) ;
child.nLayer = nLayer ;
child.material.color = new THREE.Color( 0xff0000) ;
layer_list.push( child) ;
} catch( e) {
console.log( 'Not a valid Arrow direction') ;
return false ;
}
}
// READING OTHER ENTITY --------------------
else
continue ;
}
AdaptSeceneToContest() ;
console.log(new Date()) ;
}) ;
}, 0)
})
}
function refreshElement(nStart, nEnd) {
//console.log(parseInt(nStart));
for (var i = 0; i < layer_list.length; ++i) {
if (parseInt(layer_list[i].children[0].nLayer) >= parseInt(nStart) &&
parseInt(layer_list[i].children[0].nLayer) <= parseInt(nEnd)) {
layer_list[i].visible = true;
}
else {
layer_list[i].visible = false;
}
}
render();
}
// Utility functions
function onWindowResize() {
}
function render() {
renderer.render(scene, activeCamera);
}
function setCameraZoom(bZoom) {
controls.enableZoom = bZoom;
}
function setCameraPan(bPan) {
controls.enablePan = bPan;
}
function setCameraRot(bRot) {
controls.enableRotate = bRot;
}
function setCameraAutoRot(bAutoRot) {
controls.autoRotate = bAutoRot;
}
function SetCameraPos( nPos, ORIG) {
var nTraslFactor = 3.5 ;
var x ; var y ; var z ;
y = GLBox3D.max.y ; // fixed
switch( nPos) {
case 0 :
x = GLBox3D.min.x ;
z = 0.5 * ( GLBox3D.min.z + GLBox3D.max.z) ;
break ;
case 1 :
x = GLBox3D.min.x ;
z = GLBox3D.max.z ;
break ;
case 2 :
x = 0.5 * ( GLBox3D.min.x + GLBox3D.max.x) ;
z = GLBox3D.max.z ;
break ;
case 3 :
x = GLBox3D.max.x ;
z = GLBox3D.max.z ;
break ;
case 4 :
x = GLBox3D.max.x ;
z = 0.5 * ( GLBox3D.min.z + GLBox3D.max.z) ;
break ;
case 5 :
x = GLBox3D.max.x ;
z = GLBox3D.min.z ;
break ;
case 6 :
x = 0.5 * ( GLBox3D.min.x + GLBox3D.max.x) ;
z = GLBox3D.min.z ;
break ;
case 7 :
x = GLBox3D.min.x ;
z = GLBox3D.min.z ;
break ;
case 8 : // optimal
x = ( ORIG.position.x + 1.0 * Math.abs( GLBox3D.max.x - GLBox3D.min.x)) ;
z = ( ORIG.position.z + 1.0 * Math.abs( GLBox3D.max.z - GLBox3D.min.z)) ;
break ;
default :
return ;
}
var vtPos = new THREE.Vector3( x, y, z) ;
const vtCenter = new THREE.Vector3( 0, 0, 0) ; GLBox3D.getCenter( vtCenter) ;
var vtDirOut = new THREE.Vector3( vtPos.x - vtCenter.x, vtPos.y - vtCenter.y, vtPos.z - vtCenter.z) ;
vtDirOut.x *= nTraslFactor ; vtDirOut.y *= nTraslFactor ; vtDirOut.z *= nTraslFactor ;
//vtDirOut *= nTraslFactor ;
//x *= nTraslFactor ;
//y *= nTraslFactor ;
//z *= nTraslFactor ;
activeCamera.position.set( x + vtDirOut.x, y + vtDirOut.y, z + vtDirOut.z) ;
controls.target.set( vtCenter.x, vtCenter.y, vtCenter.z) ;
console.log( controls) ;
controls.update() ;
}
function SetOrig( ORIG) {
// qui in qualche modo imposto l'origine, ora impostata secondo il BozHelper
// ---- codice da cambiare
var posX = GLBox3D.min.x - 0.3 * ( GLBox3D.max.x - GLBox3D.min.x) ;
var posY = 0 ;
var posZ = GLBox3D.min.z + 1.3 * ( GLBox3D.max.z - GLBox3D.min.z) ;
//ORIG.geometry.translate( posX, posY, posZ) ;
ORIG.position.set( posX, posY, posZ) ;
// -----------------------
//scene.add( ORIG) ;
}
function setFog() {
// var dNear = GLBox3D.max.x + 3 * ( GLBox3D.max.x - GLBox3D.min.x) ;
// var dFar = 10000 ;
// scene.fog = new THREE.Fog( 0xa0a0a0, 20000, 30000);
}
function AddFrame( ptORIG) {
if ( ! m_bShowFrame)
return ;
if ( m_bFrameType == 0) {
const axesHelper = new THREE.AxesHelper( m_lFrameLen) ;
axesHelper.rotation.set( -Math.PI/2, 0 , 0) ;
axesHelper.position.set( ptORIG.position.x, ptORIG.position.y, ptORIG.position.z) ;
scene.add( axesHelper ) ;
}
else if ( m_bFrameType == 1) {
var vtDirs = [ new THREE.Vector3( 1, 0, 0), new THREE.Vector3( 0, 0, -1), new THREE.Vector3( 0, 1, 0)] ;
var vtCols = [ new THREE.Color( 0xff0000), new THREE.Color( 0x00ff00), new THREE.Color( 0x0000ff)] ;
var vtORIG = new THREE.Vector3( ptORIG.position.x, ptORIG.position.y, ptORIG.position.z) ;
for ( var i = 0 ; i < 3 ; ++ i) {
const arrowHelper = new THREE.ArrowHelper( vtDirs[i], vtORIG, m_lFrameLen, vtCols[i]) ;
scene.add( arrowHelper ) ;
}
}
else if ( m_bFrameType == 2) {
var vtCols = [ new THREE.Color( 0x0000ff), new THREE.Color( 0xff0000), new THREE.Color( 0x00ff00)] ;
for ( var i = 0 ; i < 3 ; ++ i) {
// cylinder ----
const fr_geometry_cyl = new THREE.CylinderGeometry( m_dFrameFat, m_dFrameFat, 0.8 * m_lFrameLen, 32) ;
const fr_material = new THREE.MeshBasicMaterial({color: vtCols[i]}) ;
const fr_cylinder = new THREE.Mesh( fr_geometry_cyl, fr_material) ;
fr_cylinder.position.set( ptORIG.position.x, ptORIG.position.y, ptORIG.position.z) ;
if ( i == 1)
fr_cylinder.rotation.set( 0, 0, -Math.PI/2) ;
if ( i == 2)
fr_cylinder.rotation.set( -Math.PI/2, 0, 0) ;
scene.add( fr_cylinder) ;
fr_cylinder.translateY( 0.4 * m_lFrameLen) ;
// pyramid
const fr_geometry_cone = new THREE.CylinderGeometry( 0, 2 * m_dFrameFat, 0.2 * m_lFrameLen, 32) ;
const fr_cone = new THREE.Mesh( fr_geometry_cone, fr_material) ;
fr_cone.position.set( ptORIG.position.x, ptORIG.position.y, ptORIG.position.z) ;
if ( i == 1)
fr_cone.rotation.set( 0, 0, -Math.PI/2) ;
if ( i == 2)
fr_cone.rotation.set( -Math.PI/2, 0, 0) ;
scene.add( fr_cone) ;
fr_cone.translateY( 0.9 * m_lFrameLen) ;
}
// Origin
const fr_orig_geometry = new THREE.SphereGeometry( 2 * m_dFrameFat, 32, 16) ;
const fr_orig_material = new THREE.MeshBasicMaterial( {color: 0x00000}) ;
const fr_sphere = new THREE.Mesh( fr_orig_geometry, fr_orig_material) ;
fr_sphere.position.set( ptORIG.position.x, ptORIG.position.y, ptORIG.position.z) ;
scene.add( fr_sphere) ;
}
else
console.log( 'Frame type not defined') ;
}
function AddGrid( ptORIG) {
if ( ! m_bShowGrid)
return ;
const size = 1000000 ;
const divisions = 10000 ;
if ( m_bInfGrid) {
const gridHelper = new THREE.GridHelper( size, divisions) ;
gridHelper.position.set( ptORIG.position.x, ptORIG.position.y, ptORIG.position.z) ;
gridHelper.material.transparent = true ;
gridHelper.material.opacity = 0.25 ;
setFog() ;
scene.add( gridHelper) ;
}
else {
var dDimX = Math.abs( GLBox3D.max.x - GLBox3D.min.x) ;
var dDimY = Math.abs( GLBox3D.max.y - GLBox3D.min.y) ;
var dDimZ = Math.abs( GLBox3D.max.z - GLBox3D.min.z) ;
var dDim = 1.5 * Math.sqrt( dDimX * dDimX + dDimY * dDimY + dDimZ * dDimZ) ;
const gridHelper = new THREE.GridHelper( dDim, Math.ceil( 0.1 * dDim)) ;
gridHelper.position.set( ptORIG.position.x + 0.5 * dDim , ptORIG.position.y, ptORIG.position.z - 0.5 * dDim) ;
gridHelper.material.transparent = true ;
gridHelper.material.opacity = 0.45 ;
scene.add( gridHelper) ;
}
}
function ManageSceneElements( e) {
if ( e.srcElement.id == 'bt_refresh') {
nLayerStart = parseInt( document.getElementById('Layer_Start').value) ;
nLayerEnd = parseInt( document.getElementById('Layer_End').value) ;
for ( var i = 0 ; i < layer_list.length ; ++ i) {
if ( parseInt( layer_list[i].nLayer) >= nLayerStart &&
parseInt( layer_list[i].nLayer) <= nLayerEnd) {
if ( layer_list[i].isArrow)
layer_list[i].visible = document.getElementById( 'ck_dir').checked ;
else
layer_list[i].visible = true ;
}
else {
layer_list[i].visible = false ;
}
}
}
else if ( e.srcElement.id = 'ck_dir') {
for ( var i = 0 ; i < layer_list.length ; ++ i) {
if ( layer_list[i].isArrow) {
if ( layer_list[i].nLayer >= nLayerStart &&
layer_list[i].nLayer <= nLayerEnd)
layer_list[i].visible = document.getElementById( 'ck_dir').checked ;
else
layer_list[i].visible = false ;
}
}
}
render() ;
}