SceneBuilder.Materials.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using BabylonExport.Entities;
  7. using UnityEditor;
  8. using UnityEngine;
  9. namespace Unity3D2Babylon
  10. {
  11. partial class SceneBuilder
  12. {
  13. private void CopyTextureCube(string texturePath, Cubemap cubemap, BabylonTexture babylonTexture, bool hdr = false)
  14. {
  15. if (!babylonScene.AddTextureCube(texturePath))
  16. {
  17. return;
  18. }
  19. ExporterWindow.ReportProgress(1, "Parsing texture cube: " + texturePath);
  20. var srcTexturePath = AssetDatabase.GetAssetPath(cubemap);
  21. bool textureNotExistsMode = (SceneController != null && SceneController.skyboxOptions.textureFile == BabylonTextureExport.IfNotExists);
  22. bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
  23. string fext = (png == true) ? ".png" : ".jpg";
  24. try
  25. {
  26. if (hdr)
  27. {
  28. var hdrTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileName(texturePath));
  29. bool writeHdrTexture = true;
  30. string textureHdrName = Path.GetFileName(hdrTexturePath);
  31. if (textureNotExistsMode && File.Exists(hdrTexturePath))
  32. {
  33. writeHdrTexture = false;
  34. ExporterWindow.ReportProgress(1, "Texture hdr cube item exists: " + textureHdrName);
  35. }
  36. if (writeHdrTexture)
  37. {
  38. ExporterWindow.ReportProgress(1, "Copying hdr texture cube item: " + textureHdrName);
  39. File.Copy(srcTexturePath, hdrTexturePath, true);
  40. }
  41. }
  42. else
  43. {
  44. var importTool = new BabylonTextureImporter(srcTexturePath);
  45. bool isReadable = importTool.IsReadable();
  46. if (!isReadable) importTool.SetReadable();
  47. try
  48. {
  49. foreach (CubemapFace face in Enum.GetValues(typeof(CubemapFace)))
  50. {
  51. var faceTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileNameWithoutExtension(texturePath));
  52. switch (face)
  53. {
  54. case CubemapFace.PositiveX:
  55. faceTexturePath += ("_px" + fext);
  56. break;
  57. case CubemapFace.NegativeX:
  58. faceTexturePath += ("_nx" + fext);
  59. break;
  60. case CubemapFace.PositiveY:
  61. faceTexturePath += ("_py" + fext);
  62. break;
  63. case CubemapFace.NegativeY:
  64. faceTexturePath += ("_ny" + fext);
  65. break;
  66. case CubemapFace.PositiveZ:
  67. faceTexturePath += ("_pz" + fext);
  68. break;
  69. case CubemapFace.NegativeZ:
  70. faceTexturePath += ("_nz" + fext);
  71. break;
  72. default:
  73. continue;
  74. }
  75. bool writeFaceTexture = true;
  76. string textureFaceName = Path.GetFileName(faceTexturePath);
  77. if (textureNotExistsMode && File.Exists(faceTexturePath))
  78. {
  79. writeFaceTexture = false;
  80. ExporterWindow.ReportProgress(1, "Texture cube item exists: " + textureFaceName);
  81. }
  82. if (writeFaceTexture)
  83. {
  84. ExporterWindow.ReportProgress(1, "Exporting texture cube item: " + textureFaceName);
  85. var tempTexture = new Texture2D(cubemap.width, cubemap.height, TextureFormat.ARGB32, false);
  86. Color[] pixels = cubemap.GetPixels(face);
  87. tempTexture.SetPixels(pixels);
  88. tempTexture.Apply();
  89. // Flip faces in cube texture.
  90. tempTexture = FlipTexture(tempTexture);
  91. // Encode cube face texture
  92. if (png)
  93. {
  94. File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToPNG());
  95. }
  96. else
  97. {
  98. File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
  99. }
  100. }
  101. }
  102. }
  103. finally
  104. {
  105. if (!isReadable) importTool.ForceUpdate();
  106. }
  107. }
  108. }
  109. catch (Exception ex)
  110. {
  111. Debug.LogException(ex);
  112. }
  113. if (babylonTexture != null)
  114. {
  115. var textureName = Path.GetFileNameWithoutExtension(texturePath);
  116. if (hdr) textureName += ".hdr";
  117. babylonTexture.name = textureName;
  118. babylonTexture.isCube = true;
  119. babylonTexture.level = exportationOptions.ReflectionDefaultLevel;
  120. babylonTexture.coordinatesMode = 3;
  121. }
  122. }
  123. private Texture2D FlipTexture(Texture2D original)
  124. {
  125. Texture2D flipped = new Texture2D(original.width, original.height);
  126. for (int i = 0; i < original.width; i++)
  127. {
  128. for (int j = 0; j < original.height; j++)
  129. {
  130. flipped.SetPixel(i, original.height - j - 1, original.GetPixel(i, j));
  131. }
  132. }
  133. flipped.Apply();
  134. return flipped;
  135. }
  136. private void CopyTextureFace(string texturePath, string textureName, Texture2D textureFace)
  137. {
  138. if (!babylonScene.AddTextureCube(textureName))
  139. {
  140. return;
  141. }
  142. bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
  143. bool textureNotExistsMode = (SceneController != null && SceneController.skyboxOptions.textureFile == BabylonTextureExport.IfNotExists);
  144. bool writeTextureFile = true;
  145. if (textureNotExistsMode && File.Exists(texturePath))
  146. {
  147. writeTextureFile = false;
  148. ExporterWindow.ReportProgress(1, "Texture cube item exists: " + textureName);
  149. }
  150. if (writeTextureFile)
  151. {
  152. var srcTexturePath = AssetDatabase.GetAssetPath(textureFace);
  153. if ((png && srcTexturePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) || (!png && (srcTexturePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || srcTexturePath.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase))))
  154. {
  155. ExporterWindow.ReportProgress(1, "Copying texture cube item: " + textureName);
  156. File.Copy(srcTexturePath, texturePath, true);
  157. }
  158. else
  159. {
  160. if (textureFace != null)
  161. {
  162. var importTool = new BabylonTextureImporter(srcTexturePath);
  163. bool isReadable = importTool.IsReadable();
  164. if (!isReadable) importTool.SetReadable();
  165. try
  166. {
  167. ExporterWindow.ReportProgress(1, "Exporting texture cube item: " + textureName);
  168. var tempTexture = new Texture2D(textureFace.width, textureFace.height, TextureFormat.ARGB32, false);
  169. Color32[] pixels = textureFace.GetPixels32();
  170. tempTexture.SetPixels32(pixels);
  171. tempTexture.Apply();
  172. if (png)
  173. {
  174. File.WriteAllBytes(texturePath, tempTexture.EncodeToPNG());
  175. }
  176. else
  177. {
  178. File.WriteAllBytes(texturePath, tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183. Debug.LogException(ex);
  184. }
  185. finally
  186. {
  187. if (!isReadable) importTool.ForceUpdate();
  188. }
  189. }
  190. }
  191. }
  192. }
  193. private void CopyTexture(string texturePath, Texture2D texture2D, BabylonTexture babylonTexture, bool isLightmap = false)
  194. {
  195. string rename = null;
  196. bool needToDelete = false;
  197. // Convert unsupported file extensions
  198. if (texturePath.EndsWith(".psd") || texturePath.EndsWith(".tif") || texturePath.EndsWith(".exr"))
  199. {
  200. string srcTexturePath = AssetDatabase.GetAssetPath(texture2D);
  201. var importTool = new BabylonTextureImporter(srcTexturePath);
  202. var previousConvertToNormalmap = importTool.textureImporter.convertToNormalmap;
  203. var previousAlphaSource = importTool.textureImporter.alphaSource;
  204. var previousTextureType = importTool.textureImporter.textureType;
  205. importTool.SetReadable();
  206. importTool.textureImporter.textureType = (isLightmap) ? TextureImporterType.Lightmap : TextureImporterType.Default;
  207. importTool.textureImporter.alphaSource = TextureImporterAlphaSource.FromInput;
  208. importTool.textureImporter.convertToNormalmap = false;
  209. AssetDatabase.ImportAsset(texturePath);
  210. try
  211. {
  212. var usePNG = texture2D.alphaIsTransparency;
  213. var tempTexture = new Texture2D(texture2D.width, texture2D.height, TextureFormat.ARGB32, false);
  214. if (isLightmap)
  215. {
  216. rename = SceneName + Path.GetFileName(texturePath);
  217. Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height);
  218. for (int index = 0; index < pixels.Length; index++)
  219. {
  220. pixels[index].r = pixels[index].r * pixels[index].a * 5;
  221. pixels[index].g = pixels[index].g * pixels[index].a * 5;
  222. pixels[index].b = pixels[index].b * pixels[index].a * 5;
  223. }
  224. tempTexture.SetPixels(pixels);
  225. }
  226. else
  227. {
  228. Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height);
  229. for (int index = 0; index < pixels.Length; index++)
  230. {
  231. usePNG |= pixels[index].a <= 0.99999f;
  232. }
  233. tempTexture.SetPixels32(texture2D.GetPixels32());
  234. }
  235. tempTexture.Apply();
  236. string outputfile = (!String.IsNullOrEmpty(rename)) ? rename : texturePath;
  237. texturePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(outputfile));
  238. var extension = (usePNG || exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG) ? ".png" : ".jpg";
  239. texturePath = texturePath.Replace(".psd", extension).Replace(".tif", extension).Replace(".exr", extension);
  240. File.WriteAllBytes(texturePath, (usePNG || exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG) ? tempTexture.EncodeToPNG() : tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
  241. needToDelete = true;
  242. }
  243. catch (Exception ex)
  244. {
  245. Debug.LogException(ex);
  246. }
  247. finally
  248. {
  249. importTool.textureImporter.textureType = previousTextureType;
  250. importTool.textureImporter.alphaSource = previousAlphaSource;
  251. importTool.textureImporter.convertToNormalmap = previousConvertToNormalmap;
  252. importTool.ForceUpdate();
  253. }
  254. }
  255. else if (texture2D.alphaIsTransparency || texturePath.EndsWith(".png"))
  256. {
  257. babylonTexture.hasAlpha = true;
  258. }
  259. else
  260. {
  261. babylonTexture.hasAlpha = false;
  262. }
  263. var textureName = Path.GetFileName(texturePath);
  264. babylonTexture.name = textureName;
  265. babylonScene.AddTexture(texturePath);
  266. if (needToDelete) File.Delete(texturePath);
  267. }
  268. private static Color[] GetPixels(Texture2D texture)
  269. {
  270. Color[] pixels = null;
  271. string srcTexturePath = AssetDatabase.GetAssetPath(texture);
  272. var importTool = new BabylonTextureImporter(srcTexturePath);
  273. bool isReadable = importTool.IsReadable();
  274. if (!isReadable) importTool.SetReadable();
  275. try
  276. {
  277. pixels = texture.GetPixels();
  278. }
  279. catch (Exception ex)
  280. {
  281. Debug.LogException(ex);
  282. }
  283. finally
  284. {
  285. if (!isReadable) importTool.ForceUpdate();
  286. }
  287. return pixels;
  288. }
  289. private BabylonMaterial DumpMaterial(Material material, int lightmapIndex = -1, Vector4 lightmapScaleOffset = default(Vector4), int lightmapCoordIndex = -1)
  290. {
  291. if (material.shader.name == "Standard" || material.shader.name == "BabylonJS/Materials/PBR Material")
  292. {
  293. return DumpPBRMaterial(material, lightmapIndex, lightmapScaleOffset, true, lightmapCoordIndex);
  294. }
  295. else if (material.shader.name == "Standard (Specular setup)" || material.shader.name == "BabylonJS/Materials/PBR Material (Specular)")
  296. {
  297. return DumpPBRMaterial(material, lightmapIndex, lightmapScaleOffset, false, lightmapCoordIndex);
  298. }
  299. else if (material.shader.name.StartsWith("BabylonJS/Materials/", StringComparison.OrdinalIgnoreCase))
  300. {
  301. return DumpStandardMaterial(material, lightmapIndex, lightmapScaleOffset, lightmapCoordIndex);
  302. }
  303. else if (material.shader.name.StartsWith("BabylonJS/", StringComparison.OrdinalIgnoreCase))
  304. {
  305. return DumpShaderMaterial(material);
  306. }
  307. return DumpStandardMaterial(material, lightmapIndex, lightmapScaleOffset, lightmapCoordIndex);
  308. }
  309. private BabylonMaterial DumpStandardMaterial(Material material, int lightmapIndex = -1, Vector4 lightmapScaleOffset = default(Vector4), int lightmapCoordIndex = -1)
  310. {
  311. var materialNotSupported = false;
  312. if (!materialsDictionary.ContainsKey(material.name))
  313. {
  314. var bMat = new BabylonStandardMaterial
  315. {
  316. name = material.name,
  317. id = Guid.NewGuid().ToString(),
  318. diffuse = new float[4],
  319. specular = new float[4]
  320. };
  321. ExporterWindow.ReportProgress(1, "Exporting standard material: " + material.name);
  322. // Default diffuse
  323. bMat.diffuse[0] = 1.0f;
  324. bMat.diffuse[1] = 1.0f;
  325. bMat.diffuse[2] = 1.0f;
  326. bMat.diffuse[3] = 1.0f;
  327. // Default specular
  328. bMat.specular[0] = 0.0f;
  329. bMat.specular[1] = 0.0f;
  330. bMat.specular[2] = 0.0f;
  331. bMat.specular[3] = 1.0f;
  332. if (material.mainTexture && material.mainTexture.GetType().FullName == "UnityEngine.ProceduralTexture")
  333. {
  334. materialNotSupported = true;
  335. Debug.LogWarning("ProceduralTexture: " + material.mainTexture.name + " not supported by Babylon.js");
  336. }
  337. if (material.HasProperty("_Shininess"))
  338. {
  339. var specShininess = material.GetFloat("_Shininess");
  340. bMat.specularPower = specShininess * 128;
  341. }
  342. if (material.HasProperty("_Color"))
  343. {
  344. bMat.diffuse = material.color.ToFloat();
  345. }
  346. if (material.HasProperty("_SpecColor"))
  347. {
  348. var specColor = material.GetColor("_SpecColor");
  349. bMat.specular = specColor.ToFloat();
  350. }
  351. if (material.HasProperty("_Emission"))
  352. {
  353. if (material.GetColorNames().IndexOf("_Emission") >= 0)
  354. {
  355. var emissiveColor = material.GetColor("_Emission");
  356. bMat.emissive = emissiveColor.ToFloat();
  357. }
  358. else if (material.GetFloatNames().IndexOf("_Emission") >= 0)
  359. {
  360. // TODO: Convert Lightmapper Emission Color
  361. UnityEngine.Debug.LogWarning("Material Emission Is Float Not Color: " + material.name);
  362. }
  363. }
  364. if (material.HasProperty("_AlphaMode"))
  365. {
  366. bMat.alphaMode = material.GetInt("_AlphaMode");
  367. }
  368. if (material.HasProperty("_DisableLighting"))
  369. {
  370. bMat.disableLighting = (material.GetInt("_DisableLighting") != 0);
  371. }
  372. if (material.HasProperty("_UseEmissiveAsIllumination"))
  373. {
  374. bMat.useEmissiveAsIllumination = (material.GetInt("_UseEmissiveAsIllumination") != 0);
  375. }
  376. if (material.HasProperty("_BackFaceCulling"))
  377. {
  378. bMat.backFaceCulling = (material.GetInt("_BackFaceCulling") != 0);
  379. }
  380. if (material.mainTexture && !materialNotSupported)
  381. {
  382. var mainTexture2D = material.mainTexture as Texture2D;
  383. var mainTexturePath = AssetDatabase.GetAssetPath(mainTexture2D);
  384. var alphaCuttOff = 0f;
  385. if (material.HasProperty("_Cutoff"))
  386. {
  387. alphaCuttOff = material.GetFloat("_Cutoff");
  388. }
  389. bMat.diffuseTexture = new BabylonTexture
  390. {
  391. uScale = material.mainTextureScale.x,
  392. vScale = material.mainTextureScale.y,
  393. uOffset = material.mainTextureOffset.x,
  394. vOffset = material.mainTextureOffset.y
  395. };
  396. CopyTexture(mainTexturePath, mainTexture2D, bMat.diffuseTexture);
  397. if ((mainTexture2D && mainTexture2D.alphaIsTransparency) || alphaCuttOff > 0)
  398. {
  399. bMat.diffuseTexture.hasAlpha = true;
  400. bMat.backFaceCulling = false;
  401. }
  402. }
  403. // Normal map
  404. bMat.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");
  405. if (bMat.bumpTexture != null && material.HasProperty("_BumpScale"))
  406. {
  407. bMat.bumpTexture.level = material.GetFloat("_BumpScale");
  408. }
  409. bMat.emissiveTexture = DumpTextureFromMaterial(material, "_Illum");
  410. bMat.ambientTexture = DumpTextureFromMaterial(material, "_LightMap");
  411. bMat.reflectionTexture = DumpTextureFromMaterial(material, "_Cube");
  412. // Baking override
  413. if (exportationOptions.DefaultLightmapMode == (int)BabylonLightmapMode.FullLightBaking)
  414. {
  415. bMat.disableLighting = true;
  416. bMat.useEmissiveAsIllumination = true;
  417. }
  418. // If no ambient texture already (ambientTexture manually set for lightmaps on standard material)
  419. bool hasLightmap = (exportationOptions.ExportLightmaps && lightmapIndex >= 0 && lightmapIndex != 65535 && LightmapSettings.lightmaps.Length > lightmapIndex);
  420. if (hasLightmap && bMat.ambientTexture == null)
  421. {
  422. var lightmap = LightmapSettings.lightmaps[lightmapIndex].lightmapLight;
  423. var texturePath = AssetDatabase.GetAssetPath(lightmap);
  424. if (!String.IsNullOrEmpty(texturePath))
  425. {
  426. ExporterWindow.ReportProgress(1, "Dumping std material lightmap: " + lightmap.name);
  427. bMat.lightmapTexture = DumpTexture(lightmap, isLightmap: true);
  428. bMat.lightmapTexture.coordinatesIndex = (lightmapCoordIndex >= 0) ? lightmapCoordIndex : exportationOptions.DefaultCoordinatesIndex;
  429. bMat.useLightmapAsShadowmap = true;
  430. bMat.lightmapTexture.uScale = lightmapScaleOffset.x;
  431. bMat.lightmapTexture.vScale = lightmapScaleOffset.y;
  432. bMat.lightmapTexture.uOffset = lightmapScaleOffset.z;
  433. bMat.lightmapTexture.vOffset = lightmapScaleOffset.w;
  434. }
  435. }
  436. materialsDictionary.Add(bMat.name, bMat);
  437. return bMat;
  438. }
  439. return materialsDictionary[material.name];
  440. }
  441. private BabylonMaterial DumpPBRMaterial(Material material, int lightmapIndex = -1, Vector4 lightmapScaleOffset = default(Vector4), bool metallic = true, int lightmapCoordIndex = -1)
  442. {
  443. var materialNotSupported = false;
  444. if (materialsDictionary.ContainsKey(material.name))
  445. {
  446. return materialsDictionary[material.name];
  447. }
  448. var babylonPbrMaterial = new BabylonPBRMaterial
  449. {
  450. name = material.name,
  451. id = Guid.NewGuid().ToString(),
  452. albedo = new float[4],
  453. useEmissiveAsIllumination = true,
  454. useSpecularOverAlpha = true,
  455. useRadianceOverAlpha = true,
  456. };
  457. ExporterWindow.ReportProgress(1, "Exporting physical material: " + material.name);
  458. babylonPbrMaterial.environmentIntensity = RenderSettings.ambientIntensity;
  459. if (material.mainTexture && material.mainTexture.GetType().FullName == "UnityEngine.ProceduralTexture")
  460. {
  461. materialNotSupported = true;
  462. Debug.LogWarning("ProceduralTexture: " + material.mainTexture.name + " not supported by Babylon.js");
  463. }
  464. if (material.HasProperty("_Roughness"))
  465. {
  466. babylonPbrMaterial.roughness = material.GetInt("_Roughness");
  467. }
  468. if (material.HasProperty("_UseRoughnessFromMetallicTextureAlpha"))
  469. {
  470. babylonPbrMaterial.useRoughnessFromMetallicTextureAlpha = (material.GetInt("_UseRoughnessFromMetallicTextureAlpha") != 0);
  471. }
  472. if (material.HasProperty("_UseRoughnessFromMetallicTextureGreen"))
  473. {
  474. babylonPbrMaterial.useRoughnessFromMetallicTextureGreen = (material.GetInt("_UseRoughnessFromMetallicTextureGreen") != 0);
  475. }
  476. if (material.HasProperty("_AlphaMode"))
  477. {
  478. babylonPbrMaterial.alphaMode = material.GetInt("_AlphaMode");
  479. }
  480. if (material.HasProperty("_DisableLighting"))
  481. {
  482. babylonPbrMaterial.disableLighting = (material.GetInt("_DisableLighting") != 0);
  483. }
  484. if (material.HasProperty("_UseEmissiveAsIllumination"))
  485. {
  486. babylonPbrMaterial.useEmissiveAsIllumination = (material.GetInt("_UseEmissiveAsIllumination") != 0);
  487. }
  488. if (material.HasProperty("_BackFaceCulling"))
  489. {
  490. babylonPbrMaterial.backFaceCulling = (material.GetInt("_BackFaceCulling") != 0);
  491. }
  492. // Albedo
  493. if (material.HasProperty("_Color"))
  494. {
  495. babylonPbrMaterial.albedo = material.color.ToFloat();
  496. }
  497. babylonPbrMaterial.albedoTexture = DumpTextureFromMaterial(material, "_MainTex");
  498. if (material.mainTexture != null && !materialNotSupported)
  499. {
  500. var textureScale = material.mainTextureScale;
  501. babylonPbrMaterial.albedoTexture.uScale = textureScale.x;
  502. babylonPbrMaterial.albedoTexture.vScale = textureScale.y;
  503. var textureOffset = material.mainTextureOffset;
  504. babylonPbrMaterial.albedoTexture.uOffset = textureOffset.x;
  505. babylonPbrMaterial.albedoTexture.vOffset = textureOffset.y;
  506. }
  507. // Emissive
  508. if (material.HasProperty("_EmissionColor"))
  509. {
  510. babylonPbrMaterial.emissive = material.GetColor("_EmissionColor").ToFloat();
  511. }
  512. babylonPbrMaterial.emissiveTexture = DumpTextureFromMaterial(material, "_EmissionMap");
  513. // Transparency
  514. DumpTransparency(material, babylonPbrMaterial);
  515. // Glossiess/Reflectivity
  516. DumpGlossinessReflectivity(material, metallic, babylonPbrMaterial);
  517. // Occlusion
  518. babylonPbrMaterial.ambientTexture = DumpTextureFromMaterial(material, "_OcclusionMap");
  519. if (babylonPbrMaterial.ambientTexture != null && material.HasProperty("_OcclusionStrength"))
  520. {
  521. babylonPbrMaterial.ambientTexture.level = material.GetFloat("_OcclusionStrength");
  522. }
  523. // Normal
  524. babylonPbrMaterial.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");
  525. if (babylonPbrMaterial.bumpTexture != null && material.HasProperty("_BumpScale"))
  526. {
  527. babylonPbrMaterial.bumpTexture.level = material.GetFloat("_BumpScale");
  528. }
  529. // Reflection
  530. babylonPbrMaterial.reflectionTexture = DumpReflectionTexture();
  531. // Baking Override
  532. if (exportationOptions.DefaultLightmapMode == (int)BabylonLightmapMode.FullLightBaking)
  533. {
  534. babylonPbrMaterial.disableLighting = true;
  535. babylonPbrMaterial.useEmissiveAsIllumination = true;
  536. }
  537. // Lightmapping
  538. bool hasLightmap = (exportationOptions.ExportLightmaps && lightmapIndex >= 0 && lightmapIndex != 65535 && LightmapSettings.lightmaps.Length > lightmapIndex);
  539. if (hasLightmap && babylonPbrMaterial.ambientTexture == null)
  540. {
  541. var lightmap = LightmapSettings.lightmaps[lightmapIndex].lightmapLight;
  542. var texturePath = AssetDatabase.GetAssetPath(lightmap);
  543. if (!String.IsNullOrEmpty(texturePath))
  544. {
  545. ExporterWindow.ReportProgress(1, "Dumping pbr material lightmap: " + lightmap.name);
  546. babylonPbrMaterial.lightmapTexture = DumpTexture(lightmap, isLightmap: true);
  547. babylonPbrMaterial.lightmapTexture.coordinatesIndex = (lightmapCoordIndex >= 0) ? lightmapCoordIndex : exportationOptions.DefaultCoordinatesIndex;
  548. babylonPbrMaterial.useLightmapAsShadowmap = true;
  549. babylonPbrMaterial.lightmapTexture.uScale = lightmapScaleOffset.x;
  550. babylonPbrMaterial.lightmapTexture.vScale = lightmapScaleOffset.y;
  551. babylonPbrMaterial.lightmapTexture.uOffset = lightmapScaleOffset.z;
  552. babylonPbrMaterial.lightmapTexture.vOffset = lightmapScaleOffset.w;
  553. }
  554. }
  555. materialsDictionary.Add(babylonPbrMaterial.name, babylonPbrMaterial);
  556. return babylonPbrMaterial;
  557. }
  558. private void DumpGlossinessReflectivity(Material material, bool metallic, BabylonPBRMaterial babylonPbrMaterial)
  559. {
  560. if (material.HasProperty("_Glossiness"))
  561. {
  562. babylonPbrMaterial.microSurface = material.GetFloat("_Glossiness");
  563. }
  564. if (metallic)
  565. {
  566. if (material.HasProperty("_Metallic"))
  567. {
  568. var metalness = material.GetFloat("_Metallic");
  569. babylonPbrMaterial.reflectivity = new float[] { metalness * babylonPbrMaterial.albedo[0], metalness * babylonPbrMaterial.albedo[1], metalness * babylonPbrMaterial.albedo[2] };
  570. if (babylonPbrMaterial.albedoTexture != null)
  571. {
  572. var albedoTexture = material.GetTexture("_MainTex") as Texture2D;
  573. if (albedoTexture != null)
  574. {
  575. var albedoPixels = GetPixels(albedoTexture);
  576. var reflectivityTexture = new Texture2D(albedoTexture.width, albedoTexture.height, TextureFormat.RGBA32, false);
  577. reflectivityTexture.alphaIsTransparency = true;
  578. babylonPbrMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  579. var metallicTexture = material.GetTexture("_MetallicGlossMap") as Texture2D;
  580. if (metallicTexture == null)
  581. {
  582. for (var i = 0; i < albedoTexture.width; i++)
  583. {
  584. for (var j = 0; j < albedoTexture.height; j++)
  585. {
  586. albedoPixels[j * albedoTexture.width + i].r *= metalness;
  587. albedoPixels[j * albedoTexture.width + i].g *= metalness;
  588. albedoPixels[j * albedoTexture.width + i].b *= metalness;
  589. albedoPixels[j * albedoTexture.width + i].a = babylonPbrMaterial.microSurface;
  590. }
  591. }
  592. }
  593. else
  594. {
  595. var metallicPixels = GetPixels(metallicTexture);
  596. for (var i = 0; i < albedoTexture.width; i++)
  597. {
  598. for (var j = 0; j < albedoTexture.height; j++)
  599. {
  600. var metallicPixel = metallicPixels[j * albedoTexture.width + i];
  601. albedoPixels[j * albedoTexture.width + i].r *= metallicPixel.r;
  602. albedoPixels[j * albedoTexture.width + i].g *= metallicPixel.r;
  603. albedoPixels[j * albedoTexture.width + i].b *= metallicPixel.r;
  604. albedoPixels[j * albedoTexture.width + i].a = metallicPixel.a;
  605. }
  606. }
  607. }
  608. reflectivityTexture.SetPixels(albedoPixels);
  609. reflectivityTexture.Apply();
  610. var textureName = albedoTexture.name + "_MetallicGlossMap.png";
  611. var babylonTexture = new BabylonTexture { name = textureName };
  612. var textureScale = material.GetTextureScale("_MainTex");
  613. babylonTexture.uScale = textureScale.x;
  614. babylonTexture.vScale = textureScale.y;
  615. var textureOffset = material.GetTextureOffset("_MainTex");
  616. babylonTexture.uOffset = textureOffset.x;
  617. babylonTexture.vOffset = textureOffset.y;
  618. var reflectivityTexturePath = Path.Combine(Path.GetTempPath(), textureName);
  619. File.WriteAllBytes(reflectivityTexturePath, reflectivityTexture.EncodeToPNG());
  620. babylonScene.AddTexture(reflectivityTexturePath);
  621. if (File.Exists(reflectivityTexturePath))
  622. {
  623. File.Delete(reflectivityTexturePath);
  624. }
  625. babylonPbrMaterial.reflectivityTexture = babylonTexture;
  626. }
  627. }
  628. //else
  629. //{
  630. // TODO. Manage Albedo Cube Texture.
  631. //}
  632. }
  633. }
  634. else
  635. {
  636. if (material.HasProperty("_SpecColor"))
  637. {
  638. babylonPbrMaterial.reflectivity = material.GetColor("_SpecColor").ToFloat();
  639. }
  640. babylonPbrMaterial.reflectivityTexture = DumpTextureFromMaterial(material, "_SpecGlossMap");
  641. if (babylonPbrMaterial.reflectivityTexture != null && babylonPbrMaterial.reflectivityTexture.hasAlpha)
  642. {
  643. babylonPbrMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  644. }
  645. }
  646. }
  647. private BabylonMaterial DumpShaderMaterial(Material material)
  648. {
  649. if (materialsDictionary.ContainsKey(material.name))
  650. {
  651. return materialsDictionary[material.name];
  652. }
  653. var babylonShaderMaterial = new BabylonShaderMaterial
  654. {
  655. name = material.name,
  656. id = Guid.NewGuid().ToString(),
  657. };
  658. ExporterWindow.ReportProgress(1, "Exporting glsl material: " + material.name);
  659. List<string> tnames = material.GetTextureNames();
  660. foreach (string tname in tnames)
  661. {
  662. BabylonTexture tdata = DumpTextureFromMaterial(material, tname);
  663. if (tdata != null)
  664. {
  665. babylonShaderMaterial.textures.Add(tname, tdata);
  666. }
  667. }
  668. List<string> fnames = material.GetFloatNames();
  669. foreach (string fname in fnames)
  670. {
  671. float fdata = material.GetFloat(fname);
  672. babylonShaderMaterial.floats.Add(fname, fdata);
  673. }
  674. List<string> rnames = material.GetRangeNames();
  675. foreach (string rname in rnames)
  676. {
  677. float rdata = material.GetFloat(rname);
  678. babylonShaderMaterial.floats.Add(rname, rdata);
  679. }
  680. List<string> cnames = material.GetColorNames();
  681. foreach (string cname in cnames)
  682. {
  683. Color cdata = material.GetColor(cname);
  684. babylonShaderMaterial.vectors4.Add(cname, cdata.ToFloat());
  685. }
  686. List<string> vnames = material.GetVectorNames();
  687. foreach (string vname in vnames)
  688. {
  689. Vector4 vdata = material.GetVector(vname);
  690. babylonShaderMaterial.vectors4.Add(vname, vdata.ToFloat());
  691. }
  692. Shader shader = material.shader;
  693. string filename = AssetDatabase.GetAssetPath(shader);
  694. string program = Tools.LoadTextAsset(filename);
  695. string basename = shader.name.Replace("BabylonJS/", "").Replace("/", "_").Replace(" ", "");
  696. string outpath = (!String.IsNullOrEmpty(exportationOptions.DefaultShaderFolder)) ? exportationOptions.DefaultShaderFolder : OutputPath;
  697. var shaderpath = new Dictionary<string, string>();
  698. List<string> attributeList = new List<string>();
  699. List<string> uniformList = new List<string>();
  700. List<string> samplerList = new List<string>();
  701. List<string> defineList = new List<string>();
  702. string babylonOptions = GetShaderProgramSection(basename, program, BabylonProgramSection.Babylon);
  703. string[] babylonLines = babylonOptions.Split('\n');
  704. foreach (string babylonLine in babylonLines)
  705. {
  706. if (babylonLine.IndexOf("attributes", StringComparison.OrdinalIgnoreCase) >= 0)
  707. {
  708. string[] attributes = babylonLine.Split(':');
  709. if (attributes != null && attributes.Length > 1)
  710. {
  711. string abuffer = attributes[1].Replace("[", "").Replace("]", "").Replace("\"", "");
  712. if (!String.IsNullOrEmpty(abuffer))
  713. {
  714. abuffer = abuffer.Trim();
  715. string[] adata = abuffer.Split(',');
  716. if (adata != null && adata.Length > 0)
  717. {
  718. foreach (string aoption in adata)
  719. {
  720. string aoption_buffer = aoption.Trim();
  721. if (!String.IsNullOrEmpty(aoption_buffer))
  722. {
  723. attributeList.Add(aoption_buffer);
  724. }
  725. }
  726. }
  727. }
  728. }
  729. }
  730. else if (babylonLine.IndexOf("uniforms", StringComparison.OrdinalIgnoreCase) >= 0)
  731. {
  732. string[] uniforms = babylonLine.Split(':');
  733. if (uniforms != null && uniforms.Length > 1)
  734. {
  735. string ubuffer = uniforms[1].Replace("[", "").Replace("]", "").Replace("\"", "");
  736. if (!String.IsNullOrEmpty(ubuffer))
  737. {
  738. ubuffer = ubuffer.Trim();
  739. string[] udata = ubuffer.Split(',');
  740. if (udata != null && udata.Length > 0)
  741. {
  742. foreach (string uoption in udata)
  743. {
  744. string uoption_buffer = uoption.Trim();
  745. if (!String.IsNullOrEmpty(uoption_buffer))
  746. {
  747. uniformList.Add(uoption_buffer);
  748. }
  749. }
  750. }
  751. }
  752. }
  753. }
  754. else if (babylonLine.IndexOf("samplers", StringComparison.OrdinalIgnoreCase) >= 0)
  755. {
  756. string[] samplers = babylonLine.Split(':');
  757. if (samplers != null && samplers.Length > 1)
  758. {
  759. string sbuffer = samplers[1].Replace("[", "").Replace("]", "").Replace("\"", "");
  760. if (!String.IsNullOrEmpty(sbuffer))
  761. {
  762. sbuffer = sbuffer.Trim();
  763. string[] sdata = sbuffer.Split(',');
  764. if (sdata != null && sdata.Length > 0)
  765. {
  766. foreach (string soption in sdata)
  767. {
  768. string soption_buffer = soption.Trim();
  769. if (!String.IsNullOrEmpty(soption_buffer))
  770. {
  771. samplerList.Add(soption_buffer);
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. else if (babylonLine.IndexOf("defines", StringComparison.OrdinalIgnoreCase) >= 0)
  779. {
  780. string[] defines = babylonLine.Split(':');
  781. if (defines != null && defines.Length > 1)
  782. {
  783. string dbuffer = defines[1].Replace("[", "").Replace("]", "").Replace("\"", "");
  784. if (!String.IsNullOrEmpty(dbuffer))
  785. {
  786. dbuffer = dbuffer.Trim();
  787. string[] ddata = dbuffer.Split(',');
  788. if (ddata != null && ddata.Length > 0)
  789. {
  790. foreach (string doption in ddata)
  791. {
  792. string doption_buffer = doption.Trim();
  793. if (!String.IsNullOrEmpty(doption_buffer))
  794. {
  795. defineList.Add(doption_buffer);
  796. }
  797. }
  798. }
  799. }
  800. }
  801. }
  802. }
  803. if (material.HasProperty("_AlphaMode")) {
  804. babylonShaderMaterial.alphaMode = material.GetInt("_AlphaMode");
  805. }
  806. bool needsAlphaBlending = false;
  807. if (material.HasProperty("_NeedsAlphaBlending")) {
  808. needsAlphaBlending = (material.GetInt("_NeedsAlphaBlending") != 0);
  809. }
  810. bool needsAlphaTesting = false;
  811. if (material.HasProperty("_NeedsAlphaTesting")) {
  812. needsAlphaTesting = (material.GetInt("_NeedsAlphaTesting") != 0);
  813. }
  814. if (material.HasProperty("_BackFaceCulling")) {
  815. babylonShaderMaterial.backFaceCulling = (material.GetInt("_BackFaceCulling") != 0);
  816. }
  817. babylonShaderMaterial.options = new BabylonShaderOptions();
  818. babylonShaderMaterial.options.needAlphaBlending = needsAlphaBlending;
  819. babylonShaderMaterial.options.needAlphaTesting = needsAlphaTesting;
  820. babylonShaderMaterial.options.attributes = attributeList.ToArray();
  821. babylonShaderMaterial.options.uniforms = uniformList.ToArray();
  822. babylonShaderMaterial.options.samplers = samplerList.ToArray();
  823. babylonShaderMaterial.options.defines = defineList.ToArray();
  824. string vertexProgram = GetShaderProgramSection(basename, program, BabylonProgramSection.Vertex);
  825. var vertextFile = Path.Combine(outpath, basename + ".vertex.fx");
  826. if (exportationOptions.EmbeddedShaders)
  827. {
  828. shaderpath.Add("vertexElement", ("base64:" + Tools.FormatBase64(vertexProgram)));
  829. }
  830. else
  831. {
  832. File.WriteAllText(vertextFile, vertexProgram);
  833. }
  834. string fragmentProgram = GetShaderProgramSection(basename, program, BabylonProgramSection.Fragment);
  835. var fragmentFile = Path.Combine(outpath, basename + ".fragment.fx");
  836. if (exportationOptions.EmbeddedShaders)
  837. {
  838. shaderpath.Add("fragmentElement", ("base64:" + Tools.FormatBase64(fragmentProgram)));
  839. }
  840. else
  841. {
  842. File.WriteAllText(fragmentFile, fragmentProgram);
  843. }
  844. babylonShaderMaterial.shaderPath = (exportationOptions.EmbeddedShaders) ? (object)shaderpath : (object)basename;
  845. materialsDictionary.Add(babylonShaderMaterial.name, babylonShaderMaterial);
  846. return babylonShaderMaterial;
  847. }
  848. private string GetShaderProgramSection(string name, string program, BabylonProgramSection section)
  849. {
  850. string result = String.Empty;
  851. string[] lines = program.Split('\n');
  852. int babylonIndexStart = -1, babylonIndexEnd = -1;
  853. int vertextIndexStart = -1, vertextIndexEnd = -1;
  854. int fragmentIndexStart = -1, fragmentIndexEnd = -1;
  855. for (int ii = 0; ii < lines.Length; ii++)
  856. {
  857. string line = lines[ii];
  858. if (babylonIndexStart < 0 && line.IndexOf("#ifdef BABYLON", StringComparison.OrdinalIgnoreCase) >= 0)
  859. {
  860. babylonIndexStart = ii;
  861. }
  862. if (babylonIndexEnd < 0 && line.IndexOf("#endif //BABYLON-END", StringComparison.OrdinalIgnoreCase) >= 0)
  863. {
  864. babylonIndexEnd = ii;
  865. }
  866. if (vertextIndexStart < 0 && line.IndexOf("#ifdef VERTEX", StringComparison.OrdinalIgnoreCase) >= 0)
  867. {
  868. vertextIndexStart = ii;
  869. }
  870. if (vertextIndexEnd < 0 && line.IndexOf("#endif //VERTEX-END", StringComparison.OrdinalIgnoreCase) >= 0)
  871. {
  872. vertextIndexEnd = ii;
  873. }
  874. if (fragmentIndexStart < 0 && line.IndexOf("#ifdef FRAGMENT", StringComparison.OrdinalIgnoreCase) >= 0)
  875. {
  876. fragmentIndexStart = ii;
  877. }
  878. if (fragmentIndexEnd < 0 && line.IndexOf("#endif //FRAGMENT-END", StringComparison.OrdinalIgnoreCase) >= 0)
  879. {
  880. fragmentIndexEnd = ii;
  881. }
  882. }
  883. // Note: All Babylon Shader Blocks Are Required
  884. if (babylonIndexStart >= 0 && babylonIndexEnd >= 0 && vertextIndexStart >= 0 && vertextIndexEnd >= 0 && fragmentIndexStart >= 0 && fragmentIndexEnd >= 0)
  885. {
  886. int lineStart = -1, lineEnd = -1;
  887. switch (section)
  888. {
  889. case BabylonProgramSection.Babylon:
  890. lineStart = babylonIndexStart;
  891. lineEnd = babylonIndexEnd;
  892. break;
  893. case BabylonProgramSection.Vertex:
  894. lineStart = vertextIndexStart;
  895. lineEnd = vertextIndexEnd;
  896. break;
  897. case BabylonProgramSection.Fragment:
  898. lineStart = fragmentIndexStart;
  899. lineEnd = fragmentIndexEnd;
  900. break;
  901. }
  902. if (lineStart >= 0 && lineEnd >= 0)
  903. {
  904. lineStart++;
  905. for (int xx = lineStart; xx < lineEnd; xx++)
  906. {
  907. string buffer = lines[xx];
  908. buffer = buffer.TrimEnd('\n').TrimEnd('\r');
  909. result += (buffer + "\r\n");
  910. }
  911. }
  912. else
  913. {
  914. Debug.LogError("Invalid Babylon Shader Block Lines: " + name);
  915. }
  916. }
  917. else
  918. {
  919. Debug.LogError("Invalid Babylon Shader Block Format: " + name);
  920. }
  921. return result;
  922. }
  923. private BabylonTexture DumpReflectionTexture()
  924. {
  925. if (sceneReflectionTexture != null)
  926. {
  927. return sceneReflectionTexture;
  928. }
  929. bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
  930. string fext = (png == true) ? ".png" : ".jpg";
  931. // Take only reflection source currently and not the RenderSettings.ambientMode
  932. if (RenderSettings.defaultReflectionMode == UnityEngine.Rendering.DefaultReflectionMode.Skybox)
  933. {
  934. var skybox = RenderSettings.skybox;
  935. if (SceneController != null && skybox != null)
  936. {
  937. if (skybox.shader.name == "Skybox/Cubemap")
  938. {
  939. var cubeMap = skybox.GetTexture("_Tex") as Cubemap;
  940. if (cubeMap != null)
  941. {
  942. var srcTexturePath = AssetDatabase.GetAssetPath(cubeMap);
  943. if (srcTexturePath.EndsWith(".hdr", StringComparison.OrdinalIgnoreCase))
  944. {
  945. var hdr = new BabylonHDRCubeTexture();
  946. hdr.size = cubeMap.width;
  947. sceneReflectionTexture = hdr;
  948. sceneReflectionTexture.isCube = true;
  949. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture, true);
  950. }
  951. else
  952. {
  953. sceneReflectionTexture = new BabylonTexture();
  954. sceneReflectionTexture.isCube = true;
  955. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture, false);
  956. if (png) (sceneReflectionTexture as BabylonTexture).extensions = new string[] { "_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png" };
  957. }
  958. sceneReflectionTexture.level = (SceneController != null) ? SceneController.skyboxOptions.lightIntensity : 1.0f;
  959. }
  960. }
  961. else if (skybox.shader.name == "Skybox/6 Sided")
  962. {
  963. var frontTexture = skybox.GetTexture("_FrontTex") as Texture2D;
  964. var backTexture = skybox.GetTexture("_BackTex") as Texture2D;
  965. var leftTexture = skybox.GetTexture("_LeftTex") as Texture2D;
  966. var rightTexture = skybox.GetTexture("_RightTex") as Texture2D;
  967. var upTexture = skybox.GetTexture("_UpTex") as Texture2D;
  968. var downTexture = skybox.GetTexture("_DownTex") as Texture2D;
  969. if (frontTexture != null && backTexture != null && leftTexture != null && rightTexture != null && upTexture != null && downTexture != null)
  970. {
  971. sceneReflectionTexture = new BabylonTexture();
  972. sceneReflectionTexture.name = String.Format("{0}Reflection", SceneName);
  973. sceneReflectionTexture.isCube = true;
  974. var frontTextureName = String.Format("{0}_pz{1}", sceneReflectionTexture.name, fext);
  975. var frontTexturePath = Path.Combine(babylonScene.OutputPath, frontTextureName);
  976. CopyTextureFace(frontTexturePath, frontTextureName, frontTexture);
  977. var backTextureName = String.Format("{0}_nz{1}", sceneReflectionTexture.name, fext);
  978. var backTexturePath = Path.Combine(babylonScene.OutputPath, backTextureName);
  979. CopyTextureFace(backTexturePath, backTextureName, backTexture);
  980. var leftTextureName = String.Format("{0}_px{1}", sceneReflectionTexture.name, fext);
  981. var leftTexturePath = Path.Combine(babylonScene.OutputPath, leftTextureName);
  982. CopyTextureFace(leftTexturePath, leftTextureName, leftTexture);
  983. var rightTextureName = String.Format("{0}_nx{1}", sceneReflectionTexture.name, fext);
  984. var rightTexturePath = Path.Combine(babylonScene.OutputPath, rightTextureName);
  985. CopyTextureFace(rightTexturePath, rightTextureName, rightTexture);
  986. var upTextureName = String.Format("{0}_py{1}", sceneReflectionTexture.name, fext);
  987. var upTexturePath = Path.Combine(babylonScene.OutputPath, upTextureName);
  988. CopyTextureFace(upTexturePath, upTextureName, upTexture);
  989. var downTextureName = String.Format("{0}_ny{1}", sceneReflectionTexture.name, fext);
  990. var downTexturePath = Path.Combine(babylonScene.OutputPath, downTextureName);
  991. CopyTextureFace(downTexturePath, downTexturePath, downTexture);
  992. if (png) (sceneReflectionTexture as BabylonTexture).extensions = new string[] { "_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png" };
  993. sceneReflectionTexture.level = (SceneController != null) ? SceneController.skyboxOptions.lightIntensity : 1.0f;
  994. }
  995. }
  996. }
  997. }
  998. else if (RenderSettings.customReflection != null)
  999. {
  1000. var cubeMap = RenderSettings.customReflection;
  1001. var srcTexturePath = AssetDatabase.GetAssetPath(cubeMap);
  1002. if (srcTexturePath.EndsWith(".hdr", StringComparison.OrdinalIgnoreCase))
  1003. {
  1004. var hdr = new BabylonHDRCubeTexture();
  1005. hdr.size = cubeMap.width;
  1006. sceneReflectionTexture = hdr;
  1007. sceneReflectionTexture.isCube = true;
  1008. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture);
  1009. }
  1010. else
  1011. {
  1012. sceneReflectionTexture = new BabylonTexture();
  1013. sceneReflectionTexture.isCube = true;
  1014. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture);
  1015. if (png) (sceneReflectionTexture as BabylonTexture).extensions = new string[] { "_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png" };
  1016. }
  1017. sceneReflectionTexture.level = (SceneController != null) ? SceneController.skyboxOptions.lightIntensity : 1.0f;
  1018. }
  1019. return sceneReflectionTexture;
  1020. }
  1021. private BabylonTexture DumpTextureFromMaterial(Material material, string name)
  1022. {
  1023. if (!material.HasProperty(name))
  1024. {
  1025. return null;
  1026. }
  1027. var texture = material.GetTexture(name);
  1028. return DumpTexture(texture, material, name);
  1029. }
  1030. private BabylonTexture DumpTexture(Texture texture, Material material = null, string name = "", bool isLightmap = false)
  1031. {
  1032. if (texture == null)
  1033. {
  1034. return null;
  1035. }
  1036. var texturePath = AssetDatabase.GetAssetPath(texture);
  1037. var textureName = Path.GetFileName(texturePath);
  1038. var babylonTexture = new BabylonTexture { name = textureName };
  1039. if (material != null)
  1040. {
  1041. var textureScale = material.GetTextureScale(name);
  1042. babylonTexture.uScale = textureScale.x;
  1043. babylonTexture.vScale = textureScale.y;
  1044. var textureOffset = material.GetTextureOffset(name);
  1045. babylonTexture.uOffset = textureOffset.x;
  1046. babylonTexture.vOffset = textureOffset.y;
  1047. }
  1048. var texture2D = texture as Texture2D;
  1049. if (texture2D)
  1050. {
  1051. CopyTexture(texturePath, texture2D, babylonTexture, isLightmap);
  1052. }
  1053. else
  1054. {
  1055. var cubemap = texture as Cubemap;
  1056. if (cubemap != null)
  1057. {
  1058. CopyTextureCube(texturePath, cubemap, babylonTexture);
  1059. }
  1060. }
  1061. return babylonTexture;
  1062. }
  1063. private static void DumpTransparency(Material material, BabylonPBRMaterial babylonPbrMaterial)
  1064. {
  1065. if (material.HasProperty("_Mode"))
  1066. {
  1067. var mode = material.GetFloat("_Mode");
  1068. if (mode >= 2.0f)
  1069. {
  1070. // Transparent Albedo
  1071. if (babylonPbrMaterial.albedoTexture != null && babylonPbrMaterial.albedoTexture.hasAlpha)
  1072. {
  1073. babylonPbrMaterial.useAlphaFromAlbedoTexture = true;
  1074. }
  1075. else
  1076. {
  1077. // Material Alpha
  1078. babylonPbrMaterial.alpha = babylonPbrMaterial.albedo[3];
  1079. }
  1080. }
  1081. else if (mode == 1.0f)
  1082. {
  1083. // Cutout
  1084. // Follow the texture hasAlpha property.
  1085. }
  1086. else
  1087. {
  1088. // Opaque
  1089. if (babylonPbrMaterial.albedoTexture != null)
  1090. {
  1091. babylonPbrMaterial.albedoTexture.hasAlpha = false;
  1092. }
  1093. babylonPbrMaterial.alpha = 1.0f;
  1094. }
  1095. }
  1096. }
  1097. }
  1098. }