Browse Source

made 3d work again

master
alpcentaur 2 weeks ago
parent
commit
2977ed43c2
8 changed files with 1384 additions and 1439 deletions
  1. +5
    -0
      .well-known/matrix/client
  2. +4
    -3
      3d.php
  3. +1045
    -1175
      OrbitControls.js
  4. +243
    -261
      STLLoader.js
  5. +6
    -0
      nano
  6. BIN
      stl-files/KaosCubeTopThick2mm_cut_joints_withCannaOnTop.stl
  7. +75
    -0
      stl-viewer.js
  8. +6
    -0
      three.min.js

+ 5
- 0
.well-known/matrix/client View File

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

+ 4
- 3
3d.php View File

@ -74,15 +74,16 @@
<div style="height: 5vh; background-color:deeppink;"></div> <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 class="model0" id="model0" style="width: 80vw; height: 80vh; justify-self: center; background-color: white;"> </div>
</div> </div>
</center> </center>
</body> </body>
</html> </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"> <script type="text/javascript">

+ 1045
- 1175
OrbitControls.js
File diff suppressed because it is too large
View File


+ 243
- 261
STLLoader.js 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. * 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. * Supports both binary and ASCII encoded files, with automatic detection of type.
* *
* The loader returns a non-indexed buffer geometry.
*
* Limitations: * 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: * 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 ) );
* });
*
* 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 );
*
* 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 );
* *
* var geometry = event.content;
* scene.add( new THREE.Mesh( geometry ) );
* For example:
* *
* } );
* loader.load( './models/stl/slotted_disk.stl' );
* 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 () {};
THREE.STLLoader.prototype = {
constructor: THREE.STLLoader,
addEventListener: THREE.EventDispatcher.prototype.addEventListener,
hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
};
THREE.STLLoader.prototype.load = function (url, callback) {
var scope = this;
var xhr = new XMLHttpRequest();
function onloaded( event ) {
if ( event.target.status === 200 || event.target.status === 0 ) {
var geometry = scope.parse( event.target.response || event.target.responseText );
scope.dispatchEvent( { type: 'load', content: geometry } );
if ( callback ) callback( geometry );
constructor( manager ) {
} else {
super( manager );
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']',
response: event.target.responseText } );
}
}
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 ) {
xhr.addEventListener( 'load', onloaded, false );
try {
xhr.addEventListener( 'progress', function ( event ) {
onLoad( scope.parse( text ) );
scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
} catch ( e ) {
}, false );
if ( onError ) {
xhr.addEventListener( 'error', function () {
onError( e );
scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
} else {
}, false );
console.error( e );
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.open( 'GET', url, true );
xhr.responseType = "arraybuffer";
xhr.send( null );
}
};
scope.manager.itemError( url );
THREE.STLLoader.prototype.parse = function (data) {
}
}, onProgress, onError );
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;
parse( data ) {
};
function isBinary( data ) {
var binData = this.ensureBinary( data );
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;
return isBinary()
? this.parseBinary( binData )
: this.parseASCII( this.ensureString( data ) );
if ( expect === reader.byteLength ) {
};
return true;
THREE.STLLoader.prototype.parseBinary = function (data) {
} // 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'
var face, geometry, n_faces, reader, length, normal, i, dataOffset, faceLength, start, vertexstart;
reader = new DataView( data );
n_faces = reader.getUint32(80,true);
geometry = new THREE.Geometry();
dataOffset = 84;
faceLength = 12 * 4 + 2;
const solid = [ 115, 111, 108, 105, 100 ];
for (face = 0; face < n_faces; face++) {
for ( let off = 0; off < 5; off ++ ) {
start = dataOffset + face * faceLength;
normal = new THREE.Vector3(
reader.getFloat32(start,true),
reader.getFloat32(start + 4,true),
reader.getFloat32(start + 8,true)
);
// If "solid" text is matched to the current offset, declare it to be an ASCII STL.
if ( matchDataViewAt( solid, reader, off ) ) return false;
for (i = 1; i <= 3; i++) {
} // Couldn't find "solid" text at the beginning; it is binary STL.
vertexstart = start + i * 12;
geometry.vertices.push(
new THREE.Vector3(
reader.getFloat32(vertexstart,true),
reader.getFloat32(vertexstart +4,true),
reader.getFloat32(vertexstart + 8,true)
)
);
}
return true;
length = geometry.vertices.length;
geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
}
}
function matchDataViewAt( query, reader, offset ) {
//geometry.computeCentroids();
geometry.computeBoundingSphere();
// Check if each byte in query matches the corresponding byte from the current offset
for ( let i = 0, il = query.length; i < il; i ++ ) {
return geometry;
if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
};
}
THREE.STLLoader.prototype.parseASCII = function (data) {
return true;
var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
geometry = new THREE.Geometry();
patternFace = /facet([\s\S]*?)endfacet/g;
}
while (((result = patternFace.exec(data)) != null)) {
function parseBinary( data ) {
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;
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).
while (((result = patternNormal.exec(text)) != null)) {
for ( let index = 0; index < 80 - 10; index ++ ) {
normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
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;
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)) {
}
geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
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 );
}
for ( let face = 0; face < faces; face ++ ) {
length = geometry.vertices.length;
geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
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 );
}
if ( hasColors ) {
geometry.computeCentroids();
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
const packedColor = reader.getUint16( start + 48, true );
return geometry;
if ( ( packedColor & 0x8000 ) === 0 ) {
};
// facet has its own unique color
r = ( packedColor & 0x1F ) / 31;
g = ( packedColor >> 5 & 0x1F ) / 31;
b = ( packedColor >> 10 & 0x1F ) / 31;
THREE.STLLoader.prototype.ensureString = function (buf) {
} else {
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;
}
r = defaultR;
g = defaultG;
b = defaultB;
};
}
THREE.STLLoader.prototype.ensureBinary = function (buf) {
}
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;
}
for ( let i = 1; i <= 3; i ++ ) {
};
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 ( typeof DataView === 'undefined'){
if ( hasColors ) {
DataView = function(buffer, byteOffset, byteLength){
colors[ componentIdx ] = r;
colors[ componentIdx + 1 ] = g;
colors[ componentIdx + 2 ] = b;
this.buffer = buffer;
this.byteOffset = byteOffset || 0;
this.byteLength = byteLength || buffer.byteLength || buffer.length;
this._isString = typeof buffer === "string";
}
}
}
DataView.prototype = {
}
_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;
},
geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
_getBytes: function (length, byteOffset, littleEndian) {
if ( hasColors ) {
var result;
geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.hasColors = true;
geometry.alpha = alpha;
// Handle the lack of endianness
if (littleEndian === undefined) {
}
littleEndian = this._littleEndian;
return geometry;
}
}
// Handle the lack of byteOffset
if (byteOffset === undefined) {
function parseASCII( data ) {
byteOffset = this.byteOffset;
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;
} else {
while ( ( result = patternSolid.exec( data ) ) !== null ) {
byteOffset = this.byteOffset + byteOffset;
startVertex = endVertex;
const solid = result[ 0 ];
}
while ( ( result = patternFace.exec( solid ) ) !== null ) {
if (length === undefined) {
let vertexCountPerFace = 0;
let normalCountPerFace = 0;
const text = result[ 0 ];
length = this.byteLength - byteOffset;
while ( ( result = patternNormal.exec( text ) ) !== null ) {
}
normal.x = parseFloat( result[ 1 ] );
normal.y = parseFloat( result[ 2 ] );
normal.z = parseFloat( result[ 3 ] );
normalCountPerFace ++;
// Error Checking
if (typeof byteOffset !== 'number') {
}
throw new TypeError('DataView byteOffset is not a number');
while ( ( result = patternVertex.exec( text ) ) !== null ) {
}
vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
normals.push( normal.x, normal.y, normal.z );
vertexCountPerFace ++;
endVertex ++;
if (length < 0 || byteOffset + length > this.byteLength) {
} // every face have to own ONE valid normal
throw new Error('DataView length or (byteOffset+length) value is out of bounds');
}
if ( normalCountPerFace !== 1 ) {
if (this.isString){
console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
result = this._getCharCodes(this.buffer, byteOffset, byteOffset + length);
} // each face have to own THREE valid vertices
} else {
result = this.buffer.slice(byteOffset, byteOffset + length);
if ( vertexCountPerFace !== 3 ) {
}
console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
if (!littleEndian && length > 1) {
}
if (!(result instanceof Array)) {
faceCounter ++;
result = Array.prototype.slice.call(result);
}
}
const start = startVertex;
const count = endVertex - startVertex;
geometry.addGroup( start, count, groupCount );
groupCount ++;
result.reverse();
}
}
return result;
geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
return geometry;
},
}
// Compatibility functions on a String Buffer
function ensureString( buffer ) {
getFloat64: function (byteOffset, littleEndian) {
if ( typeof buffer !== 'string' ) {
var b = this._getBytes(8, byteOffset, littleEndian),
return THREE.LoaderUtils.decodeText( new Uint8Array( 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];
return buffer;
if (exponent === 1024) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
}
if (exponent === -1023) { // Denormalized
return sign * mantissa * Math.pow(2, -1022 - 52);
}
function ensureBinary( buffer ) {
return sign * (1 + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent);
if ( typeof buffer === 'string' ) {
},
const array_buffer = new Uint8Array( buffer.length );
getFloat32: function (byteOffset, littleEndian) {
for ( let i = 0; i < buffer.length; i ++ ) {
var b = this._getBytes(4, byteOffset, littleEndian),
array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
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;
}
}
return array_buffer.buffer || array_buffer;
if (exponent === -127) { // Denormalized
return sign * mantissa * Math.pow(2, -126 - 23);
}
} else {
return sign * (1 + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent);
},
return buffer;
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;
},
} // start
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];
},
const binData = ensureBinary( data );
return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
getInt8: function (byteOffset) {
return (this.getUint8(byteOffset) << 24) >> 24;
},
}
getUint8: function (byteOffset) {
return this._getBytes(1, byteOffset)[0];
}
}
};
THREE.STLLoader = STLLoader;
}
} )();

+ 6
- 0
nano
File diff suppressed because it is too large
View File


BIN
stl-files/KaosCubeTopThick2mm_cut_joints_withCannaOnTop.stl View File


+ 75
- 0
stl-viewer.js 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
- 0
three.min.js
File diff suppressed because it is too large
View File


Loading…
Cancel
Save