forked from MattStultz/extrusiongen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
1637 lines (1298 loc) · 51.6 KB
/
main.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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This is just a (dirty) collection of javascript functions the main page
* uses.
*
*
* The actual generator logic is located in the class files.
*
*
* @author Ikaros Kappler
* @date 2013-10-13
* @version 1.0.0
**/
// Will be initialised on initWebGL()
this.bezierCanvasHandler = null;
this.previewCanvasHandler = null;
this.keyHandler = null;
// Global constants (modidify when resizing the HTML5 canvas)
/* DEPRECATED replaced by _DILDO_CONFIG.BEZIER_CANVAS_WIDTH
* and _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT.
* See file config.js
*/
//var BEZIER_CANVAS_WIDTH = 512;
//var BEZIER_CANVAS_HEIGHT = 768;
/* DEPRECATED replaced by _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH
* and _DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT.
* See file config.js
*/
//var PREVIEW_CANVAS_WIDTH = 512;
//var PREVIEW_CANVAS_HEIGHT = 768;
/**
* This function creates a human-readable date/time string.
* Format: YYYY-MM-DD_H.i.s
**/
function createHumanReadableTimestamp() {
// Append the current date to the output filename values
var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1; // months start at 0
var day = curDate.getDate();
var hours = curDate.getHours();
var minutes = curDate.getMinutes();
var seconds = curDate.getSeconds();
if( month < 10 ) month = "0" + month;
if( day < 10 ) day = "0" + day;
if( hours < 10 ) hours = "0" + hours;
if( minutes < 10 ) minutes = "0" + minutes;
if( seconds < 10 ) seconds = "0" + seconds;
var ts = "" +
year +
"-" +
month +
"-" +
day +
"_" +
hours +
"." +
minutes +
"." +
seconds
;
return ts;
}
/**
* The signum function is not native part of the javascript Math class.
* Add Math.sign function if not present (Mozilla, ...).
**/
if( !Math.sign ) {
Math.sign = function( x ) {
// Better:
if( x == 0 )
return 0;
else
return Math.round( x / Math.abs(x) ); // round: convert to integer
}
}
/**
* This function returns the default bezier path the application initially displays.
* Note that the returned curve is a JSON string which can be parsed by
* IKRS.BezierPath.fromJSON( string ).
**/
function getDefaultBezierJSON() {
return _DILDO_CONFIG.DEFAULT_BEZIER_JSON;
}
/**
* This function simply returns the "preview_canvas" DOM element (canvas).
**/
function getPreviewCanvas() {
return document.getElementById( "preview_canvas" );
}
/**
* This function simply returns the "bezier_canvas" DOM element (canvas).
**/
function getBezierCanvas() {
return document.getElementById( "bezier_canvas" );
}
/**
* This function simply eturns the "status_bar" DOM element (div).
**/
function getStatusBar() {
return document.getElementById( "status_bar" );
}
/**
* Checks if the current canvas sizes are 512x768 pixels.
**/
function isDefaultCanvasSize() {
return (
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH == 512 &&
_DILDO_CONFIG.BEZIER_CANVAS_WIDTH == 512 &&
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT == 768 &&
_DILDO_CONFIG.BEZIER_CANVAS_HEIGHT == 768
)
}
/**
* This function is called when the page was completely loaded.
**/
function onloadHandler() {
// Display current version
if( document.getElementById( "version_tag" ) )
document.getElementById( "version_tag" ).innerHTML = VERSION_STRING;
// Prepare the sizes for the screen components?
if( _DILDO_CONFIG.AUTO_RESIZE_ON_DOCUMENT_LOAD ) {
//var maxCanvasWidth = Math.max( _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH, _DILDO_CONFIG.BEZIER_CANVAS_WIDTH );
var maxCanvasHeight = Math.max( _DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT, _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT );
var defaultHeight = 10 + 25 + maxCanvasHeight + 10 + 25 + 10 + 50;
var defaultWidth = 10 + _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH + 10 + _DILDO_CONFIG.BEZIER_CANVAS_WIDTH + 10 + 400 + 10 + 50;
// Resize at all?
if( defaultHeight > window.innerHeight || defaultWidth > window.innerWidth ) {
if( (window.innerHeight-defaultHeight) > (window.innerWidth-defaultWidth) ) {
// Height weights more than width
var effectiveHeight = Math.round( (window.innerWidth - 3*10 - 2*25 - 50)/2 );
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT = _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT = effectiveHeight;
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH = _DILDO_CONFIG.BEZIER_CANVAS_WIDTH = Math.round( effectiveHeight * (512.0/768.0) );
} else {
// Width weights more than height (or equals)
var effectiveWidth = Math.round( (window.innerWidth - 4*10 - 400 - 50)/2 );
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH = _DILDO_CONFIG.BEZIER_CANVAS_WIDTH = effectiveWidth;
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT = _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT = Math.round( effectiveWidth * (768.0/512.0) );
}
} // END if [current canvas sizes are out of screen bounds]
} // END if [auto resize on document load allowed]
// Add the canvas components
_deployCanvasComponents();
_resizeCanvasComponents();
_repositionComponentsBySize();
// Install the key handler
_installKeyHandler();
// Try to init WebGL
if( !initWebGL() ) {
// Show error message.
messageBox.show( "<br/>\n" +
"<br/>\n" +
"<h3>No WebGL!</h3><br/>\n" +
//"<br/>\n" +
"Maybe you want to visit the WebGL support site.<br/>\n" +
"<a href=\"http://get.webgl.org/\" target=\"_new\">http://get.webgl.org/</a><br/>\n"
//"<button onclick=\"messageBox.hide()\" disabled=\"disabled\">Close</button>\n"
);
return;
}
// Fetch the GET params
// Thanks to weltraumpirat
// http://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript
function getSearchParameters() {
var url = window.location.href; //search;
var index = url.indexOf("?");
if( index == -1 || index+1 >= url.length )
return {};
var prmstr = url.substr( index+1 );
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
_applyParamsToMainForm( params );
// Try to load dildo design from last session cookie (if allowed and if no data is passed)
if( _DILDO_CONFIG && _DILDO_CONFIG.AUTOLOAD_ENABLED && !params.rbdata )
loadFromCookie(true); // retainErrorStatus
if( params.rbdata )
_applyReducedBezierData( params.rbdata );
displayBendingValue();
toggleFormElementsEnabled();
updateBezierStatistics( null, null );
// Scale to perfect screen fit?
if( params._screenfit && params._screenfit == "1" ) {
//window.alert( "Scale to screen fit." );
acquireOptimalBezierView();
}
// Is the rendering engine available?
// Does this browser support WebGL?
previewCanvasHandler.preview_rebuild_model();
// Does the configured canvas size differ from the default (hard coded) bezier size?
if( !isDefaultCanvasSize() ) // _DILDO_CONFIG.BEZIER_CANVAS_WIDTH != 512 || _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT != 768 )
acquireOptimalBezierView();
preview_render();
// Finally set a timeout for auto-saving
window.setInterval( "autosaveInCookie()", 1000*30 );
}
/**
* This function add the two canvas objects to the DOM (preview_canvas for 3D,
* bezier_canvas for 2D view).
**/
function _deployCanvasComponents() {
_deployCanvasComponentWith( "bezier_canvas",
_DILDO_CONFIG.BEZIER_CANVAS_WIDTH,
_DILDO_CONFIG.BEZIER_CANVAS_HEIGHT,
"Double click onto the curve to add new control points. Press the [DEL] key to delete selected points.",
"setStatus('Double click onto the curve to add new control points. Press the [DEL] key to delete selected points.');",
"setStatus('');",
"bezier_canvas_div"
);
_deployCanvasComponentWith( "preview_canvas",
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH,
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT,
"Click, hold and drag to rotate the view.",
"setStatus('Click, hold and drag to rotate the view.');",
"setStatus('');",
"preview_canvas_div"
);
}
function _deployCanvasComponentWith( id,
width,
height,
title,
mouseover,
mouseout,
div_id
) {
var canvas = document.createElement( "canvas" );
canvas.setAttribute( "id", id );
canvas.setAttribute( "width", width );
canvas.setAttribute( "height", height );
canvas.setAttribute( "title", title );
canvas.setAttribute( "class", "tooltip" );
canvas.setAttribute( "mouseover", mouseover );
canvas.setAttribute( "mouseout", mouseout );
var preview_canvas_div = document.getElementById( div_id );
document.body.appendChild( canvas );
}
/**
* This function simply applies the dimension set in _DILDO_CONFIG to
* the canvas elements.
* - _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH
* - _DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT
* - _DILDO_CONFIG.BEZIER_CANVAS_WIDTH
* - _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT
**/
function _resizeCanvasComponents() {
var preview_canvas = getPreviewCanvas();
var bezier_canvas = getBezierCanvas();
preview_canvas.style.width = _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH + "px";
preview_canvas.style.height = _DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT + "px";
// Might be called during initialisation
if( this.previewCanvasHandler ) {
this.previewCanvasHandler.setRendererSize( _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH,
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT
);
}
bezier_canvas.style.width = _DILDO_CONFIG.BEZIER_CANVAS_WIDTH + "px";
bezier_canvas.style.height = _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT + "px";
// Might be called during initialisation
if( this.bezierCanvasHandler ) {
this.bezierCanvasHandler.setRendererSize( _DILDO_CONFIG.BEZIER_CANVAS_WIDTH,
_DILDO_CONFIG.BEZIER_CANVAS_HEIGHT,
true // redraw
);
}
}
function _repositionComponentsBySize() {
var preview_canvas = getPreviewCanvas();
var bezier_canvas = getBezierCanvas();
// Note: the members 'x' and 'y' somehow don't seem to work here.
preview_canvas.style.x = preview_canvas.style.left = "10px";
preview_canvas.style.y = preview_canvas.style.top = "40px";
var bezierLeft = (10 + _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH + 10);
bezier_canvas.style.x = bezier_canvas.style.left = bezierLeft + "px";
bezier_canvas.style.y = bezier_canvas.style.top = "40px";
var maxCanvasHeight = Math.max( _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT,
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT
);
var status_bar = getStatusBar();
status_bar.style.y = status_bar.style.top = (40 + maxCanvasHeight + 10) + "px";
status_bar.style.width = (_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH + 10 + _DILDO_CONFIG.BEZIER_CANVAS_WIDTH) + "px";
//window.alert( bezier_canvas.style.x );
// Re-align register-head
var registerHead = document.getElementById( "register_head" );
var registerLeft = ( 10 +
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH +
10 +
_DILDO_CONFIG.BEZIER_CANVAS_WIDTH +
10 );
registerHead.style.x = registerHead.style.left = registerLeft + "px";
// Re-align register-cards
var divs = document.getElementsByTagName( "DIV" );
for( var i = 0; i < divs.length; i++ ) {
var entry = divs[i];
if( !entry.className || entry.className != "register_card" )
continue;
entry.style.x = entry.style.left = registerLeft+ "px";
}
// Reposition the Gallery-Links
var galleryLinks = document.getElementById( "gallery_links" );
gallery_links.style.x = gallery_links.style.left = bezierLeft + "px";
// Reposition the 'informational' area (div)
var informational = document.getElementById( "informational" );
informational.style.x = informational.style.left = registerLeft + "px";
// Reposition the 'license' area (div)
var license = document.getElementById( "license" );
license.style.x = license.style.left = registerLeft + "px";
// Reposition the 'preview_controls' area (div)
var previewControls = document.getElementById( "preview_controls" );
previewControls.style.width = _DILDO_CONFIG.PREVIEW_CANVAS_WIDTH + "px";
// previewControls.style.backgroundColor = "#ff0000";
previewControls.style.x = previewControls.style.left = "10px";
previewControls.style.y = previewControls.style.top = (40 + _DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT + 10 + 16 + 10) + "px";
var bezierControls = document.getElementById( "bezier_controls" );
bezierControls.style.width = _DILDO_CONFIG.BEZIER_CANVAS_WIDTH + "px";
bezierControls.style.x = bezierControls.style.left = bezierLeft + "px";
bezierControls.style.y = bezierControls.style.top = (40 + _DILDO_CONFIG.BEZIER_CANVAS_HEIGHT + 10 + 16 + 10) + "px";
var donations = document.getElementById( "donations" );
donations.style.x = donations.style.left = (bezierLeft + _DILDO_CONFIG.BEZIER_CANVAS_WIDTH + 75) + "px";
var versionTag = document.getElementById( "version_tag" );
// 400px is the _constant_ width of the control panel
versionTag.style.width = "300px";
versionTag.style.x = versionTag.style.left = (bezierLeft + _DILDO_CONFIG.BEZIER_CANVAS_WIDTH + 280 + 10) + "px";
versionTag.style.y = versionTag.style.top = "200px";
//versionTag.style.backgroundColor = "#ff0000";
}
/**
* 'params' must be an object.
**/
function _applyParamsToMainForm( params ) {
// Now display the get params in the main form.
//var params = getSearchParameters();
var inputs = document.getElementsByTagName( "input" );
for( var i = 0; i < inputs.length; i++ ) {
for( var key in params ) {
if( params.hasOwnProperty(key) ) {
//window.alert( key );
var value = params[ key ];
if( value == "" )
continue;
var element = inputs[ i ];
if( element.type.toLowerCase() == "checkbox" ) {
// This element is a checkbox. Set checked?
if( element.name.toLowerCase() == key )
element.checked = (value != "0");
} else if( element.type.toLowerCase() == "radio" ) {
// This element is a radio button. Set selected?
if( element.name.toLowerCase() == key && element.value == value )
element.checked = true;
} else if( element.type.toLowerCase() == "text" ||
element.type.toLowerCase() == "number" ||
element.type.toLowerCase() == "range" ||
element.type.toLowerCase() == "hidden"
) {
//if( element.type.toLowerCase() == "hidden" )
// window.alert( "element.name=" + element.name + ", passedKey=" + key + ", passedValue=" + value );
// This element is a text/number/range. Set value?
if( element.name.toLowerCase() == key.toLowerCase() ) {
//window.alert( "Setting element value: element.name=" + element.name + ", passedKey=" + key + ", passedValue=" + value );
element.value = value;
}
}
} // END for
} // END if
} // END for
toggleFormElementsEnabled();
preview_rebuild_model();
}
/**
* The JSON representation of a bezier path can be very long.
* This function loads the integer-bezier-representation into the current
* bezier canvas handler.
* The integer-bezier-data is _much_ shorter than the JSON representation
* and should in most cases fit into the max-2048-character request URL
* (GET param).
**/
function _applyReducedBezierData( reducedBezierData ) {
try {
// Parse the point data and convert it to a bezier curve
var bezierPath = IKRS.BezierPath.fromReducedListRepresentation( reducedBezierData );
//window.alert( bezierPath );
// Set the created curve
setBezierPath( bezierPath );
return true;
} catch( e ) {
console.log( "Failed to load bezier path from GET params: " + e );
setStatus( "Failed to load bezier path from GET params: " + e );
return false;
}
}
/**
* This function installs the key handler into the window object.
*
* The key handler itself is stored in this.keyHandler.
**/
function _installKeyHandler() {
// Install the key handler
this.keyHandler = new IKRS.ExtrusiongenKeyHandler();
window.onkeydown = this.keyHandler.onKeyDown;
window.onkeypress = this.keyHandler.onKeyPress;
window.onkeyup = this.keyHandler.onKeyUp;
}
// IE < v9 does not support this function.
if( window.addEventListener ) {
window.addEventListener( "load",
onloadHandler,
false
);
} else {
window.onload = onloadHandler;
}
function getPreviewMeshes() {
return previewCanvasHandler.getMeshes();
}
function bezier_undo() {
var hasMoreUndoSteps = this.bezierCanvasHandler.undo();
window.alert( this.bezierCanvasHandler.undoHistory._toString() );
}
function bezier_redo() {
var hasMoreRedoteps = this.bezierCanvasHandler.redo();
}
/*
function setBezierPathFromJSONString( bezierString ) {
//window.alert( bezierString );
}
*/
function setBezierPath( bezierPath ) {
this.bezierCanvasHandler.setBezierPath( bezierPath );
preview_rebuild_model();
}
function getBezierPath() {
return this.bezierCanvasHandler.bezierPath;
}
function initWebGL() {
try {
this.bezierCanvasHandler = new IKRS.BezierCanvasHandler();
this.bezierCanvasHandler.addChangeListener( updateBezierStatistics ); // A function
this.previewCanvasHandler = new IKRS.PreviewCanvasHandler( this.bezierCanvasHandler,
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH, // 512,
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT // 768
);
// Indicate success.
setStatus( "WebGL initialized. Ready." );
return true;
} catch( e ) {
console.log( "Error: failed to initiate canvas handlers. Is WebGL enabled/supported?" );
setStatus( "Error: failed to initiate canvas handlers. Is WebGL enabled/supported?" );
// Indicate error.
return false;
}
}
/**
* Signature as a bezier canvas listener :)
**/
function updateBezierStatistics( source, event ) {
if( event && event.nextEventFollowing )
return; // Wait for last event in sequence, THEN update (saves resources)
// Calculate the bezier curves inner area size.
// The resulting value is in square units.
var bezierAreaSize = this.bezierCanvasHandler.getBezierPath().computeVerticalAreaSize( 1.0, // deltaSize
true // useAbsoluteValues
);
var bounds = this.bezierCanvasHandler.getBezierPath().computeBoundingBox();
// Now imagine the whole are to be a rectangle with the same height.
// The resulting radius is then:
//var imaginaryRectangleWidth = bezierAreaSize / bounds.getHeight();
// Now imagine the solid revolution of that rectangle.
// It's volume is the value we are interesed in. It equals the volume of the present mesh.
// Volume = PI * square(radius) * height
//var volumeInUnits_old = Math.PI * Math.pow(imaginaryRectangleWidth,2) * bounds.getHeight();
var volumeInUnits = this.bezierCanvasHandler.getBezierPath().computeVerticalRevolutionVolumeSize( //1.0, // deltaSize
true // useAbsoluteValues
);
var areaSize_squareMillimeters = bezierAreaSize * Math.pow( this.bezierCanvasHandler.getMillimeterPerUnit(), 2.0 );
var volume_cubeMillimeters = volumeInUnits * Math.pow( this.bezierCanvasHandler.getMillimeterPerUnit(), 3.0 );
// There is a serious bug in the calculation:
// The computed volume is about 25%-30& too high!
// Didn't find the cause so far :(
volume_cubeMillimeters *= 0.75;
var volume_cubeMilliLiters = volume_cubeMillimeters / 1000.0;
var lowDensity = 0.76;
var highDensity = 1.07;
var imperialCup = 284.130642624675; // ml
var usCup = 236.5882365; // ml
var weight_lowDensity = roundToDigits((volume_cubeMillimeters/1000)*lowDensity,0);
var weight_highDensity = roundToDigits((volume_cubeMillimeters/1000)*highDensity,0);
var tableData = [
[ "Diameter", roundToDigits((bounds.getWidth()/10)*2*this.bezierCanvasHandler.getMillimeterPerUnit(),1,3), "cm" ],
[ "Height", roundToDigits((bounds.getHeight()/10)*this.bezierCanvasHandler.getMillimeterPerUnit(),1,3), "cm" ],
[ "Bezier Area", roundToDigits((areaSize_squareMillimeters/100.0),2,3), "cm<sup>2</sup>" ],
[ "Volume", roundToDigits((volume_cubeMillimeters/1000.0),1,3), "cm<sup>3</sup> | ml" ],
[ "", roundToDigits((volume_cubeMilliLiters/imperialCup),1,3), " Imperial Cups" ],
[ "", roundToDigits((volume_cubeMilliLiters/usCup),1,3), " US Cups" ],
[ "Weight<br/> [low density silicone, " + lowDensity + "g/cm<sup>3</sup>]", roundToDigits(weight_lowDensity,0,3), "g" ],
[ "Weight<br/> [high density silicone, " + highDensity + "g/cm<sup>3</sup>]", roundToDigits(weight_highDensity,0,3), "g" ]
];
document.getElementById( "volume_and_weight" ).innerHTML = makeTable( tableData );
preview_rebuild_model();
}
function makeTable( tableData ) {
// I know, this is ugly.
// String concatenation _and_ direct HTML insert insert DOM use. Bah!
// Please optimize.
var result = "<table style=\"border: 1px solid #686868;\">";
for( var r = 0; r < tableData.length; r++ ) {
result += "<tr>\n";
for( var c = 0; c < tableData[r].length; c++ ) {
//var valign = "top";
//var align = "left";
if( c == 1 )
result += "<td valign=\"bottom\" align=\"right\">" + tableData[r][c] + " </td>\n";
else
result += "<td valign=\"bottom\">" + tableData[r][c] + " </td>\n";
}
result += "</tr>\n";
}
result += "</table>\n";
return result;
}
function preview_render() {
// Recursive call
requestAnimationFrame( this.preview_render );
previewCanvasHandler.render( this.preview_scene,
this.preview_camera
);
}
function decreaseZoomFactor( redraw ) {
this.previewCanvasHandler.decreaseZoomFactor();
if( redraw )
preview_render();
}
function increaseZoomFactor( redraw ) {
this.previewCanvasHandler.increaseZoomFactor();
if( redraw )
preview_render();
}
function increaseGUISize() {
changeGUISizeByFactor(1.1);
}
function decreaseGUISize() {
changeGUISizeByFactor(1.0/1.1);
}
function changeGUISizeByFactor( factor ) {
_DILDO_CONFIG.PREVIEW_CANVAS_WIDTH *= factor;
_DILDO_CONFIG.PREVIEW_CANVAS_HEIGHT *= factor;
_DILDO_CONFIG.BEZIER_CANVAS_WIDTH *= factor;
_DILDO_CONFIG.BEZIER_CANVAS_HEIGHT *= factor;
_resizeCanvasComponents();
_repositionComponentsBySize();
}
function increase_mesh_details() {
var shape_segments = this.document.forms["mesh_form"].elements["shape_segments"].value;
var path_segments = this.document.forms["mesh_form"].elements["path_segments"].value;
shape_segments = parseInt( shape_segments );
path_segments = parseInt( path_segments );
shape_segments = Math.ceil( shape_segments * 1.2 );
path_segments = Math.ceil( path_segments * 1.2 );
this.document.forms["mesh_form"].elements["shape_segments"].value = shape_segments;
this.document.forms["mesh_form"].elements["path_segments"].value = path_segments;
preview_rebuild_model();
}
function decrease_mesh_details() {
var shape_segments = this.document.forms["mesh_form"].elements["shape_segments"].value;
var path_segments = this.document.forms["mesh_form"].elements["path_segments"].value;
shape_segments = parseInt( shape_segments );
path_segments = parseInt( path_segments );
shape_segments = Math.max( 3, Math.floor( shape_segments / 1.2 ) );
path_segments = Math.max( 2, Math.floor( path_segments / 1.2 ) );
if( shape_segments < 3 && path_segments < 2 )
return; // No change
// The min or max bound might have been reached and the segment values
// were re-adjusted. Display the new value in the HTML form.
this.document.forms["mesh_form"].elements["shape_segments"].value = shape_segments;
this.document.forms["mesh_form"].elements["path_segments"].value = path_segments;
preview_rebuild_model();
}
function preview_rebuild_model() {
this.previewCanvasHandler.preview_rebuild_model();
}
function newScene() {
var defaultSettings = {
shapeSegments: 80,
pathSegments: 80,
bendAngle: 0,
buildNegativeMesh: false,
meshHullStrength: 12,
closePathBegin: false,
closePathEnd: true,
wireframe: false,
triangulate: true,
parts: null, // default: "both"
shapeTwist: 0,
shapeStyle: null // default: "circle"
};
ZipFileImporter._apply_mesh_settings( defaultSettings );
var json = getDefaultBezierJSON();
setBezierPathFromJSON( json, // a JSON string containing the bezier data
0 // bend_angle
);
// Clear dildo ID (otherwise the new design cannot be published)
setCurrentDildoID( -1, "" );
if( !isDefaultCanvasSize() )
acquireOptimalBezierView();
}
function setBezierPathFromJSON( bezier_json, bend_angle ) {
var bezierPath = null;
try {
bezierPath = IKRS.BezierPath.fromJSON( bezier_json );
} catch( e ) {
window.alert( "Error: " + e );
return false;
}
setBezierPath( bezierPath );
setBendingValue( bend_angle );
updateBezierStatistics( null, null );
toggleFormElementsEnabled();
preview_rebuild_model();
return true;
}
function setBezierPathFromReducedListRepresentation( array_json, bend_angle ) {
var bezierPath = null;
try {
bezierPath = IKRS.BezierPath.fromReducedListRepresentation( array_json );
} catch( e ) {
window.alert( "Error: " + e );
return false;
}
setBezierPath( bezierPath );
setBendingValue( bend_angle );
updateBezierStatistics( null, null );
toggleFormElementsEnabled();
preview_rebuild_model();
return true;
}
function saveShape() {
saveTextFile( bezierCanvasHandler.bezierPath.toJSON(), 'dildo_bezier_shape_' + createHumanReadableTimestamp() + '.json', 'application/json' );
}
function loadShape() {
upload_bezier_json_file( document.forms['bezier_file_upload_form'].elements['bezier_json_file'] );
toggleFormElementsEnabled();
}
function exportZIP() {
// Check size
if( !checkSizeBeforeSaving() )
return false;
var zip_filename = "dildo_settings_" + createHumanReadableTimestamp() + ".zip";
ZipFileExporter.exportZipFile( zip_filename );
}
function importZIP() {
var zip_filename = document.forms['zip_import_form'].elements['zip_upload_file'];
if( zip_filename ) {
ZipFileImporter.importZipFile( zip_filename );
}
}
function publishDildoDesign() {
var dongNames = new Array( "Karl",
"Intruder Alert",
"Silicone Redeemer",
"Love Machine",
"It's a fap!",
"Snoosnoo Enhancer",
"Absolutely Fapulous",
"Mind The Fap",
"Faporatory",
"Faporizer",
"The Gender Bender",
"Large Hardon Collider",
"Oh Long Johnson",
"Cereal Port",
"Needle"
);
var userNames = new Array( "Señor Pijo",
"Madame Laineux",
"Bernd",
"Navel Fluff",
"Sev",
"Fap Dancer",
"I.C. Weener",
"Captain Harrrrrdon",
"Polygon Faprications",
"Dong Quixote",
"Master Baiter",
"Obi Wank Kenobi",
"The Nice King",
"Ygritte",
"Tank Girl",
"Booga",
"Shrub-Niggurath",
"Homer Sexual",
"King Dong"
);
var dongIndex = Math.floor( Math.random() * dongNames.length );
var userIndex = Math.floor( Math.random() * userNames.length );
//window.alert( random + ", " + names.length );
// Clear bezier background data!
// Some visitors used it to upload p0rn
this.bezierCanvasHandler.setDrawCustomBackgroundImage( false, true ); // redraw=true
var imageData = get3DScreenshotData();
var bezierImageData = getBezierScreenshotData();
var currentDildoHash = getCurrentDildoHash();
// Restore the old custom background image
this.bezierCanvasHandler.setDrawCustomBackgroundImage( true, true ); // redraw=true
messageBox.show( "<br/>\n" +
"<h3>Publish your Dildo</h3>\n" +
"This will publish your dildo and add it to the gallery.<br/>\n" +
//"<div style=\"text-align: center;\">\n" +
"<form name=\"publish_form\" onkeypress=\"return event.keyCode != 13;\">\n" +
" <input type=\"hidden\" name=\"image_data\" value=\"" + imageData + "\" />\n" +
" <input type=\"hidden\" name=\"bezier_image_data\" value=\"" + bezierImageData + "\" />\n" +
//" <div id=\"screenshot_div\"></div>\n" +
" <table border=\"0\" style=\"text-align: left; margin-left: 5%; margin-right: 5%;\">\n" +
" <tr>\n" +
" <td rowspan=\"14\" style=\"padding: 10px;\"><img src=\"" + imageData + "\" width=\"256\" height=\"384\" alt=\"Preview\" /></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>Give your dong a name:</td>\n" +
" <td><input type=\"text\" maxlength=\"64\" name=\"dong_name\" value=\"" + dongNames[dongIndex] + "\" /></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>Your name/alias:</td>\n" +
" <td><input type=\"text\" name=\"user_name\" maxlength=\"128\" value=\"" + userNames[userIndex] + "\"\" /></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td style=\"vertical-align: top;\">Email address:</td>\n" +
" <td style=\"vertical-align: top;\"><input type=\"text\" id=\"hide_email_address\" name=\"email_address\" value=\"[email protected]\" /> (optional)<br/>\n" +
" <input type=\"checkbox\" name=\"hide_email_address\" value=\"1\" checked=\"checked\" /> " +
" <label for=\"hide_email_address\">Hide email address from public</label>\n" +
" </td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td><label for=\"allow_download\">Allow download:</label></td>\n" +
" <td><input type=\"checkbox\" id=\"allow_download\" name=\"allow_download\" value=\"1\" checked=\"checked\" />\n" +
" </td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>Keywords:</td>\n" +
" <td><input type=\"text\" name=\"keywords\" maxlength=\"1024\" value=\"\" /></td>\n" +
" </tr>\n" +
/*
" <tr>\n" +
" <td><label for=\"allow_edit\">Allow edit:</label></td>\n" +
" <td><input type=\"checkbox\" id=\"allow_edit\" name=\"allow_edit\" value=\"1\" />\n" +
" </td>\n" +
" </tr>\n" +
*/
" <tr>\n" +
" <td></td>\n" +
" <td><div style=\"font-size: 8pt; text-align: right;\">What does this do? Where is my dong published? See the <a href=\"javascript:open_faqs('privacy_publishing');\">FAQ</a> (popup)</div></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td></td>\n" +
" <td><div style=\"text-align: right;\">To the <a href=\"javascript:open_gallery();\">Gallery</a>.</div></td>\n" +
" </tr>\n" +
" <tr><td> </td><td></td></tr>\n" +
" <tr><td> </td><td></td></tr>\n" +
" <tr><td> </td><td></td></tr>\n" +
" <tr><td> </td><td><span id=\"loading_span_static\"></span></td></tr>\n" +
" <tr><td> </td><td><span id=\"loading_span\"></span></td></tr>\n" +
" <tr><td> </td><td></td></tr>\n" +
//" <tr>\n" +
//" <td></td>\n" +
//" <td><button onclick=\"_publish_dildo_design();\">Save</button> <button onclick=\"messageBox.hide();\">Cancel</button></td>\n" +
//" </tr>\n" +
//" <tr><td> </td><td>" + (currentDildoHash ? "Your design was already saved with ID " + currentDildoHash + "." : "") + "</td></tr>\n" +
" </tr>\n" +
" </table>\n" +
"</form>\n" +
"<button onclick=\"_publish_dildo_design();\"" + (currentDildoHash ? "disabled=\"disabled\"" : "") + ">Publish!</button> <button onclick=\"messageBox.hide()\">Cancel</button><br/>\n" +
(currentDildoHash ? "<div class=\"error\">Your design was already saved under ID <a href=\"javascript:open_gallery('?public_hash=" + currentDildoHash + "');\">" + currentDildoHash + "</a>.<br/>If you want to publish a different design please create a new scene first (go to Model→New).</div>" : ""),
//"</div>\n",
800,
600
);
// Now display the screenshot image
/*var img = document.createElement('img');
//img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
img.src = imageData;
img.width = 256; // 512/2
img.height = 384; // 768/2
document.getElementById("screenshot_div").appendChild( img );
*/
//window.alert( "Sorry, this function is not yet implemented." );
}
/**
* Toggles the 'about' dialog.
**/
function about() {