made 3d work again

This commit is contained in:
alpcentaur 2024-11-06 20:42:29 +01:00
parent 87aa33a0cc
commit 2977ed43c2
8 changed files with 1384 additions and 1439 deletions

View file

@ -0,0 +1,5 @@
{
"m.homeserver": {
"base_url": "https://matrix.kaoscube.org"
}
}

7
3d.php
View file

@ -74,15 +74,16 @@
<div style="height: 5vh; background-color:deeppink;"></div>
<div class="model0" id="model0" style="width: 80vw; height: 80vh; justify-self: center; background-color: white;"> </div>
</div>
</center>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/loaders/STLLoader.js"></script>
<script src="three.min.js"></script>
<script src="OrbitControls.js"></script>
<script src="STLLoader.js"></script>
<script type="text/javascript">

File diff suppressed because one or more lines are too long

View file

@ -1,389 +1,371 @@
/**
* @author aleeper / http://adamleeper.com/
* @author mrdoob / http://mrdoob.com/
* @author gero3 / https://github.com/gero3
*
( function () {
/**
* Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
*
* Supports both binary and ASCII encoded files, with automatic detection of type.
*
* The loader returns a non-indexed buffer geometry.
*
* Limitations:
* Binary decoding ignores header. There doesn't seem to be much of a use for it.
* There is perhaps some question as to how valid it is to always assume little-endian-ness.
* ASCII decoding assumes file is UTF-8. Seems to work for the examples...
* Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
* There is perhaps some question as to how valid it is to always assume little-endian-ness.
* ASCII decoding assumes file is UTF-8.
*
* Usage:
* var loader = new THREE.STLLoader();
* loader.addEventListener( 'load', function ( event ) {
* const loader = new STLLoader();
* loader.load( './models/stl/slotted_disk.stl', function ( geometry ) {
* scene.add( new THREE.Mesh( geometry ) );
* });
*
* var geometry = event.content;
* scene.add( new THREE.Mesh( geometry ) );
* For binary STLs geometry might contain colors for vertices. To use it:
* // use the same code to load STL as above
* if (geometry.hasColors) {
* material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: true });
* } else { .... }
* const mesh = new THREE.Mesh( geometry, material );
*
* } );
* loader.load( './models/stl/slotted_disk.stl' );
* For ASCII STLs containing multiple solids, each solid is assigned to a different group.
* Groups can be used to assign a different color by defining an array of materials with the same length of
* geometry.groups and passing it to the Mesh constructor:
*
* const mesh = new THREE.Mesh( geometry, material );
*
* For example:
*
* const materials = [];
* const nGeometryGroups = geometry.groups.length;
*
* const colorMap = ...; // Some logic to index colors.
*
* for (let i = 0; i < nGeometryGroups; i++) {
*
* const material = new THREE.MeshPhongMaterial({
* color: colorMap[i],
* wireframe: false
* });
*
* }
*
* materials.push(material);
* const mesh = new THREE.Mesh(geometry, materials);
*/
class STLLoader extends THREE.Loader {
THREE.STLLoader = function () {};
constructor( manager ) {
THREE.STLLoader.prototype = {
super( manager );
constructor: THREE.STLLoader,
}
addEventListener: THREE.EventDispatcher.prototype.addEventListener,
hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
load( url, onLoad, onProgress, onError ) {
};
const scope = this;
const loader = new THREE.FileLoader( this.manager );
loader.setPath( this.path );
loader.setResponseType( 'arraybuffer' );
loader.setRequestHeader( this.requestHeader );
loader.setWithCredentials( this.withCredentials );
loader.load( url, function ( text ) {
THREE.STLLoader.prototype.load = function (url, callback) {
try {
var scope = this;
onLoad( scope.parse( text ) );
var xhr = new XMLHttpRequest();
} catch ( e ) {
function onloaded( event ) {
if ( onError ) {
if ( event.target.status === 200 || event.target.status === 0 ) {
onError( e );
var geometry = scope.parse( event.target.response || event.target.responseText );
} else {
scope.dispatchEvent( { type: 'load', content: geometry } );
console.error( e );
if ( callback ) callback( geometry );
}
} else {
scope.manager.itemError( url );
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']',
response: event.target.responseText } );
}
}
}, onProgress, onError );
}
}
xhr.addEventListener( 'load', onloaded, false );
parse( data ) {
xhr.addEventListener( 'progress', function ( event ) {
function isBinary( data ) {
scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
const reader = new DataView( data );
const face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8;
const n_faces = reader.getUint32( 80, true );
const expect = 80 + 32 / 8 + n_faces * face_size;
}, false );
if ( expect === reader.byteLength ) {
xhr.addEventListener( 'error', function () {
return true;
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
} // An ASCII STL data must begin with 'solid ' as the first six bytes.
// However, ASCII STLs lacking the SPACE after the 'd' are known to be
// plentiful. So, check the first 5 bytes for 'solid'.
// Several encodings, such as UTF-8, precede the text with up to 5 bytes:
// https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
// Search for "solid" to start anywhere after those prefixes.
// US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd'
}, false );
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.open( 'GET', url, true );
xhr.responseType = "arraybuffer";
xhr.send( null );
const solid = [ 115, 111, 108, 105, 100 ];
};
for ( let off = 0; off < 5; off ++ ) {
THREE.STLLoader.prototype.parse = function (data) {
// If "solid" text is matched to the current offset, declare it to be an ASCII STL.
if ( matchDataViewAt( solid, reader, off ) ) return false;
} // Couldn't find "solid" text at the beginning; it is binary STL.
var isBinary = function () {
var expect, face_size, n_faces, reader;
reader = new DataView( binData );
face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
n_faces = reader.getUint32(80,true);
expect = 80 + (32 / 8) + (n_faces * face_size);
return expect === reader.byteLength;
return true;
};
}
var binData = this.ensureBinary( data );
function matchDataViewAt( query, reader, offset ) {
return isBinary()
? this.parseBinary( binData )
: this.parseASCII( this.ensureString( data ) );
// Check if each byte in query matches the corresponding byte from the current offset
for ( let i = 0, il = query.length; i < il; i ++ ) {
};
if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
THREE.STLLoader.prototype.parseBinary = function (data) {
}
var face, geometry, n_faces, reader, length, normal, i, dataOffset, faceLength, start, vertexstart;
return true;
reader = new DataView( data );
n_faces = reader.getUint32(80,true);
geometry = new THREE.Geometry();
dataOffset = 84;
faceLength = 12 * 4 + 2;
}
for (face = 0; face < n_faces; face++) {
function parseBinary( data ) {
start = dataOffset + face * faceLength;
normal = new THREE.Vector3(
reader.getFloat32(start,true),
reader.getFloat32(start + 4,true),
reader.getFloat32(start + 8,true)
);
const reader = new DataView( data );
const faces = reader.getUint32( 80, true );
let r,
g,
b,
hasColors = false,
colors;
let defaultR, defaultG, defaultB, alpha; // process STL header
// check for default color in header ("COLOR=rgba" sequence).
for (i = 1; i <= 3; i++) {
for ( let index = 0; index < 80 - 10; index ++ ) {
vertexstart = start + i * 12;
geometry.vertices.push(
new THREE.Vector3(
reader.getFloat32(vertexstart,true),
reader.getFloat32(vertexstart +4,true),
reader.getFloat32(vertexstart + 8,true)
)
);
if ( reader.getUint32( index, false ) == 0x434F4C4F
/*COLO*/
&& reader.getUint8( index + 4 ) == 0x52
/*'R'*/
&& reader.getUint8( index + 5 ) == 0x3D
/*'='*/
) {
}
hasColors = true;
colors = new Float32Array( faces * 3 * 3 );
defaultR = reader.getUint8( index + 6 ) / 255;
defaultG = reader.getUint8( index + 7 ) / 255;
defaultB = reader.getUint8( index + 8 ) / 255;
alpha = reader.getUint8( index + 9 ) / 255;
length = geometry.vertices.length;
geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
}
}
}
//geometry.computeCentroids();
geometry.computeBoundingSphere();
const dataOffset = 84;
const faceLength = 12 * 4 + 2;
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array( faces * 3 * 3 );
const normals = new Float32Array( faces * 3 * 3 );
return geometry;
for ( let face = 0; face < faces; face ++ ) {
};
const start = dataOffset + face * faceLength;
const normalX = reader.getFloat32( start, true );
const normalY = reader.getFloat32( start + 4, true );
const normalZ = reader.getFloat32( start + 8, true );
THREE.STLLoader.prototype.parseASCII = function (data) {
if ( hasColors ) {
var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
geometry = new THREE.Geometry();
patternFace = /facet([\s\S]*?)endfacet/g;
const packedColor = reader.getUint16( start + 48, true );
while (((result = patternFace.exec(data)) != null)) {
if ( ( packedColor & 0x8000 ) === 0 ) {
text = result[0];
patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
// facet has its own unique color
r = ( packedColor & 0x1F ) / 31;
g = ( packedColor >> 5 & 0x1F ) / 31;
b = ( packedColor >> 10 & 0x1F ) / 31;
while (((result = patternNormal.exec(text)) != null)) {
} else {
normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
r = defaultR;
g = defaultG;
b = defaultB;
}
}
patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
}
while (((result = patternVertex.exec(text)) != null)) {
for ( let i = 1; i <= 3; i ++ ) {
geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
const vertexstart = start + i * 12;
const componentIdx = face * 3 * 3 + ( i - 1 ) * 3;
vertices[ componentIdx ] = reader.getFloat32( vertexstart, true );
vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true );
vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true );
normals[ componentIdx ] = normalX;
normals[ componentIdx + 1 ] = normalY;
normals[ componentIdx + 2 ] = normalZ;
}
if ( hasColors ) {
length = geometry.vertices.length;
geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
colors[ componentIdx ] = r;
colors[ componentIdx + 1 ] = g;
colors[ componentIdx + 2 ] = b;
}
}
geometry.computeCentroids();
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
}
return geometry;
}
};
geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
THREE.STLLoader.prototype.ensureString = function (buf) {
if ( hasColors ) {
if (typeof buf !== "string"){
var array_buffer = new Uint8Array(buf);
var str = '';
for(var i = 0; i < buf.byteLength; i++) {
str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
}
return str;
} else {
return buf;
}
geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.hasColors = true;
geometry.alpha = alpha;
};
}
THREE.STLLoader.prototype.ensureBinary = function (buf) {
return geometry;
if (typeof buf === "string"){
var array_buffer = new Uint8Array(buf.length);
for(var i = 0; i < buf.length; i++) {
array_buffer[i] = buf.charCodeAt(i) & 0xff; // implicitly assumes little-endian
}
return array_buffer.buffer || array_buffer;
} else {
return buf;
}
}
};
function parseASCII( data ) {
if ( typeof DataView === 'undefined'){
const geometry = new THREE.BufferGeometry();
const patternSolid = /solid([\s\S]*?)endsolid/g;
const patternFace = /facet([\s\S]*?)endfacet/g;
let faceCounter = 0;
const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
const patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' );
const patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' );
const vertices = [];
const normals = [];
const normal = new THREE.Vector3();
let result;
let groupCount = 0;
let startVertex = 0;
let endVertex = 0;
DataView = function(buffer, byteOffset, byteLength){
while ( ( result = patternSolid.exec( data ) ) !== null ) {
this.buffer = buffer;
this.byteOffset = byteOffset || 0;
this.byteLength = byteLength || buffer.byteLength || buffer.length;
this._isString = typeof buffer === "string";
startVertex = endVertex;
const solid = result[ 0 ];
}
while ( ( result = patternFace.exec( solid ) ) !== null ) {
DataView.prototype = {
let vertexCountPerFace = 0;
let normalCountPerFace = 0;
const text = result[ 0 ];
_getCharCodes:function(buffer,start,length){
start = start || 0;
length = length || buffer.length;
var end = start + length;
var codes = [];
for (var i = start; i < end; i++) {
codes.push(buffer.charCodeAt(i) & 0xff);
}
return codes;
},
while ( ( result = patternNormal.exec( text ) ) !== null ) {
_getBytes: function (length, byteOffset, littleEndian) {
normal.x = parseFloat( result[ 1 ] );
normal.y = parseFloat( result[ 2 ] );
normal.z = parseFloat( result[ 3 ] );
normalCountPerFace ++;
var result;
}
// Handle the lack of endianness
if (littleEndian === undefined) {
while ( ( result = patternVertex.exec( text ) ) !== null ) {
littleEndian = this._littleEndian;
vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
normals.push( normal.x, normal.y, normal.z );
vertexCountPerFace ++;
endVertex ++;
}
} // every face have to own ONE valid normal
// Handle the lack of byteOffset
if (byteOffset === undefined) {
byteOffset = this.byteOffset;
if ( normalCountPerFace !== 1 ) {
} else {
console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
byteOffset = this.byteOffset + byteOffset;
} // each face have to own THREE valid vertices
}
if (length === undefined) {
if ( vertexCountPerFace !== 3 ) {
length = this.byteLength - byteOffset;
console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
}
}
// Error Checking
if (typeof byteOffset !== 'number') {
faceCounter ++;
throw new TypeError('DataView byteOffset is not a number');
}
}
const start = startVertex;
const count = endVertex - startVertex;
geometry.addGroup( start, count, groupCount );
groupCount ++;
if (length < 0 || byteOffset + length > this.byteLength) {
}
throw new Error('DataView length or (byteOffset+length) value is out of bounds');
geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
return geometry;
}
}
if (this.isString){
function ensureString( buffer ) {
result = this._getCharCodes(this.buffer, byteOffset, byteOffset + length);
if ( typeof buffer !== 'string' ) {
} else {
return THREE.LoaderUtils.decodeText( new Uint8Array( buffer ) );
result = this.buffer.slice(byteOffset, byteOffset + length);
}
}
return buffer;
if (!littleEndian && length > 1) {
}
if (!(result instanceof Array)) {
function ensureBinary( buffer ) {
result = Array.prototype.slice.call(result);
if ( typeof buffer === 'string' ) {
}
const array_buffer = new Uint8Array( buffer.length );
result.reverse();
}
for ( let i = 0; i < buffer.length; i ++ ) {
return result;
array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
},
}
// Compatibility functions on a String Buffer
return array_buffer.buffer || array_buffer;
getFloat64: function (byteOffset, littleEndian) {
} else {
var b = this._getBytes(8, byteOffset, littleEndian),
return buffer;
sign = 1 - (2 * (b[7] >> 7)),
exponent = ((((b[7] << 1) & 0xff) << 3) | (b[6] >> 4)) - ((1 << 10) - 1),
}
// Binary operators such as | and << operate on 32 bit values, using + and Math.pow(2) instead
mantissa = ((b[6] & 0x0f) * Math.pow(2, 48)) + (b[5] * Math.pow(2, 40)) + (b[4] * Math.pow(2, 32)) +
(b[3] * Math.pow(2, 24)) + (b[2] * Math.pow(2, 16)) + (b[1] * Math.pow(2, 8)) + b[0];
} // start
if (exponent === 1024) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
if (exponent === -1023) { // Denormalized
return sign * mantissa * Math.pow(2, -1022 - 52);
}
const binData = ensureBinary( data );
return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
return sign * (1 + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent);
}
},
}
getFloat32: function (byteOffset, littleEndian) {
THREE.STLLoader = STLLoader;
var b = this._getBytes(4, byteOffset, littleEndian),
sign = 1 - (2 * (b[3] >> 7)),
exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127,
mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0];
if (exponent === 128) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
if (exponent === -127) { // Denormalized
return sign * mantissa * Math.pow(2, -126 - 23);
}
return sign * (1 + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent);
},
getInt32: function (byteOffset, littleEndian) {
var b = this._getBytes(4, byteOffset, littleEndian);
return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
},
getUint32: function (byteOffset, littleEndian) {
return this.getInt32(byteOffset, littleEndian) >>> 0;
},
getInt16: function (byteOffset, littleEndian) {
return (this.getUint16(byteOffset, littleEndian) << 16) >> 16;
},
getUint16: function (byteOffset, littleEndian) {
var b = this._getBytes(2, byteOffset, littleEndian);
return (b[1] << 8) | b[0];
},
getInt8: function (byteOffset) {
return (this.getUint8(byteOffset) << 24) >> 24;
},
getUint8: function (byteOffset) {
return this._getBytes(1, byteOffset)[0];
}
};
}
} )();

6
nano Normal file

File diff suppressed because one or more lines are too long

75
stl-viewer.js Normal file
View file

@ -0,0 +1,75 @@
import './three.min.js';
import './STLLoader.js';
import './OrbitControls.js';
class STLViewer extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.connected = true;
const shadowRoot = this.attachShadow({ mode: 'open' });
const container = document.createElement('div');
container.style.width = '100%';
container.style.height = '100%';
shadowRoot.appendChild(container);
if (!this.hasAttribute('model')) {
throw new Error('model attribute is required');
}
const model = this.getAttribute('model');
let camera = new THREE.PerspectiveCamera(70, container.clientWidth / container.clientHeight, 1, 1000);
let renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);
window.addEventListener('resize', function () {
renderer.setSize(container.clientWidth, container.clientHeight);
camera.aspect = container.clientWidth / container.clientHeight;
camera.updateProjectionMatrix();
}, false);
let controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableZoom = true;
let scene = new THREE.Scene();
scene.add(new THREE.HemisphereLight(0xffffff, 1.5));
new THREE.STLLoader().load(model, (geometry) => {
let material = new THREE.MeshPhongMaterial({
color: 0x6A39FF,
specular: 100,
shininess: 100,
});
let mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
let middle = new THREE.Vector3();
geometry.computeBoundingBox();
geometry.boundingBox.getCenter(middle);
mesh.geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(-middle.x, -middle.y, -middle.z));
let largestDimension = Math.max(geometry.boundingBox.max.x, geometry.boundingBox.max.y, geometry.boundingBox.max.z)
camera.position.z = largestDimension * 1.5;
controls.autoRotate = true;
controls.autoRotateSpeed = 1;
let animate = () => {
controls.update();
renderer.render(scene, camera);
if (this.connected) {
requestAnimationFrame(animate);
}
};
animate();
});
}
disconnectedCallback() {
this.connected = false;
}
}
customElements.define('stl-viewer', STLViewer);

6
three.min.js vendored Normal file

File diff suppressed because one or more lines are too long