Explorar o código

Merge branch 'master' of https://github.com/BabylonJS/Babylon.js

Temechon %!s(int64=8) %!d(string=hai) anos
pai
achega
d218c5c147
Modificáronse 84 ficheiros con 56491 adicións e 3344 borrados
  1. 1 0
      .gitignore
  2. 1 0
      Exporters/3ds Max/BabylonExport.Entities/BabylonPBRMaterial.cs
  3. 8 0
      Exporters/3ds Max/BabylonExport.Entities/BabylonStandardMaterial.cs
  4. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/BabylonExport.Entities.dll
  5. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/ExportationOptions.cs
  6. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/ExporterWindow.cs
  7. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/Ionic.Zip.dll
  8. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/JsonFx.Json.dll
  9. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/JsonFx.dll
  10. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Animations.cs
  11. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Cameras.cs
  12. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Lights.cs
  13. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Materials.cs
  14. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Meshes.cs
  15. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.cs
  16. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/SerializableVector3.cs
  17. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/Tools.cs
  18. 0 0
      Exporters/Unity 5/Deprecated/Unity3D2Babylon/WebServer.cs
  19. 0 0
      Exporters/Unity 5/Deprecated/readme.md
  20. 1372 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Editor/VSCode.cs
  21. 38 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/babylon.bjs
  22. 13687 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/cannon.bjs
  23. 10 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/canvas2d.bjs
  24. 1 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/hand.bjs
  25. 2 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/manager.bjs
  26. 16659 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/navmesh.bjs
  27. 12512 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/oimo.bjs
  28. BIN=BIN
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/AjaxMin.dll
  29. BIN=BIN
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/BabylonExport.Entities.dll
  30. BIN=BIN
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/Ionic.Zip.dll
  31. BIN=BIN
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/JsonFx.Json.dll
  32. BIN=BIN
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/JsonFx.dll
  33. 13 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonAudioSource.cs
  34. 14 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonFlareSystem.cs
  35. 37 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonParticleSystem.cs
  36. 14 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonPhysicsState.cs
  37. 11 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonShadowBake.cs
  38. 11 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonTagsComponent.cs
  39. 41 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonTerrainGenerator.cs
  40. 89 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExportationOptions.cs
  41. 506 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterMetadata.cs
  42. 45 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterOutput.cs
  43. 162 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterSplitter.cs
  44. 152 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterTerrain.cs
  45. 80 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterTexture.cs
  46. 857 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterWindow.cs
  47. 225 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Animations.cs
  48. 198 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Cameras.cs
  49. 132 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Lights.cs
  50. 1098 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Materials.cs
  51. 437 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Meshes.cs
  52. 1467 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.cs
  53. 26 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SerializableColor.cs
  54. 25 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SerializableVector3.cs
  55. 1618 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/Tools.cs
  56. 211 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/WebBrowser.cs
  57. 633 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/WebServer.cs
  58. 431 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Config/index.html
  59. 13 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Config/options.json
  60. 23 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/camera.template
  61. 28 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/controller.template
  62. 19 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/editora.template
  63. 19 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/editorb.template
  64. 20 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/javascript.template
  65. 23 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/light.template
  66. 23 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/mesh.template
  67. 16 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/typescript.template
  68. 92 0
      Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Shaders/amiga.template
  69. BIN=BIN
      Exporters/Unity 5/EditorToolkit/Redist/Asset Store-5.x/BabylonJS/BabylonJS Editor Toolkit.unitypackage
  70. 21 0
      Exporters/Unity 5/EditorToolkit/Redist/readme.me
  71. 1 1
      Playground/debug.html
  72. 1 1
      Playground/index-local.html
  73. 2 1
      Playground/index.html
  74. 13 13
      dist/preview release/babylon.core.js
  75. 3219 3219
      dist/preview release/babylon.d.ts
  76. 16 16
      dist/preview release/babylon.js
  77. 22 27
      dist/preview release/babylon.max.js
  78. 16 16
      dist/preview release/babylon.noworker.js
  79. 1 0
      dist/preview release/what's new.md
  80. 2 1
      src/Cameras/babylon.camera.ts
  81. 14 16
      src/Materials/Textures/babylon.renderTargetTexture.ts
  82. 35 10
      src/Materials/babylon.pbrMaterial.ts
  83. 19 14
      src/Shaders/pbr.fragment.fx
  84. 9 9
      src/babylon.engine.ts

+ 1 - 0
.gitignore

@@ -23,6 +23,7 @@ proceduralTexturesLibrary/src/**/*.js
 postProcessLibrary/src/**/*.js
 canvas2D/src/**/*.js
 inspector/src/**/*.js
+serializers/src/**/*.js
 
 # Build results
 [Dd]ebug/

+ 1 - 0
Exporters/3ds Max/BabylonExport.Entities/BabylonPBRMaterial.cs

@@ -155,6 +155,7 @@ namespace BabylonExport.Entities
             specularIntensity = 1.0f;
             cameraExposure = 1.0f;
             cameraContrast = 1.0f;
+            useEmissiveAsIllumination = false;
 
             overloadedShadowIntensity = 1.0f;
             overloadedShadeIntensity = 1.0f;

+ 8 - 0
Exporters/3ds Max/BabylonExport.Entities/BabylonStandardMaterial.cs

@@ -62,6 +62,12 @@ namespace BabylonExport.Entities
         [DataMember]
         public bool disableLighting { get; set; }
 
+        [DataMember]
+        public bool useEmissiveAsIllumination { get; set; }
+
+        [DataMember]
+        public bool linkEmissiveWithDiffuse { get; set; }
+
         public BabylonStandardMaterial() : base()
         {
             ambient = new[] {1.0f, 1.0f, 1.0f};
@@ -70,6 +76,8 @@ namespace BabylonExport.Entities
             emissive = new[] { 0f, 0f, 0f };
             specularPower = 64;
             useSpecularOverAlpha = true;
+            useEmissiveAsIllumination = false;
+            linkEmissiveWithDiffuse = false;
         }
     }
 }

Exporters/Unity 5/Unity3D2Babylon/BabylonExport.Entities.dll → Exporters/Unity 5/Deprecated/Unity3D2Babylon/BabylonExport.Entities.dll


Exporters/Unity 5/Unity3D2Babylon/ExportationOptions.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/ExportationOptions.cs


Exporters/Unity 5/Unity3D2Babylon/ExporterWindow.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/ExporterWindow.cs


Exporters/Unity 5/Unity3D2Babylon/Ionic.Zip.dll → Exporters/Unity 5/Deprecated/Unity3D2Babylon/Ionic.Zip.dll


Exporters/Unity 5/Unity3D2Babylon/JsonFx.Json.dll → Exporters/Unity 5/Deprecated/Unity3D2Babylon/JsonFx.Json.dll


Exporters/Unity 5/Unity3D2Babylon/JsonFx.dll → Exporters/Unity 5/Deprecated/Unity3D2Babylon/JsonFx.dll


Exporters/Unity 5/Unity3D2Babylon/SceneBuilder.Animations.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Animations.cs


Exporters/Unity 5/Unity3D2Babylon/SceneBuilder.Cameras.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Cameras.cs


Exporters/Unity 5/Unity3D2Babylon/SceneBuilder.Lights.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Lights.cs


Exporters/Unity 5/Unity3D2Babylon/SceneBuilder.Materials.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Materials.cs


Exporters/Unity 5/Unity3D2Babylon/SceneBuilder.Meshes.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.Meshes.cs


Exporters/Unity 5/Unity3D2Babylon/SceneBuilder.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SceneBuilder.cs


Exporters/Unity 5/Unity3D2Babylon/SerializableVector3.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/SerializableVector3.cs


Exporters/Unity 5/Unity3D2Babylon/Tools.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/Tools.cs


Exporters/Unity 5/Unity3D2Babylon/WebServer.cs → Exporters/Unity 5/Deprecated/Unity3D2Babylon/WebServer.cs


Exporters/Unity 5/readme.md → Exporters/Unity 5/Deprecated/readme.md


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1372 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Editor/VSCode.cs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 38 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/babylon.bjs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 13687 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/cannon.bjs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 10 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/canvas2d.bjs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/hand.bjs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 2 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/manager.bjs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 16659 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/navmesh.bjs


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 12512 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Library/oimo.bjs


BIN=BIN
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/AjaxMin.dll


BIN=BIN
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/BabylonExport.Entities.dll


BIN=BIN
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/Ionic.Zip.dll


BIN=BIN
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/JsonFx.Json.dll


BIN=BIN
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Plugins/JsonFx.dll


+ 13 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonAudioSource.cs

@@ -0,0 +1,13 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Audio Source", 2)]
+    public class BabylonAudioSource : MonoBehaviour
+    {
+        public bool exportAudio = true;
+        public AudioClip sound;
+        public BabylonSoundOptions options;
+    }
+}

+ 14 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonFlareSystem.cs

@@ -0,0 +1,14 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Flare System", 3)]
+    public sealed class BabylonFlareSystem : MonoBehaviour
+    {
+        public bool exportFlare = true;
+        public string flareName = String.Empty;
+        public int borderLimit = 300;
+        public UnityLensFlareItem[] lensFlares = null;
+    }
+}

+ 37 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonParticleSystem.cs

@@ -0,0 +1,37 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Particle System", 4)]
+    public sealed class BabylonParticleSystem : MonoBehaviour
+    {
+        public bool exportParticle = true;
+        public string particleName = String.Empty;
+        public Texture2D texture = null;
+        public Color textureMask = Color.white;
+        public bool autoStart = true;
+        public float updateSpeed = 0.01f;
+        public float emitRate = 10;
+        public Vector3 gravity = new Vector3(0, -9.8f, 0);
+        public BabylonParticleBlend blendMode = BabylonParticleBlend.OneOne;
+        public int capacity = 100;
+        public Color color1 = Color.white;
+        public Color color2 = Color.white;
+        public Color colorDead = Color.black;
+        public Vector3 direction1 = new Vector3(0, 1.0f, 0);
+        public Vector3 direction2 = new Vector3(0, 1.0f, 0);
+        public Vector3 minEmitBox = new Vector3(-0.5f, -0.5f, -0.5f);
+        public Vector3 maxEmitBox = new Vector3(0.5f, 0.5f, 0.5f);
+        public float minEmitPower = 1;
+        public float maxEmitPower = 1;
+        public float minLifeTime = 1;
+        public float maxLifeTime = 1;
+        public float minSize = 1;
+        public float maxSize = 1;
+        public float minAngularSpeed = 0;
+        public float maxAngularSpeed = 0;
+        public int targetStopFrame = 0;
+        public float deadAlpha = 0;
+    }
+}

+ 14 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonPhysicsState.cs

@@ -0,0 +1,14 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Physics State", 1)]
+    public sealed class BabylonPhysicsState : MonoBehaviour
+    {
+        public float mass = 0.0f;
+        public float friction = 0.2f;
+        public float restitution = 0.2f;
+        public BabylonPhysicsImposter imposter = BabylonPhysicsImposter.None;
+    }
+}

+ 11 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonShadowBake.cs

@@ -0,0 +1,11 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Shadow Bake", 0)]
+    public sealed class BabylonShadowBake : MonoBehaviour
+    {
+        public BabylonShadowOptions shadowOption = BabylonShadowOptions.Baked;
+    }
+}

+ 11 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonTagsComponent.cs

@@ -0,0 +1,11 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Component Tags", 90)]
+    public sealed class BabylonTagsComponent : MonoBehaviour
+    {
+        public string babylonTags;
+    }
+}

+ 41 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/BabylonTerrainGenerator.cs

@@ -0,0 +1,41 @@
+using System;
+using UnityEngine;
+
+namespace UnityEditor
+{
+    [AddComponentMenu("BabylonJS/Terrain Generator", 99)]
+    public sealed class BabylonTerrainGenerator : MonoBehaviour
+    {
+        public Material surfaceMaterial = null;
+
+        public BabylonTerrainResolution terrainResolution = BabylonTerrainResolution.HighResolution;
+
+        [Header("Heightmap Tools")]
+
+        [Range(0.0f, 0.1f)]
+        public float floorThreashold = 0.001f;
+
+        [Range(0.0f, 1.0f)]
+        public float heightmapStrength = 0.01f;
+
+        [Range(10, 100)]
+        public int groundTessellation = 50;
+
+        [Header("Lightmap Details")]
+
+        [Range(0, 1)]
+        public int coordinatesIndex = 0;
+
+        [Header("Ground Physics State")]
+
+        public bool physicsActive = false;
+
+        public float physicsMass = 0.0f;
+
+        public float physicsFriction = 0.2f;
+
+        public float physicsRestitution = 0.2f;
+
+        public BabylonPhysicsImposter physicsImpostor = BabylonPhysicsImposter.Box;
+    }
+}

+ 89 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExportationOptions.cs

@@ -0,0 +1,89 @@
+using System;
+using System.IO;
+using UnityEngine;
+using BabylonHosting;
+
+namespace Unity3D2Babylon
+{
+    public class ExportationOptions
+    {
+        public bool HostPreviewPage { get; set; }
+        public bool BuildJavaScript { get; set; }
+        public bool CompileTypeScript { get; set; }
+        public bool AttachUnityEditor { get; set; }
+        public bool ShowDebugControls { get; set; }
+        public float ReflectionDefaultLevel { get; set; }
+        public int DefaultQualityLevel { get; set; }
+        public bool EmbeddedShaders { get; set; }
+        public bool ExportLightmaps { get; set; }
+        public bool ExportCollisions { get; set; }
+        public bool ExportPhysics { get; set; }
+        public bool ExportShadows { get; set; }
+        public bool WorkerCollisions { get; set; }
+        public SerializableVector3 Gravity { get; set; }
+        public SerializableVector3 CameraEllipsoid { get; set; }
+        public int ShadowMapSize { get; set; }
+        public float ShadowMapBias { get; set; }
+        public float ShadowBlurScale { get; set; }
+        public float ProductionVersion { get; set; }
+        public int DefaultUpdateOptions { get; set; }
+        public int DefaultPreviewWindow { get; set; }
+        public int DefaultLightFilter { get; set; }
+        public int DefaultImageFormat { get; set; }
+        public int DefaultPhysicsEngine { get; set; }
+        public int DefaultLightmapMode { get; set; }
+        public int DefaultLightmapBaking { get; set; }
+        public int DefaultCoordinatesIndex { get; set; }
+        public int DefaultColliderDetail { get; set; }
+        public string DefaultIndexPage { get; set; }
+        public string DefaultBuildPath { get; set; }
+        public string DefaultScenePath { get; set; }
+        public string DefaultScriptPath { get; set; }
+        public int DefaultServerPort { get; set; }
+        public string DefaultShaderFolder { get; set; }
+        public string DefaultProjectFolder { get; set; }
+        public string DefaultTypeSriptPath { get; set; }
+        public string DefaultNodeRuntimePath { get; set; }
+
+        public ExportationOptions()
+        {
+            ProductionVersion = (float)ExporterWindow.BabylonVersion;
+            HostPreviewPage = true;
+            BuildJavaScript = true;
+            CompileTypeScript = true;
+            AttachUnityEditor = true;
+            ShowDebugControls = true;
+            ReflectionDefaultLevel = 0.25f;
+            DefaultQualityLevel = 90;
+            EmbeddedShaders = true;
+            ExportLightmaps = true;
+            ExportCollisions = true;
+            ExportPhysics = true;
+            ExportShadows = false;
+            WorkerCollisions = false;
+            Gravity = new Vector3(0, -0.9f, 0);
+            CameraEllipsoid = new Vector3(0.5f, 0.85f, 0.5f);
+            ShadowMapSize = 1024;
+            ShadowMapBias = 0.0001f;
+            ShadowBlurScale = 0;
+            DefaultUpdateOptions = 0;
+            DefaultPreviewWindow = 0;
+            DefaultLightFilter = 4;
+            DefaultImageFormat = 0;
+            DefaultLightmapMode = 0;
+            DefaultLightmapBaking = 0;
+            DefaultCoordinatesIndex = 1;
+            DefaultColliderDetail = 4;
+            DefaultPhysicsEngine = 0;
+            DefaultShaderFolder = String.Empty;
+            DefaultServerPort = 8888;
+            DefaultBuildPath = "Build";
+            DefaultScenePath = "Scenes";
+            DefaultScriptPath = "Scripts";
+            DefaultIndexPage = "Index.html";
+            DefaultTypeSriptPath = Tools.GetDefaultTypeScriptPath();
+            DefaultNodeRuntimePath = Tools.GetDefaultNodeRuntimePath();
+            DefaultProjectFolder = Tools.FormatSafePath(Application.dataPath.Replace("/Assets", "/Project"));
+        }
+    }
+}

+ 506 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterMetadata.cs

@@ -0,0 +1,506 @@
+using System;
+using System.Reflection;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+using System.IO;
+using BabylonExport.Entities;
+using UnityEngine;
+using UnityEditor;
+using Object = UnityEngine.Object;
+
+namespace Unity3D2Babylon
+{
+    #region Unity Components
+    [DataContract]
+    public class UnityScriptFile
+    {
+        [DataMember]
+        public int order;
+
+        [DataMember]
+        public string name;
+
+        [DataMember]
+        public string script;
+    }
+
+    [DataContract]
+    public class UnityFlareSystem
+    {
+        [DataMember]
+        public string name;
+
+        [DataMember]
+        public string emitterId;
+
+        [DataMember]
+        public int borderLimit;
+
+        [DataMember]
+        public UnityFlareItem[] lensFlares;
+    }
+
+    [DataContract]
+    public class UnityFlareItem
+    {
+        [DataMember]
+        public float size;
+
+        [DataMember]
+        public float position;
+
+        [DataMember]
+        public float[] color;
+
+        [DataMember]
+        public string textureName;
+    }
+
+    [DataContract]
+    public class UnityBabylonColor
+    {
+        [DataMember]
+        public float r;
+
+        [DataMember]
+        public float g;
+
+        [DataMember]
+        public float b;
+
+        [DataMember]
+        public float a;
+    }
+
+    [DataContract]
+    public class UnityBablylonVector2
+    {
+        [DataMember]
+        public float x;
+
+        [DataMember]
+        public float y;
+    }
+
+    [DataContract]
+    public class UnityBablylonVector3
+    {
+        [DataMember]
+        public float x;
+
+        [DataMember]
+        public float y;
+
+        [DataMember]
+        public float z;
+    }
+
+    [DataContract]
+    public class UnityBablylonVector4
+    {
+        [DataMember]
+        public float x;
+
+        [DataMember]
+        public float y;
+
+        [DataMember]
+        public float z;
+
+        [DataMember]
+        public float w;
+    }
+
+    [DataContract]
+    public class UnityScriptComponent
+    {
+        [DataMember]
+        public int order;
+
+        [DataMember]
+        public string name;
+
+        [DataMember]
+        public string klass;
+
+        [DataMember]
+        public bool update;
+
+        [DataMember]
+        public bool controller;
+
+        [DataMember]
+        public Dictionary<string, object> properties;
+
+        [DataMember]
+        public object instance;
+
+        [DataMember]
+        public object tag;
+
+        public UnityScriptComponent()
+        {
+            this.order = 0;
+            this.name = String.Empty;
+            this.klass = String.Empty;
+            this.update = false;
+            this.controller = false;
+            this.properties = new Dictionary<string, object>();
+            this.instance = null;
+            this.tag = null;
+        }
+    }
+    #endregion
+
+    #region Read Only Attribute
+    public class ReadOnlyAttribute : PropertyAttribute { }
+    [CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
+    public class ReadOnlyDrawer : PropertyDrawer
+    {
+        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
+        {
+            return EditorGUI.GetPropertyHeight(property, label, true);
+        }
+
+        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
+        {
+            GUI.enabled = false;
+            EditorGUI.PropertyField(position, property, label, true);
+            GUI.enabled = true;
+        }
+    }
+    #endregion
+}
+
+namespace UnityEditor
+{
+    [System.Serializable]
+    public class EmbeddedAsset
+    {
+        public BabylonTextEncoding encoding = BabylonTextEncoding.RawBytes;
+        public TextAsset textAsset;
+    }
+
+    [System.Serializable]
+    public class SceneMetaData
+    {
+        public bool api;
+        public Dictionary<string, object> properties;
+        public List<string> bakedMaterials;
+
+        public SceneMetaData()
+        {
+            this.api = true;
+            this.properties = new Dictionary<string, object>();
+            this.bakedMaterials = new List<string>();
+        }
+    }
+
+    [System.Serializable]
+    public class UnityMetaData
+    {
+        public bool api;
+        public string type;
+        public string objectName;
+        public string objectId;
+        public string tagName;
+        public int layerIndex;
+        public string layerName;
+        public int areaIndex;
+        public object navAgent;
+        public object meshLink;
+        public object meshObstacle;
+        public List<object> components;
+        public Dictionary<string, object> properties;
+
+        public UnityMetaData()
+        {
+            this.api = true;
+            this.type = "Unity";
+            this.objectName = String.Empty;
+            this.objectId = String.Empty;
+            this.tagName = String.Empty;
+            this.layerIndex = -1;
+            this.layerName = String.Empty;
+            this.areaIndex = -1;
+            this.navAgent = null;
+            this.meshLink = null;
+            this.meshObstacle = null;
+            this.components = new List<object>();
+            this.properties = new Dictionary<string, object>();
+        }
+    }
+
+    [System.Serializable]
+    public sealed class UnityLensFlareItem
+    {
+        public float size;
+        public float position;
+        public Color color;
+        public Texture2D texture;
+    }
+
+    [System.Serializable]
+    public class BabylonSceneOptions
+    {
+        public bool autoClear = true;
+        public Color ambientColor = Color.clear;
+        public BabylonNavigationMesh navigationMesh = BabylonNavigationMesh.EnableNavigation;
+        public bool particleSystems = true;
+        public bool lensFlareSystems = true;
+        public bool autoDrawInterface = true;
+        public BabylonGuiMode userInterfaceMode = BabylonGuiMode.None;
+        public EmbeddedAsset graphicUserInterface = null;
+    }
+
+    [System.Serializable]
+    public class BabylonSoundOptions
+    {
+        public float volume = 1;
+        public float playbackRate = 1;
+        public bool autoplay = false;
+        public bool loop = false;
+        public int soundTrackId = -1;
+        public bool spatialSound = false;
+        public Vector3 position = new Vector3(0, 0, 0);
+        public float refDistance = 1;
+        public float rolloffFactor = 1;
+        public float maxDistance = 100;
+        public string distanceModel = "linear";
+        public string panningModel = "equalpower";
+        public bool isDirectional = false;
+        public float coneInnerAngle = 360;
+        public float coneOuterAngle = 360;
+        public float coneOuterGain = 0;
+        public Vector3 directionToMesh = new Vector3(1, 0, 0);
+    }
+
+    [System.Serializable]
+    public class BabylonLightOptions
+    {
+        public BabylonAmbientLighting lightMode = BabylonAmbientLighting.UnityAmbientLighting;
+        [Range(0.0f, 10.0f)]
+        public float lightLevel = 1;
+        public Color specularColor = Color.black;
+    }
+
+    [System.Serializable]
+    public class BabylonSkyboxOptions
+    {
+        public bool exportSkybox = true;
+        public BabylonTextureExport textureFile = BabylonTextureExport.AlwaysExport;
+        public Color albedoColor = Color.white;
+        public Color reflectivityColor = Color.white;
+        [Range(0.0f, 5.0f)]
+        public float lightIntensity = 1;
+        [Range(0.0f, 5.0f)]
+        public float microSurface = 1;
+        [Range(0.0f, 5.0f)]
+        public float cameraExposure = 1;
+        [Range(0.0f, 5.0f)]
+        public float cameraContrast = 1;
+        [Range(0.0f, 5.0f)]
+        public float directIntensity = 1;
+        [Range(0.0f, 5.0f)]
+        public float emissiveIntensity = 1;
+        [Range(0.0f, 5.0f)]
+        public float specularIntensity = 1;
+        [Range(0.0f, 5.0f)]
+        public float environmentIntensity = 1;
+    }
+
+    [System.Serializable]
+    public class BabylonManifestOptions
+    {
+        public bool exportManifest = true;
+        public int manifestVersion = 1;
+        public bool storeSceneOffline = false;
+        public bool storeTextureOffline = false;
+    }
+
+    public enum BabylonImageFormat
+    {
+        JPEG = 0,
+        PNG = 1
+    }
+
+    public enum BabylonFogMode
+    {
+        None = 0,
+        Exponential = 1,
+        FastExponential = 2,
+        Linear = 3
+    }
+
+    public enum BabylonGuiMode
+    {
+        None = 0,
+        Html = 1
+    }
+
+    public enum BabylonTickOptions
+    {
+        EnableTick = 0,
+        DisableTick = 1
+    }
+
+    public enum BabylonTextEncoding
+    {
+        RawBytes = 0,
+        EncodedText = 1
+    }
+
+    public enum BabylonLightmapMode
+    {
+        ShadowBaking = 0,
+        FullLightBaking = 1
+    }
+
+    public enum BabylonShadowOptions
+    {
+        Baked = 0,
+        Realtime = 1
+    }
+
+    public enum BabylonLightmapBaking
+    {
+        Disabled = 0,
+        Enabled = 1
+    }
+
+    public enum BabylonParticleBlend
+    {
+        OneOne = 0,
+        Standard = 1
+    }
+
+    public enum BabylonTextureExport
+    {
+        AlwaysExport = 0,
+        IfNotExists = 1
+    }
+
+    public enum BabylonPhysicsEngine
+    {
+        Cannon = 0,
+        Oimo = 1
+    }
+
+    public enum BabylonProgramSection
+    {
+        Babylon = 0,
+        Vertex = 1,
+        Fragment = 2
+    }
+
+    public enum BabylonPhysicsImposter
+    {
+        None = 0,
+        Sphere = 1,
+        Box = 2,
+        Plane = 3,
+        Mesh = 4,
+        Cylinder = 7,
+        Particle = 8,
+        HeightMap = 9
+    }
+
+    public enum BabylonAmbientLighting
+    {
+        NoAmbientLighting = 0,
+        UnityAmbientLighting = 1
+    }
+
+    public enum BabylonNavigationMesh
+    {
+        DisableNavigation = 0,
+        EnableNavigation = 1
+    }
+
+    public enum BabylonUpdateOptions
+    {
+        StableProduction = 0,
+        PreviewRelease = 1,
+    }
+
+    public enum BabylonLightingFilter
+    {
+        NoFilter = 0,
+        PoissonSampling = 1,
+        VarianceShadowMap = 2,
+        BlurVarianceShadowMap = 3,
+        SoftPoissonSampling = 4
+    }
+
+    public class BabylonTerrainData
+    {
+        public Vector3[] vertices;
+        public Vector3[] normals;
+        public Vector2[] uvs;
+        public int[] triangles;
+    }
+
+    public enum BabylonTerrainFormat
+    {
+        Triangles = 0
+    }
+
+    public enum BabylonTerrainResolution
+    {
+        FullResolution = 0,
+        HighResolution = 1,
+        MediumResolution = 2,
+        LowResolution = 3,
+        VeryLowResolution = 4
+    }
+
+    public enum BabylonColliderDetail
+    {
+        FullResolution = 0,
+        HighResolution = 1,
+        MediumResolution = 2,
+        LowResolution = 3,
+        VeryLowResolution = 4,
+        MinimumResolution = 5
+    }
+
+    public enum BabylonPreviewWindow
+    {
+        OpenDefaultBrowser = 0,
+        AttachUnityBrowser = 1
+    }
+
+    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
+    public sealed class BabylonClassAttribute : Attribute { }
+
+    [AttributeUsage(AttributeTargets.Field, Inherited = false)]
+    public sealed class BabylonPropertyAttribute : PropertyAttribute { }
+
+    public abstract class BabylonScriptComponent : MonoBehaviour
+    {
+        [Unity3D2Babylon.ReadOnly]
+        public string babylonClass;
+        public BabylonTickOptions updateOption;
+        protected BabylonScriptComponent()
+        {
+            this.babylonClass = "BABYLON.ScriptComponent";
+            this.updateOption = BabylonTickOptions.EnableTick;
+        }
+        public virtual void OnExportProperties(ref Unity3D2Babylon.ExportationOptions exportOptions, ref GameObject unityGameObject, ref Dictionary<string, object> propertyBag, string outputPath) { }
+    }
+
+    public abstract class BabylonSceneController : BabylonScriptComponent
+    {
+        public BabylonSceneOptions sceneOptions;
+        public BabylonSkyboxOptions skyboxOptions;
+        public BabylonLightOptions lightingOptions;
+        public BabylonManifestOptions manifestOptions;
+
+        protected BabylonSceneController()
+        {
+            this.babylonClass = "BABYLON.SceneController";
+            this.updateOption = BabylonTickOptions.EnableTick;
+        }
+        public virtual void OnExportGameObject(ref Unity3D2Babylon.ExportationOptions exportOptions, ref GameObject unityGameObject, ref UnityMetaData metaData, ref BabylonScene sceneBuilder, string outputPath) { }
+    }
+}

+ 45 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterOutput.cs

@@ -0,0 +1,45 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.SceneManagement;
+
+namespace Unity3D2Babylon
+{
+    public class ExporterOutput : EditorWindow
+    {
+        Vector2 scrollPosLog;
+
+        public void OnInitialize()
+        {
+        }
+
+        void OnEnable()
+        {
+            titleContent = new GUIContent("Output");
+        }
+
+        public void OnGUI()
+        {
+            if (GUILayout.Button("Clear Output Window"))
+            {
+                ExporterWindow.logs.Clear();
+            }
+            EditorGUILayout.Space();
+            scrollPosLog = EditorGUILayout.BeginScrollView(scrollPosLog, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true));
+            foreach (var log in ExporterWindow.logs)
+            {
+                var bold = log.StartsWith("*");
+                GUILayout.Label(bold ? log.Remove(0, 1) : log, bold ? (EditorStyles.boldLabel) : EditorStyles.label);
+            }
+            EditorGUILayout.EndScrollView();
+        }
+
+        public void OnInspectorUpdate()
+        {
+            this.Repaint();
+        }
+    }
+}

+ 162 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterSplitter.cs

@@ -0,0 +1,162 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.SceneManagement;
+
+namespace Unity3D2Babylon
+{
+    public class ExporterSpliter : EditorWindow
+    {
+        Cubemap splitCube;
+
+        [MenuItem("BabylonJS/Cubemap Splitter", false, 101)]
+        public static void InitSpliter()
+        {
+            ExporterSpliter splitter = ScriptableObject.CreateInstance<ExporterSpliter>();
+            splitter.OnInitialize();
+            splitter.ShowUtility();
+        }
+
+        public void OnInitialize()
+        {
+            maxSize = new Vector2(512, 155);
+            minSize = this.maxSize;
+        }
+
+        void OnEnable()
+        {
+            titleContent = new GUIContent("Cubemap Splitter");
+        }
+
+        public void OnGUI()
+        {
+            GUILayout.Label("Choose the Cubemap you want to split into 6 images", EditorStyles.boldLabel);
+            EditorGUILayout.Space();
+            splitCube = EditorGUILayout.ObjectField("Cubemap:", splitCube, typeof(Cubemap), false) as Cubemap;
+            EditorGUILayout.Space();
+            EditorGUILayout.Space();
+            if (GUILayout.Button("Split Cubemap"))
+            {
+                if (splitCube)
+                {
+                    Split();
+                }
+                if (!splitCube)
+                {
+                    ExporterWindow.ShowMessage("You must select a cubemap");
+                }
+            }
+        }
+
+        public void Split()
+        {
+            ExporterWindow.ReportProgress(1, "Splitting cubemap textures... This may take a while.");
+            var filePath = AssetDatabase.GetAssetPath(splitCube);
+            int splitSize = splitCube.width;
+            Color[] CubeMapColors;
+
+            var faceTexturePath = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
+            bool png = (ExporterWindow.exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
+            string fext = (png == true) ? ".png" : ".jpg";
+            string filename = "";
+            string preview = "";
+
+            var importTool = new BabylonTextureImporter(filePath);
+            bool isReadable = importTool.IsReadable();
+            if (!isReadable)
+            {
+                importTool.SetReadable();
+            }
+            try
+            {
+                filename = (faceTexturePath + "_py" + fext);
+                preview = Path.GetFileName(filename);
+                ExporterWindow.ReportProgress(1, "Splitting texture face " + preview + " ... This may take a while.");
+                Texture2D tex = new Texture2D(splitSize, splitSize, TextureFormat.RGB24, false);
+                CubeMapColors = splitCube.GetPixels(CubemapFace.PositiveY);
+                tex.SetPixels(CubeMapColors, 0);
+                tex.Apply();
+                WriteTextureFile(filename, tex, png);
+
+                filename = (faceTexturePath + "_ny" + fext);
+                preview = Path.GetFileName(filename);
+                ExporterWindow.ReportProgress(1, "Splitting texture face " + preview + " ... This may take a while.");
+                CubeMapColors = splitCube.GetPixels(CubemapFace.NegativeY);
+                tex.SetPixels(CubeMapColors, 0);
+                tex.Apply();
+                WriteTextureFile(filename, tex, png);
+
+                filename = (faceTexturePath + "_px" + fext);
+                preview = Path.GetFileName(filename);
+                ExporterWindow.ReportProgress(1, "Splitting texture face " + preview + " ... This may take a while.");
+                CubeMapColors = splitCube.GetPixels(CubemapFace.PositiveX);
+                tex.SetPixels(CubeMapColors, 0);
+                tex.Apply();
+                WriteTextureFile(filename, tex, png);
+
+                filename = (faceTexturePath + "_nx" + fext);
+                preview = Path.GetFileName(filename);
+                ExporterWindow.ReportProgress(1, "Splitting texture face " + preview + " ... This may take a while.");
+                CubeMapColors = splitCube.GetPixels(CubemapFace.NegativeX);
+                tex.SetPixels(CubeMapColors, 0);
+                tex.Apply();
+                WriteTextureFile(filename, tex, png);
+
+                filename = (faceTexturePath + "_pz" + fext);
+                preview = Path.GetFileName(filename);
+                ExporterWindow.ReportProgress(1, "Splitting texture face " + preview + " ... This may take a while.");
+                CubeMapColors = splitCube.GetPixels(CubemapFace.PositiveZ);
+                tex.SetPixels(CubeMapColors, 0);
+                tex.Apply();
+                WriteTextureFile(filename, tex, png);
+
+                filename = (faceTexturePath + "_nz" + fext);
+                preview = Path.GetFileName(filename);
+                ExporterWindow.ReportProgress(1, "Splitting texture face " + preview + " ... This may take a while.");
+                CubeMapColors = splitCube.GetPixels(CubemapFace.NegativeZ);
+                tex.SetPixels(CubeMapColors, 0);
+                tex.Apply();
+                WriteTextureFile(filename, tex, png);
+
+            }
+            catch (Exception ex)
+            {
+                UnityEngine.Debug.LogException(ex);
+            }
+            finally
+            {
+                if (!isReadable)
+                {
+                    ExporterWindow.ReportProgress(1, "Finalizing assets database...");
+                    importTool.ForceUpdate();
+                }
+            }
+            ExporterWindow.ReportProgress(1, "Refresing assets database...");
+            AssetDatabase.Refresh();
+
+            ExporterWindow.ReportProgress(1, "Cubemap split complete.");
+            EditorUtility.ClearProgressBar();
+            this.Close();
+        }
+
+        private void WriteTextureFile(string filename, Texture2D texture, bool png)
+        {
+            if (png)
+            {
+                File.WriteAllBytes(filename, texture.EncodeToPNG());
+            }
+            else
+            {
+                File.WriteAllBytes(filename, texture.EncodeToJPG(ExporterWindow.exportationOptions.DefaultQualityLevel));
+            }
+        }
+
+        public void OnInspectorUpdate()
+        {
+            this.Repaint();
+        }
+    }
+}

+ 152 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterTerrain.cs

@@ -0,0 +1,152 @@
+using UnityEngine;
+using UnityEditor;
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+using BabylonExport.Entities;
+
+class ExporterTerrain : EditorWindow
+{
+    BabylonTerrainFormat saveFormat = BabylonTerrainFormat.Triangles;
+
+    BabylonTerrainResolution saveResolution = BabylonTerrainResolution.HighResolution;
+
+    static TerrainData terrain;
+
+    static Terrain terrainObject;
+
+    int tCount;
+    int counter;
+    int totalCount;
+    bool flipNormals = true;
+    int progressUpdateInterval = 10000;
+
+    [MenuItem("BabylonJS/Terrain Exporter", false, 100)]
+    static void InitTerrain()
+    {
+        ExporterTerrain terrains = ScriptableObject.CreateInstance<ExporterTerrain>();
+        terrains.OnInitialize();
+        terrains.ShowUtility();
+    }
+
+    public void OnInitialize()
+    {
+        maxSize = new Vector2(512, 85);
+        minSize = this.maxSize;
+        terrain = null;
+
+        terrainObject = Selection.activeObject as Terrain;
+        if (!terrainObject)
+        {
+            terrainObject = Terrain.activeTerrain;
+        }
+        if (terrainObject)
+        {
+            terrain = terrainObject.terrainData;
+        }
+    }
+
+    void OnGUI()
+    {
+        if (!terrain)
+        {
+            GUILayout.Label("No terrain found");
+            if (GUILayout.Button("Cancel"))
+            {
+                this.Close();
+            }
+            return;
+        }
+        saveFormat = (BabylonTerrainFormat)EditorGUILayout.EnumPopup("Export Format", saveFormat);
+        saveResolution = (BabylonTerrainResolution)EditorGUILayout.EnumPopup("Mesh Resolution", saveResolution);
+        flipNormals = EditorGUILayout.Toggle("Reverse Normals", flipNormals);
+        if (GUILayout.Button("Export"))
+        {
+            Export();
+        }
+    }
+
+    void Export()
+    {
+        int index = 0;
+        string fileName = EditorUtility.SaveFilePanel("Export Terrain File", "", "Terrain", "obj");
+        BabylonMesh babylonMesh = new BabylonMesh();
+        BabylonTerrainData terrainData = Unity3D2Babylon.Tools.CreateTerrainData(terrain, (int)saveResolution, terrainObject.transform.localPosition, false);
+        Unity3D2Babylon.Tools.GenerateBabylonMeshTerrainData(terrainData, babylonMesh, flipNormals);
+
+        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
+        StreamWriter sw = new StreamWriter(fileName);
+        try
+        {
+            // StringBuilder stuff is done this way because it's faster than using the "{0} {1} {2}"etc. format
+            // Which is important when you're exporting huge terrains.
+            sw.WriteLine("# U3D - BabylonJS - Terrain Mesh File");
+
+            // Write vertices
+            counter = tCount = 0;
+            totalCount = ((babylonMesh.positions.Length / 3) * 2 + (babylonMesh.indices.Length / 3)) / progressUpdateInterval;
+            for (index = 0; index < babylonMesh.positions.Length / 3; index++)
+            {
+                UpdateProgress();
+                StringBuilder sb = new StringBuilder("v ", 32);
+                sb.Append(babylonMesh.positions[index * 3].ToString()).Append(" ").
+                Append(babylonMesh.positions[index * 3 + 1].ToString()).Append(" ").
+                Append(babylonMesh.positions[index * 3 + 2].ToString());
+                sw.WriteLine(sb);
+            }
+
+            // Write normals
+            for (index = 0; index < babylonMesh.normals.Length / 3; index++)
+            {
+                UpdateProgress();
+                StringBuilder sb = new StringBuilder("vn ", 32);
+                sb.Append(babylonMesh.normals[index * 3].ToString()).Append(" ").
+                Append(babylonMesh.normals[index * 3 + 1].ToString()).Append(" ").
+                Append(babylonMesh.normals[index * 3 + 2].ToString());
+                sw.WriteLine(sb);
+            }
+
+            // Write uvs
+            for (index = 0; index < babylonMesh.uvs.Length / 2; index++)
+            {
+                UpdateProgress();
+                StringBuilder sb = new StringBuilder("vt ", 32);
+                sb.Append(babylonMesh.uvs[index * 2].ToString()).Append(" ").
+                Append(babylonMesh.uvs[index * 2 + 1].ToString());
+                sw.WriteLine(sb);
+            }
+
+            // Write triangles
+            for (int i = 0; i < babylonMesh.indices.Length; i += 3)
+            {
+                UpdateProgress();
+                StringBuilder sb = new StringBuilder("f ", 64);
+                sb.Append(babylonMesh.indices[i] + 1).Append("/").Append(babylonMesh.indices[i] + 1).Append(" ").
+                Append(babylonMesh.indices[i + 1] + 1).Append("/").Append(babylonMesh.indices[i + 1] + 1).Append(" ").
+                Append(babylonMesh.indices[i + 2] + 1).Append("/").Append(babylonMesh.indices[i + 2] + 1);
+                sw.WriteLine(sb);
+            }
+        }
+        catch (Exception err)
+        {
+            Debug.Log("Error saving file: " + err.Message);
+        }
+        sw.Close();
+
+        terrain = null;
+        EditorUtility.DisplayProgressBar("Babylon.js", "Saving terrain mesh data... This may take a while.", 1f);
+        AssetDatabase.Refresh();
+        EditorUtility.ClearProgressBar();
+        this.Close();
+    }
+
+    void UpdateProgress()
+    {
+        if (counter++ == progressUpdateInterval)
+        {
+            counter = 0;
+            EditorUtility.DisplayProgressBar("Generating terrain mesh...", "", Mathf.InverseLerp(0, totalCount, ++tCount));
+        }
+    }
+}

+ 80 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterTexture.cs

@@ -0,0 +1,80 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.SceneManagement;
+
+namespace Unity3D2Babylon
+{
+    public class BabylonTextureImporter
+    {
+        public TextureImporter textureImporter { get; private set; }
+        private bool previousIsReadable;
+        private string texturePath;
+
+        public BabylonTextureImporter(string path)
+        {
+            try
+            {
+                texturePath = path;
+                textureImporter = AssetImporter.GetAtPath(texturePath) as TextureImporter;
+                previousIsReadable = textureImporter.isReadable;
+            }
+            catch (Exception ex)
+            {
+                UnityEngine.Debug.LogException(ex);
+            }
+        }
+
+        public bool IsReadable()
+        {
+            return previousIsReadable;
+        }
+
+        public bool SetReadable()
+        {
+            bool result = false;
+            try
+            {
+                textureImporter.isReadable = true;
+                AssetDatabase.ImportAsset(texturePath);
+                result = true;
+            }
+            catch (Exception ex)
+            {
+                UnityEngine.Debug.LogException(ex);
+            }
+            return result;
+        }
+
+        public void Resotre()
+        {
+            try
+            {
+                textureImporter.isReadable = previousIsReadable;
+            }
+            catch (Exception ex)
+            {
+                UnityEngine.Debug.LogException(ex);
+            }
+            finally
+            {
+                ForceUpdate();
+            }
+        }
+
+        public void ForceUpdate()
+        {
+            try
+            {
+                AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate);
+            }
+            catch (Exception ex)
+            {
+                UnityEngine.Debug.LogException(ex);
+            }
+        }
+    }
+}

+ 857 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/ExporterWindow.cs

@@ -0,0 +1,857 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.SceneManagement;
+
+using JsonFx.Json;
+using JsonFx.Json.Resolvers;
+using JsonFx.Serialization;
+using JsonFx.Serialization.Resolvers;
+
+using BabylonHosting;
+
+namespace Unity3D2Babylon
+{
+    public class ExporterWindow : EditorWindow
+    {
+        public const double BabylonVersion = 2.5;
+        public const string ToolkitVersion = "1.0";
+        public const string DefaultHost = "localhost";
+        public const int DefaultPort = 8888;
+
+        public static ExportationOptions exportationOptions = null;
+        public static readonly List<string> logs = new List<string>();
+        Vector2 scrollPosMain;
+        bool showLighting = false;
+        bool showCollision = false;
+        bool showShader = false;
+        bool showPreview = false;
+        EditorWindow assetStore = null;
+
+        public static void ReportProgress(float value, string message = "")
+        {
+            EditorUtility.DisplayProgressBar("Babylon.js", message, value);
+
+            if (!string.IsNullOrEmpty(message))
+            {
+                logs.Add(message);
+            }
+        }
+
+        public static bool ShowMessage(string message, string title = "Babylon.js", string ok = "OK", string cancel = "Cancel")
+        {
+            return EditorUtility.DisplayDialog(title, message, ok, cancel);
+        }
+
+        public ExportationOptions CreateSettings()
+        {
+            ExportationOptions result = new ExportationOptions();
+            string apath = Application.dataPath.Replace("/Assets", "");
+            string ufile = Path.Combine(apath, "UnityBabylonOptions.ini");
+            if (File.Exists(ufile))
+            {
+                var readText = File.ReadAllText(ufile);
+                var jsReader = new JsonReader();
+                result = jsReader.Read<ExportationOptions>(readText);
+            }
+            return result;
+        }
+
+        public void SaveSettings(bool refresh = false)
+        {
+            if (refresh) GetSceneInfomation(false);
+            string apath = Application.dataPath.Replace("/Assets", "");
+            string ufile = Path.Combine(apath, "UnityBabylonOptions.ini");
+            var settings = new DataWriterSettings() { PrettyPrint = true };
+            var jsWriter = new JsonWriter(settings);
+            File.WriteAllText(ufile, jsWriter.Write(exportationOptions));
+        }
+
+        [MenuItem("BabylonJS/Scene Exporter", false, 0)]
+        public static void InitExporter()
+        {
+            var exporter = (ExporterWindow)GetWindow(typeof(ExporterWindow));
+            exporter.minSize = new Vector2(420.0f, 480.0f);
+            exporter.OnInitialize();
+        }
+
+        [MenuItem("BabylonJS/Output Window", false, 1)]
+        public static void InitOutput()
+        {
+            var output = (ExporterOutput)GetWindow(typeof(ExporterOutput));
+            output.OnInitialize();
+        }
+
+        [MenuItem("BabylonJS/Update Libraries", false, 2)]
+        public static void InitUpdate()
+        {
+            string prodVersion = ExporterWindow.exportationOptions.ProductionVersion.ToString();
+            if (prodVersion.IndexOf(".", StringComparison.OrdinalIgnoreCase) < 0)
+            {
+                prodVersion += ".0";
+            }
+            string updateMsg = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "Are you sure you want to update libraries using the github preview release version?" : "Are you sure you want to update libraries using the github stable release version " + prodVersion + "?";
+            if (ExporterWindow.ShowMessage(updateMsg, "Babylon.js", "Update"))
+            {
+                EditorUtility.DisplayProgressBar("Babylon.js", "Updating github editor toolkit library files...", 1);
+
+                string libPath = Path.Combine(Application.dataPath, "Babylon/Library/");
+                string bjsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/babylon.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".js";
+                string bjsTsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/babylon.d.ts" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".d.ts";
+
+                string c2dPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/canvas2D/babylon.canvas2d.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".canvas2d.js";
+                string c2dTsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/canvas2D/babylon.canvas2d.d.ts" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".canvas2d.d.ts";
+
+                string cannonPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/cannon.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/cannon.js";
+                string oimoPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/Oimo.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/Oimo.js";
+
+                try
+                {
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating babylon.bjs...", 0.10f);
+                    Tools.DownloadFile(bjsPath, Path.Combine(libPath, "babylon.bjs"));
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating babylon.d.ts...", 0.20f);
+                    Tools.DownloadFile(bjsTsPath, Path.Combine(libPath, "babylon.d.ts"));
+
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating canvas2d.bjs...", 0.30f);
+                    Tools.DownloadFile(c2dPath, Path.Combine(libPath, "canvas2d.bjs"));
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating canvas2d.d.ts...", 0.40f);
+                    Tools.DownloadFile(c2dTsPath, Path.Combine(libPath, "canvas2d.d.ts"));
+
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating cannon.bjs...", 0.50f);
+                    Tools.DownloadFile(cannonPath, Path.Combine(libPath, "cannon.bjs"));
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating oimo.bjs...", 0.60f);
+                    Tools.DownloadFile(oimoPath, Path.Combine(libPath, "oimo.bjs"));
+
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating navmesh.bjs...", 0.70f);
+                    Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.navigation.mesh.js", Path.Combine(libPath, "navmesh.bjs"));
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating manager.bjs...", 0.80f);
+                    Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.scenemanager.js", Path.Combine(libPath, "manager.bjs"));
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Updating manager.d.ts...", 0.90f);
+                    Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.scenemanager.d.ts", Path.Combine(libPath, "manager.d.ts"));
+                }
+                catch (System.Exception ex)
+                {
+                    UnityEngine.Debug.LogException(ex);
+                }
+                finally
+                {
+                    EditorUtility.DisplayProgressBar("Babylon.js", "Refresing assets database...", 1.0f);
+                    AssetDatabase.Refresh();
+                    EditorUtility.ClearProgressBar();
+                }
+            }
+        }
+
+        [MenuItem("BabylonJS/Babylon Dashboard", false, 999)]
+        public static void InitDashboard()
+        {
+            Application.OpenURL("http://www.babylonjs.com");
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Javascript Class", false, 101)]
+        public static void CreateJavascript()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewJavascript.bjs");
+            string template = "Assets/Babylon/Templates/Scripts/javascript.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Javascript File";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Typescript Class", false, 102)]
+        public static void CreateTypescript()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewTypescript.ts");
+            string template = "Assets/Babylon/Templates/Scripts/typescript.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Typescript File";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Scene Controller", false, 201)]
+        public static void CreateSceneController_TS()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewSceneController.ts");
+            string template = "Assets/Babylon/Templates/Scripts/controller.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Scene Controller";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Mesh Component", false, 301)]
+        public static void CreateMeshComponent_TS()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewMeshComponent.ts");
+            string template = "Assets/Babylon/Templates/Scripts/mesh.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Mesh Class";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Light Component", false, 302)]
+        public static void CreateLightComponent_TS()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewLightComponent.ts");
+            string template = "Assets/Babylon/Templates/Scripts/light.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Light Class";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Camera Component", false, 303)]
+        public static void CreateCameraComponent_TS()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewCameraComponent.ts");
+            string template = "Assets/Babylon/Templates/Scripts/camera.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Camera Class";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Unity Editor Script/Babylon Scene Controller (C#)", false, 901)]
+        public static void CreateEditorController_CS()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewSceneController.cs");
+            string template = "Assets/Babylon/Templates/Scripts/editora.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Controller Class";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Unity Editor Script/Babylon Script Component (C#)", false, 902)]
+        public static void CreateEditorComponent_CS()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewScriptComponent.cs");
+            string template = "Assets/Babylon/Templates/Scripts/editorb.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Script Class";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        [MenuItem("Assets/Create/BabylonJS/Unity Editor Script/Universal Shader Program (GLSL)", false, 999)]
+        public static void CreateShader()
+        {
+            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
+            if (String.IsNullOrEmpty(path))
+            {
+                path = "Assets";
+            }
+            else if (!String.IsNullOrEmpty(Path.GetExtension(path)))
+            {
+                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
+            }
+            string filename = Path.Combine(path, "NewShaderProgram.shader");
+            string template = "Assets/Babylon/Templates/Shaders/amiga.template";
+            if (!File.Exists(template))
+            {
+                string defaultTemplate = "// Babylon Shader Class";
+                File.WriteAllText(template, defaultTemplate);
+            }
+            var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon") as Texture2D;
+            var DoCreateScriptAsset = Type.GetType("UnityEditor.ProjectWindowCallback.DoCreateScriptAsset, UnityEditor");
+            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(DoCreateScriptAsset) as UnityEditor.ProjectWindowCallback.EndNameEditAction, filename, icon, template);
+        }
+
+        public void OnInitialize() { }
+
+        public void OnEnable()
+        {
+            this.titleContent = new GUIContent("Exporter");
+            if (ExporterWindow.exportationOptions == null)
+            {
+                ExporterWindow.exportationOptions = CreateSettings();
+            }
+            // Attach unity editor buttons
+            UnityEditor.EditorApplication.playmodeStateChanged = () =>
+            {
+                if (exportationOptions != null && exportationOptions.AttachUnityEditor)
+                {
+                    bool wantsToPlay = UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode;
+                    bool wantsToPause = UnityEditor.EditorApplication.isPaused;
+                    if (wantsToPlay || wantsToPause)
+                    {
+                        UnityEditor.EditorApplication.isPlaying = false;
+                        UnityEditor.EditorApplication.isPaused = false;
+                    }
+                    if (wantsToPlay) Execute();
+                }
+            };
+            // Activate asset store window
+            if (this.assetStore == null)
+            {
+                this.assetStore = Tools.GetAssetStoreWindow();
+            }
+            // Activate internl web server
+            this.StartServer();
+        }
+
+        public void StartServer()
+        {
+            if (exportationOptions.HostPreviewPage)
+            {
+                // Validate default project folder selected
+                if (String.IsNullOrEmpty(exportationOptions.DefaultProjectFolder))
+                {
+                    UnityEngine.Debug.LogWarning("No default project file selected. Web server not started.");
+                    return;
+                }
+
+                // Validate default project folder exists
+                if (!Directory.Exists(exportationOptions.DefaultProjectFolder))
+                {
+                    UnityEngine.Debug.LogWarning("No default project file created. Web server not started.");
+                    return;
+                }
+
+                bool supported = WebServer.IsSupported;
+                string prefix = "http://*:";
+                string root = exportationOptions.DefaultProjectFolder;
+                int port = exportationOptions.DefaultServerPort;
+                bool started = WebServer.Activate(prefix, root, port);
+                if (started) UnityEngine.Debug.Log("Babylon.js web server started on port: " + port.ToString());
+                if (!started && supported) UnityEngine.Debug.LogWarning("Babylon.js web server is available.");
+                if (!started && !supported) UnityEngine.Debug.LogWarning("Babylon.js web server is not available.");
+            }
+        }
+
+        public void OnGUI()
+        {
+            GUILayout.Label("BabylonJS Toolkit - Version: " + ExporterWindow.ToolkitVersion, EditorStyles.boldLabel);
+            EditorGUI.BeginDisabledGroup(true);
+            exportationOptions.DefaultProjectFolder = EditorGUILayout.TextField("", exportationOptions.DefaultProjectFolder);
+            EditorGUI.EndDisabledGroup();
+            if (GUILayout.Button("Select Project Folder"))
+            {
+                SelectFolder();
+            }
+            if (GUILayout.Button("Save Export Settings"))
+            {
+                SaveSettings();
+                ShowMessage("Export settings saved.");
+            }
+
+            scrollPosMain = EditorGUILayout.BeginScrollView(scrollPosMain, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true));
+            EditorGUILayout.Space();
+            exportationOptions.DefaultBuildPath = EditorGUILayout.TextField(" Project Build Path", exportationOptions.DefaultBuildPath);
+            EditorGUILayout.Space();
+            exportationOptions.DefaultScenePath = EditorGUILayout.TextField(" Project Scene Path", exportationOptions.DefaultScenePath);
+            EditorGUILayout.Space();
+            exportationOptions.DefaultScriptPath = EditorGUILayout.TextField(" Project Script Path", exportationOptions.DefaultScriptPath);
+            EditorGUILayout.Space();
+            exportationOptions.DefaultIndexPage = EditorGUILayout.TextField(" Project Index Page", exportationOptions.DefaultIndexPage);
+            EditorGUILayout.Space();
+            EditorGUILayout.BeginHorizontal();
+            exportationOptions.ExportPhysics = EditorGUILayout.Toggle(" Enable Physics Engine", exportationOptions.ExportPhysics);
+            exportationOptions.DefaultPhysicsEngine = (int)(BabylonPhysicsEngine)EditorGUILayout.EnumPopup("Default Physics Engine", (BabylonPhysicsEngine)exportationOptions.DefaultPhysicsEngine, GUILayout.ExpandWidth(true));
+            EditorGUILayout.EndHorizontal();
+            EditorGUILayout.Space();
+            exportationOptions.ReflectionDefaultLevel = EditorGUILayout.Slider(" Default Reflection Level", exportationOptions.ReflectionDefaultLevel, 0, 1.0f);
+            EditorGUILayout.Space();
+            exportationOptions.DefaultImageFormat = (int)(BabylonImageFormat)EditorGUILayout.EnumPopup(" Prefered Texture Format", (BabylonImageFormat)exportationOptions.DefaultImageFormat, GUILayout.ExpandWidth(true));
+            EditorGUILayout.Space();
+            exportationOptions.DefaultQualityLevel = (int)EditorGUILayout.Slider(" Texture Image Quality", exportationOptions.DefaultQualityLevel, 0, 100);
+            EditorGUILayout.Space();
+
+            showCollision = EditorGUILayout.Foldout(showCollision, "Scene Collision Options");
+            if (showCollision)
+            {
+                EditorGUILayout.Space();
+                exportationOptions.ExportCollisions = EditorGUILayout.Toggle("   Enable Collisions", exportationOptions.ExportCollisions);
+                EditorGUILayout.Space();
+                EditorGUILayout.BeginHorizontal();
+                GUILayout.Label("   Camera Ellipsoid");
+                exportationOptions.CameraEllipsoid = EditorGUILayout.Vector3Field("", exportationOptions.CameraEllipsoid, GUILayout.ExpandWidth(false));
+                EditorGUILayout.EndHorizontal();
+                EditorGUILayout.Space();
+                EditorGUILayout.BeginHorizontal();
+                GUILayout.Label("   Default Scene Gravity");
+                exportationOptions.Gravity = EditorGUILayout.Vector3Field("", exportationOptions.Gravity, GUILayout.ExpandWidth(false));
+                EditorGUILayout.EndHorizontal();
+                EditorGUILayout.Space();
+                exportationOptions.DefaultColliderDetail = (int)(BabylonColliderDetail)EditorGUILayout.EnumPopup("   Default Collider Detail", (BabylonColliderDetail)exportationOptions.DefaultColliderDetail, GUILayout.ExpandWidth(true));
+                EditorGUILayout.Space();
+                exportationOptions.WorkerCollisions = EditorGUILayout.Toggle("   Enable Worker Collisions", exportationOptions.WorkerCollisions);
+                EditorGUILayout.Space();
+            }
+
+            showShader = EditorGUILayout.Foldout(showShader, "Shader Program Options");
+            if (showShader)
+            {
+                EditorGUILayout.Space();
+                exportationOptions.EmbeddedShaders = EditorGUILayout.Toggle("   Embed Shader Files", exportationOptions.EmbeddedShaders);
+                EditorGUILayout.Space();
+                exportationOptions.DefaultShaderFolder = EditorGUILayout.TextField("   Output Src Shader Path", exportationOptions.DefaultShaderFolder);
+                EditorGUILayout.Space();
+            }
+
+            showLighting = EditorGUILayout.Foldout(showLighting, "Lightmap Baking Options");
+            if (showLighting)
+            {
+                EditorGUILayout.Space();
+                EditorGUILayout.BeginHorizontal();
+                exportationOptions.ExportLightmaps = EditorGUILayout.Toggle("   Export Lightmaps", exportationOptions.ExportLightmaps);
+                exportationOptions.DefaultLightmapBaking = (int)(BabylonLightmapBaking)EditorGUILayout.EnumPopup("    Synchronous Baking", (BabylonLightmapBaking)exportationOptions.DefaultLightmapBaking, GUILayout.ExpandWidth(true));
+                EditorGUILayout.EndHorizontal();
+                EditorGUILayout.Space();
+                exportationOptions.DefaultLightmapMode = (int)(BabylonLightmapMode)EditorGUILayout.EnumPopup("   Light Mapper Mode", (BabylonLightmapMode)exportationOptions.DefaultLightmapMode, GUILayout.ExpandWidth(true));
+                EditorGUILayout.Space();
+                exportationOptions.DefaultCoordinatesIndex = (int)EditorGUILayout.Slider("   Coordinates Index", exportationOptions.DefaultCoordinatesIndex, 0, 1);
+                EditorGUILayout.Space();
+                EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
+                exportationOptions.ExportShadows = EditorGUILayout.Toggle("   Enable Shadow Map", exportationOptions.ExportShadows);
+                GUILayout.Label("   Default Shadow Map Size");
+                exportationOptions.ShadowMapSize = EditorGUILayout.IntField("", exportationOptions.ShadowMapSize, GUILayout.Width(50));
+                EditorGUILayout.EndHorizontal();
+                EditorGUILayout.Space();
+                exportationOptions.DefaultLightFilter = (int)(BabylonLightingFilter)EditorGUILayout.EnumPopup("   Shadow Map Filter", (BabylonLightingFilter)exportationOptions.DefaultLightFilter, GUILayout.ExpandWidth(true));
+                EditorGUILayout.Space();
+                exportationOptions.ShadowMapBias = EditorGUILayout.Slider("   Shadow Map Bias", exportationOptions.ShadowMapBias, 0, 1.0f);
+                EditorGUILayout.Space();
+                exportationOptions.ShadowBlurScale = EditorGUILayout.Slider("   Shadow Blur Scale", exportationOptions.ShadowBlurScale, 0, 5.0f);
+                EditorGUILayout.Space();
+            }
+
+            showPreview = EditorGUILayout.Foldout(showPreview, "Default Exporting Options");
+            if (showPreview)
+            {
+                EditorGUILayout.Space();
+                exportationOptions.AttachUnityEditor = EditorGUILayout.Toggle("   Attach Unity Editor", exportationOptions.AttachUnityEditor);
+                EditorGUILayout.Space();
+                exportationOptions.HostPreviewPage = EditorGUILayout.Toggle("   Host Preview Server", exportationOptions.HostPreviewPage);
+                EditorGUILayout.Space();
+                exportationOptions.ShowDebugControls = EditorGUILayout.Toggle("   Show Debug Controls", exportationOptions.ShowDebugControls);
+                EditorGUILayout.Space();
+                exportationOptions.DefaultServerPort = EditorGUILayout.IntField("   Default Server Port", exportationOptions.DefaultServerPort);
+                EditorGUILayout.Space();
+                exportationOptions.DefaultPreviewWindow = (int)(BabylonPreviewWindow)EditorGUILayout.EnumPopup("   Default Preview Window", (BabylonPreviewWindow)exportationOptions.DefaultPreviewWindow, GUILayout.ExpandWidth(true));
+                EditorGUILayout.Space();
+                exportationOptions.BuildJavaScript = EditorGUILayout.Toggle("   Build Javascript Files", exportationOptions.BuildJavaScript);
+                EditorGUILayout.Space();
+                exportationOptions.CompileTypeScript = EditorGUILayout.Toggle("   Build Typescript Files", exportationOptions.CompileTypeScript);
+                EditorGUILayout.Space();
+                exportationOptions.DefaultTypeSriptPath = EditorGUILayout.TextField("   Typescript Compiler", exportationOptions.DefaultTypeSriptPath);
+                EditorGUILayout.Space();
+                exportationOptions.DefaultNodeRuntimePath = EditorGUILayout.TextField("   Node Runtime System", exportationOptions.DefaultNodeRuntimePath);
+                EditorGUILayout.Space();
+                exportationOptions.ProductionVersion = EditorGUILayout.FloatField("   Stable Babylon Version", exportationOptions.ProductionVersion);
+                EditorGUILayout.Space();
+                exportationOptions.DefaultUpdateOptions = (int)(BabylonUpdateOptions)EditorGUILayout.EnumPopup("   Github Update Version", (BabylonUpdateOptions)exportationOptions.DefaultUpdateOptions, GUILayout.ExpandWidth(true));
+                EditorGUILayout.Space();
+            }
+            EditorGUILayout.EndScrollView();
+            EditorGUILayout.Space();
+
+            // Exporter buttons
+            if (GUILayout.Button("Build Script"))
+            {
+                if (ExporterWindow.ShowMessage("Are you sure you want to build the project script files?", "Babylon.js", "Build"))
+                {
+                    Build(true);
+                }
+            }
+            if (GUILayout.Button("Export Scene"))
+            {
+                Export(false);
+            }
+            if (GUILayout.Button("Export & Preview"))
+            {
+                Export(true);
+            }
+            if (ExporterWindow.exportationOptions.HostPreviewPage == true)
+            {
+                if (GUILayout.Button("Start Preview Server"))
+                {
+                    StartServer();
+                }
+            }
+            if (GUILayout.Button("Launch Preview Window"))
+            {
+                Execute();
+            }
+            EditorGUILayout.Space();
+        }
+
+        public void OnInspectorUpdate()
+        {
+            this.Repaint();
+        }
+
+        public void SelectFolder()
+        {
+            exportationOptions.DefaultProjectFolder = EditorUtility.SaveFolderPanel("Please select a folder", exportationOptions.DefaultProjectFolder, "");
+        }
+
+        public void Build(bool solo, string[] info = null)
+        {
+            if (solo)
+            {
+                // Validate default project folder selected
+                if (String.IsNullOrEmpty(exportationOptions.DefaultProjectFolder))
+                {
+                    ShowMessage("No default project file selected.");
+                    return;
+                }
+
+                // Validate default project folder exists
+                if (!Directory.Exists(exportationOptions.DefaultProjectFolder))
+                {
+                    ShowMessage("No default project file created.");
+                    return;
+                }
+            }
+
+            try
+            {
+                var sceneInfo = info ?? GetSceneInfomation(false);
+                string scriptPath = sceneInfo[2];
+                string projectScript = sceneInfo[4];
+
+                // Save and clear console
+                if (solo)
+                {
+                    try { UnityEngine.Debug.ClearDeveloperConsole(); } catch { }
+                    SaveSettings();
+                }
+
+                // Assemble javascript files
+                string javascriptFile = Tools.FormatProjectJavaScript(scriptPath, projectScript);
+                if (solo || exportationOptions.BuildJavaScript)
+                {
+                    ReportProgress(1, "Building project javascript files...");
+                    Tools.BuildProjectJavaScript(scriptPath, projectScript, javascriptFile);
+                }
+
+                // Compile typescript files
+                if (solo || exportationOptions.CompileTypeScript)
+                {
+                    ReportProgress(1, "Compiling project typescript files... This may take a while.");
+                    string config = String.Empty;
+                    string options = Path.Combine(Application.dataPath, "Babylon/Templates/Config/options.json");
+                    if (File.Exists(options)) config = File.ReadAllText(options);
+                    Tools.BuildProjectTypeScript(exportationOptions.DefaultNodeRuntimePath, exportationOptions.DefaultTypeSriptPath, scriptPath, javascriptFile, config);
+                }
+            }
+            catch (Exception ex)
+            {
+                UnityEngine.Debug.LogException(ex);
+            }
+            finally
+            {
+                if (solo) EditorUtility.ClearProgressBar();
+            }
+        }
+
+        public void Export(bool preview)
+        {
+            try
+            {
+                // Validate lightmap bake in progress
+                if (exportationOptions.ExportLightmaps && exportationOptions.DefaultLightmapBaking == (int)BabylonLightmapBaking.Enabled && Lightmapping.isRunning)
+                {
+                    ShowMessage("There is a bake already in progress.");
+                    return;
+                }
+
+                // Validate default project folder selected
+                if (String.IsNullOrEmpty(exportationOptions.DefaultProjectFolder))
+                {
+                    ShowMessage("No default project file selected.");
+                    return;
+                }
+
+                // Validate default project folder exists
+                if (!Directory.Exists(exportationOptions.DefaultProjectFolder))
+                {
+                    if (ExporterWindow.ShowMessage("Create default project folder: " + exportationOptions.DefaultProjectFolder, "Babylon.js - Project not found", "Create"))
+                    {
+                        Directory.CreateDirectory(exportationOptions.DefaultProjectFolder);
+                    }
+                    else
+                    {
+                        return;
+                    }
+                }
+
+                // Get validate scene path info
+                string[] sceneInfo = GetSceneInfomation(true);
+                string sceneName = sceneInfo[0];
+                string scenePath = sceneInfo[1];
+                string scriptPath = sceneInfo[2];
+                string outputFile = sceneInfo[3];
+                string projectScript = sceneInfo[4];
+                if (!ExporterWindow.ShowMessage("Export current scene to babylon: " + sceneName, "Babylon.js", "Export"))
+                {
+                    return;
+                }
+
+                // Save current scene info
+                SaveSettings();
+                ExporterWindow.logs.Clear();
+                Stopwatch watch = new Stopwatch();
+                watch.Start();
+                ReportProgress(0, "Exporting " + scenePath);
+
+                // Auto lightmap baking
+                if (exportationOptions.ExportLightmaps && exportationOptions.DefaultLightmapBaking == (int)BabylonLightmapBaking.Enabled)
+                {
+                    ReportProgress(1, "Baking lightmap textures... This may take a while.");
+                    Lightmapping.GIWorkflowMode workflow = Lightmapping.giWorkflowMode;
+                    Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand;
+                    Lightmapping.Bake();
+                    Lightmapping.giWorkflowMode = workflow;
+                }
+
+                // Save all open scenes
+                ReportProgress(1, "Saving open scene information...");
+                UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes();
+
+                // Build project preview
+                if (preview)
+                {
+                    Tools.GenerateProjectIndexPage(exportationOptions.DefaultProjectFolder, exportationOptions.ShowDebugControls, exportationOptions.DefaultScenePath, Path.GetFileName(outputFile), exportationOptions.DefaultScriptPath, Path.GetFileName(projectScript));
+                    if (exportationOptions.BuildJavaScript || exportationOptions.CompileTypeScript)
+                    {
+                        Build(false, sceneInfo);
+                    }
+                }
+
+                // Build current scene
+                BabylonSceneController sceneController = Tools.GetSceneController();
+                var sceneBuilder = new SceneBuilder(scenePath, sceneName, exportationOptions, sceneController, scriptPath);
+                sceneBuilder.ConvertFromUnity();
+
+                ReportProgress(1, "Generating babylon scene... This may take a while.");
+                sceneBuilder.WriteToBabylonFile(outputFile);
+
+                watch.Stop();
+                ReportProgress(1, string.Format("Exportation done in {0:0.00}s", watch.Elapsed.TotalSeconds));
+                EditorUtility.ClearProgressBar();
+
+                sceneBuilder.GenerateStatus(logs);
+
+                string done = preview ? "Preview" : "OK";
+                bool ok = ShowMessage("Scene exportation complete.", "Babylon.js", done);
+                if (preview && ok)
+                {
+                    Preview();
+                }
+            }
+            catch (Exception ex)
+            {
+                EditorUtility.ClearProgressBar();
+                ShowMessage("A problem occurred: " + ex.Message + ex.StackTrace, "Error");
+            }
+        }
+
+        public string[] GetSceneInfomation(bool validate)
+        {
+            string[] result = new string[6];
+            string sceneName = SceneManager.GetActiveScene().name;
+            if (String.IsNullOrEmpty(exportationOptions.DefaultBuildPath))
+            {
+                exportationOptions.DefaultBuildPath = "Build";
+            }
+            string buildPath = Tools.FormatSafePath(Path.Combine(exportationOptions.DefaultProjectFolder, exportationOptions.DefaultBuildPath));
+            if (validate && !Directory.Exists(buildPath))
+            {
+                Directory.CreateDirectory(buildPath);
+            }
+            if (String.IsNullOrEmpty(exportationOptions.DefaultScenePath))
+            {
+                exportationOptions.DefaultScenePath = "Scenes";
+            }
+            string scenePath = Tools.FormatSafePath(Path.Combine(exportationOptions.DefaultProjectFolder, exportationOptions.DefaultScenePath));
+            if (validate && !Directory.Exists(scenePath))
+            {
+                Directory.CreateDirectory(scenePath);
+            }
+            if (String.IsNullOrEmpty(exportationOptions.DefaultScriptPath))
+            {
+                exportationOptions.DefaultScriptPath = "Scripts";
+            }
+            string scriptPath = Tools.FormatSafePath(Path.Combine(exportationOptions.DefaultProjectFolder, exportationOptions.DefaultScriptPath));
+            if (validate && !Directory.Exists(scriptPath))
+            {
+                Directory.CreateDirectory(scriptPath);
+            }
+            if (String.IsNullOrEmpty(exportationOptions.DefaultIndexPage))
+            {
+                exportationOptions.DefaultIndexPage = "Index.html";
+            }
+            if (String.IsNullOrEmpty(exportationOptions.DefaultTypeSriptPath))
+            {
+                exportationOptions.DefaultTypeSriptPath = Tools.GetDefaultTypeScriptPath();
+            }
+            if (String.IsNullOrEmpty(exportationOptions.DefaultNodeRuntimePath))
+            {
+                exportationOptions.DefaultNodeRuntimePath = Tools.GetDefaultNodeRuntimePath();
+            }
+            if (exportationOptions.DefaultServerPort < 1024)
+            {
+                exportationOptions.DefaultServerPort = ExporterWindow.DefaultPort;
+            }
+            string projectName = Application.productName;
+            if (String.IsNullOrEmpty(projectName))
+            {
+                projectName = "Application";
+            }
+            string outputFile = Tools.FormatSafePath(Path.Combine(scenePath, sceneName.Replace(" ", "") + ".babylon"));
+            string projectScript = Tools.FormatSafePath(Path.Combine(scenePath, projectName.Replace(" ", "") + ".babylon"));
+            result[0] = sceneName;
+            result[1] = scenePath;
+            result[2] = buildPath;
+            result[3] = outputFile;
+            result[4] = projectScript;
+            return result;
+        }
+
+        public void Preview()
+        {
+            string hostProtocol = "http://";
+            string previewUrl = hostProtocol + "localhost:" + exportationOptions.DefaultServerPort.ToString() + "/" + exportationOptions.DefaultIndexPage;
+            if (exportationOptions.DefaultPreviewWindow == (int)BabylonPreviewWindow.AttachUnityBrowser)
+            {
+                var browser = Tools.AttachToAssetStoreWindow("Babylon", previewUrl);
+                if (browser == null)
+                {
+                    ShowMessage("The asset store browser must be opened. Please try your request again after the asset store has opened.", "Babylon.js - Failed to attach browser");
+                }
+            }
+            else
+            {
+                Application.OpenURL(previewUrl);
+            }
+        }
+
+        public void Execute()
+        {
+            Scene scene = SceneManager.GetActiveScene();
+            string[] sceneInfo = GetSceneInfomation(true);
+            string outputFile = sceneInfo[3];
+            if (!scene.isDirty && File.Exists(outputFile))
+            {
+                Preview();
+            }
+            else
+            {
+                Export(true);
+            }
+        }
+    }
+}
+

+ 225 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Animations.cs

@@ -0,0 +1,225 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using BabylonExport.Entities;
+using UnityEditor;
+using UnityEditor.Animations;
+using UnityEngine;
+
+namespace Unity3D2Babylon
+{
+    partial class SceneBuilder
+    {
+        private static void ExportAnimations(Transform transform, BabylonIAnimatable animatable)
+        {
+            var animator = transform.gameObject.GetComponent<Animator>();
+            if (animator != null)
+            {
+                AnimatorController ac = animator.runtimeAnimatorController as AnimatorController;
+                if (ac == null)
+                {
+                    return;
+                }
+                var layer = ac.layers[0];
+                if (layer == null)
+                {
+                    return;
+                }
+                AnimatorStateMachine sm = layer.stateMachine;
+                if (sm.states.Length > 0)
+                {
+                    var state = sm.states[0].state; // We only support the first one
+                    AnimationClip clip = state.motion as AnimationClip;
+                    if (clip != null)
+                    {
+                        ExportAnimationClip(clip, true, animatable);
+                    }
+                }
+            }
+            else
+            {
+                var animation = transform.gameObject.GetComponent<Animation>();
+                if (animation != null && animation.clip != null)
+                {
+                    ExportAnimationClip(animation.clip, animation.playAutomatically, animatable);
+                }
+            }
+        }
+
+        private static bool IsRotationQuaternionAnimated(BabylonIAnimatable animatable)
+        {
+            if (animatable.animations == null)
+            {
+                return false;
+            }
+
+            return animatable.animations.Any(animation => animation.property.Contains("rotationQuaternion"));
+        }
+
+        private static void ExportSkeletonAnimationClips(Animator animator, bool autoPlay, BabylonSkeleton skeleton, Transform[] bones, BabylonMesh babylonMesh)
+        {
+            AnimationClip clip = null;
+            AnimatorController ac = animator.runtimeAnimatorController as AnimatorController;
+            if (ac == null)
+            {
+                return;
+            }
+            var layer = ac.layers[0];
+            if (layer == null)
+            {
+                return;
+            }
+            AnimatorStateMachine sm = layer.stateMachine;
+            if (sm.states.Length > 0)
+            {
+                // Only the first state is supported so far.
+                var state = sm.states[0].state;
+                clip = state.motion as AnimationClip;
+            }
+
+            if (clip == null)
+            {
+                return;
+            }
+
+            ExportSkeletonAnimationClipData(animator, autoPlay, skeleton, bones, babylonMesh, clip);
+        }
+
+        private static void ExportSkeletonAnimationClipData(Animator animator, bool autoPlay, BabylonSkeleton skeleton, Transform[] bones, BabylonMesh babylonMesh, AnimationClip clip)
+        {
+            var frameTime = 1.0f / clip.frameRate;
+            int animationFrameCount = (int)(clip.length * clip.frameRate);
+
+            if (autoPlay)
+            {
+                babylonMesh.autoAnimate = true;
+                babylonMesh.autoAnimateFrom = 0;
+                babylonMesh.autoAnimateTo = animationFrameCount;
+                babylonMesh.autoAnimateLoop = true;
+            }
+
+            foreach (var bone in skeleton.bones)
+            {
+                var keys = new List<BabylonAnimationKey>();
+                var transform = bones.Single(b => b.name == bone.name);
+
+                AnimationMode.BeginSampling();
+                for (var i = 0; i < animationFrameCount; i++)
+                {
+                    clip.SampleAnimation(animator.gameObject, i * frameTime);
+
+                    var local = (transform.parent.localToWorldMatrix.inverse * transform.localToWorldMatrix);
+                    float[] matrix = new[] {
+                        local[0, 0], local[1, 0], local[2, 0], local[3, 0],
+                        local[0, 1], local[1, 1], local[2, 1], local[3, 1],
+                        local[0, 2], local[1, 2], local[2, 2], local[3, 2],
+                        local[0, 3], local[1, 3], local[2, 3], local[3, 3]
+                    };
+
+                    var key = new BabylonAnimationKey
+                    {
+                        frame = i,
+                        values = matrix,
+                    };
+                    keys.Add(key);
+                }
+                AnimationMode.EndSampling();
+
+                var babylonAnimation = new BabylonAnimation
+                {
+                    name = bone.name + "Animation",
+                    property = "_matrix",
+                    dataType = (int)BabylonAnimation.DataType.Matrix,
+                    loopBehavior = (int)BabylonAnimation.LoopBehavior.Cycle,
+                    framePerSecond = (int)clip.frameRate,
+                    keys = keys.ToArray()
+                };
+
+                bone.animation = babylonAnimation;
+            }
+        }
+
+        private static void ExportAnimationClip(AnimationClip clip, bool autoPlay, BabylonIAnimatable animatable)
+        {
+            var curveBindings = AnimationUtility.GetCurveBindings(clip);
+            var animations = new List<BabylonAnimation>();
+
+            var maxFrame = 0;
+
+            foreach (var binding in curveBindings)
+            {
+                var curve = AnimationUtility.GetEditorCurve(clip, binding);
+                string property;
+
+                switch (binding.propertyName)
+                {
+                    case "m_LocalPosition.x":
+                        property = "position.x";
+                        break;
+                    case "m_LocalPosition.y":
+                        property = "position.y";
+                        break;
+                    case "m_LocalPosition.z":
+                        property = "position.z";
+                        break;
+
+                    case "m_LocalRotation.x":
+                        property = "rotationQuaternion.x";
+                        break;
+                    case "m_LocalRotation.y":
+                        property = "rotationQuaternion.y";
+                        break;
+                    case "m_LocalRotation.z":
+                        property = "rotationQuaternion.z";
+                        break;
+                    case "m_LocalRotation.w":
+                        property = "rotationQuaternion.w";
+                        break;
+
+                    case "m_LocalScale.x":
+                        property = "scaling.x";
+                        break;
+                    case "m_LocalScale.y":
+                        property = "scaling.y";
+                        break;
+                    case "m_LocalScale.z":
+                        property = "scaling.z";
+                        break;
+                    default:
+                        continue;
+                }
+
+                var babylonAnimation = new BabylonAnimation
+                {
+                    dataType = (int)BabylonAnimation.DataType.Float,
+                    name = property + " animation",
+                    keys = curve.keys.Select(keyFrame => new BabylonAnimationKey
+                    {
+                        frame = (int)(keyFrame.time * clip.frameRate),
+                        values = new[] { keyFrame.value }
+                    }).ToArray(),
+                    framePerSecond = (int)clip.frameRate,
+                    loopBehavior = (int)BabylonAnimation.LoopBehavior.Cycle,
+                    property = property
+                };
+
+                maxFrame = Math.Max(babylonAnimation.keys.Last().frame, maxFrame);
+
+                animations.Add(babylonAnimation);
+            }
+
+            if (animations.Count > 0)
+            {
+                animatable.animations = animations.ToArray();
+                if (autoPlay)
+                {
+                    animatable.autoAnimate = true;
+                    animatable.autoAnimateFrom = 0;
+                    animatable.autoAnimateTo = maxFrame;
+                    animatable.autoAnimateLoop = clip.isLooping;
+                }
+            }
+        }
+    }
+}

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 198 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Cameras.cs


+ 132 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Lights.cs

@@ -0,0 +1,132 @@
+using System;
+using System.IO;
+using System.Collections.Generic;
+using BabylonExport.Entities;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.Rendering;
+
+namespace Unity3D2Babylon
+{
+    partial class SceneBuilder
+    {
+        private void GenerateShadowsGenerator(Light light, float progress)
+        {
+            var generator = new BabylonShadowGenerator
+            {
+                lightId = GetID(light.gameObject),
+                mapSize = exportationOptions.ShadowMapSize,
+                blurScale = exportationOptions.ShadowBlurScale,
+                bias = exportationOptions.ShadowMapBias,
+                forceBackFacesOnly = false
+            };
+
+            BabylonLightingFilter filter = (BabylonLightingFilter)exportationOptions.DefaultLightFilter;
+            switch (filter)
+            {
+                case BabylonLightingFilter.PoissonSampling:
+                    generator.usePoissonSampling = true;
+                    break;
+                case BabylonLightingFilter.VarianceShadowMap:
+                    generator.useVarianceShadowMap = true;
+                    break;
+                case BabylonLightingFilter.BlurVarianceShadowMap:
+                    generator.useBlurVarianceShadowMap = true;
+                    break;
+                case BabylonLightingFilter.SoftPoissonSampling:
+                    generator.usePoissonSampling = (light.shadows == LightShadows.Soft);
+                    break;
+            }
+
+            var renderList = new List<string>();
+            foreach (var gameObject in gameObjects)
+            {
+                var shadowBake = gameObject.GetComponent<BabylonShadowBake>();
+                bool realtimeShadows = (shadowBake != null && shadowBake.shadowOption == BabylonShadowOptions.Realtime);
+                if (realtimeShadows)
+                {
+                    var renderer = gameObject.GetComponent<Renderer>();
+                    var meshFilter = gameObject.GetComponent<MeshFilter>();
+                    if (meshFilter != null && renderer != null && renderer.shadowCastingMode != ShadowCastingMode.Off)
+                    {
+                        renderList.Add(GetID(gameObject));
+                        continue;
+                    }
+                    var skinnedMesh = gameObject.GetComponent<SkinnedMeshRenderer>();
+                    if (skinnedMesh != null && renderer != null && renderer.shadowCastingMode != ShadowCastingMode.Off)
+                    {
+                        renderList.Add(GetID(gameObject));
+                    }
+                }
+            }
+
+            generator.renderList = renderList.ToArray();
+
+            babylonScene.ShadowGeneratorsList.Add(generator);
+        }
+
+        private void ConvertUnityLightToBabylon(Light light, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List<BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List<UnityFlareSystem> lensFlares, ref string componentTags)
+        {
+            // No Inactive Or Baking Lights
+            if (light.isActiveAndEnabled == false || light.type == LightType.Area || light.lightmappingMode == LightmappingMode.Baked) return;
+
+            ExporterWindow.ReportProgress(progress, "Exporting light: " + light.name);
+            BabylonLight babylonLight = new BabylonLight
+            {
+                name = light.name,
+                id = GetID(light.gameObject),
+                parentId = GetParentID(light.transform)
+            };
+            metaData.type = "Light";
+            babylonLight.tags = componentTags;
+
+            switch (light.type)
+            {
+                case LightType.Point:
+                    babylonLight.type = 0;
+                    babylonLight.range = light.range;
+                    break;
+                case LightType.Directional:
+                    babylonLight.type = 1;
+                    break;
+                case LightType.Spot:
+                    babylonLight.type = 2;
+                    break;
+            }
+
+            babylonLight.position = light.transform.localPosition.ToFloat();
+
+            var direction = new Vector3(0, 0, 1);
+            var transformedDirection = light.transform.TransformDirection(direction);
+            babylonLight.direction = transformedDirection.ToFloat();
+
+            babylonLight.diffuse = light.color.ToFloat();
+
+            babylonLight.intensity = light.intensity;
+
+            babylonLight.angle = light.spotAngle * (float)Math.PI / 180;
+            babylonLight.exponent = 1.0f;
+
+            babylonLight.metadata = metaData;
+            babylonScene.LightsList.Add(babylonLight);
+
+            // Animations
+            ExportAnimations(light.transform, babylonLight);
+
+            // Lens Flares
+            ParseLensFlares(gameObject, babylonLight.id, ref lensFlares);
+
+            // Particles Systems
+            ParseParticleSystems(gameObject, babylonLight.id, ref particleSystems);
+
+            // Shadow Maps
+            if (exportationOptions.ExportShadows)
+            {
+                if ((light.type == LightType.Directional || light.type == LightType.Spot) && light.shadows != LightShadows.None)
+                {
+                    GenerateShadowsGenerator(light, progress);
+                }
+            }
+        }
+    }
+}

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1098 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Materials.cs


+ 437 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.Meshes.cs

@@ -0,0 +1,437 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Collections.Generic;
+using System.Linq;
+using BabylonExport.Entities;
+using UnityEditor;
+using UnityEngine;
+
+namespace Unity3D2Babylon
+{
+    partial class SceneBuilder
+    {
+        private BabylonMesh ConvertUnityEmptyObjectToBabylon(GameObject gameObject, ref UnityMetaData metaData, ref List<BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List<UnityFlareSystem> lensFlares, ref string componentTags, BabylonMesh collisionMesh = null, Collider collider = null)
+        {
+            BabylonMesh babylonMesh = new BabylonMesh { name = gameObject.name, id = GetID(gameObject) };
+            metaData.type = "Game";
+            if (!String.IsNullOrEmpty(componentTags))
+            {
+                babylonMesh.tags = componentTags;
+            }
+
+            var transform = gameObject.transform;
+
+            babylonMesh.parentId = GetParentID(transform);
+
+            babylonMesh.position = transform.localPosition.ToFloat();
+
+            babylonMesh.rotation = new float[3];
+            babylonMesh.rotation[0] = transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
+            babylonMesh.rotation[1] = transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
+            babylonMesh.rotation[2] = transform.localRotation.eulerAngles.z * (float)Math.PI / 180;
+
+            babylonMesh.scaling = transform.localScale.ToFloat();
+
+            babylonMesh.isVisible = false;
+            babylonMesh.visibility = 0;
+            babylonMesh.checkCollisions = false;
+
+            // Collision mesh (No detail mesh fallback)
+            string collisionMeshId = null;
+            if (collider != null && collisionMesh != null)
+            {
+                collisionMeshId = collisionMesh.id;
+                collisionMesh.parentId = babylonMesh.id;
+                collisionMesh.visibility = collider.isTrigger ? 0.25f : 0.5f;
+                collisionMesh.checkCollisions = (exportationOptions.ExportCollisions && collider.isTrigger == false);
+            }
+            metaData.properties["collisionMeshId"] = collisionMeshId;
+
+            babylonMesh.metadata = metaData;
+            babylonScene.MeshesList.Add(babylonMesh);
+
+            // Animations
+            ExportAnimations(transform, babylonMesh);
+            if (IsRotationQuaternionAnimated(babylonMesh))
+            {
+                babylonMesh.rotationQuaternion = transform.localRotation.ToFloat();
+            }
+
+            // Lens Flares
+            ParseLensFlares(gameObject, babylonMesh.id, ref lensFlares);
+
+            // Particles Systems
+            ParseParticleSystems(gameObject, babylonMesh.id, ref particleSystems);
+
+            return babylonMesh;
+        }
+
+        private BabylonMesh ConvertUnityTerrainToBabylon(Terrain terrain, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List<BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List<UnityFlareSystem> lensFlares, ref string componentTags)
+        {
+            ExporterWindow.ReportProgress(progress, "Exporting terrain: " + gameObject.name);
+            var transform = gameObject.transform;
+            float[] position = transform.localPosition.ToFloat();
+            float[] rotation = new float[3];
+            rotation[0] = transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
+            rotation[1] = transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
+            rotation[2] = transform.localRotation.eulerAngles.z * (float)Math.PI / 180;
+            float[] scaling = transform.localScale.ToFloat();
+
+            BabylonMesh babylonMesh = new BabylonMesh { name = gameObject.name, id = GetID(gameObject) };
+            metaData.type = "Terrain";
+            if (!String.IsNullOrEmpty(componentTags))
+            {
+                babylonMesh.tags = componentTags;
+            }
+            babylonMesh.tags += " [TERRAIN]";
+            if (!String.IsNullOrEmpty(babylonMesh.tags))
+            {
+                babylonMesh.tags = babylonMesh.tags.Trim();
+            }
+            babylonMesh.parentId = GetParentID(transform);
+            babylonMesh.position = Vector3.zero.ToFloat();
+            babylonMesh.rotation = rotation;
+            babylonMesh.scaling = scaling;
+            babylonMesh.isVisible = true;
+            babylonMesh.visibility = 1;
+            babylonMesh.checkCollisions = false;
+            metaData.properties["collisionMeshId"] = null;
+
+            var generator = gameObject.GetComponent<BabylonTerrainGenerator>();
+            if (generator != null && terrain != null)
+            {
+                // TODO: Terrain tree information
+                object treeInstances = null;
+                object treePrototypes = null;
+
+                // Terrain metadata infomation
+                Vector3 terrainSize = terrain.terrainData.size;
+                metaData.properties.Add("width", terrainSize.x);
+                metaData.properties.Add("length", terrainSize.z);
+                metaData.properties.Add("height", terrainSize.y);
+                metaData.properties.Add("position", position);
+                metaData.properties.Add("rotation", rotation);
+                metaData.properties.Add("scaling", scaling);
+                metaData.properties.Add("thickness", terrain.terrainData.thickness);
+                metaData.properties.Add("detailWidth", terrain.terrainData.detailWidth);
+                metaData.properties.Add("detailHeight", terrain.terrainData.detailHeight);
+                metaData.properties.Add("heightmapWidth", terrain.terrainData.heightmapWidth);
+                metaData.properties.Add("heightmapHeight", terrain.terrainData.heightmapHeight);
+                metaData.properties.Add("wavingGrassAmount", terrain.terrainData.wavingGrassAmount);
+                metaData.properties.Add("wavingGrassSpeed", terrain.terrainData.wavingGrassSpeed);
+                metaData.properties.Add("wavingGrassStrength", terrain.terrainData.wavingGrassStrength);
+                metaData.properties.Add("wavingGrassTint", terrain.terrainData.wavingGrassTint.ToFloat());
+                metaData.properties.Add("treeInstanceCount", terrain.terrainData.treeInstanceCount);
+                metaData.properties.Add("treeInstances", treeInstances);
+                metaData.properties.Add("treePrototypes", treePrototypes);
+                metaData.properties.Add("physicsState", generator.physicsActive);
+                metaData.properties.Add("physicsMass", generator.physicsMass);
+                metaData.properties.Add("physicsFriction", generator.physicsFriction);
+                metaData.properties.Add("physicsRestitution", generator.physicsRestitution);
+                metaData.properties.Add("physicsImpostor", (int)generator.physicsImpostor);
+                metaData.properties.Add("groundTessellation", generator.groundTessellation);
+
+                // Generate detailed mesh
+                ExporterWindow.ReportProgress(progress, "Generating terrain mesh: " + gameObject.name);
+                BabylonTerrainData terrainMeshData = Unity3D2Babylon.Tools.CreateTerrainData(terrain.terrainData, (int)generator.terrainResolution, transform.localPosition, true);
+                Tools.GenerateBabylonMeshTerrainData(terrainMeshData, babylonMesh, false, babylonScene, transform);
+                if (generator.surfaceMaterial != null)
+                {
+                    babylonMesh.materialId = DumpMaterial(generator.surfaceMaterial, terrain.lightmapIndex, terrain.lightmapScaleOffset, generator.coordinatesIndex).id;
+                }
+
+                // Generate collision heightmap
+                var terrainCollider = gameObject.GetComponent<TerrainCollider>();
+                if (terrainCollider != null && terrainCollider.enabled)
+                {
+                    ExporterWindow.ReportProgress(progress, "Generating terrain heightmap: " + gameObject.name);
+                    float minheight = float.MaxValue;
+                    float maxheight = float.MinValue;
+                    int hwidth = terrain.terrainData.heightmapWidth;
+                    int hheight = terrain.terrainData.heightmapHeight;
+                    float[,] rawHeights = terrain.terrainData.GetHeights(0, 0, hwidth, hheight);
+                    Texture2D heightMap = new Texture2D(hwidth, hheight, TextureFormat.ARGB32, false);
+                    for (int y = 0; y < hheight; y++)
+                    {
+                        for (int x = 0; x < hwidth; x++)
+                        {
+                            float inverted = rawHeights[y, x];
+                            minheight = Mathf.Min(minheight, inverted);
+                            maxheight = Mathf.Max(maxheight, inverted);
+                        }
+                    }
+                    List<Color32> pixels = new List<Color32>();
+                    for (int y = 0; y < hheight; y++)
+                    {
+                        for (int x = 0; x < hwidth; x++)
+                        {
+                            float inverted = rawHeights[y, x];
+                            if (generator.heightmapStrength > 0)
+                            {
+                                float threadhold = minheight + generator.floorThreashold;
+                                if (inverted > threadhold)
+                                {
+                                    inverted += (generator.heightmapStrength / 10.0f);
+                                }
+                            }
+                            byte[] packed = BitConverter.GetBytes(inverted);
+                            if (packed != null && packed.Length >= 4)
+                            {
+                                pixels.Add(new Color32(packed[0], packed[1], packed[2], packed[3]));
+                            }
+                        }
+                    }
+                    heightMap.SetPixels32(pixels.ToArray());
+                    heightMap.Apply();
+                    byte[] heightmapBytes = heightMap.EncodeToPNG();
+                    metaData.properties.Add("heightmapBase64", ("data:image/png;base64," + Convert.ToBase64String(heightmapBytes)));
+                }
+            }
+            else
+            {
+                UnityEngine.Debug.LogWarning("No valid terrain or generator found for: " + gameObject.name);
+            }
+
+            babylonMesh.metadata = metaData;
+            babylonScene.MeshesList.Add(babylonMesh);
+            SceneBuilder.Metadata.properties["hasTerrainMeshes"] = true;
+
+            // Animations
+            ExportAnimations(transform, babylonMesh);
+            if (IsRotationQuaternionAnimated(babylonMesh))
+            {
+                babylonMesh.rotationQuaternion = transform.localRotation.ToFloat();
+            }
+
+            // Lens Flares
+            ParseLensFlares(gameObject, babylonMesh.id, ref lensFlares);
+
+            // Particles Systems
+            ParseParticleSystems(gameObject, babylonMesh.id, ref particleSystems);
+
+            return babylonMesh;
+        }
+
+        private BabylonMesh ConvertUnityMeshToBabylon(Mesh mesh, Transform transform, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List<BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List<UnityFlareSystem> lensFlares, ref string componentTags, BabylonMesh collisionMesh = null, Collider collider = null)
+        {
+            BabylonMesh babylonMesh = new BabylonMesh();
+            metaData.type = "Mesh";
+            if (!String.IsNullOrEmpty(componentTags))
+            {
+                babylonMesh.tags = componentTags;
+            }
+
+            ExporterWindow.ReportProgress(progress, "Exporting mesh: " + gameObject.name);
+
+            babylonMesh.name = gameObject.name;
+            babylonMesh.id = GetID(transform.gameObject);
+
+            var renderer = gameObject.GetComponent<Renderer>();
+            if (renderer != null)
+            {
+                babylonMesh.receiveShadows = renderer.receiveShadows;
+            }
+
+            babylonMesh.parentId = GetParentID(transform);
+
+            babylonMesh.position = transform.localPosition.ToFloat();
+
+            babylonMesh.rotation = new float[3];
+            babylonMesh.rotation[0] = transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
+            babylonMesh.rotation[1] = transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
+            babylonMesh.rotation[2] = transform.localRotation.eulerAngles.z * (float)Math.PI / 180;
+
+            babylonMesh.scaling = transform.localScale.ToFloat();
+            babylonMesh.checkCollisions = false;
+
+            // Collision mesh (With detail mesh fallback)
+            string collisionMeshId = null;
+            if (collider != null)
+            {
+                if (collisionMesh != null)
+                {
+                    collisionMeshId = collisionMesh.id;
+                    collisionMesh.parentId = babylonMesh.id;
+                    collisionMesh.visibility = collider.isTrigger ? 0.25f : 0.5f;
+                    collisionMesh.checkCollisions = (exportationOptions.ExportCollisions && collider.isTrigger == false);
+                }
+                else
+                {
+                    babylonMesh.checkCollisions = exportationOptions.ExportCollisions;
+                }
+            }
+            metaData.properties["collisionMeshId"] = collisionMeshId;
+
+            if (mesh != null)
+            {
+                Tools.GenerateBabylonMeshData(mesh, babylonMesh, babylonScene, transform);
+                int index = 0;
+                if (mesh.boneWeights.Length == mesh.vertexCount)
+                {
+                    babylonMesh.matricesIndices = new int[mesh.vertexCount];
+                    babylonMesh.matricesWeights = new float[mesh.vertexCount * 4];
+                    index = 0;
+                    foreach (BoneWeight bw in mesh.boneWeights)
+                    {
+                        babylonMesh.matricesIndices[index] = (bw.boneIndex3 << 24) | (bw.boneIndex2 << 16) | (bw.boneIndex1 << 8) | bw.boneIndex0;
+                        babylonMesh.matricesWeights[index * 4 + 0] = bw.weight0;
+                        babylonMesh.matricesWeights[index * 4 + 1] = bw.weight1;
+                        babylonMesh.matricesWeights[index * 4 + 2] = bw.weight2;
+                        babylonMesh.matricesWeights[index * 4 + 3] = bw.weight3;
+                        var totalWeight = bw.weight0 + bw.weight1 + bw.weight2 + bw.weight3;
+                        if (Mathf.Abs(totalWeight - 1.0f) > 0.01f)
+                        {
+                            throw new Exception("Total bone weights is not normalized for: " + mesh);
+                        }
+                        index++;
+                    }
+                }
+                index = 0;
+                if (renderer != null && renderer.sharedMaterial != null)
+                {
+                    // Validate Multi Materials
+                    if (mesh.subMeshCount > 1)
+                    {
+                        BabylonMultiMaterial bMultiMat;
+                        if (!multiMatDictionary.ContainsKey(renderer.sharedMaterial.name))
+                        {
+                            bMultiMat = new BabylonMultiMaterial
+                            {
+                                materials = new string[mesh.subMeshCount],
+                                id = Guid.NewGuid().ToString(),
+                                name = renderer.sharedMaterial.name
+                            };
+
+                            for (int i = 0; i < renderer.sharedMaterials.Length; i++)
+                            {
+                                var sharedMaterial = renderer.sharedMaterials[i];
+                                BabylonMaterial babylonMaterial;
+
+                                babylonMaterial = DumpMaterial(sharedMaterial, renderer.lightmapIndex, renderer.lightmapScaleOffset);
+
+                                bMultiMat.materials[i] = babylonMaterial.id;
+                            }
+                            if (mesh.subMeshCount > 1)
+                            {
+                                multiMatDictionary.Add(bMultiMat.name, bMultiMat);
+                            }
+                        }
+                        else
+                        {
+                            bMultiMat = multiMatDictionary[renderer.sharedMaterial.name];
+                        }
+
+                        babylonMesh.materialId = bMultiMat.id;
+                        babylonMesh.subMeshes = new BabylonSubMesh[mesh.subMeshCount];
+
+                        var offset = 0;
+                        for (int materialIndex = 0; materialIndex < mesh.subMeshCount; materialIndex++)
+                        {
+                            var unityTriangles = mesh.GetTriangles(materialIndex);
+                            babylonMesh.subMeshes[materialIndex] = new BabylonSubMesh
+                            {
+                                verticesStart = 0,
+                                verticesCount = mesh.vertexCount,
+                                materialIndex = materialIndex,
+                                indexStart = offset,
+                                indexCount = unityTriangles.Length
+                            };
+                            offset += unityTriangles.Length;
+                        }
+                    }
+                    else
+                    {
+                        babylonMesh.materialId = DumpMaterial(renderer.sharedMaterial, renderer.lightmapIndex, renderer.lightmapScaleOffset).id;
+                    }
+                }
+
+                babylonMesh.metadata = metaData;
+                babylonScene.MeshesList.Add(babylonMesh);
+
+                // Animations
+                ExportAnimations(transform, babylonMesh);
+                if (IsRotationQuaternionAnimated(babylonMesh))
+                {
+                    babylonMesh.rotationQuaternion = transform.localRotation.ToFloat();
+                }
+
+                // Lens Flares
+                ParseLensFlares(gameObject, babylonMesh.id, ref lensFlares);
+
+                // Particles Systems
+                ParseParticleSystems(gameObject, babylonMesh.id, ref particleSystems);
+
+                // Babylon Physics
+                if (exportationOptions.ExportPhysics)
+                {
+                    var physics = gameObject.GetComponent<BabylonPhysicsState>();
+                    if (physics != null)
+                    {
+                        babylonMesh.physicsMass = physics.mass;
+                        babylonMesh.physicsFriction = physics.friction;
+                        babylonMesh.physicsRestitution = physics.restitution;
+                        babylonMesh.physicsImpostor = (int)physics.imposter;
+                    }
+                }
+            }
+            return babylonMesh;
+        }
+
+        private BabylonSkeleton ConvertUnitySkeletonToBabylon(Transform[] bones, Matrix4x4[] bindPoses, Transform transform, GameObject gameObject, float progress)
+        {
+            ExporterWindow.ReportProgress(progress, "Exporting skeleton: " + gameObject.name);
+            BabylonSkeleton babylonSkeleton = new BabylonSkeleton();
+            babylonSkeleton.name = gameObject.name;
+            babylonSkeleton.id = Math.Abs(GetID(transform.gameObject).GetHashCode());
+            babylonSkeleton.needInitialSkinMatrix = false;
+
+            // Prefilled to keep order and track parents.
+            int index = 0;
+            var transformToBoneMap = new Dictionary<Transform, BabylonBone>();
+            foreach (Transform unityBone in bones)
+            {
+                var babylonBone = new BabylonBone();
+                babylonBone.name = unityBone.name;
+                babylonBone.index = index;
+
+                transformToBoneMap.Add(unityBone, babylonBone);
+                index++;
+            }
+
+            // Attaches Matrix and parent.
+            index = 0;
+            foreach (Transform unityBone in bones)
+            {
+                var babylonBone = transformToBoneMap[unityBone];
+                Matrix4x4 localTransform;
+
+                // Unity BindPose is already inverse so take the inverse again :-)
+                if (transformToBoneMap.ContainsKey(unityBone.parent))
+                {
+                    var babylonParentBone = transformToBoneMap[unityBone.parent];
+                    babylonBone.parentBoneIndex = babylonParentBone.index;
+                    localTransform = bindPoses[babylonBone.parentBoneIndex] * bindPoses[index].inverse;
+                }
+                else
+                {
+                    babylonBone.parentBoneIndex = -1;
+                    localTransform = bindPoses[index].inverse;
+                }
+
+                transformToBoneMap[unityBone].matrix = new[] {
+                    localTransform[0, 0], localTransform[1, 0], localTransform[2, 0], localTransform[3, 0],
+                    localTransform[0, 1], localTransform[1, 1], localTransform[2, 1], localTransform[3, 1],
+                    localTransform[0, 2], localTransform[1, 2], localTransform[2, 2], localTransform[3, 2],
+                    localTransform[0, 3], localTransform[1, 3], localTransform[2, 3], localTransform[3, 3]
+                };
+                index++;
+            }
+
+            // Reorder and attach the skeleton.
+            babylonSkeleton.bones = transformToBoneMap.Values.OrderBy(b => b.index).ToArray();
+            babylonScene.SkeletonsList.Add(babylonSkeleton);
+            return babylonSkeleton;
+        }
+    }
+}

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1467 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SceneBuilder.cs


+ 26 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SerializableColor.cs

@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using UnityEngine;
+
+namespace Unity3D2Babylon
+{
+    public class SerializableColor
+    {
+        public float r { get; set; }
+        public float g { get; set; }
+        public float b { get; set; }
+        public float a { get; set; }
+
+        public static implicit operator Color(SerializableColor source)
+        {
+            return new Color(source.r, source.g, source.b, source.a);
+        }
+
+        public static implicit operator SerializableColor(Color source)
+        {
+            return new SerializableColor { r = source.r, g = source.g, b = source.b, a = source.a };
+        }
+    }
+}

+ 25 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/SerializableVector3.cs

@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using UnityEngine;
+
+namespace Unity3D2Babylon
+{
+    public class SerializableVector3
+    {
+        public float X { get; set; }
+        public float Y { get; set; }
+        public float Z { get; set; }
+
+        public static implicit operator Vector3(SerializableVector3 source)
+        {
+            return new Vector3(source.X, source.Y, source.Z);
+        }
+
+        public static implicit operator SerializableVector3(Vector3 source)
+        {
+            return new SerializableVector3 { X = source.x, Y = source.y, Z = source.z };
+        }
+    }
+}

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1618 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/Tools.cs


+ 211 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/WebBrowser.cs

@@ -0,0 +1,211 @@
+using System;
+using UnityEditor;
+using UnityEngine;
+using System.Reflection;
+
+namespace Unity3D2Babylon
+{
+
+    public sealed class WebBrowser : ScriptableObject
+    {
+        public static Type WebViewType = Tools.GetTypeFromAllAssemblies("WebView");
+        public static Type WebScriptObjectType = Tools.GetTypeFromAllAssemblies("WebScriptObject");
+
+        private ScriptableObject internalWebView;
+
+        private MethodInfo dockedGetterMethod;
+
+        private EditorWindow parentWin;
+
+        private object hostView;
+
+        public WebBrowser()
+        {
+            this.hostView = null;
+            this.parentWin = null;
+            this.internalWebView = null;
+            this.dockedGetterMethod = null;
+        }
+
+        public bool CreateView(EditorWindow parent)
+        {
+            return AttachView(parent, ScriptableObject.CreateInstance(WebBrowser.WebViewType), true);
+        }
+
+        public bool AttachView(EditorWindow parent, ScriptableObject webView, bool initialize = false)
+        {
+            this.parentWin = parent;
+            this.internalWebView = webView;
+            if (this.internalWebView != null)
+            {
+                this.hostView = Tools.GetReflectionField<object>(parent, "m_Parent");
+                this.dockedGetterMethod = this.parentWin.GetType().GetProperty("docked", Tools.FullBinding).GetGetMethod(true);
+                if (this.hostView != null && dockedGetterMethod != null)
+                {
+                    if (initialize)
+                    {
+                        Rect initViewRect = new Rect(0, 20, this.parentWin.position.width, this.parentWin.position.height - ((this.IsDocked()) ? 20 : 40));
+                        this.InitWebView(this.hostView, (int)initViewRect.x, (int)initViewRect.y, (int)initViewRect.width, (int)initViewRect.height, false);
+                        this.SetHideFlags(HideFlags.HideAndDontSave);
+                        this.AllowRightClickMenu(true);
+                    }
+                }
+                else
+                {
+                    throw new Exception("Failed to get parent window or docked property");
+                }
+            }
+            return (this.internalWebView != null);
+        }
+
+        public bool IsValid()
+        {
+            return (this.internalWebView != null);
+        }
+
+        public bool IsDocked()
+        {
+            return (this.parentWin != null && dockedGetterMethod != null) ? (bool)(dockedGetterMethod.Invoke(this.parentWin, null)) : false;
+        }
+
+        public bool HasFocus()
+        {
+            return (this.parentWin != null) ? Tools.GetReflectionProperty<bool>(this.parentWin, "hasFocus") : false;
+        }
+
+        public ScriptableObject GetWebView()
+        {
+            return this.internalWebView;
+        }
+
+        public object GetHostView()
+        {
+            return this.hostView;
+        }
+
+        public Type GetViewType()
+        {
+            return this.internalWebView.GetType();
+        }
+
+        public void OnDestroy()
+        {
+            UnityEngine.Object.DestroyImmediate(this.internalWebView, true);
+        }
+
+        public void SetHideFlags(HideFlags flags)
+        {
+            this.internalWebView.hideFlags = flags;
+        }
+
+        public void DestroyWebView()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "DestroyWebView");
+        }
+
+        public void InitWebView(object host, int x, int y, int width, int height, bool showResizeHandle)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "InitWebView", host, x, y, width, height, showResizeHandle);
+        }
+
+        public void ExecuteJavascript(string scriptCode)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "ExecuteJavascript", scriptCode);
+        }
+
+        public void LoadURL(string url)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "LoadURL", url);
+        }
+
+        public void LoadFile(string path)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "LoadFile", path);
+        }
+
+        public bool DefineScriptObject(string path, ScriptableObject obj)
+        {
+            return Tools.CallReflectionMethod<bool>(this.internalWebView, "DefineScriptObject", path, obj);
+        }
+
+        public void SetDelegateObject(ScriptableObject value)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "SetDelegateObject", value);
+        }
+
+        public void SetHostView(object view)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "SetHostView", view);
+        }
+
+        public void SetSizeAndPosition(int x, int y, int width, int height)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "SetSizeAndPosition", x, y, width, height);
+        }
+
+        public void SetFocus(bool value)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "SetFocus", value);
+        }
+
+        public bool HasApplicationFocus()
+        {
+            return Tools.CallReflectionMethod<bool>(this.internalWebView, "HasApplicationFocus");
+        }
+
+        public void SetApplicationFocus(bool applicationFocus)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "SetApplicationFocus", applicationFocus);
+        }
+
+        public void Show()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "Show");
+        }
+
+        public void Hide()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "Hide");
+        }
+
+        public void Back()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "Back");
+        }
+
+        public void Forward()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "Forward");
+        }
+
+        public void SendOnEvent(string jsonStr)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "SendOnEvent", jsonStr);
+        }
+
+        public void Reload()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "Reload");
+        }
+
+        public void AllowRightClickMenu(bool allowRightClickMenu)
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "AllowRightClickMenu", allowRightClickMenu);
+        }
+
+        public void ShowDevTools()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "ShowDevTools");
+        }
+
+        public void ToggleMaximize()
+        {
+            Tools.CallReflectionMethod(this.internalWebView, "ToggleMaximize");
+        }
+
+        public static void OnDomainReload()
+        {
+            Tools.CallStaticReflectionMethod(WebBrowser.WebViewType, "OnDomainReload");
+        }
+    }
+}

+ 633 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Source/WebServer.cs

@@ -0,0 +1,633 @@
+using System;
+using System.IO;
+using System.Net;
+using System.Text;
+using System.Threading;
+using System.Collections.Generic;
+
+namespace BabylonHosting
+{
+    public static class WebServer
+    {
+        public static string Root { get; private set; }
+        public static bool IsSupported { get; private set; }
+        public static HttpListener HostListener { get; private set; }
+
+        static WebServer()
+        {
+            Root = String.Empty;
+            IsSupported = false;
+            HostListener = null;
+            SetupFileTypeMappings();
+        }
+
+        public static bool Activate(string prefix, string root, int port)
+        {
+            bool started = false;
+            WebServer.Root = root;
+            if (WebServer.HostListener == null)
+            {
+                try
+                {
+                    WebServer.HostListener = new HttpListener();
+
+                    if (!HttpListener.IsSupported)
+                    {
+                        IsSupported = false;
+                        return false;
+                    }
+
+                    string protocol = prefix;
+                    if (String.IsNullOrEmpty(protocol))
+                    {
+                        protocol = "http://*:";
+                    }
+
+                    if (protocol.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
+                    {
+                        // TODO: Enable Basic SSL Support
+                    }
+
+                    WebServer.HostListener.Prefixes.Add(protocol + port.ToString() + "/");
+                    WebServer.HostListener.Start();
+
+                    ThreadPool.QueueUserWorkItem(Listen);
+
+                    started = true;
+                    IsSupported = true;
+                }
+                catch
+                {
+                    WebServer.HostListener = null;
+                    IsSupported = false;
+                }
+            }
+            return started;
+        }
+
+        static void Listen(object state)
+        {
+            try
+            {
+                while (WebServer.HostListener.IsListening)
+                {
+                    var context = WebServer.HostListener.GetContext();
+                    var request = context.Request;
+                    var url = request.Url;
+
+                    if (String.IsNullOrEmpty(WebServer.Root)) WebServer.Root = "/";
+                    try
+                    {
+                        string path = String.Empty;
+                        context.Response.AddHeader("Cache-Control", "no-cache");
+                        if (string.IsNullOrEmpty(url.LocalPath) || url.LocalPath == "/")
+                        {
+                            path = Path.Combine(WebServer.Root, "index.html");
+                            if (!File.Exists(path))
+                            {
+                                path = Path.Combine(WebServer.Root, "index.htm");
+                                if (!File.Exists(path))
+                                {
+                                    path = Path.Combine(WebServer.Root, "default.html");
+                                    if (!File.Exists(path))
+                                    {
+                                        path = Path.Combine(WebServer.Root, "default.htm");
+                                        if (!File.Exists(path))
+                                        {
+                                            path = Path.Combine(WebServer.Root, "index.html");
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                        else
+                        {
+                            path = Path.Combine(WebServer.Root, UnityEngine.WWW.UnEscapeURL(url.PathAndQuery.Substring(1)));
+                        }
+                        if (!String.IsNullOrEmpty(path))
+                        {
+                            var questionMarkIndex = path.IndexOf("?");
+                            if (questionMarkIndex != -1)
+                            {
+                                path = path.Substring(0, questionMarkIndex);
+                            }
+                            var hashIndex = path.IndexOf("#");
+                            if (hashIndex != -1)
+                            {
+                                path = path.Substring(0, hashIndex);
+                            }
+                            if (File.Exists(path))
+                            {
+                                WriteResponse(context, new FileInfo(path));
+                            }
+                            else
+                            {
+                                context.Response.StatusCode = 404;
+                                context.Response.StatusDescription = "File Not Found";
+                                context.Response.Close();
+                                continue;
+                            }
+                        }
+                        else
+                        {
+                            throw new Exception("Failed to format valid request path.");
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        context.Response.StatusCode = 500;
+                        context.Response.StatusDescription = ex.Message;
+                        context.Response.Close();
+                        UnityEngine.Debug.LogException(ex);
+                        continue;
+                    }
+                }
+            }
+            catch
+            {
+                // Note: Thread Abort Excpetions Caught Here
+            }
+        }
+
+        static void WriteResponse(HttpListenerContext context, string s)
+        {
+            WriteResponse(context.Response, s);
+        }
+
+        static void WriteResponse(HttpListenerContext context, byte[] buffer)
+        {
+            WriteResponse(context.Response, buffer);
+        }
+
+        static void WriteResponse(HttpListenerContext context, FileInfo info)
+        {
+            WriteResponse(context.Response, info);
+        }
+
+        static void WriteResponse(HttpListenerContext context, Stream stream)
+        {
+            WriteResponse(context.Response, stream);
+        }
+
+        static void WriteResponse(HttpListenerResponse response, string s)
+        {
+            byte[] buffer = Encoding.UTF8.GetBytes(s);
+            WriteResponse(response, buffer);
+        }
+
+        static void WriteResponse(HttpListenerResponse response, byte[] buffer)
+        {
+            response.ContentLength64 = buffer.Length;
+            Stream output = response.OutputStream;
+            output.Write(buffer, 0, buffer.Length);
+            output.Close();
+        }
+
+        static void WriteResponse(HttpListenerResponse response, FileInfo info)
+        {
+            Stream file = info.OpenRead();
+            response.ContentType = GetMimeType(info);
+            WriteResponse(response, file);
+            file.Close();
+        }
+
+        static void WriteResponse(HttpListenerResponse response, Stream stream)
+        {
+            response.ContentLength64 = stream.Length;
+            Stream output = response.OutputStream;
+            stream.CopyTo(response.OutputStream, true, (1024 * 32));
+            output.Close();
+        }
+
+        static string GetMimeType(string filename)
+        {
+            return GetMimeType(new FileInfo(filename));
+        }
+
+        static string GetMimeType(FileInfo info)
+        {
+            string content_type = "application/octet-stream";
+            if (Mappings != null)
+            {
+                string extension = info.Extension;
+                if (!String.IsNullOrEmpty(extension))
+                {
+                    Mappings.TryGetValue(extension, out content_type);
+                }
+            }
+            return (!String.IsNullOrEmpty(content_type)) ? content_type : "application/octet-stream";
+        }
+
+        public static void CopyTo(this Stream source, Stream destination, bool finalFlush = false, int bufferSize = 4096, long maxCount = -1)
+        {
+            byte[] buffer = new byte[bufferSize];
+            long totalBytesWritten = 0;
+            while (true)
+            {
+                int count = buffer.Length;
+                if (maxCount > 0)
+                {
+                    if (totalBytesWritten > maxCount - count)
+                    {
+                        count = (int)(maxCount - totalBytesWritten);
+                        if (count <= 0)
+                        {
+                            break;
+                        }
+                    }
+                }
+                int read = source.Read(buffer, 0, count);
+                if (read <= 0)
+                {
+                    break;
+                }
+                destination.Write(buffer, 0, read);
+                totalBytesWritten += read;
+            }
+            if (finalFlush)
+            {
+                try { destination.Flush(); } catch { }
+            }
+        }
+
+        static IDictionary<string, string> Mappings = null;
+        static void SetupFileTypeMappings()
+        {
+            #region Default Content Mappings
+            Mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
+            { ".323", "text/h323" },
+            { ".3g2", "video/3gpp2" },
+            { ".3gp2", "video/3gpp2" },
+            { ".3gp", "video/3gpp" },
+            { ".3gpp", "video/3gpp" },
+            { ".aac", "audio/aac" },
+            { ".aaf", "application/octet-stream" },
+            { ".aca", "application/octet-stream" },
+            { ".accdb", "application/msaccess" },
+            { ".accde", "application/msaccess" },
+            { ".accdt", "application/msaccess" },
+            { ".acx", "application/internet-property-stream" },
+            { ".adt", "audio/vnd.dlna.adts" },
+            { ".adts", "audio/vnd.dlna.adts" },
+            { ".afm", "application/octet-stream" },
+            { ".ai", "application/postscript" },
+            { ".aif", "audio/x-aiff" },
+            { ".aifc", "audio/aiff" },
+            { ".aiff", "audio/aiff" },
+            { ".application", "application/x-ms-application" },
+            { ".art", "image/x-jg" },
+            { ".asd", "application/octet-stream" },
+            { ".asf", "video/x-ms-asf" },
+            { ".asi", "application/octet-stream" },
+            { ".asm", "text/plain" },
+            { ".asr", "video/x-ms-asf" },
+            { ".asx", "video/x-ms-asf" },
+            { ".atom", "application/atom+xml" },
+            { ".au", "audio/basic" },
+            { ".avi", "video/x-msvideo" },
+            { ".axs", "application/olescript" },
+            { ".bas", "text/plain" },
+            { ".bcpio", "application/x-bcpio" },
+            { ".bin", "application/octet-stream" },
+            { ".bmp", "image/bmp" },
+            { ".c", "text/plain" },
+            { ".cab", "application/vnd.ms-cab-compressed" },
+            { ".calx", "application/vnd.ms-office.calx" },
+            { ".cat", "application/vnd.ms-pki.seccat" },
+            { ".cdf", "application/x-cdf" },
+            { ".chm", "application/octet-stream" },
+            { ".class", "application/x-java-applet" },
+            { ".clp", "application/x-msclip" },
+            { ".cmx", "image/x-cmx" },
+            { ".cnf", "text/plain" },
+            { ".cod", "image/cis-cod" },
+            { ".cpio", "application/x-cpio" },
+            { ".cpp", "text/plain" },
+            { ".crd", "application/x-mscardfile" },
+            { ".crl", "application/pkix-crl" },
+            { ".crt", "application/x-x509-ca-cert" },
+            { ".csh", "application/x-csh" },
+            { ".css", "text/css" },
+            { ".csv", "application/octet-stream" },
+            { ".cur", "application/octet-stream" },
+            { ".dcr", "application/x-director" },
+            { ".deploy", "application/octet-stream" },
+            { ".der", "application/x-x509-ca-cert" },
+            { ".dib", "image/bmp" },
+            { ".dir", "application/x-director" },
+            { ".disco", "text/xml" },
+            { ".dlm", "text/dlm" },
+            { ".doc", "application/msword" },
+            { ".docm", "application/vnd.ms-word.document.macroEnabled.12" },
+            { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
+            { ".dot", "application/msword" },
+            { ".dotm", "application/vnd.ms-word.template.macroEnabled.12" },
+            { ".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" },
+            { ".dsp", "application/octet-stream" },
+            { ".dtd", "text/xml" },
+            { ".dvi", "application/x-dvi" },
+            { ".dvr-ms", "video/x-ms-dvr" },
+            { ".dwf", "drawing/x-dwf" },
+            { ".dwp", "application/octet-stream" },
+            { ".dxr", "application/x-director" },
+            { ".eml", "message/rfc822" },
+            { ".emz", "application/octet-stream" },
+            { ".eot", "application/vnd.ms-fontobject" },
+            { ".eps", "application/postscript" },
+            { ".etx", "text/x-setext" },
+            { ".evy", "application/envoy" },
+            { ".fdf", "application/vnd.fdf" },
+            { ".fif", "application/fractals" },
+            { ".fla", "application/octet-stream" },
+            { ".flr", "x-world/x-vrml" },
+            { ".flv", "video/x-flv" },
+            { ".gif", "image/gif" },
+            { ".gtar", "application/x-gtar" },
+            { ".gz", "application/x-gzip" },
+            { ".h", "text/plain" },
+            { ".hdf", "application/x-hdf" },
+            { ".hdml", "text/x-hdml" },
+            { ".hhc", "application/x-oleobject" },
+            { ".hhk", "application/octet-stream" },
+            { ".hhp", "application/octet-stream" },
+            { ".hlp", "application/winhlp" },
+            { ".hqx", "application/mac-binhex40" },
+            { ".hta", "application/hta" },
+            { ".htc", "text/x-component" },
+            { ".htm", "text/html" },
+            { ".html", "text/html" },
+            { ".htt", "text/webviewhtml" },
+            { ".hxt", "text/html" },
+            { ".ical", "text/calendar" },
+            { ".icalendar", "text/calendar" },
+            { ".ico", "image/x-icon" },
+            { ".ics", "text/calendar" },
+            { ".ief", "image/ief" },
+            { ".ifb", "text/calendar" },
+            { ".iii", "application/x-iphone" },
+            { ".inf", "application/octet-stream" },
+            { ".ins", "application/x-internet-signup" },
+            { ".isp", "application/x-internet-signup" },
+            { ".IVF", "video/x-ivf" },
+            { ".jar", "application/java-archive" },
+            { ".java", "application/octet-stream" },
+            { ".jck", "application/liquidmotion" },
+            { ".jcz", "application/liquidmotion" },
+            { ".jfif", "image/pjpeg" },
+            { ".jpb", "application/octet-stream" },
+            { ".jpe", "image/jpeg" },
+            { ".jpeg", "image/jpeg" },
+            { ".jpg", "image/jpeg" },
+            { ".js", "application/javascript" },
+            { ".bjs", "application/javascript" },
+            { ".javascript", "application/javascript" },
+            { ".latex", "application/x-latex" },
+            { ".lit", "application/x-ms-reader" },
+            { ".lpk", "application/octet-stream" },
+            { ".lsf", "video/x-la-asf" },
+            { ".lsx", "video/x-la-asf" },
+            { ".lzh", "application/octet-stream" },
+            { ".m13", "application/x-msmediaview" },
+            { ".m14", "application/x-msmediaview" },
+            { ".m1v", "video/mpeg" },
+            { ".m2ts", "video/vnd.dlna.mpeg-tts" },
+            { ".m3u", "audio/x-mpegurl" },
+            { ".m4a", "audio/mp4" },
+            { ".m4v", "video/mp4" },
+            { ".man", "application/x-troff-man" },
+            { ".manifest", "application/x-ms-manifest" },
+            { ".map", "text/plain" },
+            { ".mdb", "application/x-msaccess" },
+            { ".mdp", "application/octet-stream" },
+            { ".me", "application/x-troff-me" },
+            { ".mht", "message/rfc822" },
+            { ".mhtml", "message/rfc822" },
+            { ".mid", "audio/mid" },
+            { ".midi", "audio/mid" },
+            { ".mix", "application/octet-stream" },
+            { ".mmf", "application/x-smaf" },
+            { ".mno", "text/xml" },
+            { ".mny", "application/x-msmoney" },
+            { ".mov", "video/quicktime" },
+            { ".movie", "video/x-sgi-movie" },
+            { ".mp2", "video/mpeg" },
+            { ".mp3", "audio/mpeg" },
+            { ".mp4", "video/mp4" },
+            { ".mp4v", "video/mp4" },
+            { ".mpa", "video/mpeg" },
+            { ".mpe", "video/mpeg" },
+            { ".mpeg", "video/mpeg" },
+            { ".mpg", "video/mpeg" },
+            { ".mpp", "application/vnd.ms-project" },
+            { ".mpv2", "video/mpeg" },
+            { ".ms", "application/x-troff-ms" },
+            { ".msi", "application/octet-stream" },
+            { ".mso", "application/octet-stream" },
+            { ".mvb", "application/x-msmediaview" },
+            { ".mvc", "application/x-miva-compiled" },
+            { ".nc", "application/x-netcdf" },
+            { ".nsc", "video/x-ms-asf" },
+            { ".nws", "message/rfc822" },
+            { ".ocx", "application/octet-stream" },
+            { ".oda", "application/oda" },
+            { ".odc", "text/x-ms-odc" },
+            { ".ods", "application/oleobject" },
+            { ".oga", "audio/ogg" },
+            { ".ogg", "video/ogg" },
+            { ".ogv", "video/ogg" },
+            { ".ogx", "application/ogg" },
+            { ".one", "application/onenote" },
+            { ".onea", "application/onenote" },
+            { ".onetoc", "application/onenote" },
+            { ".onetoc2", "application/onenote" },
+            { ".onetmp", "application/onenote" },
+            { ".onepkg", "application/onenote" },
+            { ".osdx", "application/opensearchdescription+xml" },
+            { ".otf", "font/otf" },
+            { ".p10", "application/pkcs10" },
+            { ".p12", "application/x-pkcs12" },
+            { ".p7b", "application/x-pkcs7-certificates" },
+            { ".p7c", "application/pkcs7-mime" },
+            { ".p7m", "application/pkcs7-mime" },
+            { ".p7r", "application/x-pkcs7-certreqresp" },
+            { ".p7s", "application/pkcs7-signature" },
+            { ".pbm", "image/x-portable-bitmap" },
+            { ".pcx", "application/octet-stream" },
+            { ".pcz", "application/octet-stream" },
+            { ".pdf", "application/pdf" },
+            { ".pfb", "application/octet-stream" },
+            { ".pfm", "application/octet-stream" },
+            { ".pfx", "application/x-pkcs12" },
+            { ".pgm", "image/x-portable-graymap" },
+            { ".pko", "application/vnd.ms-pki.pko" },
+            { ".pma", "application/x-perfmon" },
+            { ".pmc", "application/x-perfmon" },
+            { ".pml", "application/x-perfmon" },
+            { ".pmr", "application/x-perfmon" },
+            { ".pmw", "application/x-perfmon" },
+            { ".png", "image/png" },
+            { ".pnm", "image/x-portable-anymap" },
+            { ".pnz", "image/png" },
+            { ".pot", "application/vnd.ms-powerpoint" },
+            { ".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12" },
+            { ".potx", "application/vnd.openxmlformats-officedocument.presentationml.template" },
+            { ".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12" },
+            { ".ppm", "image/x-portable-pixmap" },
+            { ".pps", "application/vnd.ms-powerpoint" },
+            { ".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" },
+            { ".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" },
+            { ".ppt", "application/vnd.ms-powerpoint" },
+            { ".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12" },
+            { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
+            { ".prf", "application/pics-rules" },
+            { ".prm", "application/octet-stream" },
+            { ".prx", "application/octet-stream" },
+            { ".ps", "application/postscript" },
+            { ".psd", "application/octet-stream" },
+            { ".psm", "application/octet-stream" },
+            { ".psp", "application/octet-stream" },
+            { ".pub", "application/x-mspublisher" },
+            { ".qt", "video/quicktime" },
+            { ".qtl", "application/x-quicktimeplayer" },
+            { ".qxd", "application/octet-stream" },
+            { ".ra", "audio/x-pn-realaudio" },
+            { ".ram", "audio/x-pn-realaudio" },
+            { ".rar", "application/octet-stream" },
+            { ".ras", "image/x-cmu-raster" },
+            { ".rf", "image/vnd.rn-realflash" },
+            { ".rgb", "image/x-rgb" },
+            { ".rm", "application/vnd.rn-realmedia" },
+            { ".rmi", "audio/mid" },
+            { ".roff", "application/x-troff" },
+            { ".rpm", "audio/x-pn-realaudio-plugin" },
+            { ".rtf", "application/rtf" },
+            { ".rtx", "text/richtext" },
+            { ".scd", "application/x-msschedule" },
+            { ".sct", "text/scriptlet" },
+            { ".sea", "application/octet-stream" },
+            { ".setpay", "application/set-payment-initiation" },
+            { ".setreg", "application/set-registration-initiation" },
+            { ".sgml", "text/sgml" },
+            { ".sh", "application/x-sh" },
+            { ".shar", "application/x-shar" },
+            { ".sit", "application/x-stuffit" },
+            { ".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12" },
+            { ".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" },
+            { ".smd", "audio/x-smd" },
+            { ".smi", "application/octet-stream" },
+            { ".smx", "audio/x-smd" },
+            { ".smz", "audio/x-smd" },
+            { ".snd", "audio/basic" },
+            { ".snp", "application/octet-stream" },
+            { ".spc", "application/x-pkcs7-certificates" },
+            { ".spl", "application/futuresplash" },
+            { ".spx", "audio/ogg" },
+            { ".src", "application/x-wais-source" },
+            { ".ssm", "application/streamingmedia" },
+            { ".sst", "application/vnd.ms-pki.certstore" },
+            { ".stl", "application/vnd.ms-pki.stl" },
+            { ".sv4cpio", "application/x-sv4cpio" },
+            { ".sv4crc", "application/x-sv4crc" },
+            { ".svg", "image/svg+xml" },
+            { ".svgz", "image/svg+xml" },
+            { ".swf", "application/x-shockwave-flash" },
+            { ".t", "application/x-troff" },
+            { ".tar", "application/x-tar" },
+            { ".tcl", "application/x-tcl" },
+            { ".tex", "application/x-tex" },
+            { ".texi", "application/x-texinfo" },
+            { ".texinfo", "application/x-texinfo" },
+            { ".tgz", "application/x-compressed" },
+            { ".thmx", "application/vnd.ms-officetheme" },
+            { ".thn", "application/octet-stream" },
+            { ".tif", "image/tiff" },
+            { ".tiff", "image/tiff" },
+            { ".toc", "application/octet-stream" },
+            { ".tr", "application/x-troff" },
+            { ".trm", "application/x-msterminal" },
+            { ".ts", "video/vnd.dlna.mpeg-tts" },
+            { ".tsv", "text/tab-separated-values" },
+            { ".ttf", "application/octet-stream" },
+            { ".tts", "video/vnd.dlna.mpeg-tts" },
+            { ".txt", "text/plain" },
+            { ".u32", "application/octet-stream" },
+            { ".uls", "text/iuls" },
+            { ".ustar", "application/x-ustar" },
+            { ".vbs", "text/vbscript" },
+            { ".vcf", "text/x-vcard" },
+            { ".vcs", "text/plain" },
+            { ".vdx", "application/vnd.ms-visio.viewer" },
+            { ".vml", "text/xml" },
+            { ".vsd", "application/vnd.visio" },
+            { ".vss", "application/vnd.visio" },
+            { ".vst", "application/vnd.visio" },
+            { ".vsto", "application/x-ms-vsto" },
+            { ".vsw", "application/vnd.visio" },
+            { ".vsx", "application/vnd.visio" },
+            { ".vtx", "application/vnd.visio" },
+            { ".wav", "audio/wav" },
+            { ".wax", "audio/x-ms-wax" },
+            { ".wbmp", "image/vnd.wap.wbmp" },
+            { ".wcm", "application/vnd.ms-works" },
+            { ".wdb", "application/vnd.ms-works" },
+            { ".webm", "video/webm" },
+            { ".wks", "application/vnd.ms-works" },
+            { ".wm", "video/x-ms-wm" },
+            { ".wma", "audio/x-ms-wma" },
+            { ".wmd", "application/x-ms-wmd" },
+            { ".wmf", "application/x-msmetafile" },
+            { ".wml", "text/vnd.wap.wml" },
+            { ".wmlc", "application/vnd.wap.wmlc" },
+            { ".wmls", "text/vnd.wap.wmlscript" },
+            { ".wmlsc", "application/vnd.wap.wmlscriptc" },
+            { ".wmp", "video/x-ms-wmp" },
+            { ".wmv", "video/x-ms-wmv" },
+            { ".wmx", "video/x-ms-wmx" },
+            { ".wmz", "application/x-ms-wmz" },
+            { ".woff", "application/font-woff" },
+            { ".wps", "application/vnd.ms-works" },
+            { ".wri", "application/x-mswrite" },
+            { ".wrl", "x-world/x-vrml" },
+            { ".wrz", "x-world/x-vrml" },
+            { ".wsdl", "text/xml" },
+            { ".wtv", "video/x-ms-wtv" },
+            { ".wvx", "video/x-ms-wvx" },
+            { ".x", "application/directx" },
+            { ".xaf", "x-world/x-vrml" },
+            { ".xaml", "application/xaml+xml" },
+            { ".xap", "application/x-silverlight-app" },
+            { ".xbap", "application/x-ms-xbap" },
+            { ".xbm", "image/x-xbitmap" },
+            { ".xdr", "text/plain" },
+            { ".xht", "application/xhtml+xml" },
+            { ".xhtml", "application/xhtml+xml" },
+            { ".xla", "application/vnd.ms-excel" },
+            { ".xlam", "application/vnd.ms-excel.addin.macroEnabled.12" },
+            { ".xlc", "application/vnd.ms-excel" },
+            { ".xlm", "application/vnd.ms-excel" },
+            { ".xls", "application/vnd.ms-excel" },
+            { ".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12" },
+            { ".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12" },
+            { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
+            { ".xlt", "application/vnd.ms-excel" },
+            { ".xltm", "application/vnd.ms-excel.template.macroEnabled.12" },
+            { ".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" },
+            { ".xlw", "application/vnd.ms-excel" },
+            { ".xml", "text/xml" },
+            { ".xof", "x-world/x-vrml" },
+            { ".xpm", "image/x-xpixmap" },
+            { ".xps", "application/vnd.ms-xpsdocument" },
+            { ".xsd", "text/xml" },
+            { ".xsf", "text/xml" },
+            { ".xsl", "text/xml" },
+            { ".xslt", "text/xml" },
+            { ".xsn", "application/octet-stream" },
+            { ".xtp", "application/octet-stream" },
+            { ".xwd", "image/x-xwindowdump" },
+            { ".z", "application/x-compress" },
+            { ".zip", "application/x-zip-compressed" }
+            };
+            #endregion
+        }
+    }
+}

+ 431 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Config/index.html

@@ -0,0 +1,431 @@
+<!doctype html>
+<html>
+<head>
+    <title>###TITLE###</title>
+    <style>
+        html, body {
+            width: 100%;
+            height: 100%;
+            padding: 0;
+            margin: 0;
+            overflow: hidden;
+            position: fixed;
+            font-family: "Segoe UI", "Segoe WP", "Verdana", "Arial";
+            background-color: #000000;
+        }
+
+        button {
+            cursor: hand;
+            border: 1px solid #888888;
+            background-color: #DEDEDE;
+            color: #888888;
+        }
+
+        button:focus {
+            outline: none;
+        }
+
+        button:hover {
+            background-color: #EEEEEE;
+        }
+
+        button:active {
+            transform: scale(0.98);
+            -webkit-transform: scale(0.98);
+        }
+
+        .warning {
+            color: red;
+        }
+
+        .hidden {
+            display: none;
+        }
+
+        .tag {
+            position: absolute;
+            height: 34px;
+            width: 160px;
+            left: 50%;
+            padding: 6px;
+            font-size: 14px;
+            text-align: center;
+            margin-left: -80px;
+            top: -34px;
+            border-top-left-radius: 6px 6px;
+            border-top-right-radius: 6px 6px;
+            background-color: #EEEEEE;
+            color: #888888;
+        }
+
+        #cvs {
+            width: 100%;
+            height: 100%;
+            opacity: 0;
+            z-index: 0;
+            outline: none;
+            touch-action: none;
+            -ms-touch-action: none;
+            background-color: #000000;
+        }
+
+        #gui {
+            width: 100%;
+            height: 100%;
+            z-index: 1;
+            outline: none;
+            background-color: transparent;
+        }
+
+        #sts {
+            position: absolute;
+            left: 20px;
+            bottom: 20px;
+            font-size: 14px;
+            z-index: 2;
+            color: white;
+            text-shadow: 2px 2px 0 black;
+        }
+
+        #fps {
+            position: absolute;
+            right: 20px;
+            top: 1em;
+            z-index: 2;
+            font-size: 18px;
+            color: white;
+            text-shadow: 2px 2px 0 black;
+        }
+
+        #project {
+            position: absolute;
+            left: 20px;
+            top: 1em;
+            z-index: 2;
+            font-size: 18px;
+            color: white;
+            text-shadow: 2px 2px 0 black;
+        }
+
+        #controlPanel {
+            position: absolute;
+            height: 100px;
+            bottom: 0px;
+            width: 220px;
+            left: 50%;
+            margin-left: -120px;
+            z-index: 2;
+            transition: transform 0.25s ease-in-out;
+            transform: translateY(100px);
+            -webkit-transition: -webkit-transform 0.25s ease-in-out;
+            -webkit-transform: translateY(100px);
+        }
+
+        #clickableTag {
+            cursor: hand;
+            background-color: transparent;
+        }
+
+        #controlsZone {
+            width: 100%;
+            height: 100%;
+            background-color: #EEEEEE;
+            color: #888888;
+            border-top-left-radius: 6px 6px;
+            border-top-right-radius: 6px 6px;
+            padding: 6px;
+        }
+
+        #togglePause {
+            width: 24px;
+        }
+
+        #frameStep {
+            width: 28px;
+        }
+
+        #enableDebug, #fullscreen {
+            width: 160px;
+            margin-left: 30px;
+        }
+    </style>
+</head>
+<body>
+    <canvas id="cvs"></canvas>
+    <div id="sts">Please wait...</div>
+    <div id="gui" class="hidden"></div>
+    <div id="fps" class="hidden"></div>
+    <div id="project" class="hidden"></div>
+    <div id="controlPanel" class="hidden">
+        <div id="controlsZone">
+            <p>
+                <button id="enableDebug">Debug Layer</button>
+            </p>
+            <p>
+                <button id="fullscreen">Full Screen</button>
+            </p>
+        </div>
+        <div class="tag" id="controlTab" >
+            <button id="togglePause">||</button>
+            <button id="clickableTag">Control Panel</button>
+            <button id="frameStep">>></button>
+        </div>
+    </div>
+	<script type="text/javascript" src="###SCRIPT###/hand.js"></script>
+	<script type="text/javascript" src="###SCRIPT###/oimo.js"></script>
+	<script type="text/javascript" src="###SCRIPT###/cannon.js"></script>
+	<script type="text/javascript" src="###SCRIPT###/babylon.js"></script>
+	<script type="text/javascript" src="###SCRIPT###/canvas2d.js"></script>
+	<script type="text/javascript" src="###SCRIPT###/navmesh.js"></script>
+	<script type="text/javascript" src="###SCRIPT###/manager.js"></script>
+	<script type="text/javascript" src="###PATH###/###PROJECT###.js"></script>
+    <script type="text/javascript">
+        var clickableTag = document.getElementById("clickableTag");
+        var controlsZone = document.getElementById("controlsZone");
+        var controlPanel = document.getElementById("controlPanel");
+        var togglePause = document.getElementById("togglePause");
+        var enableDebug = document.getElementById("enableDebug");
+        var fullscreen = document.getElementById("fullscreen");
+        var frameStep = document.getElementById("frameStep");
+        var project = document.getElementById("project");
+        var canvas = document.getElementById("cvs");
+        var divgui = document.getElementById("gui");
+        var divfps = document.getElementById("fps");
+        var divsts = document.getElementById("sts");
+        var folder = "###PATH###/";
+        var title = "###TITLE###";
+        var controls = ###DEBUG###;
+        var paused = false;
+        var loaded = false;
+        var scene = null;
+        var last = -1;
+
+        // Start project scene loader
+        var engine = new BABYLON.Engine(canvas, true);
+        engine.clear(new BABYLON.Color3(0.0,0.0,0.0), true, true);
+        var loadBabylonScene = function(root, name) {
+            last = -1;
+            scene = null;
+            loaded = false;
+            paused = false;
+            project.innerHTML = "";
+            divfps.innerHTML = "";
+            divgui.innerHTML = "";
+            divsts.innerHTML = "";
+            divsts.className = "";
+            project.className = "hidden";
+            divfps.className = "hidden";
+            divgui.className = "hidden";
+            controlPanel.className = "hidden";
+            canvas.style.opacity = "0";
+            engine.clear(new BABYLON.Color3(0.0,0.0,0.0), true, true);
+            BABYLON.SceneLoader.ShowLoadingScreen = false;
+            engine.loadingUIText = title;
+            engine.displayLoadingUI();
+            project.innerHTML = name;
+            togglePause.style.backgroundColor = "#DEDEDE";
+            divsts.innerHTML = "Streaming items...";
+            setTimeout(function(){ executeSceneLoader(root, name); }, 1000);   
+        };
+        var progressSceneLoader = function() {
+            if (engine && scene) {
+                if (!loaded) {
+                    var waiting = scene.getWaitingItemsCount();
+                    divsts.innerHTML = (waiting > 0) ? "Streaming items..." + waiting + " remaining" : "Loading scene...";
+                    setTimeout(progressSceneLoader, 100);
+                }
+            }
+        };
+        var executeSceneLoader = function(root, name) {
+            BABYLON.SceneManager.LoadScene(root, name, engine, function (newscene) {
+                scene = newscene;
+                progressSceneLoader();
+                scene.executeWhenReady(function () {
+                    loaded = true;
+                    startRenderLoop();
+                    engine.hideLoadingUI();
+                    BABYLON.SceneLoader.ShowLoadingScreen = true;
+                    canvas.style.opacity = "1";
+                    divsts.className = "hidden";
+                    project.className = "";
+                    divfps.className = "";
+                    divgui.className = "";
+                    controlPanel.className = "";
+                });
+            });
+        };
+
+        // Register scene loader (load-level)
+        BABYLON.SceneManager.RegisterLoader(loadBabylonScene);        
+        window.addEventListener("DOMContentLoaded", function () {
+            loadBabylonScene(folder, "###SCENE###");
+        });
+
+        // Developer page render loop function
+        var renderFunction = function () {
+            if (engine && scene) {
+                if (controls) {
+                    // Show
+                    if (project.className === "hidden") {
+                        project.className = "";
+                        console.log("Showing debug project label...");
+                    }
+                    if (divfps.className === "hidden") {
+                        divfps.className = "";
+                        console.log("Showing debug fps status...");
+                    }
+                    if (controlPanel.className === "hidden") {
+                        controlPanel.className = "";
+                        console.log("Showing debug control panel...");
+                    }
+                    var current = engine.getFps().toFixed();
+                    if (current != last) {
+                        divfps.innerHTML = ("" + current + " fps");
+                        last = current;
+                    }
+                } else {
+                    // Hide
+                    if (project.className !== "hidden") {
+                        project.className = "hidden";
+                        console.log("Hiding debug project label...");
+                    }
+                    if (divfps.className !== "hidden") {
+                        divfps.className = "hidden";
+                        console.log("Hiding debug fps status...");
+                    }
+                    if (controlPanel.className !== "hidden") {
+                        controlPanel.className = "hidden";
+                        console.log("Hiding debug control panel...");
+                    }
+                    if (divfps.innerHTML !== "") {
+                        divfps.innerHTML = "";
+                    }
+                }
+            }
+        };
+
+        // Start managed render loop
+        var startRenderLoop = function() {
+            if (scene.manager) {
+                scene.manager.onrender = renderFunction;
+                scene.manager.start();
+            } else {
+                console.log("Index.html: Null scene manager detected.");
+            }
+        };
+
+        // Stop managed render loop
+        var stopRenderLoop = function() {
+            if (scene.manager) {
+                scene.manager.stop();
+            } else {
+                console.log("Index.html: Null scene manager detected.");
+            }
+        };
+
+        // Toggle managed render loop
+        var toggleRenderLoop = function() {
+            if (scene.manager) {
+                scene.manager.toggle();
+                paused = !scene.manager.isRunning();
+                if (paused) {
+                    togglePause.style.backgroundColor = "#800000";
+                } else {
+                    togglePause.style.backgroundColor = "#DEDEDE";
+                }
+            } else {
+                console.log("Index.html: Null scene manager detected.");
+            }
+        };
+
+        // Step managed render loop
+        var stepRenderLoop = function() {
+            if (scene.manager) {
+                scene.manager.stepFrame();
+                var running = scene.manager.isRunning();
+                if (!running) {
+                    frameStep.style.backgroundColor = "#008000";
+                    setTimeout(function(){ frameStep.style.backgroundColor = "#DEDEDE"; }, 25);
+                }
+                if (!running) {
+                    togglePause.style.backgroundColor = "#800000";
+                } else {
+                    togglePause.style.backgroundColor = "#DEDEDE";
+                }
+                
+            } else {
+                console.log("Index.html: Null scene manager detected.");
+            }
+        };
+
+        // Show window fullscreen
+        var showFullscreen = function() {
+            if (scene.manager) {
+                scene.manager.showFullscreen();
+            } else {
+                console.log("Index.html: Null scene manager detected.");
+            }
+        };
+
+        // Toggle debug layer
+        var toggleDebugLayer = function() {
+            if (scene.manager) {
+                scene.manager.toggleDebug();
+            } else {
+                console.log("Index.html: Null scene manager detected.");
+            }
+        };
+
+        // Toggle scene pause
+        if (togglePause) {
+            togglePause.addEventListener("click", function () {
+                toggleRenderLoop();
+            });
+        };
+
+        // Frame step scene
+        if (frameStep) {
+            frameStep.addEventListener("click", function () {
+                stepRenderLoop();
+            });
+        };
+
+        // Toggle control panel
+        var panelIsClosed = true;
+        if (clickableTag) {
+            clickableTag.addEventListener("click", function () {
+                if (panelIsClosed) {
+                    panelIsClosed = false;
+                    controlPanel.style.webkitTransform = "translateY(0px)";
+                    controlPanel.style.transform = "translateY(0px)";
+                } else {
+                    panelIsClosed = true;
+                    controlPanel.style.webkitTransform = "translateY(100px)";
+                    controlPanel.style.transform = "translateY(100px)";
+                }
+            });
+        };
+
+        // Show debug layer
+        if (enableDebug) {
+            enableDebug.addEventListener("click", function () {
+                toggleDebugLayer();
+            });
+        };
+
+        // Switch full screen
+        if (fullscreen) {
+            fullscreen.addEventListener("click", function () {
+                showFullscreen();
+            });
+        };
+
+        // Resize window handler
+        if (engine) {
+            window.addEventListener("resize", function () {
+                engine.resize();
+            });
+        }
+    </script>
+</body>
+</html>

+ 13 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Config/options.json

@@ -0,0 +1,13 @@
+{
+    "compilerOptions": {
+        "target": "ES5",
+        "module": "system",
+        "allowJs" : false,
+        "declaration": true,
+        "outFile": "###OUTFILE###",
+        "sourceMap": false
+    },
+    "include": [
+        "assets/**/*"
+    ]    
+}

+ 23 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/camera.template

@@ -0,0 +1,23 @@
+/* Babylon Camera Component Template */
+/* <reference path="{*path*}/Assets/Babylon/Library/babylon.d.ts" /> */
+
+module PROJECT {
+    export class NewCameraComponent extends BABYLON.CameraComponent {
+
+        public start() :void {
+            // Start component function
+        }
+
+        public update() :void {
+            // Update render loop function
+        }
+
+        public after() :void {
+            // After render loop function
+        }
+
+        public destroy() :void {
+            // Destroy component function
+        }
+    }
+}

+ 28 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/controller.template

@@ -0,0 +1,28 @@
+/* Babylon Scene Controller Template */
+/* <reference path="{*path*}/Assets/Babylon/Library/babylon.d.ts" /> */
+
+module PROJECT {
+    export class NewSceneController extends BABYLON.SceneController {
+
+        public ready() :void {
+            // Scene execute when ready
+            this.scene.activeCamera.attachControl(this.engine.getRenderingCanvas());
+        }
+
+        public start() :void {
+            // Start component function
+        }
+
+        public update() :void {
+            // Update render loop function
+        }
+
+        public after() :void {
+            // After render loop function
+        }
+
+        public destroy() :void {
+            // Destroy component function
+        }
+    }
+}

+ 19 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/editora.template

@@ -0,0 +1,19 @@
+/* Babylon Editor Scene Controller (C# UnityScript) */
+using UnityEditor;
+using UnityEngine;
+
+namespace MyProject
+{
+	public class NewSceneController : BabylonSceneController
+	{
+        [Header("New Scene Controller")]
+
+        [BabylonProperty]
+        public string hello = "Hello World";
+
+		protected NewSceneController()
+		{
+			this.babylonClass = "PROJECT.BabylonSceneController";
+		}
+	}
+}

+ 19 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/editorb.template

@@ -0,0 +1,19 @@
+/* Babylon Editor Script Component (C# UnityScript) */
+using UnityEditor;
+using UnityEngine;
+
+namespace MyProject
+{
+	public class NewScriptComponent : BabylonScriptComponent
+	{
+        [Header("New Script Component")]
+
+        [BabylonProperty]
+        public string hello = "Hello World";
+
+		protected NewScriptComponent()
+		{
+			this.babylonClass = "PROJECT.BabylonSceneComponent";
+		}
+	}
+}

+ 20 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/javascript.template

@@ -0,0 +1,20 @@
+/* Babylon Javascript Class Template */
+/* <reference path="{*path*}/Assets/Babylon/Library/babylon.bjs" /> */
+
+var PROJECT;
+(function (PROJECT) {
+
+    var NewScriptClass = (function () {
+        function NewScriptClass() {
+            this.hello = "Hello World";
+        }
+
+        NewScriptClass.prototype.sayHello = function (name) {
+            return "Hello, " + name;
+        };
+
+        return NewScriptClass;
+    }());
+    PROJECT.NewScriptClass = NewScriptClass;
+
+})(PROJECT || (PROJECT = {}));

+ 23 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/light.template

@@ -0,0 +1,23 @@
+/* Babylon Light Component Template */
+/* <reference path="{*path*}/Assets/Babylon/Library/babylon.d.ts" /> */
+
+module PROJECT {
+    export class NewLightComponent extends BABYLON.LightComponent {
+
+        public start() :void {
+            // Start component function
+        }
+
+        public update() :void {
+            // Update render loop function
+        }
+
+        public after() :void {
+            // After render loop function
+        }
+
+        public destroy() :void {
+            // Destroy component function
+        }
+    }
+}

+ 23 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/mesh.template

@@ -0,0 +1,23 @@
+/* Babylon Mesh Component Template */
+/* <reference path="{*path*}/Assets/Babylon/Library/babylon.d.ts" /> */
+
+module PROJECT {
+    export class NewMeshComponent extends BABYLON.MeshComponent {
+
+        public start() :void {
+            // Start component function
+        }
+
+        public update() :void {
+            // Update render loop function
+        }
+
+        public after() :void {
+            // After render loop function
+        }
+
+        public destroy() :void {
+            // Destroy component function
+        }
+    }
+}

+ 16 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Scripts/typescript.template

@@ -0,0 +1,16 @@
+/* Babylon Typescript Class Template */
+/* <reference path="{*path*}/Assets/Babylon/Library/babylon.d.ts" /> */
+
+module PROJECT {
+    export class NewScriptClass {
+        public hello:string;
+
+        public constructor() {
+            this.hello = "Hello World";
+        }
+
+        public sayHello(name:String): string {
+            return "Hello, " + name;
+        }
+    }
+}

+ 92 - 0
Exporters/Unity 5/EditorToolkit/Assets/Babylon/Templates/Shaders/amiga.template

@@ -0,0 +1,92 @@
+Shader "BabylonJS/NewShaderProgram" {
+	Properties {
+		_Color ("Color", Color) = (1,1,1,1)
+		[NoScaleOffset] _MainTex ("Albedo (RGB)", 2D) = "white" {}
+		_Glossiness ("Smoothness", Range(0,1)) = 0.5
+		_Metallic ("Metallic", Range(0,1)) = 0.0
+		_ScaleX ("Scale Factor X", Range (0.0, 10.0)) = 1.0
+		_ScaleY ("Scale Factor Y", Range (0.0, 10.0)) = 1.0
+	}
+	SubShader {
+		Tags { "RenderType"="Opaque" }
+		LOD 200
+		CGPROGRAM
+
+		//////////////////////////////////////////////////////////
+		// BABYLON WEBGL RUNTIME SHADER PROGRAM SECTIONS (GLSL) //
+		//////////////////////////////////////////////////////////
+
+		#ifdef BABYLON
+		attributes: ["position", "normal", "uv"]
+		uniforms: ["worldViewProjection, _Color, _Glossiness, _Metallic, _ScaleX, _ScaleY"]
+		samplers: []
+		defines: []
+		#endif //BABYLON-END
+
+
+		#ifdef VERTEX
+		attribute vec3 position;
+		attribute vec3 normal;
+		attribute vec2 uv;
+		uniform mat4 worldViewProjection;
+		precision highp float;
+
+		varying vec2 vUV;
+		
+		void main(void)
+		{
+			gl_Position = worldViewProjection * vec4(position, 1.0);
+			vUV = uv;
+		}
+		#endif //VERTEX-END
+
+
+		#ifdef FRAGMENT
+		precision highp float;
+
+		varying vec2 vUV;
+		uniform vec4 _Color;
+		uniform float _Glossiness;
+		uniform float _Metallic;
+		uniform float _ScaleX;
+		uniform float _ScaleY;
+		uniform sampler2D _MainTex;
+
+		void main(void)
+		{
+			gl_FragColor = texture2D(_MainTex, vec2(vUV.x * _ScaleX, vUV.y * _ScaleY)) * _Color;
+		}
+		#endif //FRAGMENT-END 
+
+
+		////////////////////////////////////////////////////////
+		// DEFAULT UNITY EDITOR SHADER PROGRAM SECTION (HLSL) //
+		////////////////////////////////////////////////////////
+
+		#pragma exclude_renderers d3d11 xbox360 gles
+		#pragma surface surf Standard fullforwardshadows
+		#pragma target 3.0
+		sampler2D _MainTex;
+		struct Input {
+			float2 uv_MainTex;
+		};
+		half _Glossiness;
+		half _Metallic;
+		half _ScaleX;
+		half _ScaleY;
+		fixed4 _Color;
+		void surf (Input IN, inout SurfaceOutputStandard o) {
+			// Albedo comes from a texture tinted by color
+			float2 vUV = IN.uv_MainTex;
+			fixed4 c = tex2D (_MainTex, float2(vUV.x * _ScaleX, vUV.y * _ScaleY)) * _Color;
+			o.Albedo = c.rgb;
+			// Metallic and smoothness come from slider variables
+			o.Metallic = _Metallic;
+			o.Smoothness = _Glossiness;
+			o.Alpha = c.a;
+		}
+
+		ENDCG
+	}
+	FallBack "Diffuse"
+}

BIN=BIN
Exporters/Unity 5/EditorToolkit/Redist/Asset Store-5.x/BabylonJS/BabylonJS Editor Toolkit.unitypackage


+ 21 - 0
Exporters/Unity 5/EditorToolkit/Redist/readme.me

@@ -0,0 +1,21 @@
+==========================================
+BabylonJS - Toolkit Binary Package
+==========================================
+
+Place the 'BabylonJS' folder containing the .unitypackage in your Unity Asset Store folder:
+
+- Mac: ~/Library/Unity/Asset Store-5x/
+
+- Windows: %AppData%\Roaming\Unity\Asset Store-5.x\
+
+- Example: ---> Asset Store-5.x
+             ---> BabylonJS
+                 ---> BabylonJS Editor Toolkit.unitypackage
+
+
+==========================================
+BabylonJS - Creating New Projects
+==========================================
+
+When creating a new unity project, select 'Add Asset Package' and enable 'BabylonJS Toolkit' support.
+

+ 1 - 1
Playground/debug.html

@@ -117,7 +117,7 @@
                 <li><a href="http://www.html5gamedevs.com/forum/16-babylonjs/">Forum</a></li>
                 <li><a href="https://babylonjs.azurewebsites.net/sandbox">Sandbox</a></li>
                 <li><a href="https://github.com/BabylonJS/Babylon.js/wiki">Wiki</a></li>
-                <li><a href="http://www.sokrate.fr/documentation/babylonjs/index.html">Documentation</a></li>
+                <li><a href="https://doc.babylonjs.com">Documentation</a></li>
             </ul>
         </div>
     </div>

+ 1 - 1
Playground/index-local.html

@@ -85,7 +85,7 @@
                 <li><a href="http://www.html5gamedevs.com/forum/16-babylonjs/">Forum</a></li>
                 <li><a href="http://www.babylonjs.com/sandbox">Sandbox</a></li>
                 <li><a href="https://github.com/BabylonJS/Babylon.js/wiki">Wiki</a></li>
-                <li><a href="http://www.sokrate.fr/documentation/babylonjs/index.html">Documentation</a></li>
+                <li><a href="https://doc.babylonjs.com">Documentation</a></li>
             </ul>
         </div>
     </div>

+ 2 - 1
Playground/index.html

@@ -20,6 +20,7 @@
     <!--<script src="../babylon.js"></script>-->
     <script src="https://babylonjs.azurewebsites.net/babylon.js"></script>
     <script src="https://babylonjs.azurewebsites.net/babylon.canvas2d.js"></script>
+    <script src="https://babylonjs.azurewebsites.net/babylon.inspector.bundle.js"></script>
     
     <script src="https://babylonjs.azurewebsites.net/lib/babylon.fireMaterial.min.js"></script>
     <script src="https://babylonjs.azurewebsites.net/lib/babylon.waterMaterial.min.js"></script>
@@ -116,7 +117,7 @@
                 <li><a href="http://www.html5gamedevs.com/forum/16-babylonjs/">Forum</a></li>
                 <li><a href="https://babylonjs.azurewebsites.net/sandbox">Sandbox</a></li>
                 <li><a href="https://github.com/BabylonJS/Babylon.js/wiki">Wiki</a></li>
-                <li><a href="http://www.sokrate.fr/documentation/babylonjs/index.html">Documentation</a></li>
+                <li><a href="https://doc.babylonjs.com">Documentation</a></li>
             </ul>
         </div>
     </div>

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 13 - 13
dist/preview release/babylon.core.js


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 3219 - 3219
dist/preview release/babylon.d.ts


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 16 - 16
dist/preview release/babylon.js


+ 22 - 27
dist/preview release/babylon.max.js

@@ -6535,7 +6535,7 @@ var BABYLON;
          * @param options - further options to be sent to the getContext function
          */
         function Engine(canvas, antialias, options, adaptToDeviceRatio) {
-            if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
+            if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
             var _this = this;
             // Public members
             this.isFullscreen = false;
@@ -6609,14 +6609,14 @@ var BABYLON;
             var renderToFullFloat = this._canRenderToFloatTexture();
             var renderToHalfFloat = this._canRenderToHalfFloatTexture();
             // GL
-            //try {
-            //    this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
-            //    if (this._gl) {
-            //        this._webGLVersion = "2.0";
-            //    }
-            //} catch (e) {
-            //    // Do nothing
-            //}
+            try {
+                this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
+                if (this._gl) {
+                    this._webGLVersion = "2.0";
+                }
+            }
+            catch (e) {
+            }
             if (!this._gl) {
                 if (!canvas) {
                     throw new Error("The provided canvas is null or undefined.");
@@ -24349,6 +24349,17 @@ var BABYLON;
             if (this.renderList && this.renderList.length === 0) {
                 return;
             }
+            // Set custom projection.
+            // Needs to be before binding to prevent changing the aspect ratio.
+            if (this.activeCamera) {
+                engine.setViewport(this.activeCamera.viewport);
+                if (this.activeCamera !== scene.activeCamera) {
+                    scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
+                }
+            }
+            else {
+                engine.setViewport(scene.activeCamera.viewport);
+            }
             // Prepare renderingManager
             this._renderingManager.reset();
             var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
@@ -24402,21 +24413,6 @@ var BABYLON;
                     engine.bindFramebuffer(this._texture);
                 }
             }
-            // Set states for projection (this does not change accross faces)
-            if (!this.isCube || faceIndex === 0) {
-                if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                    scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
-                }
-                else {
-                    scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
-                }
-                if (this.activeCamera) {
-                    engine.setViewport(this.activeCamera.viewport);
-                }
-                else {
-                    engine.setViewport(scene.activeCamera.viewport);
-                }
-            }
             this.onBeforeRenderObservable.notifyObservers(faceIndex);
             // Clear
             if (this.onClearObservable.hasObservers()) {
@@ -54183,7 +54179,7 @@ var BABYLON;
             }
         };
         PBRMaterial.prototype.isReady = function (mesh, useInstances) {
-            if (this.checkReadyOnlyOnce) {
+            if (this.isFrozen) {
                 if (this._wasPreviouslyReady) {
                     return true;
                 }
@@ -54746,8 +54742,7 @@ var BABYLON;
                 this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
                 this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
                 this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
-                this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
-                this._effect.setColor3("vOverloadedAmbient", this._tempColor);
+                this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
                 this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
                 this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
                 this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 16 - 16
dist/preview release/babylon.noworker.js


+ 1 - 0
dist/preview release/what's new.md

@@ -1,6 +1,7 @@
 # 2.6.0:
 
 ### Major updates
+ - New Unity 5 Editor Toolkit. Complete pipeline integration [Doc](TODO) - ([MackeyK24](https://github.com/MackeyK24))
  - New DebugLayer. [Doc](TODO) - ([temechon](https://github.com/temechon))
  - New `VideoTexture.CreateFromWebCam` to generate video texture using WebRTC. [Demo](https://www.babylonjs-playground.com#1R77YT#2) - (Sebastien Vandenberghe)(https://github.com/sebavanmicrosoft) / ([deltakosh](https://github.com/deltakosh))
 

+ 2 - 1
src/Cameras/babylon.camera.ts

@@ -527,7 +527,8 @@
             }
 
             // Postprocesses
-            for (var i = 0; i < this._postProcesses.length; ++i) {
+            var i = this._postProcesses.length;
+            while (--i >= 0) {
                 this._postProcesses[i].dispose(this);
             }
 

+ 14 - 16
src/Materials/Textures/babylon.renderTargetTexture.ts

@@ -241,6 +241,20 @@
                 return;
             }
 
+            // Set custom projection.
+            // Needs to be before binding to prevent changing the aspect ratio.
+            if (this.activeCamera) {
+                engine.setViewport(this.activeCamera.viewport);
+
+                if (this.activeCamera !== scene.activeCamera)
+                {
+                    scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
+                }
+            }
+            else {
+                engine.setViewport(scene.activeCamera.viewport);
+            }
+
             // Prepare renderingManager
             this._renderingManager.reset();
 
@@ -304,22 +318,6 @@
                 }
             }
 
-            // Set states for projection (this does not change accross faces)
-            if (!this.isCube || faceIndex === 0) {            
-                if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
-                    scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
-                } else {
-                    scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));               
-                }
-
-                if (this.activeCamera) {
-                    engine.setViewport(this.activeCamera.viewport);
-                }
-                else {
-                    engine.setViewport(scene.activeCamera.viewport);
-                }
-            }
-
             this.onBeforeRenderObservable.notifyObservers(faceIndex);
 
             // Clear

+ 35 - 10
src/Materials/babylon.pbrMaterial.ts

@@ -64,8 +64,9 @@
         public INVERTNORMALMAPX = false;
         public INVERTNORMALMAPY = false;
         public SHADOWFULLFLOAT = false;
-        
+
         public METALLICWORKFLOW = false;
+        public METALLICROUGHNESSMAP = false;
         public METALLICROUGHNESSGSTOREINALPHA = false;
         public METALLICROUGHNESSGSTOREINGREEN = false;
 
@@ -292,6 +293,20 @@
         @serializeAsTexture()
         public metallicTexture: BaseTexture;
 
+        /**
+         * Specifies the metallic scalar of the metallic/roughness workflow.
+         * Can also be used to scale the metalness values of the metallic texture.
+         */
+        @serialize()
+        public metallic: number;
+
+        /**
+         * Specifies the roughness scalar of the metallic/roughness workflow.
+         * Can also be used to scale the roughness values of the metallic texture.
+         */
+        @serialize()
+        public roughness: number;
+
         @serializeAsTexture()
         public bumpTexture: BaseTexture;
 
@@ -620,8 +635,7 @@
         }
 
         public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
-
-            if (this.checkReadyOnlyOnce) {
+            if (this.isFrozen) {
                 if (this._wasPreviouslyReady) {
                     return true;
                 }
@@ -750,13 +764,14 @@
                     }
                 }
 
-                if (StandardMaterial.SpecularTextureEnabled) {                        
+                if (StandardMaterial.SpecularTextureEnabled) {
                     if (this.metallicTexture) {
                         if (!this.metallicTexture.isReady()) {
                             return false;
                         } else {
                             needUVs = true;
                             this._defines.METALLICWORKFLOW = true;
+                            this._defines.METALLICROUGHNESSMAP = true;
                             this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
                             this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
                         }
@@ -918,6 +933,10 @@
                 this._defines.RADIANCEOVERALPHA = true;
             }
 
+            if (this.metallic !== undefined || this.roughness !== undefined) {
+                this._defines.METALLICWORKFLOW = true;
+            }
+
             // Attribs
             if (mesh) {
                 if (needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
@@ -1269,13 +1288,20 @@
 
                 // Colors
                 this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
-                
-                // GAMMA CORRECTION.
-                this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
+
+                if (this._defines.METALLICWORKFLOW) {
+                    PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
+                    PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
+                    this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
+                }
+                else {
+                    // GAMMA CORRECTION.
+                    this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
+                    this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
+                }
 
                 this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
                 this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
-                this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
 
                 // GAMMA CORRECTION.
                 this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
@@ -1329,8 +1355,7 @@
                 this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
                 this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
 
-                this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
-                this._effect.setColor3("vOverloadedAmbient", this._tempColor);
+                this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
                 this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
                 this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
                 this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);

+ 19 - 14
src/Shaders/pbr.fragment.fx

@@ -269,35 +269,40 @@ void main(void) {
 #endif
 
 #ifdef METALLICWORKFLOW
-	vec4 surfaceMetallicColorMap = texture2D(reflectivitySampler, vReflectivityUV + uvOffset);
-
-	// No gamma space fro the metallic map in metallic workflow.
-	float metallic = surfaceMetallicColorMap.r; // Unity like base channel for metallness.
+	vec2 metallicRoughness = surfaceReflectivityColor.rg;
+
+	#ifdef METALLICROUGHNESSMAP
+		vec4 surfaceMetallicColorMap = texture2D(reflectivitySampler, vReflectivityUV + uvOffset);
+
+		// No gamma space from the metallic map in metallic workflow.
+		metallicRoughness.r *= surfaceMetallicColorMap.r;
+		#ifdef METALLICROUGHNESSGSTOREINALPHA
+			metallicRoughness.g *= surfaceMetallicColorMap.a;
+		#else
+			#ifdef METALLICROUGHNESSGSTOREINGREEN
+				metallicRoughness.g *= surfaceMetallicColorMap.g;
+			#endif
+		#endif
+	#endif
 
 	// Diffuse is used as the base of the reflectivity.
 	vec3 baseColor = surfaceAlbedo.rgb;
 
 	// Drop the surface diffuse by the 1.0 - metalness.
-	surfaceAlbedo.rgb *= (1.0 - metallic);
+	surfaceAlbedo.rgb *= (1.0 - metallicRoughness.r);
 	
 	// Default specular reflectance at normal incidence.
-	// 4% corresponds to index of refraction (IOR) of 1.50, approximately equal to glass.    
+	// 4% corresponds to index of refraction (IOR) of 1.50, approximately equal to glass.
 	const vec3 DefaultSpecularReflectanceDielectric = vec3(0.04, 0.04, 0.04);
 
 	// Compute the converted reflectivity.
-	surfaceReflectivityColor = mix(DefaultSpecularReflectanceDielectric, baseColor, metallic);
+	surfaceReflectivityColor = mix(DefaultSpecularReflectanceDielectric, baseColor, metallicRoughness.r);
 
 	#ifdef OVERLOADEDVALUES
 		surfaceReflectivityColor = mix(surfaceReflectivityColor, vOverloadedReflectivity, vOverloadedIntensity.z);
 	#endif
 
-	#ifdef METALLICROUGHNESSGSTOREINALPHA
-		microSurface = 1.0 - surfaceMetallicColorMap.a;
-	#else
-		#ifdef METALLICROUGHNESSGSTOREINGREEN
-			microSurface = 1.0 - surfaceMetallicColorMap.g;
-		#endif
-	#endif
+	microSurface = 1.0 - metallicRoughness.g;
 #endif
 
 #ifdef OVERLOADEDVALUES

+ 9 - 9
src/babylon.engine.ts

@@ -504,7 +504,7 @@
          * @param {boolean} [antialias] - enable antialias
          * @param options - further options to be sent to the getContext function
          */
-        constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = true) {
+        constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
             this._renderingCanvas = canvas;
 
             this._externalData = new StringDictionary<Object>();
@@ -524,14 +524,14 @@
             var renderToHalfFloat = this._canRenderToHalfFloatTexture();
 
             // GL
-            //try {
-            //    this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
-            //    if (this._gl) {
-            //        this._webGLVersion = "2.0";
-            //    }
-            //} catch (e) {
-            //    // Do nothing
-            //}
+            try {
+               this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
+               if (this._gl) {
+                   this._webGLVersion = "2.0";
+               }
+            } catch (e) {
+               // Do nothing
+            }
 
             if (!this._gl) {
                 if (!canvas) {