-
Notifications
You must be signed in to change notification settings - Fork 2
/
VNE.js
3320 lines (2775 loc) · 111 KB
/
VNE.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
/**
* アドベンチャーゲームのゲームエンジン
*
* VNE.js
*
* Copyright (c) train12
* http://funprogramming.ojaru.jp
* Licensed under the GPL Version 3 licenses
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//TODO: リファクタリングする
enchant();
function randInt(max){
return Math.floor(Math.random() * max);
}
/**
* sourceのプロパティーの内destにないもののみをコピーする
* @param dest コピー先のオブジェクト
* @param source コピー元のオブジェクト
* @returns {Object}
*/
function setNonExistentProperties(dest, source){
for(const property in source){
if(source.hasOwnProperty(property) && !dest.hasOwnProperty(property))
dest[property] = source[property];
}
return dest;
}
/**
* 単純なJSオブジェクトのコピーを作成する
* @param obj {Object} コピーを作るJSオブジェクト
* @returns コピーされたJSオブジェクト
*/
function clone(obj){
const tmp = setNonExistentProperties({}, obj);
return tmp;
}
/**
* 文字列とRulerに指定したスタイルからその文字列を表示するのに最低限必要な幅と高さを算出する
* @returns {Object} width: 縁(border)を含めた実効範囲の幅
* idealWidth: 実効範囲の理想的な幅(詰まってほしくない時に)
* height: 縁を含めた要素の実効範囲の高さ
* boundingWidth: 縁(border)を除いた幅
* boundingHeight: 縁を除いた高さ
*/
String.prototype.getExpansion = function(){
const e = document.getElementById("ruler");
let c;
while(c = e.lastChild)
e.removeChild(c);
e.innerHTML = this;
// 計算で出した幅きっかりだと、縦に詰まったような表示になることがあるため、表示に適した幅も出す
// プラス10するのは、メインメニューの項目が改行されないようにするため
const expansion = {width : e.clientWidth, idealWidth: e.clientWidth + 5, height : e.clientHeight, boundingWidth: e.offsetWidth, boundingHeight: e.offsetHeight};
e.innerHTML = "";
return expansion;
};
/**
* 独自のスタイルオブジェクトを使用して、CSSのスタイルを設定する。
* @param style {Object} or {string} SystemManager.interpretStyleの結果オブジェクト
*/
function setRulerStyle(style){
const elem = document.getElementById("ruler");
if(typeof(style) === "object"){
// 参照で渡されたオブジェクトを変更して以下の4プロパティを元のオブジェクトに追加してしまわないよう、オブジェクトを複製する
style = clone(style);
style.visibility = "hidden";
style.position = "absolute";
style.whiteSpace = "noWrap";
style.lineHeight = 1;
for(const s in style){
if(s !== "width" && s !== "height" && s !== "display")
elem.style[s] = style[s];
}
}else if(typeof(style) === "string"){
const new_style = "visibility: hidden; position: absolute; white-space: noWrap; line-height: 1; " + style;
elem.setAttribute("style", new_style);
}
}
/**
* 引数の配列内からidに合致するオブジェクトを探しだす
*/
function getObjById(array, id){
let result = null;
array.every(function(obj){
if(obj.id == id){
result = obj;
return false;
}
return true;
});
return result;
}
/**
* 指定した座標がobj内かどうか調べる
*/
function isInArea(obj, x, y){
if(!obj.visible)
return false;
const width = obj.width || obj._domManager.element.offsetWidth, height = obj.height || obj._domManager.element.offsetHeight;
return(obj.x <= x && x < obj.x + width && obj.y <= y && y < obj.y + height);
}
/**
* テンプレート文字列内のプレースホルダー文字列を対応する値に置換する
* @param tmpl {string} 置換対象のプレースホルダー文字列を含む文字列
* @param values {Object|Array} 置換を行うキーを含むハッシュオブジェクト、または置換を行うインデックスを含む配列
*/
function substituteTemplate(tmpl, values){
return tmpl.replace(/\{(.+?)\}/g, function(whole_match, key){
return values[key];
});
}
/**
* CSS形式のプロパティ名(ハイフンあり)からプログラミング言語のプロパティ名(キャメルケース)に変換する
* @param cssName {string} 変換するプロパティ名
* @returns {string} 変換されたプロパティ名
*/
function cssNameToPropertyName(cssName){
const res = cssName.replace(/^[a-zA-Z]+(?:-([a-zA-Z]+))+/g, function(whole_match, after_hyphen){
const pos_after_hyphen = whole_match.indexOf(after_hyphen);
return whole_match.substr(0, pos_after_hyphen - 1) + after_hyphen.charAt(0).toUpperCase() + after_hyphen.substr(1);
});
return res;
}
/**
* 指定されたタブのみをアクティブに変更する
*/
function displayTab(tab_name){
const tab_btns = document.getElementsByClassName("tabButton");
if(tab_name === "game_console" && tab_btns[1].classList.contains("activeTab")
|| tab_name === "enchant-stage" && tab_btns[0].classList.contains("activeTab")){
return;
}
const tabs = document.getElementsByClassName("tab");
for(let i = 0; i < tabs.length; ++i)
tabs[i].style.display = "none";
const activate_tab = document.getElementById(tab_name);
activate_tab.style.display = "block";
for(let j = 0; j < tab_btns.length; ++j)
tab_btns[j].classList.toggle("activeTab");
if(tab_name === "enchant-stage"){
const tab_holder = document.getElementById("tab_holder");
tab_holder.style.display = "none";
}
}
/**
* ページ読み込み完了後にスクリプトを追加で読み込む
*/
function loadScriptLazily(script_path, callback){
const loaded = false;
const head = document.getElementsByTagName("head")[0];
const script_tag = document.createElement("script");
script_tag.src = script_path;
script_tag.onload = function(){
callback();
};
head.appendChild(script_tag);
}
/**
* ページ読み込み完了後にCSSを追加で読み込む
*/
function loadCssLazily(css_path){
const head = document.getElementsByTagName("head")[0];
const link_tag = document.createElement("link");
link_tag.rel = "stylesheet";
link_tag.type = "text/css";
link_tag.href = css_path;
head.appendChild(link_tag);
}
/**
* プレースホルダー文字列をメッセージに含むエラークラス
*/
const TemplateError = enchant.Class.create(Error, {
initialize : function(tmpl, values){
var no_placeholder = substituteTemplate(tmpl, values);
Error.call(this, no_placeholder);
}
});
const msg_tmpls = {
errorMissingTag : "Expected \"{type}\" but there isn't such a tag.",
errorMissingHeader : "A header that is the type of {type} and named {name} is missing!",
errorInvalidExpression : "The expression \"{expr}\" is invalid!",
errorUnknownTag : "Unknown tag name {type}",
errorMissingImageFile : "An image file named {fileName} is missing! Please make sure that the file name or variable name is valid. Or if it is a variable name, please verify that a \"$\" sign is placed before it.",
errorMissingSoundFile : "A sound file named {fileName} is missing! Please make sure that the file name or variable name is valid. Or if it is a variable name, please verify that a \"$\" sign is placed before it.",
errorUnknownOperation : "Unknown operation: {operation}",
errorInvalidJumpString : "Jump strings must be in form 'title:xxx(, ids:yyy)', but actual string was {actual}.",
debugLogMessage : "Currently working on a(n) {type} tag at line {lineNumber} : {column} inside {parentType}",
succeedLoadingMessage : "{path} successfully loaded!",
failedLoadingMessage : "Failed to load {path}; {msg}",
unknownResourceType : "Unknown resource type found; {0}",
loadingSound : "Loading a sound '{path}'...",
loadingBgm : "Loading a bgm '{path}'..."
};
/**
* ゲーム全体の統括を行う。各オブジェクトの画面上に表示する実体のルートオブジェクトでもある。
*/
const SystemManager = enchant.Class.create(Group, {
initialize : function(xml_paths){
enchant.Group.call(this);
const xml_manager = new XmlManager(xml_paths[0].file_name, this), msg_manager = new MessageManager(this, xml_manager);
const log_manager = new LogManager(this, xml_manager);
const console_manager = new ConsoleManager(this);
const path_header = xml_manager.getHeader("paths"), paths = xml_manager.getVarStore().getVar("paths");
game._debug = (xml_manager.getVarStore().getVar("settings.is_debug") == "true");
xml_manager.getVarStore().setVar("file_paths", xml_paths);
xml_manager.addDefaultOptions({auto_scroll_delta : 60, sound_bgm : 0.5, sound_se : 0.5, sound_ope : 0.5, text_speed : 0.5});
const managers = {
xml : xml_manager,
message : msg_manager,
tag : new TagManager(this, xml_manager, msg_manager, log_manager),
label : new LabelManager(this),
sound : new SoundManager(this),
effect : new EffectManager(this),
log : log_manager,
input : new InputManager(this),
image : new ImageManager(this),
choices : new ChoicesManager(this),
console : console_manager
};
if(!localStorage.getItem("save"))
localStorage.setItem("save", JSON.stringify([]));
const array = [];
for(const name in managers){
if(managers.hasOwnProperty(name))
array.push(managers[name]);
}
this.loadResources = function(path_header, paths){
const audio = new Audio();
const success_func = function(path, e){
console_manager.logFormatted(msg_tmpls.succeedLoadingMessage, {path: path});
game.assets[path] = e.target;
};
const error_func = function(path, e){
console_manager.logFormatted(msg_tmpls.failedLoadingMessage, {path: path, msg: e.message});
};
for(const name in path_header){ //各種リソースファイルを読み込む
if(name !== "type" && path_header.hasOwnProperty(name)){
const path_obj = path_header[name];
const path = path_obj.value;
switch(path_obj.kind){
case "sound":
const mime_type = "audio/" + enchant.Core.findExt(path);
if(game._debug)
console_manager.logFormatted(msg_tmpls.loadingSound, {path: path});
game.assets[path] = enchant.WebAudioSound.load(path, mime_type, success_func.bind(null, path), error_func.bind(null, path));
break;
case "bgm":
if(path.search(/.ogg/) !== -1 && !audio.canPlayType("audio/ogg")){
path = path.replace(/.ogg/, ".wav");
path_header[name].value = path;
paths[name] = path;
}
if(game._debug)
console_manager.logFormatted(msg_tmpls.loadingBgm, {path: path});
game.assets[path] = enchant.DOMSound.load(path, null, success_func.bind(null, path), error_func.bind(null, path));
break;
case "image":
game.load(path);
break;
default:
console_manager.log(msg_tmpls.unknownResourceType, [path]);
}
}
}
};
this.loadResources(path_header, paths);
this.reset = function(){
array.forEach(function(manager){
manager.reset();
});
};
this.setManager = function(name, manager){
const prev_manager = managers.xml, index = array.indexOf(prev_manager);
managers[name] = manager;
array.splice(index, 1, manager);
};
this.getManager = function(name){
return managers[name];
};
this.update = function(){
managers.xml.setCurrentTimeToVarStore(); //variable_storeの現在時刻を更新
array.forEach(function(manager){
manager.update();
});
};
this.showNoticeLabel = function(text, tag_obj){
tag_obj.should_be_front = true;
managers.label.add(text, tag_obj, tag_obj.end_time);
};
this.makeAllManagerDisabled = function(){
array.forEach(function(manager){
manager.is_available = false;
});
};
},
interpretStyle : function(str){ //CSS形式で記述されたスタイル指定文字列を解析してプロパティー名をキー、その設定を値とするオブジェクトに変換する
str = this.getManager("xml").replaceVars(str);
const style = {};
while(str){
let result;
if(result = str.match(/^[ \t]+/)){
}else if((result = str.match(/^([\w\-]+)\s*:\s*([^;]+);?/)) && result[1] !== "position"){
const property_name = cssNameToPropertyName(result[1]);
style[property_name] = result[2];
}
str = str.slice(result[0].length);
}
return style;
},
setStyleOnEnchantObject : function(obj, style_name, style){
if(style_name in obj)
obj[style_name] = style;
else if(obj._domManager)
obj._domManager.style[style_name] = style;
else
obj._style[style_name] = style;
},
/**
* 引数で与えられた位置にある一番手前のオブジェクトにイベントを発行する
*/
dispatchEventAt : function(e, x, y){
for(let nodes = this.childNodes, i = nodes.length - 1; i >= 0; --i){
const node = nodes[i];
if(isInArea(node, x, y)){
node.dispatchEvent(e);
return;
}
}
game.currentScene.dispatchEvent(e); //自分の子供に引数の位置に合致するオブジェクトがなかったので、ディスプレイがタッチされたとみなす
},
/**
* indexの次の位置にnodeを挿入する
*/
insertChildAfter : function(node, index){
const ref = this.childNodes[index];
this.insertBefore(node, ref);
}
});
/**
* 各機能を取り扱うManagerの基底クラス
*/
const Manager = enchant.Class.create({
initialize : function(system){
this.is_available = true; //このManagerが有効かどうか。falseの間は、updateを呼ばれても何もしない
this.system = system; //SystemManagerへの参照
}
});
/**
* Xmlを取り扱う
*/
const XmlManager = enchant.Class.create(Manager, {
initialize : function(url, system){
Manager.call(this, system);
this.tag_manager = null;
this.console_manager = null;
const http_obj = new XMLHttpRequest();
var contents = [], headers = [], jump_table = {};
let variable_store = new VarStore(), now = new Date(), expresso = new ExpressoMin(variable_store);
variable_store.setVar("time", { //predefined変数を追加する
year : now.getFullYear(),
month : now.getMonth() + 1,
date : now.getDate(),
day : now.getDay(),
hours : now.getHours(),
mins : now.getMinutes(),
secs : now.getSeconds(),
millis : now.getTime()
}, true);
variable_store.setVar("now", {
year : now.getFullYear(),
month : now.getMonth() + 1,
date : now.getDate(),
day : now.getDay(),
hours : now.getHours(),
mins : now.getMinutes(),
secs : now.getSeconds(),
millis : now.getTime()
}, true);
variable_store.setVar("display", {width : game.width, height : game.height}, true);
variable_store.setVar("cur_frame", 0, true);
this.next_updating_time = now.getTime() + 1000;
const _self = this;
http_obj.onload = function(){
let text = http_obj.responseText.replace(/[\t\r]+/g, ""), split = {};
const total_num_lines = text.split(/[\n]/).length - 1;
const squeezeValues = function(elem){ //この要素のアトリビュートをすべて絞り出す
const obj = {};
for(let attrs = elem.attributes, i = 0; i < attrs.length; ++i)
obj[attrs[i].name] = attrs[i].value;
return obj;
};
const notHaveTrailingCp = function(elem, remaining_text, content){
// タグの末尾にcpタグがないのは、まだテキストが続いているか、最後のタグがcpタグでない場合
return elem.tagName.search(/label|log|text|menu|choice/) == -1 &&
(remaining_text.length && remaining_text.search(/[^\s]/) !== -1 || content[content.length - 1].type !== "cp");
};
const calculateLineNumber = function(tag_name, next_index, tag_pos){
const lines = split[tag_name].texts[next_index].split("\n");
if(tag_pos)
tag_pos.column = lines[lines.length - 1].length + 1; // +1するのは、単位を文字数ではなく、文字目にするため
return split[tag_name].lineNumber + lines.length - 1;
};
const createObjFromChild = function(type, obj, elem, parent){ //DOMツリーをたどってタグをオブジェクト化する
if(!elem)
return obj;
const child_obj = squeezeValues(elem);
if(typeof split[elem.tagName] === "undefined"){
const texts = text.split(new RegExp("<" + elem.tagName + "(?: [^>]+)?/?>"));
const lines = texts[0].split("\n");
split[elem.tagName] = {
texts : texts,
lineNumber : lines.length,
column : lines[lines.length - 1].length + 1, // +1するのは、単位を文字数ではなく、文字目にするため
nextIndex : 1
};
}
const split_obj = split[elem.tagName];
child_obj.lineNumber = split_obj.lineNumber;
child_obj.column = split_obj.column;
if(split_obj.nextIndex < split_obj.texts.length){
const tag_pos = {column : 0};
split_obj.lineNumber = calculateLineNumber(elem.tagName, split_obj.nextIndex, tag_pos);
split_obj.column = tag_pos.column;
}
if(elem.tagName === "scene") //sceneタグは入れ子になるので、子オブジェクトを探す前にnextIndexをインクリメントする
++split["scene"].nextIndex;
if(elem.childElementCount !== 0){
const content = createObjFromChild(type, [], elem.firstElementChild, child_obj);
if(type !== "header" && elem.tagName !== "scene"){ //scene以外のコンテナ要素の子要素の位置を記録する
let container_text = "";
let container_text_content = split[elem.tagName].texts[split[elem.tagName].nextIndex].replace(/[\n]/g, "");
content.forEach(function(tag){
const result = container_text_content.match(/(<\/?)([^\s>\/]+)/), result2 = container_text_content.match(/>/);
const before_tag_text = container_text_content.substring(0, result.index);
if(result !== null && result2 !== null && result[2] == tag.type){
container_text_content = container_text_content.slice(result2.index + 1);
}else{
_self.console_manager.log(msg_tmpls.errorMissingTag, {type : tag.type});
throw new Error();
}
// ここでコンテナ要素の子要素の位置を設定するのは、下記の方法では、他のタグの影響を受けたカラム番号が記録されてしまうため
tag.pos = result.index;
const close_tag_name = "</" + tag.type + ">", end_tag = container_text_content.match(close_tag_name);
if(end_tag !== null){
container_text_content = container_text_content.slice(end_tag.index + close_tag_name.length);
}
container_text = container_text.concat(before_tag_text);
});
child_obj.text = container_text;
var remaining_text = container_text_content.split("</" + elem.tagName + ">")[0];
}
child_obj.children = content;
}
if(elem.tagName !== "scene")
++split[elem.tagName].nextIndex;
child_obj.type = elem.tagName;
if(typeof parent !== "undefined")
child_obj.parent = parent;
if(elem.textContent.length !== 0 && elem.childElementCount === 0){
child_obj.text = elem.textContent.replace(/[\t\n\r]+/g, "");
child_obj.debugText = elem.textContent.replace(/[\r]/g, "");
}else if(elem.textContent.length === 0){
child_obj.text = "";
child_obj.debugText = "";
}
obj.push(child_obj);
return createObjFromChild(type, obj, elem.nextElementSibling, parent);
};
const createJumpTable = function(objs, table, index){ //sceneオブジェクトのインデックスを記録したハッシュテーブルを作成する
if(index == objs.length)
return table;
if(objs[index].type == "scene"){
if(objs[index].title){
table[objs[index].title] = (objs[index].children) ? {index : index, children : createJumpTable(objs[index].children, {}, 0)} :
{index : index};
}else{
table[objs[index].id] = (objs[index].children) ? {index : index, children : createJumpTable(objs[index].children, {}, 0)} :
{index : index};
}
}
return createJumpTable(objs, table, index + 1);
};
const xml = http_obj.responseXML, doc = xml.documentElement;
const header_elem = doc.getElementsByTagName("header")[0];
headers = createObjFromChild("header", [], header_elem.firstElementChild, undefined);
headers.forEach(function(header, index, array){ //ヘッダー部分の要素をオブジェクトの形に変換する
if(header.type.search(/profile|style/) == -1 || header.children){
const original = array[index];
array[index] = {type : header.type};
if(header.type == "profile"){
array[index].name = original.name;
array[index].src = original.src;
array[index].style = original.style;
array[index].frame_width = original.frame_width;
array[index].charaname_window_height = parseFloat(original.charaname_window_height);
}
header.children.forEach(function(child){
const name = child.name, value = child.text;
if(header.type === "paths")
array[index][name] = {kind: child.kind, value: child.text};
else
array[index][name] = value;
switch(header.type){
case "characters" :
case "colors" :
variable_store.setVar(name + "." + child.type, value);
break;
case "paths" :
case "settings" :
variable_store.setVar(header.type + "." + name, value);
break;
case "variables" :
variable_store.setVar(name, (text.search(/^\d*.?\d*$/) != -1) ? parseFloat(value) : value);
break;
case "profile" :
variable_store.setVar(header.name + "." + name, value);
break;
}
});
}
});
split = {};
contents = createObjFromChild("body", contents, header_elem.nextElementSibling, null);
const body = {type : "root", children : contents};
contents.forEach(function(content){
content.parent = body;
});
jump_table = createJumpTable(contents, {}, 0);
};
// パフォーマンスに関する警告が出るが、syncにしないと他のマネージャクラスの初期化に影響が出るので、asyncにはできない
http_obj.open("get", url, false);
http_obj.send(null);
this.first_tag = contents[0];
this.reset = function(){
this.tag_manager.setNextTag(this.first_tag);
};
const getSceneImpl = function(objs, table, ids, level){
const tmp_tbl = table[ids[level]];
const tmp = objs[tmp_tbl.index];
if(level == ids.length - 1) return tmp;
return getSceneImpl(tmp.children, tmp_tbl.children, ids, level + 1);
};
this.getScene = function(str){
const result = str.replace(/\s/g, "").replace(/\\s/g, " ").match(/title:([^,]+)(?:,ids:((?:[^,]+,?)+))?/);
if(!result)
throw new TemplateError(msg_tmpls.errorInvalidJumpString, {actual: str});
const title = result[1], ids = result[2] && result[2].split(",");
const tmp_tbl = jump_table[title];
const tmp = contents[tmp_tbl.index];
if(!ids || typeof ids[0] === "undefined") return tmp;
return getSceneImpl(tmp.children, tmp_tbl.children, ids, 0);
};
this.getHeader = function(type_name, name){
let header_obj = null;
headers.every(function(header){
if(header.type == type_name && (typeof name === "undefined" || header.name == name)){
header_obj = header;
return false;
}
return true;
});
if(!header_obj)
throw new TemplateError(msg_tmpls.errorMissingHeader, {type: type_name, name : name});
return header_obj;
};
this.getVarStore = function(){
return variable_store;
};
const replaceVarImpl = function(str, name){
return variable_store.getVar(name);
};
this.replaceVars = function(str){
return str.replace(/\$([^\s;]+)/g, replaceVarImpl);
};
this.interpretExpression = function(expr){
const result = expresso.evaluate(expr);
if(!result){
if(game._debug){
if(!this.console_manager) this.console_manager = this.system.getManager("console");
this.console_manager.log(expresso.stringifyErrors());
}
throw new TemplateError(msg_tmpls.errorInvalidExpression, {expr : expr});
}
return result.value;
};
this.setCurrentTimeToVarStore = function(){
if(game.currentTime >= this.next_updating_time){ //$now.millis以外はほぼ1秒ごとに更新する
const now = new Date();
variable_store.setVar("now", {
year : now.getFullYear(),
month : now.getMonth() + 1,
date : now.getDate(),
day : now.getDay(),
hours : now.getHours(),
mins : now.getMinutes(),
secs : now.getSeconds()
}, true);
this.next_updating_time = game.currentTime + 1000;
}
variable_store.setVar("now.millis", game.currentTime, true);
variable_store.setVar("cur_frame", game.frame, true);
};
this.save = function(tag){
this.saveOptions();
let scene = tag;
for(; scene.type != "scene"; scene = scene.parent) ;
const ids = [];
for(; !scene.title; scene = scene.parent){
if(scene.id)
ids.push(scene.id);
}
const save_data = {scene_str : `title:${scene.title.replace(/ /g, "\\s")},ids:${ids.reverse()}`};
return save_data;
};
this.saveOptions = function(){
const options = variable_store.getVar("options");
localStorage.setItem("options", JSON.stringify(options));
};
this.load = function(data){
this.loadOptions();
const scene = this.getScene(data.scene_str);
this.is_available = false;
return scene;
};
this.loadOptions = function(){
const options = JSON.parse(localStorage.getItem("options"));
variable_store.setVar("options", options);
};
this.addDefaultOptions = function(options){ //loadOptionsで読み込まれなかった設定に対してデフォルト値を設定する
if(!variable_store.getVar("options"))
variable_store.setVar("options", {});
const old_options = variable_store.getVar("options");
const new_options = setNonExistentProperties(old_options, options);
variable_store.setVar("options", new_options);
};
this.updateOptions = function(options){
options.forEach(function(option){
variable_store.setVar(`options.${option.name}`, option.value);
}, this);
};
this.getUrl = function(){
return url;
};
this.loadOptions();
},
update : function(){
if(!this.is_available)
return;
if(!this.tag_manager) this.tag_manager = this.system.getManager("tag");
this.tag_manager.setNextTag(this.first_tag);
this.is_available = false;
}
});
/**
* メイン画面の下に表示されるメッセージウインドウを管理するクラス
* メッセージウインドウに表示するテキストも管理していてそのテキストは一旦キューに追加した後、updateを呼ばれた際に
* メッセージウインドウに追加するようになっている。
*/
const MessageManager = enchant.Class.create(Manager, {
initialize : function(system, xml_manager){
Manager.call(this, system);
let pre_line_text = "";
this.setPreLineText = function(line_text){
pre_line_text = pre_line_text.concat(line_text);
};
this.getPreLineText = function(){
const tmp = pre_line_text;
pre_line_text = "";
return tmp;
};
this.msgs = "";
this.msg_window = new enchant.DomLayer();
this.msg_window.moveTo(0, Math.round(game.height * 2 / 3));
this.msg_window.width = game.width;
this.msg_window.height = Math.round(game.height / 3);
this.msg_window.onClicked = function(e){
game.input.a = true;
};
this.msg_window.onHeld = function(e){
game.input.b = true;
}
this.chara_name_window = new enchant.Label("");
this.chara_name_window.moveTo(50, this.msg_window.y - 18);
this.chara_name_window.updateBoundArea();
this.chara_name_window.visible = false;
system.addChild(this.msg_window);
system.addChild(this.chara_name_window);
xml_manager.getVarStore().setVar("msg_window", {
x : this.msg_window.x,
y : this.msg_window.y,
width : this.msg_window.width,
height : this.msg_window.height
}, true);
this.xml_manager = xml_manager;
this.tag_manager = null;
this.cur_text_y = 0;
this.initial_text_y = 0; //テキストを表示する初期位置のy座標
this.cur_text_appending_element = this.msg_window._element; //現在テキストを追加していくタグ
},
reset : function(){
this.xml_manager = this.system.getManager("xml");
this.system.removeChild(this.msg_window);
this.msg_window = new enchant.DomLayer();
this.msg_window.moveTo(0, Math.round(game.height * 2 / 3));
this.msg_window.width = game.width;
this.msg_window.height = Math.round(game.height / 3);
this.msg_window.onClicked = function(){
game.input.a = true;
};
this.msg_window.onHeld = function(){
game.input.b = true;
};
this.xml_manager.getVarStore().setVar("msg_window", {
x : this.msg_window.x,
y : this.msg_window.y,
width : this.msg_window.width,
height : this.msg_window.height
}, true);
this.cur_text_appending_element = this.msg_window._element;
this.system.addChild(this.msg_window);
this.msgs = "";
this.chara_name_window.text = "";
this.makeMsgWindowVisible(true);
},
setText : function(text){
this.msg_window._element.appendChild(document.createTextNode(text));
this.msg_window._element.normalize();
},
setStyle : function(tag){
const style = tag.style || this.xml_manager.getHeader("profile", tag.chara).style;
const style_obj = this.system.interpretStyle(style);
for(let s in style_obj){
if(s === "width" || s === "height" || s === "left" || s === "top")
continue;
if(s === "backgroundColor"){ //メッセージウインドウの背景は自動で透かす
const rgb = style_obj[s].match(/(\d+)(?!\.)|(\d+\.\d+)/g);
if(rgb.length !== 4){
rgb[3] = 0.6;
style_obj[s] = "rgba(" + rgb.join(",") + ")";
}
}
this.msg_window._element.style[s] = style_obj[s];
this.system.setStyleOnEnchantObject(this.chara_name_window, s, style_obj[s]);
}
},
msgWindowIsVisible : function(){
return this.msg_window.visible;
},
clearChildNodes : function(){
while(this.msg_window._element.firstChild)
this.msg_window._element.removeChild(this.msg_window._element.firstChild);
},
appendChildNode : function(node){
return this.msg_window._element.appendChild(node);
},
getDiffTextPos : function(text){
// ここで反映させるのはfontの値だけでいい
setRulerStyle("font: " + this.cur_text_appending_element.style.font);
this.cur_text_appending_element = this.msg_window._element;
const is_line_empty = (text.length === 0);
if(is_line_empty)
text = "ダミー";
const expansion = text.getExpansion();
if(is_line_empty)
expansion.width = 0;
expansion.width += this.msg_window._element.clientLeft;
return expansion;
},
setPosition : function(tag){
if(tag.type == "narrativef"){
this.msg_window.y = 0;
this.msg_window.height = game.height;
this.initial_text_y = this.msg_window._element.clientTop;
}else{
if(this.msg_window.y == 0){
this.msg_window.y = Math.round(game.height * 2 / 3);
this.msg_window.height = Math.round(game.height / 3);
}
this.initial_text_y = this.msg_window.y + this.msg_window._element.clientTop;
}
if(this.msg_window.y + this.msg_window._domManager.element.offsetHeight != game.height){ //メッセージウインドウの大きさを微調整する
const margin_height = game.height - this.msg_window.y;
this.msg_window.height = margin_height + (this.msg_window.height - this.msg_window._domManager.element.offsetHeight);
this.xml_manager.getVarStore().setVar("msg_window.height", this.msg_window.height, true);
}
if(this.msg_window._domManager.element.offsetWidth != game.width){
this.msg_window.width = game.width + (this.msg_window.width - this.msg_window._domManager.element.offsetWidth);
this.xml_manager.getVarStore().setVar("msg_window.width", this.msg_window.width, true);
}
this.cur_text_y = this.initial_text_y;
},
makeMsgWindowVisible : function(is_visible){
this.msg_window.visible = is_visible;
this.chara_name_window.visible = (this.msg_window.y == 0 || this.chara_name_window.text.length == 0) ? false : this.msg_window.visible;
//this.tag_manager.makeBrIconVisible(this.msg_window.visible);
},
setCurTextY : function(pos){
this.cur_text_y = pos;
},
setTextAppendingElem : function(elem){
this.cur_text_appending_element = elem;
},
makeCharaNameWindowVisible : function(is_visible, tag){
if(is_visible){
const chara_names = this.xml_manager.getHeader("characters");
const charaname_window_height = this.xml_manager.getHeader("profile", tag.chara).charaname_window_height;
this.chara_name_window.text = chara_names[tag.chara];
this.chara_name_window.visible = true;
setRulerStyle(this.chara_name_window._domManager.style);
const expansion = this.chara_name_window.text.getExpansion();
this.chara_name_window.width = expansion.idealWidth;
if(isNaN(charaname_window_height))
this.chara_name_window.height = expansion.height;
else
this.chara_name_window.height = charaname_window_height;