-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathindex.html
625 lines (541 loc) · 23.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<link rel="icon" href="data:;base64,=">
<title>Rhino Compute Sample - Brep Boolean</title>
<style>
body {
margin: 0px;
overflow: hidden;
font-size: 30pt;
font-family: arial;
}
button {
font-size: 20pt;
}
.inner {
margin: 3px 0px 3px 0px;
}
#glcanvas {
width: 100%;
height: 100%;
}
#controls {
display: flex;
flex-direction: column;
overflow: auto;
position: absolute;
top: 0px;
padding: 10px;
}
#loader {
border: 5px solid #f3f3f3;
/* Light grey */
border-top: 5px solid #3d3d3d;
/* Grey */
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
position: absolute;
top: 50%;
left: 50%;
z-index: 2;
display: none;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div id="loader"></div>
<div id="glcanvas"></div>
<div id="controls">
<button id="load_model" class="inner">Fetch Rhino Logo</button>
<button id="load_cutters" class="inner">Fetch Cutters</button>
<button id="diff" class="inner">BooleanDifference</button>
</div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.7.0/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.144.0/build/three.module.js",
"three/examples/jsm/controls/OrbitControls": "https://unpkg.com/three@0.144.0/examples/jsm/controls/OrbitControls.js",
"rhino3dm":"https://unpkg.com/rhino3dm@8.0.0-beta/rhino3dm.module.js",
"rhinocompute": "https://www.unpkg.com/compute-rhino3d@0.13.0-beta/compute.rhino3d.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import rhino3dm from 'rhino3dm'
import { RhinoCompute } from 'rhinocompute'
// holds top level variables
var RHINOLOGO = {};
let logo, cutters, difference;
// load rhino3dm
const rhino = await rhino3dm()
console.log("rhino3dm loaded!")
init();
animate();
/**
* Set up empty GL canvas with a gradient background. The geomtry will
* be loaded into the scene through a separate routine.
*/
function init() {
RhinoCompute.url = getAuth('RHINO_COMPUTE_URL') // RhinoCompute server url. Use http://localhost:8081/ if debugging locally.
RhinoCompute.apiKey = getAuth('RHINO_COMPUTE_KEY') // RhinoCompute server api key. Leave blank if debugging locally.
RHINOLOGO.scene = new THREE.Scene();
RHINOLOGO.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
RHINOLOGO.camera.position.z = 40;
RHINOLOGO.wireMaterial = new THREE.LineBasicMaterial({ color: 0x000000 });
RHINOLOGO.wireHighlightMaterial = new THREE.LineBasicMaterial({ color: 0xf4a142 });
RHINOLOGO.meshMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff });
RHINOLOGO.meshHighlightMaterial = new THREE.MeshPhongMaterial({ color: 0xffff00 });
// create a gradient background
var canvas = document.createElement('canvas');
canvas.width = 128;
canvas.height = 128;
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(1, 'rgba(79,198,237,1');
gradient.addColorStop(0.1, 'rgba(112,137,212,1)');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
RHINOLOGO.scene.background = new THREE.CanvasTexture(canvas);
// add a couple lights
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 0, 1);
RHINOLOGO.scene.add(light);
var light2 = new THREE.DirectionalLight(0x666666);
light2.position.set(0.2, 0.2, -1);
RHINOLOGO.scene.add(light2);
RHINOLOGO.renderer = new THREE.WebGLRenderer({ antialias: true });
// orbit controls help with mouse/trackpad interaction
controls = new OrbitControls(RHINOLOGO.camera, RHINOLOGO.renderer.domElement);
controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false;
controls.minDistance = 10;
controls.maxDistance = 500;
RHINOLOGO.renderer.setPixelRatio(window.devicePixelRatio);
RHINOLOGO.renderer.setSize(window.innerWidth / 2, window.innerHeight);
var glcanvas = document.getElementById('glcanvas');
glcanvas.appendChild(RHINOLOGO.renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
document.getElementById('load_model').addEventListener('click', async () => {
console.log( 'fetchLogo' )
console.log( RhinoCompute)
logo = await loadBrepsFromUrl('https://files.mcneel.com/rhino3dm/models/RhinoLogo.3dm', true)
});
document.getElementById('load_cutters').addEventListener('click', async () => { cutters = await loadBrepsFromUrl('https://files.mcneel.com/rhino3dm/models/Cutters.3dm', false) });
document.getElementById('diff').addEventListener('click', performDifference);
onWindowResize();
}
function getAuth(key) {
let value = localStorage[key]
if (value === undefined) {
const prompt = key.includes('URL') ? 'Server URL' : 'Server API Key'
value = window.prompt('RhinoCompute ' + prompt)
if (value !== null) {
localStorage.setItem(key, value)
}
}
return value
}
function onWindowResize() {
RHINOLOGO.camera.aspect = window.innerWidth / window.innerHeight;
RHINOLOGO.camera.updateProjectionMatrix();
RHINOLOGO.renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
RHINOLOGO.renderer.render(RHINOLOGO.scene, RHINOLOGO.camera);
}
async function load3dmFromUrl(url) {
let three3m = await fetch(url);
let buffer = await three3m.arrayBuffer();
let arr = new Uint8Array(buffer);
return rhino.File3dm.fromByteArray(arr);
}
async function performDifference() {
// show spinner
document.getElementById('loader').style.display = 'block';
let cutObjects = await RhinoCompute.Brep.createBooleanDifference(logo, cutters, 0.01);
difference = cutObjects.map(r => rhino.CommonObject.decode(r));
clearScene();
RHINOLOGO.doc = new jsDoc();
RHINOLOGO.doc.setBreps(difference);
RHINOLOGO.doc.computeBrepMeshes();
// hide spinner
//document.getElementById('loader').style.display = 'block';
}
async function performDifferenceFanOut() {
clearScene();
let queue = [];
let breps = [];
for (let b of logo) {
queue.push(RhinoCompute.Brep.createBooleanDifference([b], cutters, 0.01));
}
for (let promise of queue) {
let result = await promise;
console.log("Got Boolean Difference");
let new_breps = result.map(r => rhino.CommonObject.decode(r));
RHINOLOGO.doc.setBreps(new_breps);
await RHINOLOGO.doc.computeBrepMeshes();
}
// await RHINOLOGO.doc.computeBrepMeshes();
}
async function loadBrepsFromUrl(url, bDrawMeshes) {
// show spinner
document.getElementById('loader').style.display = 'block';
let model = await load3dmFromUrl(url);
let objecttable = model.objects();
let breps = [];
for (let i = 0; i < objecttable.count; i++) {
let brep = objecttable.get(i).geometry();
brep.rotate(-1.571, [1, 0, 0], [0, 0, 0]);
breps.push(brep);
}
RHINOLOGO.doc = new jsDoc();
RHINOLOGO.doc.setBreps(breps);
if (bDrawMeshes) {
RHINOLOGO.doc.computeBrepMeshes();
}
else {
RHINOLOGO.doc.computeBrepWires();
}
return breps;
}
function clearScene() {
let scene = RHINOLOGO.scene;
scene.remove.apply(scene, scene.children);
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 0, 1);
scene.add(light);
var light2 = new THREE.DirectionalLight(0x666666);
light2.position.set(0.2, 0.2, -1);
scene.add(light2);
}
/*
* Loads the 'Rhino Logo.3dm' model and computes meshes for each of
* breps in the model.
*/
async function getRhinoLogoMeshes() {
let model = await load3dmFromUrl("RhinoLogo.3dm");
let cutters = await load3dmFromUrl("Cutters.3dm");
let objecttable = model.objects();
let modelBreps = [];
for (let i = 0; i < objecttable.count; i++) {
modelBreps.push(objecttable.get(i).geometry());
}
objecttable = cutters.objects();
let cutterBreps = [];
for (let i = 0; i < objecttable.count; i++) {
cutterBreps.push(objecttable.get(i).geometry());
}
//let logoDoc = new jsDoc(model);
//let cutterDoc = new jsDoc(cutters);
let cutObjects = await RhinoCompute.Brep.createBooleanDifference(modelBreps, cutterBreps, 0.01);
let cutBreps = cutObjects.map(r => rhino.CommonObject.decode(r));
RHINOLOGO.doc = new jsDoc();
RHINOLOGO.doc.setBreps(cutBreps);
for (let geom of RHINOLOGO.doc.breps) {
geom.geometry.rotate(-1.571, [1, 0, 0], [0, 0, 0]);
}
//onModelLoaded(RHINOLOGO.doc);
let d = document.getElementById('model_data');
//var objects = model.objects();
for (let i = 0; i < RHINOLOGO.doc.breps.length; i++) {
let row = d.insertRow();
let cell1 = row.insertCell(0);
cell1.innerHTML = "<button class='btn_select' type='button' onclick='RHINOLOGO.doc.highlightMesh(" + i + ");'>" + i + "</button>";
let cell2 = row.insertCell(1);
cell2.innerHTML = "<button class='btn_mesh' type='button' onclick='RHINOLOGO.doc.computeBrepMesh(" + i + "); this.style.display = \"none\";'>M</button>";
let cell3 = row.insertCell(2);
cell3.innerHTML = "<button class='btn_wires' type='button' onclick='RHINOLOGO.doc.computeBrepWire(" + i + "); this.style.display = \"none\";'>W</button>";
//console.Log()
}
// let breps = doc.computeBrepWires();
// let wires = doc.computeBrepMeshes();
// await breps;
// await wires;
}
/**
* Create a THREE.LineSegments class representing the face edges of a
* rhino3dm.Mesh class. This is not the best way to get the edges as the
* topology edges are not exposed in rhino3dm yet.
*
* @param {rhino3dm.Mesh} mesh - the mesh geometry to extract wires from
* @param {THREE.Material} material - material to associate with the wires
* for drawing.
* @return {THREE.LineSegments} line segments geometry for a scene
*/
function meshToLineSegments(mesh, material) {
function tovec3(pt) {
return new THREE.Vector3(pt[0], pt[1], pt[2]);
}
var verts = mesh.vertices();
var faces = mesh.faces();
//var geometry = new THREE.Geometry();
var points = []
for (var i = 0; i < faces.count; i++) {
var face = faces.get(i);
var pts = [verts.get(face[0]), verts.get(face[1]), verts.get(face[2]), verts.get(face[3])];
let p0 = verts.get(face[0])
let p1 = verts.get(face[1])
let p2 = verts.get(face[2])
let p3 = verts.get(face[3])
points.push(new THREE.Vector3(p0[0], p0[1], p0[2]))
points.push(new THREE.Vector3(p1[0], p1[1], p1[2]))
points.push(new THREE.Vector3(p1[0], p1[1], p1[2]))
points.push(new THREE.Vector3(p2[0], p2[1], p2[2]))
points.push(new THREE.Vector3(p2[0], p2[1], p2[2]))
points.push(new THREE.Vector3(p3[0], p3[1], p3[2]))
/*
geometry.vertices.push(
tovec3(pts[0]), tovec3(pts[1]),
tovec3(pts[1]), tovec3(pts[2]),
tovec3(pts[2]), tovec3(pts[3])
);*/
if (face[2] != face[3]) {
// geometry.vertices.push(tovec3(pts[3]), tovec3(pts[0]));
points.push(new THREE.Vector3(p3[0], p3[1], p3[2]))
points.push(new THREE.Vector3(p0[0], p0[1], p0[2]))
}
}
const bufferGeometry = new THREE.BufferGeometry().setFromPoints(points);
return new THREE.LineSegments(bufferGeometry, material);
}
function curveToLineSegments(curve, material) {
var domain = curve.domain;
var start = domain[0];
var range = domain[1] - domain[0];
var interval = range / 50.0;
const points = []
for (var i = 0; i < 51; i++) {
let t = start + i * interval;
var pt = curve.pointAt(t);
//geometry.vertices.push(new THREE.Vector3(pt[0], pt[1], pt[2]));
points.push(new THREE.Vector3(pt[0], pt[1], pt[2]))
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
return new THREE.Line(geometry, material);
}
/**
* Create a THREE.Mesh class representing a rhino3dm.Mesh class.
*
* @param {rhino3dm.Mesh} mesh - the mesh geometry to extract triangles from
* @param {THREE.Material} material - material to associate with the mesh
* for drawing.
* @return {THREE.Mesh} mesh geometry for a scene
*/
function meshToThreejs(mesh, material) {
var geometry = new THREE.BufferGeometry();
var vertices = mesh.vertices();
var vertexbuffer = new Float32Array(3 * vertices.count);
for (var i = 0; i < vertices.count; i++) {
let pt = vertices.get(i);
vertexbuffer[i * 3] = pt[0];
vertexbuffer[i * 3 + 1] = pt[1];
vertexbuffer[i * 3 + 2] = pt[2];
}
// itemSize = 3 because there are 3 values (components) per vertex
geometry.setAttribute('position', new THREE.BufferAttribute(vertexbuffer, 3));
let indices = [];
var faces = mesh.faces();
for (var i = 0; i < faces.count; i++) {
let face = faces.get(i);
indices.push(face[0], face[1], face[2]);
if (face[2] != face[3]) {
indices.push(face[2], face[3], face[0]);
}
}
geometry.setIndex(indices);
var normals = mesh.normals();
var normalBuffer = new Float32Array(3 * normals.count);
for (var i = 0; i < normals.count; i++) {
let pt = normals.get(i);
normalBuffer[i * 3] = pt[0];
normalBuffer[i * 3 + 1] = pt[1];
normalBuffer[i * 3 + 2] = pt[1];
}
geometry.setAttribute('normal', new THREE.BufferAttribute(normalBuffer, 3));
let newmesh = new THREE.Mesh(geometry, material);
return newmesh;
}
/**
* Called every time compute.rhino3d.com returns a set of meshes for a brep
* This is a good time to convert the rhino3dm.Mesh geometry into geometry
* used in three.js
*
* @param(SampleDoc) model - the model being computed
*/
function addMeshToScene(brep) {
if (brep["meshes"].length > 0 && brep["threejs"] == null) {
let meshes = brep["meshes"];
brep["threejs"] = [];
for (let mesh of meshes) {
let lines = null;
let threemesh = meshToThreejs(mesh, RHINOLOGO.meshMaterial);
console.log("Drawing mesh");
RHINOLOGO.scene.add(threemesh);
brep["threejs"].push([lines, threemesh]);
}
}
}
function addWireframeToScene(brep) {
if (brep["wires"].length > 0 && brep["threejswires"] == null) {
let curves = brep["wires"];
brep["threejswires"] = [];
for (let curveindex = 0; curveindex < curves.length; curveindex++) {
let curve = curves[curveindex];
let lines = curveToLineSegments(curve, RHINOLOGO.wireMaterial);
RHINOLOGO.scene.add(lines);
console.log("Drawing wire");
brep["threejswires"].push(lines);
}
}
}
/**
* called once the "Rhino Logo.3dm" file has been downloaded and converted
* into an instance of a rhino3dm.File3dm class.
*
* @param(SampleDoc) model - the model just loaded
*/
function onModelLoaded(doc) {
RHINOLOGO.doc = doc;
// the Rhino Logo works better when rotated on to the XY plane
var objects = doc.model.objects();
for (var i = 0; i < objects.count; i++) {
var geometry = objects.get(i).geometry();
geometry.rotate(-1.571, [1, 0, 0], [0, 0, 0]);
}
}
class jsDoc {
constructor(model) {
this.breps = [];
if (model) {
this.model = model;
var objecttable = model.objects();
for (var i = 0; i < objecttable.count; i++) {
var modelobject = objecttable.get(i);
this.breps.push({
"geometry": modelobject.geometry(),
"meshes": [],
"wires": [],
"threejs": null,
"threejswires": null
});
}
}
}
setBreps(breps) {
for (let brep of breps) {
this.breps.push({
"geometry": brep,
"meshes": [],
"meshing": false,
"wires": [],
"threejs": null,
"threejswires": null
});
}
}
async computeBrepMesh(index) {
let brep = this.breps[index]["geometry"];
let meshes = this.breps[index]["meshes"];
if (meshes.length === 0) {
let promise = RhinoCompute.Mesh.createFromBrep(brep);
let result = await promise;
console.log("Got mesh for one brep");
brep["meshes"] = result.map(r => rhino.CommonObject.decode(r));
addMeshToScene(brep);
}
// hide spinner
document.getElementById('loader').style.display = 'none';
}
highlightMesh(index) {
if (this.breps[index].geometry.threejs !== undefined) {
for (let srf of this.breps[index].geometry.threejs) {
if (srf[1] !== null) {
if (srf[1].material == RHINOLOGO.meshHighlightMaterial)
srf[1].material = RHINOLOGO.meshMaterial;
else
srf[1].material = RHINOLOGO.meshHighlightMaterial;
}
}
}
if (this.breps[index].geometry.threejswires !== undefined) {
for (let srf of this.breps[index].geometry.threejswires) {
if (srf != null) {
if (srf.material == RHINOLOGO.wireHighlightMaterial)
srf.material = RHINOLOGO.wireMaterial;
else
srf.material = RHINOLOGO.wireHighlightMaterial;
}
}
}
}
async computeBrepMeshes() {
let queue = [];
for (let b of this.breps) {
let brep = b.geometry;
if (!b.meshing) {
b.meshing = true;
//queue.push([RhinoCompute.Mesh.createFromBrep(brep), brep]);
const result = await RhinoCompute.Mesh.createFromBrep(brep)
console.log(result)
brep["meshes"] = result.map(r => rhino.CommonObject.decode(r));
addMeshToScene(brep);
}
}
/*
for (let [promise, brep] of queue) {
let result = await promise;
console.log("Got mesh for one brep");
brep["meshes"] = result.map(r => rhino.CommonObject.decode(r));
addMeshToScene(brep);
}
*/
// hide spinner
document.getElementById('loader').style.display = 'none';
}
async computeBrepWire(index) {
let brep = this.breps[index]["geometry"];
let promise = RhinoCompute.Brep.getWireframe(brep, 1);
let result = await promise;
console.log("Got wires for one brep");
brep["wires"] = result.map(r => rhino.CommonObject.decode(r));
addWireframeToScene(brep);
}
async computeBrepWires() {
let queue = [];
for (let b of this.breps) {
let brep = b["geometry"];
queue.push([RhinoCompute.Brep.getWireframe(brep, 1), brep]);
}
for (let [promise, brep] of queue) {
let result = await promise;
console.log("Got wires for one brep");
brep["wires"] = result.map(r => rhino.CommonObject.decode(r));
addWireframeToScene(brep);
}
// hide spinner
document.getElementById('loader').style.display = 'none';
}
}
</script>
</body>
</html>