/
J3MLoader.java
910 lines (795 loc) · 36.1 KB
/
J3MLoader.java
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
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.material.plugins;
import com.jme3.material.logic.MultiPassLightingLogic;
import com.jme3.material.logic.SinglePassLightingLogic;
import com.jme3.material.logic.DefaultTechniqueDefLogic;
import com.jme3.asset.*;
import com.jme3.material.*;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.material.RenderState.FaceCullMode;
import com.jme3.material.TechniqueDef.LightMode;
import com.jme3.material.TechniqueDef.ShadowMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.shader.DefineList;
import com.jme3.shader.Shader;
import com.jme3.shader.VarType;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture2D;
import com.jme3.texture.image.ColorSpace;
import com.jme3.util.PlaceholderAssets;
import com.jme3.util.blockparser.BlockLanguageParser;
import com.jme3.util.blockparser.Statement;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class J3MLoader implements AssetLoader {
private static final Logger logger = Logger.getLogger(J3MLoader.class.getName());
// private ErrorLogger errors;
private ShaderNodeLoaderDelegate nodesLoaderDelegate;
boolean isUseNodes = false;
private AssetManager assetManager;
private AssetKey key;
private MaterialDef materialDef;
private Material material;
private TechniqueDef technique;
private RenderState renderState;
private ArrayList<String> presetDefines = new ArrayList<String>();
private EnumMap<Shader.ShaderType, String> shaderLanguages;
private EnumMap<Shader.ShaderType, String> shaderNames;
private static final String whitespacePattern = "\\p{javaWhitespace}+";
public J3MLoader() {
shaderLanguages = new EnumMap<>(Shader.ShaderType.class);
shaderNames = new EnumMap<>(Shader.ShaderType.class);
}
// <TYPE> <LANG> : <SOURCE>
private void readShaderStatement(String statement) throws IOException {
String[] split = statement.split(":");
if (split.length != 2) {
throw new IOException("Shader statement syntax incorrect" + statement);
}
String[] typeAndLang = split[0].split(whitespacePattern);
if (typeAndLang.length != 2) {
throw new IOException("Shader statement syntax incorrect: " + statement);
}
for (Shader.ShaderType shaderType : Shader.ShaderType.values()) {
if (typeAndLang[0].equals(shaderType.toString() + "Shader")) {
readShaderDefinition(shaderType, split[1].trim(), typeAndLang[1]);
}
}
}
private void readShaderDefinition(Shader.ShaderType shaderType, String name, String language) {
shaderNames.put(shaderType, name);
shaderLanguages.put(shaderType, language);
}
// LightMode <MODE>
private void readLightMode(String statement) throws IOException{
String[] split = statement.split(whitespacePattern);
if (split.length != 2){
throw new IOException("LightMode statement syntax incorrect");
}
LightMode lm = LightMode.valueOf(split[1]);
technique.setLightMode(lm);
}
// ShadowMode <MODE>
private void readShadowMode(String statement) throws IOException{
String[] split = statement.split(whitespacePattern);
if (split.length != 2){
throw new IOException("ShadowMode statement syntax incorrect");
}
ShadowMode sm = ShadowMode.valueOf(split[1]);
technique.setShadowMode(sm);
}
private List<String> tokenizeTextureValue(final String value) {
final List<String> matchList = new ArrayList<String>();
final Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
final Matcher regexMatcher = regex.matcher(value.trim());
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
matchList.add(regexMatcher.group(2));
} else {
matchList.add(regexMatcher.group());
}
}
return matchList;
}
private List<TextureOptionValue> parseTextureOptions(final List<String> values) {
final List<TextureOptionValue> matchList = new ArrayList<TextureOptionValue>();
if (values.isEmpty() || values.size() == 1) {
return matchList;
}
// Loop through all but the last value, the last one is going to be the path.
for (int i = 0; i < values.size() - 1; i++) {
final String value = values.get(i);
final TextureOption textureOption = TextureOption.getTextureOption(value);
if (textureOption == null && !value.contains("\\") && !value.contains("/") && !values.get(0).equals("Flip") && !values.get(0).equals("Repeat")) {
logger.log(Level.WARNING, "Unknown texture option \"{0}\" encountered for \"{1}\" in material \"{2}\"", new Object[]{value, key, material.getKey().getName()});
} else if (textureOption != null){
final String option = textureOption.getOptionValue(value);
matchList.add(new TextureOptionValue(textureOption, option));
}
}
return matchList;
}
private boolean isTexturePathDeclaredTheTraditionalWay(final List<TextureOptionValue> optionValues, final String texturePath) {
final boolean startsWithOldStyle = texturePath.startsWith("Flip Repeat ") || texturePath.startsWith("Flip ") ||
texturePath.startsWith("Repeat ") || texturePath.startsWith("Repeat Flip ");
if (!startsWithOldStyle) {
return false;
}
if (optionValues.size() == 1 && (optionValues.get(0).textureOption == TextureOption.Flip || optionValues.get(0).textureOption == TextureOption.Repeat)) {
return true;
} else if (optionValues.size() == 2 && optionValues.get(0).textureOption == TextureOption.Flip && optionValues.get(1).textureOption == TextureOption.Repeat) {
return true;
} else if (optionValues.size() == 2 && optionValues.get(0).textureOption == TextureOption.Repeat && optionValues.get(1).textureOption == TextureOption.Flip) {
return true;
}
return false;
}
private Texture parseTextureType(final VarType type, final String value) {
final List<String> textureValues = tokenizeTextureValue(value);
final List<TextureOptionValue> textureOptionValues = parseTextureOptions(textureValues);
TextureKey textureKey = null;
// If there is only one token on the value, it must be the path to the texture.
if (textureValues.size() == 1) {
textureKey = new TextureKey(textureValues.get(0), false);
} else {
String texturePath = value.trim();
// If there are no valid "new" texture options specified but the path is split into several parts, lets parse the old way.
if (isTexturePathDeclaredTheTraditionalWay(textureOptionValues, texturePath)) {
boolean flipY = false;
if (texturePath.startsWith("Flip Repeat ") || texturePath.startsWith("Repeat Flip ")) {
texturePath = texturePath.substring(12).trim();
flipY = true;
} else if (texturePath.startsWith("Flip ")) {
texturePath = texturePath.substring(5).trim();
flipY = true;
} else if (texturePath.startsWith("Repeat ")) {
texturePath = texturePath.substring(7).trim();
}
// Support path starting with quotes (double and single)
if (texturePath.startsWith("\"") || texturePath.startsWith("'")) {
texturePath = texturePath.substring(1);
}
// Support path ending with quotes (double and single)
if (texturePath.endsWith("\"") || texturePath.endsWith("'")) {
texturePath = texturePath.substring(0, texturePath.length() - 1);
}
textureKey = new TextureKey(texturePath, flipY);
}
if (textureKey == null) {
textureKey = new TextureKey(textureValues.get(textureValues.size() - 1), false);
}
// Apply texture options to the texture key
if (!textureOptionValues.isEmpty()) {
for (final TextureOptionValue textureOptionValue : textureOptionValues) {
textureOptionValue.applyToTextureKey(textureKey);
}
}
}
switch (type) {
case Texture3D:
textureKey.setTextureTypeHint(Texture.Type.ThreeDimensional);
break;
case TextureArray:
textureKey.setTextureTypeHint(Texture.Type.TwoDimensionalArray);
break;
case TextureCubeMap:
textureKey.setTextureTypeHint(Texture.Type.CubeMap);
break;
}
textureKey.setGenerateMips(true);
Texture texture;
try {
texture = assetManager.loadTexture(textureKey);
} catch (AssetNotFoundException ex){
logger.log(Level.WARNING, "Cannot locate {0} for material {1}", new Object[]{textureKey, key});
texture = null;
}
if (texture == null){
texture = new Texture2D(PlaceholderAssets.getPlaceholderImage(assetManager));
texture.setKey(textureKey);
texture.setName(textureKey.getName());
}
// Apply texture options to the texture
if (!textureOptionValues.isEmpty()) {
for (final TextureOptionValue textureOptionValue : textureOptionValues) {
textureOptionValue.applyToTexture(texture);
}
}
return texture;
}
private Object readValue(final VarType type, final String value) throws IOException{
if (type.isTextureType()) {
return parseTextureType(type, value);
} else {
String[] split = value.trim().split(whitespacePattern);
switch (type){
case Float:
if (split.length != 1){
throw new IOException("Float value parameter must have 1 entry: " + value);
}
return Float.parseFloat(split[0]);
case Vector2:
if (split.length != 2){
throw new IOException("Vector2 value parameter must have 2 entries: " + value);
}
return new Vector2f(Float.parseFloat(split[0]),
Float.parseFloat(split[1]));
case Vector3:
if (split.length != 3){
throw new IOException("Vector3 value parameter must have 3 entries: " + value);
}
return new Vector3f(Float.parseFloat(split[0]),
Float.parseFloat(split[1]),
Float.parseFloat(split[2]));
case Vector4:
if (split.length != 4){
throw new IOException("Vector4 value parameter must have 4 entries: " + value);
}
return new ColorRGBA(Float.parseFloat(split[0]),
Float.parseFloat(split[1]),
Float.parseFloat(split[2]),
Float.parseFloat(split[3]));
case Int:
if (split.length != 1){
throw new IOException("Int value parameter must have 1 entry: " + value);
}
return Integer.parseInt(split[0]);
case Boolean:
if (split.length != 1){
throw new IOException("Boolean value parameter must have 1 entry: " + value);
}
return Boolean.parseBoolean(split[0]);
default:
throw new UnsupportedOperationException("Unknown type: "+type);
}
}
}
// <TYPE> <NAME> [ "(" <FFBINDING> ")" ] [-LINEAR] [ ":" <DEFAULTVAL> ]
private void readParam(String statement) throws IOException{
String name;
String defaultVal = null;
ColorSpace colorSpace = null;
String[] split = statement.split(":");
// Parse default val
if (split.length == 1){
// Doesn't contain default value
}else{
if (split.length != 2){
throw new IOException("Parameter statement syntax incorrect");
}
statement = split[0].trim();
defaultVal = split[1].trim();
}
if (statement.endsWith("-LINEAR")) {
colorSpace = ColorSpace.Linear;
statement = statement.substring(0, statement.length() - "-LINEAR".length());
}
// Parse ffbinding
int startParen = statement.indexOf("(");
if (startParen != -1){
// get content inside parentheses
int endParen = statement.indexOf(")", startParen);
String bindingStr = statement.substring(startParen+1, endParen).trim();
// don't care about bindingStr
statement = statement.substring(0, startParen);
}
// Parse type + name
split = statement.split(whitespacePattern);
if (split.length != 2){
throw new IOException("Parameter statement syntax incorrect");
}
VarType type;
if (split[0].equals("Color")){
type = VarType.Vector4;
}else{
type = VarType.valueOf(split[0]);
}
name = split[1];
Object defaultValObj = null;
if (defaultVal != null){
defaultValObj = readValue(type, defaultVal);
}
if(type.isTextureType()){
materialDef.addMaterialParamTexture(type, name, colorSpace);
}else{
materialDef.addMaterialParam(type, name, defaultValObj);
}
}
private void readValueParam(String statement) throws IOException{
// Use limit=1 incase filename contains colons
String[] split = statement.split(":", 2);
if (split.length != 2){
throw new IOException("Value parameter statement syntax incorrect");
}
String name = split[0].trim();
// parse value
MatParam p = material.getMaterialDef().getMaterialParam(name);
if (p == null){
throw new IOException("The material parameter: "+name+" is undefined.");
}
Object valueObj = readValue(p.getVarType(), split[1]);
if (p.getVarType().isTextureType()){
material.setTextureParam(name, p.getVarType(), (Texture) valueObj);
}else{
material.setParam(name, p.getVarType(), valueObj);
}
}
private void readMaterialParams(List<Statement> paramsList) throws IOException{
for (Statement statement : paramsList){
readParam(statement.getLine());
}
}
private void readExtendingMaterialParams(List<Statement> paramsList) throws IOException{
for (Statement statement : paramsList){
readValueParam(statement.getLine());
}
}
private void readWorldParams(List<Statement> worldParams) throws IOException{
for (Statement statement : worldParams){
technique.addWorldParam(statement.getLine());
}
}
private boolean parseBoolean(String word){
return word != null && word.equals("On");
}
private void readRenderStateStatement(Statement statement) throws IOException{
String[] split = statement.getLine().split(whitespacePattern);
if (split[0].equals("Wireframe")){
renderState.setWireframe(parseBoolean(split[1]));
}else if (split[0].equals("FaceCull")){
renderState.setFaceCullMode(FaceCullMode.valueOf(split[1]));
}else if (split[0].equals("DepthWrite")){
renderState.setDepthWrite(parseBoolean(split[1]));
}else if (split[0].equals("DepthTest")){
renderState.setDepthTest(parseBoolean(split[1]));
}else if (split[0].equals("Blend")){
renderState.setBlendMode(BlendMode.valueOf(split[1]));
}else if (split[0].equals("AlphaTestFalloff")){
// Ignore for backwards compatbility
}else if (split[0].equals("PolyOffset")){
float factor = Float.parseFloat(split[1]);
float units = Float.parseFloat(split[2]);
renderState.setPolyOffset(factor, units);
}else if (split[0].equals("ColorWrite")){
renderState.setColorWrite(parseBoolean(split[1]));
}else if (split[0].equals("PointSprite")){
// Ignore for backwards compatbility
}else if (split[0].equals("DepthFunc")){
renderState.setDepthFunc(RenderState.TestFunction.valueOf(split[1]));
}else if (split[0].equals("AlphaFunc")){
renderState.setAlphaFunc(RenderState.TestFunction.valueOf(split[1]));
}else if (split[0].equals("LineWidth")){
renderState.setLineWidth(Float.parseFloat(split[1]));
} else {
throw new MatParseException(null, split[0], statement);
}
}
private void readAdditionalRenderState(List<Statement> renderStates) throws IOException{
renderState = material.getAdditionalRenderState();
for (Statement statement : renderStates){
readRenderStateStatement(statement);
}
renderState = null;
}
private void readRenderState(List<Statement> renderStates) throws IOException{
renderState = new RenderState();
for (Statement statement : renderStates){
readRenderStateStatement(statement);
}
technique.setRenderState(renderState);
renderState = null;
}
private void readForcedRenderState(List<Statement> renderStates) throws IOException{
renderState = new RenderState();
for (Statement statement : renderStates){
readRenderStateStatement(statement);
}
technique.setForcedRenderState(renderState);
renderState = null;
}
// <DEFINENAME> [ ":" <PARAMNAME> ]
private void readDefine(String statement) throws IOException{
String[] split = statement.split(":");
if (split.length == 1){
String defineName = split[0].trim();
presetDefines.add(defineName);
}else if (split.length == 2){
String defineName = split[0].trim();
String paramName = split[1].trim();
MatParam param = materialDef.getMaterialParam(paramName);
if (param == null) {
logger.log(Level.WARNING, "In technique ''{0}'':\n"
+ "Define ''{1}'' mapped to non-existent"
+ " material parameter ''{2}'', ignoring.",
new Object[]{technique.getName(), defineName, paramName});
return;
}
VarType paramType = param.getVarType();
technique.addShaderParamDefine(paramName, paramType, defineName);
}else{
throw new IOException("Define syntax incorrect");
}
}
private void readDefines(List<Statement> defineList) throws IOException{
for (Statement statement : defineList){
readDefine(statement.getLine());
}
}
private void readTechniqueStatement(Statement statement) throws IOException{
String[] split = statement.getLine().split("[ \\{]");
if (split[0].equals("VertexShader") ||
split[0].equals("FragmentShader") ||
split[0].equals("GeometryShader") ||
split[0].equals("TessellationControlShader") ||
split[0].equals("TessellationEvaluationShader")) {
readShaderStatement(statement.getLine());
}else if (split[0].equals("LightMode")){
readLightMode(statement.getLine());
}else if (split[0].equals("ShadowMode")){
readShadowMode(statement.getLine());
}else if (split[0].equals("WorldParameters")){
readWorldParams(statement.getContents());
}else if (split[0].equals("RenderState")){
readRenderState(statement.getContents());
}else if (split[0].equals("ForcedRenderState")){
readForcedRenderState(statement.getContents());
}else if (split[0].equals("Defines")){
readDefines(statement.getContents());
} else if (split[0].equals("ShaderNodesDefinitions")) {
initNodesLoader();
if (isUseNodes) {
nodesLoaderDelegate.readNodesDefinitions(statement.getContents());
}
} else if (split[0].equals("VertexShaderNodes")) {
initNodesLoader();
if (isUseNodes) {
nodesLoaderDelegate.readVertexShaderNodes(statement.getContents());
}
} else if (split[0].equals("FragmentShaderNodes")) {
initNodesLoader();
if (isUseNodes) {
nodesLoaderDelegate.readFragmentShaderNodes(statement.getContents());
}
} else if (split[0].equals("NoRender")) {
technique.setNoRender(true);
} else {
throw new MatParseException(null, split[0], statement);
}
}
private void readTransparentStatement(String statement) throws IOException{
String[] split = statement.split(whitespacePattern);
if (split.length != 2){
throw new IOException("Transparent statement syntax incorrect");
}
material.setTransparent(parseBoolean(split[1]));
}
private static String createShaderPrologue(List<String> presetDefines) {
DefineList dl = new DefineList(presetDefines.size());
for (int i = 0; i < presetDefines.size(); i++) {
dl.set(i, 1);
}
StringBuilder sb = new StringBuilder();
dl.generateSource(sb, presetDefines, null);
return sb.toString();
}
private void readTechnique(Statement techStat) throws IOException{
isUseNodes = false;
String[] split = techStat.getLine().split(whitespacePattern);
String name;
if (split.length == 1) {
name = TechniqueDef.DEFAULT_TECHNIQUE_NAME;
} else if (split.length == 2) {
name = split[1];
} else {
throw new IOException("Technique statement syntax incorrect");
}
String techniqueUniqueName = materialDef.getAssetName() + "@" + name;
technique = new TechniqueDef(name, techniqueUniqueName.hashCode());
for (Statement statement : techStat.getContents()){
readTechniqueStatement(statement);
}
if(isUseNodes){
nodesLoaderDelegate.computeConditions();
//used for caching later, the shader here is not a file.
// KIRILL 9/19/2015
// Not sure if this is needed anymore, since shader caching
// is now done by TechniqueDef.
technique.setShaderFile(technique.hashCode() + "", technique.hashCode() + "", "GLSL100", "GLSL100");
}
if (shaderNames.containsKey(Shader.ShaderType.Vertex) && shaderNames.containsKey(Shader.ShaderType.Fragment)) {
technique.setShaderFile(shaderNames, shaderLanguages);
} else {
technique = null;
shaderLanguages.clear();
shaderNames.clear();
presetDefines.clear();
logger.log(Level.WARNING, "Fixed function technique was ignored");
logger.log(Level.WARNING, "Fixed function technique ''{0}'' was ignored for material {1}",
new Object[]{name, key});
return;
}
technique.setShaderPrologue(createShaderPrologue(presetDefines));
switch (technique.getLightMode()) {
case Disable:
technique.setLogic(new DefaultTechniqueDefLogic(technique));
break;
case MultiPass:
technique.setLogic(new MultiPassLightingLogic(technique));
break;
case SinglePass:
technique.setLogic(new SinglePassLightingLogic(technique));
break;
default:
throw new UnsupportedOperationException();
}
materialDef.addTechniqueDef(technique);
technique = null;
shaderLanguages.clear();
shaderNames.clear();
presetDefines.clear();
}
private void loadFromRoot(List<Statement> roots) throws IOException{
if (roots.size() == 2){
Statement exception = roots.get(0);
String line = exception.getLine();
if (line.startsWith("Exception")){
throw new AssetLoadException(line.substring("Exception ".length()));
}else{
throw new IOException("In multiroot material, expected first statement to be 'Exception'");
}
}else if (roots.size() != 1){
throw new IOException("Too many roots in J3M/J3MD file");
}
boolean extending = false;
Statement materialStat = roots.get(0);
String materialName = materialStat.getLine();
if (materialName.startsWith("MaterialDef")){
materialName = materialName.substring("MaterialDef ".length()).trim();
extending = false;
}else if (materialName.startsWith("Material")){
materialName = materialName.substring("Material ".length()).trim();
extending = true;
}else{
throw new IOException("Specified file is not a Material file");
}
String[] split = materialName.split(":", 2);
if (materialName.equals("")){
throw new MatParseException("Material name cannot be empty", materialStat);
}
if (split.length == 2){
if (!extending){
throw new MatParseException("Must use 'Material' when extending.", materialStat);
}
String extendedMat = split[1].trim();
MaterialDef def = (MaterialDef) assetManager.loadAsset(new AssetKey(extendedMat));
if (def == null) {
throw new MatParseException("Extended material " + extendedMat + " cannot be found.", materialStat);
}
material = new Material(def);
material.setKey(key);
material.setName(split[0].trim());
// material.setAssetName(fileName);
}else if (split.length == 1){
if (extending){
throw new MatParseException("Expected ':', got '{'", materialStat);
}
materialDef = new MaterialDef(assetManager, materialName);
// NOTE: pass file name for defs so they can be loaded later
materialDef.setAssetName(key.getName());
}else{
throw new MatParseException("Cannot use colon in material name/path", materialStat);
}
for (Statement statement : materialStat.getContents()){
split = statement.getLine().split("[ \\{]");
String statType = split[0];
if (extending){
if (statType.equals("MaterialParameters")){
readExtendingMaterialParams(statement.getContents());
}else if (statType.equals("AdditionalRenderState")){
readAdditionalRenderState(statement.getContents());
}else if (statType.equals("Transparent")){
readTransparentStatement(statement.getLine());
}
}else{
if (statType.equals("Technique")){
readTechnique(statement);
}else if (statType.equals("MaterialParameters")){
readMaterialParams(statement.getContents());
}else{
throw new MatParseException("Expected material statement, got '"+statType+"'", statement);
}
}
}
}
public Object load(AssetInfo info) throws IOException {
this.assetManager = info.getManager();
InputStream in = info.openStream();
try {
key = info.getKey();
if (key.getExtension().equals("j3m") && !(key instanceof MaterialKey)) {
throw new IOException("Material instances must be loaded via MaterialKey");
} else if (key.getExtension().equals("j3md") && key instanceof MaterialKey) {
throw new IOException("Material definitions must be loaded via AssetKey");
}
loadFromRoot(BlockLanguageParser.parse(in));
} finally {
if (in != null){
in.close();
}
}
if (material != null){
// material implementation
return material;
}else{
// material definition
return materialDef;
}
}
public MaterialDef loadMaterialDef(List<Statement> roots, AssetManager manager, AssetKey key) throws IOException {
this.key = key;
this.assetManager = manager;
loadFromRoot(roots);
return materialDef;
}
protected void initNodesLoader() {
if (!isUseNodes) {
isUseNodes = shaderNames.get(Shader.ShaderType.Vertex) == null && shaderNames.get(Shader.ShaderType.Fragment) == null;
if (isUseNodes) {
if (nodesLoaderDelegate == null) {
nodesLoaderDelegate = new ShaderNodeLoaderDelegate();
}else{
nodesLoaderDelegate.clear();
}
nodesLoaderDelegate.setTechniqueDef(technique);
nodesLoaderDelegate.setMaterialDef(materialDef);
nodesLoaderDelegate.setAssetManager(assetManager);
}
}
}
/**
* Texture options allow you to specify how a texture should be initialized by including an option before
* the path to the texture in the .j3m file.
* <p>
* <b>Example:</b>
* <pre>
* DiffuseMap: MinTrilinear MagBilinear WrapRepeat_S "some/path/to a/texture.png"
* </pre>
* This would apply a minification filter of "Trilinear", a magnification filter of "Bilinear" and set the wrap mode to "Repeat".
* </p>
* <p>
* <b>Note:</b> If several filters of the same type are added, eg. MinTrilinear MinNearestLinearMipMap, the last one will win.
* </p>
*/
private enum TextureOption {
/**
* Applies a {@link com.jme3.texture.Texture.MinFilter} to the texture.
*/
Min {
@Override
public void applyToTexture(final String option, final Texture texture) {
texture.setMinFilter(Texture.MinFilter.valueOf(option));
}
},
/**
* Applies a {@link com.jme3.texture.Texture.MagFilter} to the texture.
*/
Mag {
@Override
public void applyToTexture(final String option, final Texture texture) {
texture.setMagFilter(Texture.MagFilter.valueOf(option));
}
},
/**
* Applies a {@link com.jme3.texture.Texture.WrapMode} to the texture. This also supports {@link com.jme3.texture.Texture.WrapAxis}
* by adding "_AXIS" to the texture option. For instance if you wanted to repeat on the S (horizontal) axis, you
* would use <pre>WrapRepeat_S</pre> as a texture option.
*/
Wrap {
@Override
public void applyToTexture(final String option, final Texture texture) {
final int separatorPosition = option.indexOf("_");
if (separatorPosition >= option.length() - 2) {
final String axis = option.substring(separatorPosition + 1);
final String mode = option.substring(0, separatorPosition);
final Texture.WrapAxis wrapAxis = Texture.WrapAxis.valueOf(axis);
texture.setWrap(wrapAxis, Texture.WrapMode.valueOf(mode));
} else {
texture.setWrap(Texture.WrapMode.valueOf(option));
}
}
},
/**
* Applies a {@link com.jme3.texture.Texture.WrapMode#Repeat} to the texture. This is simply an alias for
* WrapRepeat, please use WrapRepeat instead if possible as this may become deprecated later on.
*/
Repeat {
@Override
public void applyToTexture(final String option, final Texture texture) {
Wrap.applyToTexture("Repeat", texture);
}
},
/**
* Applies flipping on the Y axis to the {@link TextureKey#setFlipY(boolean)}.
*/
Flip {
@Override
public void applyToTextureKey(final String option, final TextureKey textureKey) {
textureKey.setFlipY(true);
}
};
public String getOptionValue(final String option) {
return option.substring(name().length());
}
public void applyToTexture(final String option, final Texture texture) {
}
public void applyToTextureKey(final String option, final TextureKey textureKey) {
}
public static TextureOption getTextureOption(final String option) {
for(final TextureOption textureOption : TextureOption.values()) {
if (option.startsWith(textureOption.name())) {
return textureOption;
}
}
return null;
}
}
/**
* Internal object used for holding a {@link com.jme3.material.plugins.J3MLoader.TextureOption} and it's value. Also
* contains a couple of convenience methods for applying the TextureOption to either a TextureKey or a Texture.
*/
private static class TextureOptionValue {
private final TextureOption textureOption;
private final String value;
public TextureOptionValue(TextureOption textureOption, String value) {
this.textureOption = textureOption;
this.value = value;
}
public void applyToTextureKey(final TextureKey textureKey) {
textureOption.applyToTextureKey(value, textureKey);
}
public void applyToTexture(final Texture texture) {
textureOption.applyToTexture(value, texture);
}
}
}