/
script.js
2452 lines (2317 loc) · 105 KB
/
script.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
import 'whatwg-fetch';
import Promise from 'promise-polyfill';
import {Fragmen} from './fragmen.js';
import {Onomat} from './onomat.js';
import {Musician} from './music.js';
import {FireDB} from './firedb.js';
import {registerCursorTimeout} from './registerCursorTimeout.js';
import * as firebase from 'firebase/app';
import 'firebase/database';
import 'firebase/analytics';
(() => {
let wrap = null; // だいたいすべてを包んでいるラッパー DOM
let canvas = null; // スクリーン
let editor = null; // Ace editor のインスタンス
let lineout = null; // ステータスバー DOM
let counter = null; // 文字数カウンター DOM
let message = null; // メッセージ DOM
let mode = null; // variable mode select
let animate = null; // アニメーション用 toggle
let frames = null; // render frame select
let size = null; // resolution select
let download = null; // download button
let link = null; // generate link button
let layer = null; // dialog layer
let dialog = null; // dialog message wrapper
let infoIcon = null; // information icon
let fullIcon = null; // fullscreen icon
let broadIcon = null; // broadcast mode icon
let starIcon = null; // star icon
let menuIcon = null; // menu icon
let noteIcon = null; // note icon
let hideIcon = null; // hide menu icon
let showIcon = null; // show menu icon
let syncToggle = null; // スクロール同期用のチェックボックス
let audioWrap = null; // サウンドシェーダペインのラッパー
let audioEditor = null; // Ace editor のインスタンス
let audioLineout = null; // ステータスバー DOM
let audioCounter = null; // 文字数カウンター DOM
let audioMessage = null; // メッセージ DOM
let audioToggle = null; // トグルボタン
let audioPlayIcon = null; // 再生ボタン
let audioStopIcon = null; // 停止ボタン
let latestStatus = 'success'; // 直近のステータス
let latestAudioStatus = 'success'; // 直近のステータス(サウンドシェーダ)
let isEncoding = false; // エンコード中かどうか
let currentMode = Fragmen.MODE_CLASSIC; // 現在の Fragmen モード
let currentSource = ''; // 直近のソースコード
let currentAudioSource = ''; // 直近の Sound Shader のソースコード
let fragmen = null; // fragmen.js のインスタンス
let onomat = null; // onomat.js のインスタンス
let musician = null; // music.js のインスタンス
let urlParameter = null; // GET パラメータを解析するための searchParams オブジェクト
let vimMode = false; // vim mode
let syncScroll = true; // エディタ上で配信を受けている場合にスクロール同期するか
/** @type {FireDB | null} */
let fire = null;
let currentDirectorId = null; // 自分自身のディレクター ID
let friendDirectorId = null; // 招待用のディレクター ID
let currentChannelId = null; // 自分自身がディレクターとなったチャンネルの ID
let currentDirectorName = null; // ディレクターが指定した名前・グループ名
let currentSnapshotId = null; // 読み込むスナップショットID
let broadcastForm = null; // 登録用フォームの実体
let broadcastSetting = null; // 登録用フォームの入力内容
let directionMode = null; // 何に対するディレクターなのか
let friendDirectionMode = null; // フレンドが何に対するディレクターなのか
let isOwner = null; // チャンネルのオーナーなのかどうか
let isDirectorInitialized = true; // オーナー自身(及びフレンド)が復帰 URL を踏んだ際に初期化が完了しているかどうか
let shareURL = ''; // 配信用共有 URL
let ownerURL = ''; // ディレクターとして同環境に復帰できる URL
let friendURL = ''; // フレンド共有用 URL
let starCounterTimer = null; // スターのアニメーション用タイマー
let viewerCounterTimer = null; // 視聴者数のアニメーション用タイマー
let graphicsDisable = false; // グラフィックス用のエディタを無効化するかどうか
let soundDisable = false; // サウンド用のエディタを無効化するかどうか
let broadcastMode = 'none'; // 配信に対する挙動(none, owner, friend, audience)
let soundPlay = 0; // サウンドが配信者の元で再生された際のカウント
let channelData = null; // チャンネルのデータを保持
let starData = null; // スターに関するデータを保持
let viewerData = null; // 視聴者数に関するデータを保持
let editorFontSize = 17; // エディタのフォントサイズ
let isEdit = false; // コードの編集を行ったことがあるかどうか
let disableAttachEvent = false; // コードの編集時、beforeunload を設定させない場合真を設定する
/** {@link registerCursorTimeout} で追加した処理を消す関数 */
let unregisterCursorTimeout = null;
// fragmen.js 用のオプションの雛形
const FRAGMEN_OPTION = {
target: null,
eventTarget: null,
mouse: true,
resize: true,
escape: false
}
// 外部サービスへリクエストする際のベース URL
const BASE_URL = location.origin;
// firebase のコンフィグ
const FIREBASE_CONFIG = {
apiKey: 'AIzaSyAcRObIHeZUmCt_X3FEzLdBJzUDYTVRte8',
authDomain: 'twigl-f67a0.firebaseapp.com',
databaseURL: 'https://twigl-f67a0.firebaseio.com',
projectId: 'twigl-f67a0',
storageBucket: 'twigl-f67a0.appspot.com',
messagingSenderId: '653821260349',
appId: '1:653821260349:web:17e2128ca9a60f2c7ff054',
measurementId: 'G-WHMVELFNCW'
};
// 配信のアサイン設定
const BROADCAST_ASSIGN = {
BOTH: 'both',
ONLY_GRAPHICS: 'onlygraphics',
INVITE_SOUND: 'invitesound',
ONLY_SOUND: 'onlysound',
INVITE_GRAPHICS: 'invitegraphics',
};
// 何に対するディレクターなのか
const BROADCAST_DIRECTION = {
BOTH: 'both',
GRAPHICS: 'graphics',
SOUND: 'sound',
};
window.addEventListener('DOMContentLoaded', () => {
// firebase の初期化
firebase.initializeApp(FIREBASE_CONFIG);
firebase.analytics();
fire = new FireDB(firebase);
// DOM への参照
wrap = document.querySelector('#wrap');
canvas = document.querySelector('#webgl');
lineout = document.querySelector('#lineout');
counter = document.querySelector('#counter');
message = document.querySelector('#message');
mode = document.querySelector('#modeselect');
animate = document.querySelector('#pausetoggle');
frames = document.querySelector('#frameselect');
size = document.querySelector('#sizeselect');
download = document.querySelector('#downloadgif');
link = document.querySelector('#permanentlink');
layer = document.querySelector('#layer');
dialog = document.querySelector('#dialogmessage');
infoIcon = document.querySelector('#informationicon');
fullIcon = document.querySelector('#fullscreenicon');
broadIcon = document.querySelector('#broadcasticon');
starIcon = document.querySelector('#stariconwrap');
menuIcon = document.querySelector('#togglemenuicon');
noteIcon = document.querySelector('#noteicon');
hideIcon = document.querySelector('#hidemenuicon');
showIcon = document.querySelector('#showmenuicon');
syncToggle = document.querySelector('#syncscrolltoggle');
audioWrap = document.querySelector('#audio');
audioLineout = document.querySelector('#lineoutaudio');
audioCounter = document.querySelector('#counteraudio');
audioMessage = document.querySelector('#messageaudio');
audioToggle = document.querySelector('#audiotoggle');
audioPlayIcon = document.querySelector('#playicon');
audioStopIcon = document.querySelector('#stopicon');
// fragmen からデフォルトのソース一覧を取得
const fragmenDefaultSource = Fragmen.DEFAULT_SOURCE;
// メニュー及びエディタを非表示にするかどうかのフラグ
let isLayerHidden = false;
// URL の GET パラメータの解析
urlParameter = getParameter();
urlParameter.forEach((value, key) => {
switch(key){
case 'mode':
currentMode = parseInt(value);
break;
case 'sound':
audioToggle.checked = value === 'true';
break;
case 'source':
currentSource = value;
break;
case 'soundsource':
currentAudioSource = value;
break;
case 'gd': // graphics director
currentDirectorId = value;
break;
case 'sd': // sound director
currentDirectorId = value;
break;
case 'fd': // friend director
friendDirectorId = value;
break;
case 'dm': // direction mode
directionMode = value;
let directionFlag = Object.entries(BROADCAST_DIRECTION).some(([key, val]) => {
return val === value;
});
if(directionFlag !== true){
directionMode = null;
}
break;
case 'ss':
currentSnapshotId = value;
break;
case 'ch': // channel
currentChannelId = value;
break;
case 'ow': // is owner
isOwner = value === 'true';
break;
case 'ol': // overlay (hide menu view)
wrap.classList.add('overlay');
isLayerHidden = true;
break;
}
});
// URL パラメータより得たカレントモードが存在するか
if(fragmenDefaultSource[currentMode] != null){
mode.selectedIndex = currentMode;
}else{
currentMode = Fragmen.MODE_CLASSIC;
}
// この時点でカレントソースが空である場合既定のソースを利用する
if(currentSource === ''){
if (currentChannelId != null || currentSnapshotId != null) {
// broadcast・snapshotの場合は、空のまま通す
// 最初に一瞬デフォルトシェーダが読み込まれるのを防ぐため
} else {
currentSource = fragmenDefaultSource[currentMode];
}
}
// audioToggle が checked ではないかサウンドシェーダのソースが空の場合既定のソースを利用する
if(audioToggle.checked !== true || currentAudioSource === ''){
currentAudioSource = Onomat.FRAGMENT_SHADER_SOURCE_DEFAULT;
}
// channel ID がある場合は配信に関係している状態とみなす
let invalidURL = false;
if(currentChannelId != null && directionMode != null){
if(currentDirectorId != null){
// ディレクター ID が存在する場合視聴者ではなくいずれかの配信者
if(isOwner === true){
// この時点でオーナーだということは復帰 URL を踏んでいる
// つまり先に firebase から復帰すべき情報を取得してやらなくてならない
// isDirectorInitialized は通常は true だが、初期化が完了するまでは false に設定する
isDirectorInitialized = false;
broadcastSetting = {validation: true, assign: 'both'};
// フレンドがいるかどうか
if(friendDirectorId != null){
// フレンドがいる場合、招待したほうのエディタは編集不可能にする
if(directionMode === BROADCAST_DIRECTION.GRAPHICS){
// フレンドはサウンドを担当
soundDisable = true;
broadcastSetting.assign = BROADCAST_ASSIGN.INVITE_SOUND;
}else{
// フレンドはグラフィックスを担当
graphicsDisable = true;
disableRegulation();
broadcastSetting.assign = BROADCAST_ASSIGN.INVITE_GRAPHICS;
}
}
// オーナーの場合配信アイコン押下で URL を再表示できる必要があるのであらかじめ生成しておく
ownerURL = BASE_URL + '?' + generateDirectorURL(
currentMode,
directionMode,
broadcastSetting.assign,
currentDirectorId,
currentChannelId,
friendDirectorId,
);
if(friendDirectorId != null){
friendURL = BASE_URL + '?' + generateFriendURL(
currentMode,
directionMode,
broadcastSetting.assign,
currentDirectorId,
currentChannelId,
friendDirectorId,
);
}
shareURL = `${BASE_URL}?ch=${currentChannelId}&dm=${directionMode}`;
// 配信モードはオーナー
broadcastMode = 'owner';
}else{
// 招待を受けた側
if(friendDirectorId != null){
// フレンドの場合もオーナーの場合と同じでコードを復元する必要がある
isDirectorInitialized = false;
// この箇所での friend == オーナーディレクターなのでオーナー側のエディタは編集不可能にする
if(directionMode === BROADCAST_DIRECTION.GRAPHICS){
// オーナーはグラフィックスを担当
graphicsDisable = true;
// フレンド側からはレギュレーションは操作できない
disableRegulation();
}else{
// オーナーはサウンドを担当
soundDisable = true;
}
// 配信モードはフレンド
broadcastMode = 'friend';
}else{
// オーナーがいないことになってしまうので不正
invalidURL = true;
}
}
}else{
// 視聴者の場合エディタは強制的に読み取り専用になる
graphicsDisable = true;
soundDisable = true;
// 配信モードは視聴者
broadcastMode = 'audience';
}
}
if(invalidURL === true){
// 無効な URL とみなされるなにかがあったので通常の初期化フローにする
currentDirectorId = null;
friendDirectorId = null;
currentChannelId = null;
broadcastSetting = null;
broadcastForm = null;
directionMode = null;
friendDirectionMode = null;
isOwner = null;
shareURL = '';
ownerURL = '';
friendURL = '';
graphicsDisable = false;
soundDisable = false;
broadcastMode = 'none';
}
// Ace editor 関連の初期化
let timeoutId = null;
editor = editorSetting('editor', currentSource, (evt) => {
// イベントの設定が抑止されていない場合だけ行う
if(disableAttachEvent !== true){
// ブロードキャストの視聴者ではなく、かつ一度も編集していなかった場合、一度だけ設定する
if(isEdit !== true && broadcastMode !== 'audience'){
isEdit = true;
window.addEventListener('beforeunload', (evt) => {
evt.preventDefault();
evt.returnValue = '';
}, false);
}
isEdit = true;
}else{
disableAttachEvent = false;
}
// 1秒以内の場合はタイマーをキャンセル
if(timeoutId != null){clearTimeout(timeoutId);}
timeoutId = setTimeout(() => {
timeoutId = null;
update(editor.getValue());
}, 1000);
// 文字数の出力
counter.textContent = `${editor.getValue().length}`;
}, (evt) => {
// 配信中はステータスとは無関係に状態を送る
if(currentChannelId != null && (broadcastMode === 'owner' || broadcastMode === 'friend')){
// グラフィックスを編集する立場かどうか
if(
(broadcastMode === 'owner' && directionMode !== BROADCAST_DIRECTION.SOUND) ||
(broadcastMode === 'friend' && directionMode === BROADCAST_DIRECTION.SOUND)
){
updateGraphicsData(currentDirectorId, currentChannelId, currentMode);
}
}
});
let audioTimeoutId = null;
audioEditor = editorSetting('editoraudio', currentAudioSource, (evt) => {
// イベントの設定が抑止されていない場合だけ行う
if(disableAttachEvent !== true){
// ブロードキャストの視聴者ではなく、かつ一度も編集していなかった場合、一度だけ設定する
if(isEdit !== true && broadcastMode !== 'audience'){
isEdit = true;
window.addEventListener('beforeunload', (evt) => {
evt.preventDefault();
evt.returnValue = '';
}, false);
}
isEdit = true;
}else{
disableAttachEvent = false;
}
// 1秒以内の場合はタイマーをキャンセル
if(audioTimeoutId != null){clearTimeout(audioTimeoutId);}
audioTimeoutId = setTimeout(() => {
audioTimeoutId = null;
updateAudio(audioEditor.getValue());
}, 1000);
// 文字数の出力
audioCounter.textContent = `${audioEditor.getValue().length}`;
}, (evt) => {
// 配信中はステータスとは無関係に状態を送る
if(currentChannelId != null && (broadcastMode === 'owner' || broadcastMode === 'friend')){
// グラフィックスを編集する立場かどうか
if(
(broadcastMode === 'owner' && directionMode !== BROADCAST_DIRECTION.GRAPHICS) ||
(broadcastMode === 'friend' && directionMode === BROADCAST_DIRECTION.GRAPHICS)
){
updateSoundData(currentDirectorId, currentChannelId, soundPlay);
}
}
});
// audioToggle が checked である場合、URL からサウンドシェーダが有効化されている
if(audioToggle.checked === true){
// まず自家製ダイアログを出しユーザーにクリック操作をさせる
showDialog('This URL is a valid of sound shader.\nIt is OK play the audio?', {
okLabel: 'yes',
cancelLabel: 'no',
})
.then((result) => {
// ユーザーが OK, Cancel のいずれをクリックしたかのフラグを引数に与える
onomatSetting(result);
// OK がクリックされた場合は文字数等を更新する
if(result === true){
update(editor.getValue());
counter.textContent = `${editor.getValue().length}`;
audioCounter.textContent = `${audioEditor.getValue().length}`;
}
});
}
// ウィンドウのリサイズ時
window.addEventListener('resize', () => {
resize();
}, false);
// 最初に一回リサイズ相当の処理を行っておく
resize();
// モード変更時の処理
mode.addEventListener('change', () => {
const defaultSourceInPrevMode = fragmenDefaultSource[currentMode];
const source = editor.getValue();
currentMode = parseInt(mode.value);
fragmen.mode = currentMode;
// 既定のソースと同じならモードに応じた既定のソースに書き換える
if(source === defaultSourceInPrevMode){
const defaultSource = fragmenDefaultSource[currentMode];
editor.setValue(defaultSource);
setTimeout(() => {editor.gotoLine(1);}, 100);
}else{
// ソースを置き換えないとしてもビルドはしなおす
update(editor.getValue());
}
}, false);
// アニメーション有効・無効設定用トグル
animate.addEventListener('change', () => {
if(animate.checked === true){
// オンにされた場合はコンパイルを行う
if(fragmen != null){
fragmen.setAnimation(true);
update(editor.getValue());
fragmen.draw();
}
}else{
// オフにされた場合はアニメーションさせない設定に切り替える
if(fragmen != null){
fragmen.setAnimation(false);
}
}
}, false);
// ダウンロードボタン
download.addEventListener('click', () => {
// ボタンに disabled が付与されているかエンコード中は即時終了
if(
download.classList.contains('disabled') === true ||
isEncoding === true
){
return;
}
// ダウンロード用のパラメータを設定するダイアログを表示する
const wrap = document.createElement('div');
wrap.setAttribute('id', 'downloadconfig');
const infoHeader = document.createElement('h3');
infoHeader.textContent = 'Download';
wrap.appendChild(infoHeader);
// エクスポートの種類
const typeWrap = document.createElement('div');
const typeRadioGif = document.createElement('input');
typeRadioGif.setAttribute('type', 'radio');
typeRadioGif.setAttribute('name', 'typeradio');
typeRadioGif.checked = true;
const typeRadioGifLabel = document.createElement('label');
const typeRadioGifCaption = document.createElement('span');
typeRadioGifCaption.textContent = 'Gif';
typeRadioGifLabel.appendChild(typeRadioGif);
typeRadioGifLabel.appendChild(typeRadioGifCaption);
const typeRadioWebM = document.createElement('input');
typeRadioWebM.setAttribute('type', 'radio');
typeRadioWebM.setAttribute('name', 'typeradio');
const typeRadioWebMLabel = document.createElement('label');
const typeRadioWebMCaption = document.createElement('span');
typeRadioWebMCaption.textContent = 'WebM';
typeRadioWebMLabel.appendChild(typeRadioWebM);
typeRadioWebMLabel.appendChild(typeRadioWebMCaption);
const typeRadioJpeg = document.createElement('input');
typeRadioJpeg.setAttribute('type', 'radio');
typeRadioJpeg.setAttribute('name', 'typeradio');
typeRadioJpeg.checked = true;
const typeRadioJpegLabel = document.createElement('label');
const typeRadioJpegCaption = document.createElement('span');
typeRadioJpegCaption.textContent = 'JPEG';
typeRadioJpegLabel.appendChild(typeRadioJpeg);
typeRadioJpegLabel.appendChild(typeRadioJpegCaption);
const typeRadioPng = document.createElement('input');
typeRadioPng.setAttribute('type', 'radio');
typeRadioPng.setAttribute('name', 'typeradio');
typeRadioPng.checked = true;
const typeRadioPngLabel = document.createElement('label');
const typeRadioPngCaption = document.createElement('span');
typeRadioPngCaption.textContent = 'PNG';
typeRadioPngLabel.appendChild(typeRadioPng);
typeRadioPngLabel.appendChild(typeRadioPngCaption);
typeWrap.appendChild(typeRadioGifLabel);
typeWrap.appendChild(typeRadioWebMLabel);
typeWrap.appendChild(typeRadioJpegLabel);
typeWrap.appendChild(typeRadioPngLabel);
wrap.appendChild(typeWrap);
// フレーム数
const frameWrap = document.createElement('div');
const frameInput = document.createElement('input');
frameInput.setAttribute('type', 'number');
frameInput.value = parseInt(frames.value);
frameInput.min = 1;
frameInput.addEventListener('change', () => {
frameInput.value = Math.max(frameInput.value, 1);
}, false);
const frameCaption = document.createElement('span');
frameCaption.textContent = 'frames';
frameWrap.appendChild(frameCaption);
frameWrap.appendChild(frameInput);
wrap.appendChild(frameWrap);
// 解像度
const sizes = size.value.split('x');
const resolutionWrap = document.createElement('div');
const resolutionCaption = document.createElement('span');
resolutionCaption.textContent = 'resolution';
const widthInput = document.createElement('input');
widthInput.setAttribute('type', 'number');
widthInput.value = parseInt(sizes[0]);
widthInput.min = 1;
widthInput.addEventListener('change', () => {
widthInput.value = Math.max(widthInput.value, 1);
}, false);
const heightInput = document.createElement('input');
heightInput.setAttribute('type', 'number');
heightInput.value = parseInt(sizes[1]);
heightInput.min = 1;
heightInput.addEventListener('change', () => {
heightInput.value = Math.max(heightInput.value, 1);
}, false);
const resolutionCross = document.createElement('span');
resolutionCross.classList.add('cross');
resolutionCross.textContent = 'x';
resolutionWrap.appendChild(resolutionCaption);
resolutionWrap.appendChild(widthInput);
resolutionWrap.appendChild(resolutionCross);
resolutionWrap.appendChild(heightInput);
wrap.appendChild(resolutionWrap);
// フレームレート
const framerateWrap = document.createElement('div');
const framerateInput = document.createElement('input');
framerateInput.setAttribute('type', 'number');
framerateInput.value = 60;
framerateInput.min = 10;
framerateInput.max = 60;
framerateInput.addEventListener('change', () => {
framerateInput.value = Math.min(Math.max(framerateInput.value, 10), 60);
}, false);
const framerateCaption = document.createElement('span');
framerateCaption.textContent = 'framerate';
framerateWrap.appendChild(framerateCaption);
framerateWrap.appendChild(framerateInput);
wrap.appendChild(framerateWrap);
// 品質
const qualityWrap = document.createElement('div');
const qualityInput = document.createElement('input');
qualityInput.setAttribute('type', 'number');
qualityInput.value = 100;
qualityInput.min = 10;
qualityInput.max = 100;
qualityInput.addEventListener('change', () => {
qualityInput.value = Math.min(Math.max(qualityInput.value, 0), 100);
}, false);
const qualityCaption = document.createElement('span');
qualityCaption.textContent = 'quality';
qualityWrap.appendChild(qualityCaption);
qualityWrap.appendChild(qualityInput);
wrap.appendChild(qualityWrap);
// 時間指定
const timeWrap = document.createElement('div');
const timeInput = document.createElement('input');
timeInput.setAttribute('type', 'number');
timeInput.value = parseInt(0);
timeInput.min = 0;
timeInput.step = 0.1;
const timeCaption = document.createElement('span');
timeCaption.textContent = 'start time';
timeWrap.appendChild(timeCaption);
timeWrap.appendChild(timeInput);
wrap.appendChild(timeWrap);
// ラジオボタンに変更があった場合の有効・無効
const radioListener = () => {
const flag = typeRadioGif.checked === true || typeRadioWebM.checked === true;
frameInput.disabled = !flag;
framerateInput.disabled = !flag;
qualityInput.disabled = !flag;
};
typeRadioGif.addEventListener('change', radioListener, false);
typeRadioWebM.addEventListener('change', radioListener, false);
typeRadioJpeg.addEventListener('change', radioListener, false);
typeRadioPng.addEventListener('change', radioListener, false);
typeRadioGif.checked = true;
typeRadioWebM.checked = false;
typeRadioJpeg.checked = false;
typeRadioPng.checked = false;
radioListener();
showDialog(wrap, {okLabel: 'start'})
.then((isOk) => {
if(isOk !== true){return;}
if(
isNaN(parseInt(frameInput.value)) === true ||
isNaN(parseInt(widthInput.value)) === true ||
isNaN(parseInt(heightInput.value)) === true ||
isNaN(parseInt(framerateInput.value)) === true ||
isNaN(parseInt(qualityInput.value)) === true ||
false
){
alert('Should not be blank.');
return;
}
// disabled を付与して連続で押せないようにする
download.classList.add('disabled');
// ダウンロードボタンの表記を変えておく
download.textContent = 'generate...';
// エンコード中のフラグを立てておく
isEncoding = true;
// フォーマットを確定する
let formatName = 'gif';
if(typeRadioWebM.checked === true){
formatName = 'webm';
}else if(typeRadioJpeg.checked === true){
formatName = 'jpg';
}else if(typeRadioPng.checked === true){
formatName = 'png';
}
// 各種パラメータを DOM から取得してキャプチャ開始する
setTimeout(() => {
switch(formatName){
case 'gif':
case 'webm':
captureAnimation(
parseInt(frameInput.value),
parseInt(widthInput.value),
parseInt(heightInput.value),
formatName,
parseInt(framerateInput.value),
parseInt(qualityInput.value) * 0.99999,
parseInt(timeInput.value),
);
break;
case 'jpg':
case 'png':
captureImage(
parseInt(timeInput.value),
parseInt(widthInput.value),
parseInt(heightInput.value),
formatName,
parseInt(qualityInput.value) * 0.99999,
);
break;
}
}, 100);
});
}, false);
// リンク生成ボタン
link.addEventListener('click', async () => {
if(link.classList.contains('disabled') === true){return;}
link.classList.add('disabled');
const snapshotLink = await generateSnapshotLink().catch((error) => {
console.error(error);
alert('Failed to create a snapshot. See the console for more info.');
return null;
});
if (snapshotLink != null) {
if (currentChannelId == null) {
// Broadcast中でない場合
// オムニバー(アドレスバー)の状態をシェアリンクと同じ URL に変更
// Broadcast中の場合は、そっちのほうが大事なので、そちらを優先する
history.replaceState('', '', snapshotLink);
// 視聴者数・スター数を消す
// Broadcast中の場合は消さない
hideViewerIcon();
hideStarIcon();
}
// 投稿日時を隠す
clearSnapshotDate();
// クリップボードにコピーし、通知する
copyToClipboard(snapshotLink);
alert('Copied link to the clipboard!');
}
link.classList.remove('disabled');
}, false);
// スクロール同期
syncToggle.addEventListener('change', () => {
syncScroll = syncToggle.checked;
}, false);
// メインとなる fragmen のインスタンス
const option = Object.assign(FRAGMEN_OPTION, {
target: canvas,
eventTarget: window,
});
fragmen = new Fragmen(option);
// シェーダが更新された段階で同時にメッセージを更新
fragmen.onBuild((status, msg) => {
latestStatus = status;
lineout.classList.remove('warn');
lineout.classList.remove('error');
lineout.classList.add(status);
message.textContent = msg;
switch(status){
case 'warn':
case 'error':
download.classList.add('disabled');
link.classList.add('disabled');
break;
default:
download.classList.remove('disabled');
if(latestStatus === 'success' && latestAudioStatus === 'success'){
link.classList.remove('disabled');
}else{
link.classList.add('disabled');
}
}
// 配信中はステータスとは無関係に状態を送る
if(currentChannelId != null && (broadcastMode === 'owner' || broadcastMode === 'friend')){
// グラフィックスを編集する立場かどうか
if(
(broadcastMode === 'owner' && directionMode !== BROADCAST_DIRECTION.SOUND) ||
(broadcastMode === 'friend' && directionMode === BROADCAST_DIRECTION.SOUND)
){
updateGraphicsData(currentDirectorId, currentChannelId, currentMode);
}
}
});
fragmen.onDraw(() => {
let freq = 0.0;
if(musician != null && musician.isPlay === true){
freq += musician.getFrequencyFloat();
}
if(onomat != null && audioToggle.checked === true && latestAudioStatus === 'success'){
freq += onomat.getFrequencyFloat();
}
if(freq > 0.0){
fragmen.setFrequency(freq);
}
});
// デフォルトのメッセージを出力
counter.textContent = `${currentSource.length}`;
message.textContent = ' ● ready';
// レンダリング開始
// currentSourceが空の場合は、BroadcastあるいはSnapshotの待ち状態
if (currentSource !== '') {
fragmen.mode = currentMode;
fragmen.render(currentSource);
}
// WebGL 2.0 に対応しているかどうかによりドロップダウンリストの状態を変更
if(fragmen.isWebGL2 !== true){
for(let i = 0; i < mode.children.length; ++i){
mode.children[i].disabled = Fragmen.MODE_WITH_ES_300.includes(i);
}
}
// サウンドシェーダ関連
audioToggle.addEventListener('change', () => {
onomatSetting();
}, false);
audioPlayIcon.addEventListener('click', () => {
if(audioToggle.checked !== true || latestAudioStatus !== 'success'){return;}
++soundPlay;
updateAudio(audioEditor.getValue(), true);
// 配信中はステータスとは無関係に状態を送る
if(currentChannelId != null && (broadcastMode === 'owner' || broadcastMode === 'friend')){
// グラフィックスを編集する立場かどうか
if(
(broadcastMode === 'owner' && directionMode !== BROADCAST_DIRECTION.GRAPHICS) ||
(broadcastMode === 'friend' && directionMode === BROADCAST_DIRECTION.GRAPHICS)
){
updateSoundData(currentDirectorId, currentChannelId, soundPlay);
}
}
}, false);
audioStopIcon.addEventListener('click', () => {
if(musician != null){musician.stop();}
if(audioToggle.checked !== true){return;}
onomat.stop();
}, false);
window.addEventListener('keydown', (evt) => {
// vim mode
if(
((evt.ctrlKey === true || evt.metaKey === true) && evt.altKey === true) &&
(evt.key === 'v' || evt.key === 'V' || evt.key === '√')
){
vimMode = !vimMode;
if(vimMode === true){
editor.setKeyboardHandler('ace/keyboard/vim');
audioEditor.setKeyboardHandler('ace/keyboard/vim');
}else{
editor.setKeyboardHandler(null);
audioEditor.setKeyboardHandler(null);
}
}
if((evt.ctrlKey === true || evt.metaKey === true) && evt.altKey === true && (evt.key === '†' || evt.key === 't')){
toggleEditorView();
}
if((evt.ctrlKey === true || evt.metaKey === true) && evt.altKey === true && (evt.key === '≤' || evt.key === ',')){
--editorFontSize;
document.querySelector('#editor').style.fontSize = `${editorFontSize}px`;
document.querySelector('#editoraudio').style.fontSize = `${editorFontSize}px`;
}
if((evt.ctrlKey === true || evt.metaKey === true) && evt.altKey === true && (evt.key === '≥' || evt.key === '.')){
++editorFontSize;
document.querySelector('#editor').style.fontSize = `${editorFontSize}px`;
document.querySelector('#editoraudio').style.fontSize = `${editorFontSize}px`;
}
if(evt.key === 'Enter' && evt.altKey === true){
if(evt.ctrlKey === true){
if(musician != null){musician.stop();}
}
}
// onomat
if(audioToggle.checked !== true || latestAudioStatus !== 'success'){return;}
// Alt + Enter で再生、Ctrl をさらに付与すると停止
if(evt.key === 'Enter' && evt.altKey === true){
if(evt.ctrlKey === true){
if(musician != null){musician.stop();}
onomat.stop();
}else{
++soundPlay;
updateAudio(audioEditor.getValue(), true);
// 配信中はステータスとは無関係に状態を送る
if(currentChannelId != null && (broadcastMode === 'owner' || broadcastMode === 'friend')){
// グラフィックスを編集する立場かどうか
if(
(broadcastMode === 'owner' && directionMode !== BROADCAST_DIRECTION.GRAPHICS) ||
(broadcastMode === 'friend' && directionMode === BROADCAST_DIRECTION.GRAPHICS)
){
updateSoundData(currentDirectorId, currentChannelId, soundPlay);
}
}
}
}
}, false);
// デフォルトのメッセージを出力
audioCounter.textContent = `${Onomat.FRAGMENT_SHADER_SOURCE_DEFAULT.length}`;
audioMessage.textContent = ' ● ready';
// フルスクリーン解除時に DOM を元に戻すためのリスナー
const onFullscreenChange = (evt) => {
if(
document.FullscreenElement == null &&
document.webkitFullscreenElement == null &&
document.msFullscreenElement == null
){
// すべての要素が null だった場合、DOM 操作を行いエディタを表示させる
exitFullscreenMode();
}
};
// F11 ではなく、意図的なショートカットキー操作によってフルスクリーンへと移行するためのリスナー
const onFullscreenKeyDown = (evt) => {
if(evt.altKey === true && evt.ctrlKey === true && (evt.key.toLowerCase() === 'f' || evt.key === 'ƒ')){
if(
document.FullscreenElement != null ||
document.webkitFullscreenElement != null ||
document.msFullscreenElement != null
){
// この場合、絶対に JavaScript から fullscreen 化しているので強制的に戻せばよい
// ただし、イベントリスナーによって事後処理が自動的に行われることになるので
// 発火するのは document.exitFullsScreen までで、DOM はここでは操作しない
exitFullscreen();
}else{
// この場合、F11 で既に見た目上は fullscreen 化している可能性がある
// F11 の fullscreen は requestFullscreen 等で fullscreen 化したものとは
// 別物として扱われているが、いずれも Escape で解除できるため注意
requestFullscreenMode();
}
}
};
// アイコンが押されたとき
const onFullscreenRequest = () => {
if(
document.FullscreenElement == null ||
document.webkitFullscreenElement == null ||
document.msFullscreenElement == null
){
requestFullscreenMode();
}
};
// API がサポートされている場合に限りフルスクリーン関連のリスナーを登録する
if(document.fullscreenEnabled === true){
document.addEventListener('fullscreenchange', onFullscreenChange, false);
window.addEventListener('keydown', onFullscreenKeyDown, false);
fullIcon.addEventListener('click', onFullscreenRequest, false);
}else if(document.webkitFullscreenEnabled === true){
document.addEventListener('webkitfullscreenchange', onFullscreenChange, false);
window.addEventListener('keydown', onFullscreenKeyDown, false);
fullIcon.addEventListener('click', onFullscreenRequest, false);
}else{
// いずれでもない場合は API でフルスクリーン化することができないのでアイコンを消す
fullIcon.classList.add('nevershow');
}
// information アイコンが押されたとき
infoIcon.addEventListener('click', () => {
const wrap = document.createElement('div');
const infoHeader = document.createElement('h3');
infoHeader.textContent = 'Information';
const infoCaption = document.createElement('div');
infoCaption.textContent = 'twigl.app is an online editor for One tweet shader, with GIF generator, sound shader, and broadcast live coding.';
wrap.appendChild(infoHeader);
wrap.appendChild(infoCaption);
const modeHeader = document.createElement('h3');
modeHeader.textContent = 'Edit mode';
const modeCaption = document.createElement('div');
const modeMessage = [
'There are four modes in twigl.app, each of which has a sub-mode that uses GLSL ES 3.0, or in addition to it, a mode that enables MRT.',
'classic:',
'This mode is compatible with GLSLSandbox.',
'The uniform variables are "resolution", "mouse", "time", "frame", and "backbuffer".',
'geek:',
'In this mode, the various uniform variables are in a single-character style.',
'"r", "m", "t", "f", and "b", respectively.',
'geeker:',
'In this mode, there is no need to declare precision and uniform. They are automatically complemented on the implementation side. Otherwise, it is the same as in geek mode.',
'geekest:',
'In this mode, the description of "void main(){}" can be omitted (or not), and "gl_FragCoord" can be described as "FC". In addition, a variety of GLSL snippets are available.',
'The reason why we support the notation that does not omit the definition of the main function is to allow users to define their own functions.',
'For more information on snippets, please see below.',
];
modeMessage.forEach((v) => {
const e = document.createElement('div');
e.textContent = v;
modeCaption.appendChild(e);
});
const modeInfoAnchorWrap = document.createElement('div');
const modeInfoAnchor = document.createElement('a');
modeInfoAnchor.setAttribute('href', 'https://github.com/doxas/twigl');
modeInfoAnchor.setAttribute('target', '_blank');
modeInfoAnchor.textContent = 'doxas/twigl - GitHub';
modeInfoAnchorWrap.appendChild(modeInfoAnchor);
modeCaption.appendChild(modeInfoAnchorWrap);
wrap.appendChild(modeHeader);
wrap.appendChild(modeCaption);
const soundHeader = document.createElement('h3');
soundHeader.textContent = 'Sound Shader';
const soundCaption = document.createElement('div');
const soundMessage = [
'Sound Shader is compatible with the great pioneer, Shadertoy.',
'Also, the output from the "mainSound" function can be referred to as a uniform variable with the name "sound" or "s" in various graphics modes.',
];
soundMessage.forEach((v) => {
const e = document.createElement('div');
e.textContent = v;
soundCaption.appendChild(e);
});
wrap.appendChild(soundHeader);