-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
451 lines (355 loc) · 15.6 KB
/
app.js
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
// Global Variables
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
const camera = new BABYLON.ArcRotateCamera("Camera", 0, Math.PI / 3, 25, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// mode controls
var drawMode = false;
var moveMode = false;
var vertexEditMode = false;
var colour=null;
// uniform mesh color , changes is every iteration
const a=Math.random();
const b=Math.random();
const c=Math.random();
// arrays to store objects like points or shapes
var points = [];
var shapesToExtrude = [];
// Get reference to the paragraph element
var innerTextElement = document.getElementById('instructions');
innerTextElement.innerText = "Draw, Extrude, Edit Vertices and Move \n\n Hint : Click Draw";
// Step 0: Background color
scene.clearColor = new BABYLON.Color3(0.3, 0.4, 0.5);
// Light setup
var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
// Step 1: Create a ground
const ground = BABYLON.MeshBuilder.CreateGround("ground", { width: 20, height: 26}, scene);
ground.material = new BABYLON.StandardMaterial("groundMat", scene);
ground.material.diffuseColor = new BABYLON.Color3(0.9, 0.7, 0.5);
ground.material.specularColor = new BABYLON.Color3(0, 0, 0); // Disable light reflection on the ground
ground.enableEdgesRendering();
ground.edgesWidth = 14.0;
ground.edgesColor = new BABYLON.Color4(0, 0, 0, 1);
// Step 2: Draw a 2D shape
scene.onPointerObservable.add(handlePointer);
function enterDrawMode() {
drawMode = true;
moveMode = false;
vertexEditMode = false;
extrudeMode = false;
innerTextElement.innerText = "Left-click to add points and Right-click to complete the polygon \n\n Click Extrude after right-click ";
}
function handlePointer(pointerInfo) {
if(drawMode){
var pickInfo = pointerInfo.pickInfo;
switch (pointerInfo.type) {
case BABYLON.PointerEventTypes.POINTERDOWN:
// Left-Click then accumulate the points and represent it on screen
if(pointerInfo.event.inputIndex == 2 && pickInfo.pickedMesh && (pickInfo.pickedMesh.id === "ground" || pickInfo.pickedMesh.id === "lines")){
points.push(pickInfo.pickedPoint);
drawPointMarker(pickInfo.pickedPoint);
}
// Right-Click then draw the 2-D closed loop shape from points
else if(pointerInfo.event.inputIndex == 4){
points.push(points[0]);
var idx = shapesToExtrude.length;
var lines = BABYLON.MeshBuilder.CreateLines("lines"+idx.toString(), {points: points, updatable: true}, scene);
lines.color = new BABYLON.Color4(1, 1, 1, 1);
shapesToExtrude.push(points);
points = [];
}
break;
}
}
}
function drawPointMarker(point) {
// Creating point
var curShapeNumber = shapesToExtrude.length;
var curSphereWithinShape = points.length - 1;
var sphere = BABYLON.MeshBuilder.CreateSphere("pointMarker" + curShapeNumber.toString() + "_" + curSphereWithinShape.toString(), { diameter: 0.3}, scene);
sphere.position = point;
// point UI Enhancements
var material = new BABYLON.StandardMaterial("pointMarkerMaterial", scene);
material.emissiveColor = new BABYLON.Color3(1, 1, 1);
sphere.material = material;
}
// Step 3: 2D-Shape Extrusion
var shapesExtruded = [] // boolean array to avoid multiple extrusion objects
function extrudeShape(){
drawMode = false;
moveMode = false;
vertexEditMode = false;
extrudeMode = true;
innerTextElement.innerText = "Click Vertex Edit to edit the object \n Click Move to move the 3D object";
for(let i=0; i<shapesToExtrude.length; i++){
if(i == shapesExtruded.length){
shapesExtruded.push(false);
}
if(shapesExtruded[i] == false){
// Extruding shape with constant height = 3
var extrudedShapeUniqueId = "shapeExtruded" + i.toString();
const extrusion = BABYLON.MeshBuilder.ExtrudePolygon(extrudedShapeUniqueId, {shape: shapesToExtrude[i], depth: 3, updatable: true}, scene);
extrusion.position.y = 3;
// Extruded shape UI Enhancements
var material = new BABYLON.StandardMaterial("extrudedMaterial", scene);
//material.emissiveColor = new BABYLON.Color3(0, 128, 128);
extrusion.material = material;
extrusion.material.emissiveColor=new BABYLON.Color3(a, b, c);
colour=extrusion.material.emissiveColor;
extrusion.enableEdgesRendering();
extrusion.edgesWidth = 2.8;
extrusion.edgesColor = new BABYLON.Color4(0, 0, 0, 1);
// marking as shape extruded
shapesExtruded[i] = true;
}
}
}
// Step 4: Move/edit the extruded shape
function enterMoveMode() {
moveMode = true;
drawMode = false;
vertexEditMode = false;
extrudeMode = false;
runMoveMode();
}
function runMoveMode() {
var canvas = engine.getRenderingCanvas();
var startingPoint;
var currentMesh = null;
var getGroundPosition = function () {
var pickinfo = scene.pick(scene.pointerX, scene.pointerY, function (mesh) { return mesh == ground; });
if (pickinfo.hit) {
return pickinfo.pickedPoint;
}
return null;
}
var onPointerDownDrag = function (evt) {
if(moveMode === false){
canvas.removeEventListener("pointerdown", onPointerDownDrag);
canvas.removeEventListener("pointerup", onPointerUpDrag);
canvas.removeEventListener("pointermove", onPointerMoveDrag);
}
if (evt.button !== 0) {
return;
}
// check if we are under a mesh
var pickInfo = scene.pick(scene.pointerX, scene.pointerY, function (mesh) { return mesh !== ground && mesh.id.startsWith("shapeExtruded"); });
if (pickInfo.hit) {
currentMesh = pickInfo.pickedMesh;
startingPoint = getGroundPosition(evt);
if (startingPoint) {
// we need to disconnect camera from canvas
setTimeout(function () {
camera.detachControl(canvas);
}, 0);
}
}
}
var onPointerUpDrag = function () {
if (startingPoint) {
var material = new BABYLON.StandardMaterial("extrudedMaterial", scene);
material.emissiveColor = colour;
currentMesh.material = material;
camera.attachControl(canvas, true);
startingPoint = null;
return;
}
}
var onPointerMoveDrag = function (evt) {
if (!startingPoint) {
return;
}
var current = getGroundPosition();
if (!current) {
return;
}
var diff = current.subtract(startingPoint);
// 3d shape update
currentMesh.position.addInPlace(diff);
var material = new BABYLON.StandardMaterial("extrudedMaterial", scene);
material.emissiveColor = colour;
currentMesh.material = material;
// 2d mesh update
var lineMeshId = "lines" + currentMesh.id.slice(13);
var lineMesh = scene.getMeshByID(lineMeshId);
lineMesh.position.addInPlace(diff);
// vertices mesh update
var idx = Number(currentMesh.id.slice(13));
curPointSet = shapesToExtrude[idx];
var updatedPath = []
for(var i=0; i<curPointSet.length; i++){
sphereName = "pointMarker"+idx.toString() + "_" + i.toString();
curSphere = scene.getMeshByName(sphereName);
if(curSphere != null){
curSphere.position.addInPlace(diff);
curPointSet[i] = curSphere.position;
updatedPath.push(curSphere.position.x);
updatedPath.push(curSphere.position.y);
updatedPath.push(curSphere.position.z);
}
else{
console.log("sphere not found: ", sphereName);
break;
}
}
// disposing existing line and recreating them (as the inplace does not update several other params)
// updating the points as per move motion
var n = curPointSet.length;
curPointSet[n-1] = curPointSet[0];
updatedPath.push(updatedPath[0]);
updatedPath.push(updatedPath[1]);
updatedPath.push(updatedPath[2]);
// creating new line mesh (2d shape) & disposing earlier one
var lineMeshId = "lines" + currentMesh.id.slice(13);
var lineMesh = scene.getMeshByID(lineMeshId);
lineMesh.dispose();
lineMesh = new BABYLON.MeshBuilder.CreateLines(lineMeshId, {points: curPointSet}, scene);
lineMesh.color = new BABYLON.Color3(0, 1, 0);
startingPoint = current;
}
canvas.addEventListener("pointerdown", onPointerDownDrag, false);
canvas.addEventListener("pointerup", onPointerUpDrag, false);
canvas.addEventListener("pointermove", onPointerMoveDrag, false);
}
// Step 5: Edit the vertex Position
function enterVertexEditMode(){
vertexEditMode = true;
moveMode = false;
drawMode = false;
extrudeMode = false;
runVertexEditMode();
}
function runVertexEditMode(){
var canvas = engine.getRenderingCanvas();
var startingPoint;
var currentMesh;
var currentMeshNonSphere;
var isVertex = function (){
var isVertexBool = false;
// determine the cursor point from scene 2d coordinates to vector 3d cordinates
var ray = scene.createPickingRay(scene.pointerX, scene.pointerY, BABYLON.Matrix.Identity(), camera);
var rayCastHit = scene.pickWithRay(ray);
// preparing parameters for ray from cursor perpendicular to ground in -ve y axis direction
var origin = rayCastHit.pickedPoint;
var direction = new BABYLON.Vector3(0, -1, 0);
var length = 3;
var rayPerpedicular = new BABYLON.Ray(origin, direction, length);
// for debugging
// var rayHelper = new BABYLON.RayHelper(rayPerpedicular);
// rayHelper.show(scene, new BABYLON.Color3(1, 0, 0)); // Red color
// determine all the meshes hit by the perpendicular ray
var hits = scene.multiPickWithRay(rayPerpedicular);
if (hits){
for (var i=0; i<hits.length; i++){
// if pointMarker on ground is hit, then it is a vertex of the extruded polygon
// which can be used to update the extruded polygon
if(hits[i].pickedMesh.name.startsWith("pointMarker")){
currentMeshNonSphere = hits[i].pickedMesh;
isVertexBool = true;
break;
}
}
}
return isVertexBool;
}
var getGroundPosition = function () {
var pickinfo = scene.pick(scene.pointerX, scene.pointerY, function (mesh) { return mesh == ground; });
if (pickinfo.hit) {
return pickinfo.pickedPoint;
}
return null;
}
var onPointerDown = function (evt) {
if(vertexEditMode === false){
canvas.removeEventListener("pointerdown", onPointerDown);
canvas.removeEventListener("pointerup", onPointerUp);
canvas.removeEventListener("pointermove", onPointerMove);
}
if (evt.button !== 0) {
return;
}
// check if we are under a mesh
var pickInfo = scene.pick(scene.pointerX, scene.pointerY, function (mesh) {
console.log(mesh.position);
return mesh !== ground && (mesh.id.startsWith("pointMarker") || (mesh.id.startsWith("shapeExtruded") && isVertex())); });
if (pickInfo.hit) {
currentMesh = pickInfo.pickedMesh;
console.log("current meshhh: ", currentMesh);
if(!currentMesh.id.startsWith("pointMarker"))
currentMesh = currentMeshNonSphere;
console.log("picked mesh: ", currentMesh);
startingPoint = getGroundPosition(evt);
if (startingPoint) { // we need to disconnect camera from canvas
setTimeout(function () {
camera.detachControl(canvas);
}, 0);
}
}
}
var onPointerUp = function () {
if (startingPoint) {
camera.attachControl(canvas, true);
startingPoint = null;
return;
}
}
var onPointerMove = function (evt) {
if (!startingPoint) {
return;
}
var current = getGroundPosition(evt);
if (!current) {
return;
}
// updating the vertices
var diff = current.subtract(startingPoint);
currentMesh.position.addInPlace(diff);
// updating the line mesh 2D shape
var curMeshIdxs = currentMesh.id.split("_");
var lineMeshId = "lines" + curMeshIdxs[0].slice(11);
var pointToUpdate = Number(curMeshIdxs[1]);
var lineMesh = scene.getMeshByID(lineMeshId);
var positions = lineMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var startIdx = 3*Number(pointToUpdate);
positions[startIdx] = currentMesh.position.x;
positions[startIdx+1] = currentMesh.position.y;
positions[startIdx+2] = currentMesh.position.z;
if(startIdx == 0){
var n = positions.length;
positions[n-3] = positions[startIdx];
positions[n-2] = positions[startIdx+1];
positions[n-1] = positions[startIdx+2];
}
var myPoints = [];
for (var i = 0; i < positions.length; i += 3) {
var x = positions[i];
var y = positions[i + 1];
var z = positions[i + 2];
myPoints.push(new BABYLON.Vector3(x, y, z));
}
lineMesh.dispose(); // Dispose of the existing mesh
lineMesh = BABYLON.MeshBuilder.CreateLines(lineMeshId, { points: myPoints, updatable: true}, scene);
lineMesh.color = new BABYLON.Color3(0, 0, 1);
// updating the extruded polygon
var extrudedMeshId = "shapeExtruded" + curMeshIdxs[0].slice(11);
var extrudedMesh = scene.getMeshByID(extrudedMeshId);
extrudedMesh.dispose();
extrudedMesh = BABYLON.MeshBuilder.ExtrudePolygon(extrudedMeshId, {shape: myPoints, depth: 3, updatable: true}, scene);
extrudedMesh.position.y = 3;
var material = new BABYLON.StandardMaterial("extrudedMaterial", scene);
material.emissiveColor = colour;
extrudedMesh.material = material;
extrudedMesh.enableEdgesRendering();
extrudedMesh.edgesWidth = 4.0; // Set the width of the edges
extrudedMesh.edgesColor = new BABYLON.Color4(0, 0, 0, 1);
startingPoint = current;
}
canvas.addEventListener("pointerdown", onPointerDown, false);
canvas.addEventListener("pointerup", onPointerUp, false);
canvas.addEventListener("pointermove", onPointerMove, false);
}
// Run the app
engine.runRenderLoop(function(){
scene.render();
});