Browse Source

Merge remote-tracking branch 'upstream/master'

Conflicts:
	Script/TypeScript/ToolCore.d.ts
Matt Benic 10 years ago
parent
commit
7d0f45d850
100 changed files with 5597 additions and 3738 deletions
  1. 6 0
      CMake/Modules/AtomicMac.cmake
  2. 1 0
      Data/AtomicEditor/ProjectTemplates/.gitignore
  3. 3 11
      Data/AtomicEditor/ProjectTemplates/EmptyProject/Resources/Scripts/main.js
  4. 9 10
      Data/AtomicEditor/ProjectTemplates/Project2D/Resources/Components/Star.js
  5. 45 0
      Data/AtomicEditor/ProjectTemplates/Project2D/Resources/Scenes/Scene.scene
  6. 1 23
      Data/AtomicEditor/ProjectTemplates/Project2D/Resources/Scripts/main.js
  7. 16 0
      Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Components/Spinner.js
  8. BIN
      Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Models/Chest.fbx
  9. 9 0
      Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Models/Chest.fbx.asset
  10. 15 0
      Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Models/Materials/DefaultMaterial.material
  11. 18 5
      Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Scenes/Scene.scene
  12. BIN
      Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Textures/Chest.png
  13. 8 1
      Resources/EditorData/AtomicEditor/Script/jsutils.js
  14. 1 0
      Resources/EditorData/AtomicEditor/Script/source-map.js
  15. 5 0
      Resources/EditorData/AtomicEditor/editor/skin/skin.tb.txt
  16. 1 1
      Script/AtomicEditor/.gitignore
  17. 0 21
      Script/AtomicEditor/assets/AssetImport.ts
  18. 3 7
      Script/AtomicEditor/editor/Editor.ts
  19. 3 1
      Script/AtomicEditor/tsconfig.json
  20. 2 2
      Script/AtomicEditor/ui/EditorUI.ts
  21. 47 5
      Script/AtomicEditor/ui/frames/HierarchyFrame.ts
  22. 5 5
      Script/AtomicEditor/ui/frames/MainFrame.ts
  23. 23 13
      Script/AtomicEditor/ui/frames/ProjectFrame.ts
  24. 3 3
      Script/AtomicEditor/ui/frames/ResourceFrame.ts
  25. 4 4
      Script/AtomicEditor/ui/frames/WelcomeFrame.ts
  26. 0 0
      Script/AtomicEditor/ui/frames/inspector/ArrayEditWidget.ts
  27. 60 129
      Script/AtomicEditor/ui/frames/inspector/ComponentInspector.ts
  28. 13 1
      Script/AtomicEditor/ui/frames/inspector/CreateComponentButton.ts
  29. 155 3
      Script/AtomicEditor/ui/frames/inspector/DataBinding.ts
  30. 2 2
      Script/AtomicEditor/ui/frames/inspector/InspectorFrame.ts
  31. 4 2
      Script/AtomicEditor/ui/frames/inspector/InspectorUtils.ts
  32. 1 1
      Script/AtomicEditor/ui/frames/inspector/InspectorWidget.ts
  33. 7 4
      Script/AtomicEditor/ui/frames/inspector/MaterialInspector.ts
  34. 0 0
      Script/AtomicEditor/ui/frames/inspector/ModelInspector.ts
  35. 10 5
      Script/AtomicEditor/ui/frames/inspector/NodeInspector.ts
  36. 0 0
      Script/AtomicEditor/ui/frames/inspector/TextureSelector.ts
  37. 4 4
      Script/AtomicEditor/ui/frames/menus/HierarchyFrameMenu.ts
  38. 4 4
      Script/AtomicEditor/ui/frames/menus/MainFrameMenu.ts
  39. 3 3
      Script/AtomicEditor/ui/frames/menus/MenuItemSources.ts
  40. 4 4
      Script/AtomicEditor/ui/frames/menus/ProjectFrameMenu.ts
  41. 4 4
      Script/AtomicEditor/ui/modal/ModalOps.ts
  42. 2 2
      Script/AtomicEditor/ui/modal/UIResourceOps.ts
  43. 3 3
      Script/AtomicEditor/ui/modal/license/ActivationSuccessWindow.ts
  44. 4 4
      Script/AtomicEditor/ui/modal/license/ActivationWindow.ts
  45. 3 3
      Script/AtomicEditor/ui/modal/license/EULAWindow.ts
  46. 4 4
      Script/AtomicEditor/ui/modal/license/ManageLicense.ts
  47. 1 1
      Script/Packages/Atomic/Atomic2D.json
  48. 7 0
      Script/Packages/Atomic/Atomic3D.json
  49. 3 1
      Script/Packages/Atomic/Scene.json
  50. 13 8
      Script/TypeScript/Atomic.d.ts
  51. 3 0
      Script/TypeScript/AtomicPlayer.d.ts
  52. 17 0
      Script/TypeScript/AtomicWork.d.ts
  53. 45 33
      Script/TypeScript/ToolCore.d.ts
  54. 1 1
      Source/Atomic/Atomic2D/CollisionShape2D.cpp
  55. 1 1
      Source/Atomic/Atomic2D/Constraint2D.cpp
  56. 185 92
      Source/Atomic/Atomic2D/Light2D.cpp
  57. 18 9
      Source/Atomic/Atomic2D/Light2D.h
  58. 2 1
      Source/Atomic/Atomic2D/RigidBody2D.cpp
  59. 1 3
      Source/Atomic/IO/File.cpp
  60. 76 27
      Source/Atomic/Scene/PrefabComponent.cpp
  61. 0 4
      Source/Atomic/Scene/PrefabComponent.h
  62. 34 1
      Source/Atomic/UI/UIListView.cpp
  63. 2 1
      Source/Atomic/UI/UIListView.h
  64. 7 7
      Source/AtomicEditor/Application/AEEditorApp.cpp
  65. 35 10
      Source/AtomicEditor/Editors/SceneEditor3D/SceneView3D.cpp
  66. 23 0
      Source/AtomicJS/Javascript/JSAPI.cpp
  67. 6 0
      Source/AtomicJS/Javascript/JSAtomic.cpp
  68. 38 0
      Source/AtomicJS/Javascript/JSAtomic3D.cpp
  69. 16 0
      Source/AtomicJS/Javascript/JSAtomic3D.h
  70. 4 1
      Source/AtomicJS/Javascript/JSComponent.cpp
  71. 48 17
      Source/AtomicJS/Javascript/JSComponentFile.cpp
  72. 1 0
      Source/AtomicJS/Javascript/JSComponentFile.h
  73. 1 0
      Source/AtomicJS/Javascript/JSRequire.cpp
  74. 49 5
      Source/AtomicJS/Javascript/JSScene.cpp
  75. 69 0
      Source/AtomicJS/Javascript/JSSceneSerializable.cpp
  76. 46 0
      Source/AtomicJS/Javascript/JSVM.cpp
  77. 9 2
      Source/AtomicJS/Javascript/JSVM.h
  78. 15 2
      Source/AtomicPlayer/Player.cpp
  79. 7 0
      Source/AtomicPlayer/Player.h
  80. 2 2
      Source/AtomicTool/AtomicTool.cpp
  81. 3191 0
      Source/ThirdParty/Duktape/duk_config.h
  82. 674 138
      Source/ThirdParty/Duktape/duktape.c
  83. 101 3069
      Source/ThirdParty/Duktape/duktape.h
  84. 25 1
      Source/ToolCore/Assets/Asset.cpp
  85. 4 0
      Source/ToolCore/Assets/Asset.h
  86. 22 0
      Source/ToolCore/Assets/AssetDatabase.cpp
  87. 4 0
      Source/ToolCore/Assets/AssetDatabase.h
  88. 2 0
      Source/ToolCore/Assets/AssetImporter.h
  89. 17 0
      Source/ToolCore/Assets/JavascriptImporter.cpp
  90. 2 0
      Source/ToolCore/Assets/JavascriptImporter.h
  91. 11 0
      Source/ToolCore/Assets/ModelImporter.cpp
  92. 2 0
      Source/ToolCore/Assets/ModelImporter.h
  93. 70 1
      Source/ToolCore/Assets/PrefabImporter.cpp
  94. 53 0
      Source/ToolCore/Assets/SpriterImporter.cpp
  95. 29 0
      Source/ToolCore/Assets/SpriterImporter.h
  96. 53 0
      Source/ToolCore/Assets/TMXImporter.cpp
  97. 29 0
      Source/ToolCore/Assets/TMXImporter.h
  98. 5 5
      Source/ToolCore/Command/ImportCmd.cpp
  99. 1 1
      Source/ToolCore/Command/ImportCmd.h
  100. 2 0
      Source/ToolCore/Import/JSONSceneImporter.cpp

+ 6 - 0
CMake/Modules/AtomicMac.cmake

@@ -6,6 +6,12 @@ set (JAVASCRIPT_BINDINGS_PLATFORM "MACOSX")
 
 
 add_definitions(-DATOMIC_PLATFORM_OSX -DATOMIC_OPENGL -DKNET_UNIX)
 add_definitions(-DATOMIC_PLATFORM_OSX -DATOMIC_OPENGL -DKNET_UNIX)
 
 
+if (CMAKE_GENERATOR STREQUAL "Xcode")
+
+add_definitions(-DATOMIC_XCODE)
+
+endif()
+
 list (APPEND ATOMIC_LINK_LIBRARIES GLEW)
 list (APPEND ATOMIC_LINK_LIBRARIES GLEW)
 
 
 set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-offsetof -std=gnu++0x")
 set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-offsetof -std=gnu++0x")

+ 1 - 0
Data/AtomicEditor/ProjectTemplates/.gitignore

@@ -0,0 +1 @@
+*/Cache/*

+ 3 - 11
Data/AtomicEditor/ProjectTemplates/EmptyProject/Resources/Scripts/main.js

@@ -1,17 +1,9 @@
 
 
 // This script is the main entry point of the game
 // This script is the main entry point of the game
-require("AtomicGame");
 
 
-Atomic.game.init(start, update);
-
-// called at the start of play
-function start() {
-
-	var game = Atomic.game;
-}
-
-// called per frame
+// called per frame, optional
 function update(timeStep) {
 function update(timeStep) {
 
 
-
 }
 }
+
+exports.update = update;

+ 9 - 10
Data/AtomicEditor/ProjectTemplates/Project2D/Resources/Components/Star.js

@@ -1,16 +1,15 @@
-var game = Atomic.game;
-var node = self.node;
+"atomic component";
 
 
-function start() {
-
-	var sprite2D = node.createComponent("StaticSprite2D");
-	sprite2D.sprite = game.getSprite2D("Sprites/star.png");
-	sprite2D.blendMode = Atomic.BLEND_ALPHA;
-	
+var inspectorFields = {
+  speed: 1.0
 }
 }
 
 
-function update(timeStep) {	
+module.exports = function(self) {
+
+  self.update = function(timeStep) {
+
+    self.node.rotate2D(timeStep * 75 * self.speed);
 
 
-	node.roll(timeStep * 100);
+  }
 
 
 }
 }

+ 45 - 0
Data/AtomicEditor/ProjectTemplates/Project2D/Resources/Scenes/Scene.scene

@@ -0,0 +1,45 @@
+<?xml version="1.0"?>
+<scene id="1">
+	<attribute name="Name" value="" />
+	<attribute name="Time Scale" value="1" />
+	<attribute name="Smoothing Constant" value="50" />
+	<attribute name="Snap Threshold" value="5" />
+	<attribute name="Elapsed Time" value="0" />
+	<attribute name="Next Replicated Node ID" value="364" />
+	<attribute name="Next Replicated Component ID" value="1978" />
+	<attribute name="Next Local Node ID" value="16778496" />
+	<attribute name="Next Local Component ID" value="16777216" />
+	<attribute name="Variables" />
+	<attribute name="Variable Names" value="" />
+	<component type="PhysicsWorld" id="1" />
+	<component type="Octree" id="2" />
+	<component type="DebugRenderer" id="3" />
+	<component type="Renderer2D" id="1976" />
+	<node id="361">
+		<attribute name="Is Enabled" value="true" />
+		<attribute name="Name" value="Camera" />
+		<attribute name="Position" value="0 0 -5" />
+		<attribute name="Rotation" value="1 0 0 0" />
+		<attribute name="Scale" value="1 1 1" />
+		<attribute name="Variables" />
+		<component type="Camera" id="1973">
+			<attribute name="Near Clip" value="0" />
+			<attribute name="Orthographic" value="true" />
+			<attribute name="Orthographic Size" value="8" />
+		</component>
+	</node>
+	<node id="363">
+		<attribute name="Is Enabled" value="true" />
+		<attribute name="Name" value="Node" />
+		<attribute name="Position" value="0 0 0" />
+		<attribute name="Rotation" value="1 0 0 0" />
+		<attribute name="Scale" value="1 1 1" />
+		<attribute name="Variables" />
+		<component type="StaticSprite2D" id="1975">
+			<attribute name="Sprite" value="Sprite2D;Sprites/star.png" />
+		</component>
+		<component type="JSComponent" id="1977">
+			<attribute name="ComponentFile" value="JSComponentFile;Components/Star.js" />
+		</component>
+	</node>
+</scene>

+ 1 - 23
Data/AtomicEditor/ProjectTemplates/Project2D/Resources/Scripts/main.js

@@ -1,25 +1,3 @@
-
 // This script is the main entry point of the game
 // This script is the main entry point of the game
-require("AtomicGame");
-
-Atomic.game.init(start, update);
-
-
-// called at the start of play
-function start() {
-
-	var game = Atomic.game;
-
-	// create a 2D scene
-	game.createScene2D();
-
-    var spaceNode = game.scene.createChild("Star");
-    spaceNode.createJSComponent("Star");
-
-}
-
-// called per frame
-function update(timeStep) {
-
 
 
-}
+Atomic.player.loadScene("Scenes/Scene.scene");

+ 16 - 0
Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Components/Spinner.js

@@ -0,0 +1,16 @@
+
+"atomic component";
+
+var inspectorFields = {
+  speed: 1.0
+}
+
+module.exports = function(self) {
+
+  self.update = function(timeStep) {
+
+    self.node.yaw(timeStep * 75 * self.speed);
+
+  }
+
+}

BIN
Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Models/Chest.fbx


+ 9 - 0
Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Models/Chest.fbx.asset

@@ -0,0 +1,9 @@
+{
+	"version": 1,
+	"guid": "2788364e8ff6f81f4b566a9d58e3fb5b",
+	"ModelImporter": {
+		"scale": 0.01,
+		"importAnimations": false,
+		"animInfo": []
+	}
+}

+ 15 - 0
Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Models/Materials/DefaultMaterial.material

@@ -0,0 +1,15 @@
+<?xml version="1.0"?>
+<material>
+	<technique name="Techniques/Diff.xml" quality="0" loddistance="0" />
+	<texture unit="diffuse" name="Textures/Chest.png" />
+	<parameter name="UOffset" value="1 0 0 0" />
+	<parameter name="VOffset" value="0 1 0 0" />
+	<parameter name="MatDiffColor" value="0.8 0.8 0.8 1" />
+	<parameter name="MatEmissiveColor" value="0 0 0 1" />
+	<parameter name="MatEnvMapColor" value="1 1 1" />
+	<parameter name="MatSpecColor" value="0.5 0.5 0.5 16" />
+	<cull value="ccw" />
+	<shadowcull value="ccw" />
+	<fill value="solid" />
+	<depthbias constant="0" slopescaled="0" />
+</material>

+ 18 - 5
Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Scenes/Scene.scene

@@ -5,8 +5,8 @@
 	<attribute name="Smoothing Constant" value="50" />
 	<attribute name="Smoothing Constant" value="50" />
 	<attribute name="Snap Threshold" value="5" />
 	<attribute name="Snap Threshold" value="5" />
 	<attribute name="Elapsed Time" value="0" />
 	<attribute name="Elapsed Time" value="0" />
-	<attribute name="Next Replicated Node ID" value="362" />
-	<attribute name="Next Replicated Component ID" value="1974" />
+	<attribute name="Next Replicated Node ID" value="364" />
+	<attribute name="Next Replicated Component ID" value="1977" />
 	<attribute name="Next Local Node ID" value="16778496" />
 	<attribute name="Next Local Node ID" value="16778496" />
 	<attribute name="Next Local Component ID" value="16777216" />
 	<attribute name="Next Local Component ID" value="16777216" />
 	<attribute name="Variables" />
 	<attribute name="Variables" />
@@ -47,12 +47,25 @@
 	<node id="361">
 	<node id="361">
 		<attribute name="Is Enabled" value="true" />
 		<attribute name="Is Enabled" value="true" />
 		<attribute name="Name" value="Camera" />
 		<attribute name="Name" value="Camera" />
-		<attribute name="Position" value="0 0 -5" />
+		<attribute name="Position" value="0 0 -2" />
 		<attribute name="Rotation" value="1 0 0 0" />
 		<attribute name="Rotation" value="1 0 0 0" />
 		<attribute name="Scale" value="1 1 1" />
 		<attribute name="Scale" value="1 1 1" />
 		<attribute name="Variables" />
 		<attribute name="Variables" />
-		<component type="Camera" id="1973">
-			<attribute name="FOV" value="45" />
+		<component type="Camera" id="1973" />
+	</node>
+	<node id="363">
+		<attribute name="Is Enabled" value="true" />
+		<attribute name="Name" value="Chest" />
+		<attribute name="Position" value="0 -0.374877 0" />
+		<attribute name="Rotation" value="1 0 0 0" />
+		<attribute name="Scale" value="1 1 1" />
+		<attribute name="Variables" />
+		<component type="StaticModel" id="1975">
+			<attribute name="Model" value="Model;Cache/2788364e8ff6f81f4b566a9d58e3fb5b.mdl" />
+			<attribute name="Material" value="Material;Models/Materials/DefaultMaterial.material" />
+		</component>
+		<component type="JSComponent" id="1976">
+			<attribute name="ComponentFile" value="JSComponentFile;Components/Spinner.js" />
 		</component>
 		</component>
 	</node>
 	</node>
 </scene>
 </scene>

BIN
Data/AtomicEditor/ProjectTemplates/Project3D/Resources/Textures/Chest.png


+ 8 - 1
Resources/EditorData/AtomicEditor/Script/jsutils.js

@@ -1,5 +1,6 @@
 __atomic_acorn = require('./acorn');
 __atomic_acorn = require('./acorn');
 __atomic_beautify = require('./beautify');
 __atomic_beautify = require('./beautify');
+__atomic_sourcemap = require('./source-map');
 
 
 exports.parseToJSON = function (source) {
 exports.parseToJSON = function (source) {
 
 
@@ -37,7 +38,6 @@ exports.parseErrorCheck = function(source) {
 
 
 
 
 	try {
 	try {
-
 		__atomic_acorn.parse( source, {
 		__atomic_acorn.parse( source, {
 	    	ranges: true,
 	    	ranges: true,
 	    	locations: true,
 	    	locations: true,
@@ -65,3 +65,10 @@ exports.jsBeautify = function (source) {
 	return __atomic_beautify.js_beautify(source);
 	return __atomic_beautify.js_beautify(source);
 
 
 }
 }
+
+exports.getRealLineNumber = function (map, line) {
+    var jsonMap = JSON.parse(map);
+    var smc = new __atomic_sourcemap.SourceMapConsumer(jsonMap);
+    var pos = smc.originalPositionFor({line: line, column: 100000});
+    return pos.line;
+}

File diff suppressed because it is too large
+ 1 - 0
Resources/EditorData/AtomicEditor/Script/source-map.js


+ 5 - 0
Resources/EditorData/AtomicEditor/editor/skin/skin.tb.txt

@@ -178,3 +178,8 @@ elements
 		text-color #aaaaaa
 		text-color #aaaaaa
 		min-width 140
 		min-width 140
 		max-width 140
 		max-width 140
+
+	HierarchyPrefabText
+		text-color #11aaaa
+	HierarchyPrefabText.selected
+		text-color #11ffff

+ 1 - 1
Script/AtomicEditor/.gitignore

@@ -1 +1 @@
-*.js
+out/*

+ 0 - 21
Script/AtomicEditor/assets/AssetImport.ts

@@ -1,21 +0,0 @@
-
-class AssetImport extends Atomic.ScriptObject {
-
-  constructor() {
-
-    super();
-
-    this.subscribeToEvent("DragAndDrop", (data) => this.handleDropFile(data));
-
-  }
-
-  handleDropFile(data):void {
-
-    Atomic.print("Dropped: ", data.fileName);
-
-  }
-
-
-}
-
-export = AssetImport;

+ 3 - 7
Script/AtomicEditor/editor/Editor.ts

@@ -1,8 +1,7 @@
 
 
-import EditorUI = require("../ui/EditorUI");
-import UIEvents = require("../ui/UIEvents");
-import AssetImport = require("../assets/AssetImport");
-import PlayMode = require("../ui/playmode/PlayMode");
+import EditorUI = require("ui/EditorUI");
+import UIEvents = require("ui/UIEvents");
+import PlayMode = require("ui/playmode/PlayMode");
 import EditorLicense = require("./EditorLicense");
 import EditorLicense = require("./EditorLicense");
 import EditorEvents = require("./EditorEvents");
 import EditorEvents = require("./EditorEvents");
 import Preferences = require("./Preferences");
 import Preferences = require("./Preferences");
@@ -10,7 +9,6 @@ import Preferences = require("./Preferences");
 class Editor extends Atomic.ScriptObject {
 class Editor extends Atomic.ScriptObject {
 
 
     project: ToolCore.Project;
     project: ToolCore.Project;
-    assetImport: AssetImport;
     editorLicense: EditorLicense;
     editorLicense: EditorLicense;
     playMode: PlayMode;
     playMode: PlayMode;
 
 
@@ -35,8 +33,6 @@ class Editor extends Atomic.ScriptObject {
 
 
         Atomic.getResourceCache().autoReloadResources = true;
         Atomic.getResourceCache().autoReloadResources = true;
 
 
-        this.assetImport = new AssetImport();
-
         this.subscribeToEvent(EditorEvents.LoadProject, (data) => this.handleEditorLoadProject(data));
         this.subscribeToEvent(EditorEvents.LoadProject, (data) => this.handleEditorLoadProject(data));
         this.subscribeToEvent(EditorEvents.CloseProject, (data) => this.handleEditorCloseProject(data));
         this.subscribeToEvent(EditorEvents.CloseProject, (data) => this.handleEditorCloseProject(data));
         this.subscribeToEvent("ProjectUnloaded", (data) => this.handleProjectUnloaded(data));
         this.subscribeToEvent("ProjectUnloaded", (data) => this.handleProjectUnloaded(data));

+ 3 - 1
Script/AtomicEditor/tsconfig.json

@@ -5,7 +5,9 @@
         "declaration": false,
         "declaration": false,
         "noImplicitAny": false,
         "noImplicitAny": false,
         "removeComments": true,
         "removeComments": true,
-        "noLib": false
+        "noLib": false,
+        "outDir": "out/",
+        "sourceMap": true
     },
     },
     "filesGlob": [
     "filesGlob": [
         "./**/*.ts"
         "./**/*.ts"

+ 2 - 2
Script/AtomicEditor/ui/EditorUI.ts

@@ -1,6 +1,6 @@
 
 
-import EditorEvents = require("../editor/EditorEvents");
-import MainFrame = require("../ui/MainFrame");
+import EditorEvents = require("editor/EditorEvents");
+import MainFrame = require("./frames/MainFrame");
 import ModalOps = require("./modal/ModalOps");
 import ModalOps = require("./modal/ModalOps");
 import Shortcuts = require("./Shortcuts");
 import Shortcuts = require("./Shortcuts");
 
 

+ 47 - 5
Script/AtomicEditor/ui/HierarchyFrame.ts → Script/AtomicEditor/ui/frames/HierarchyFrame.ts

@@ -1,7 +1,7 @@
 
 
-import HierarchyFrameMenu = require("./HierarchyFrameMenu");
+import HierarchyFrameMenu = require("./menus/HierarchyFrameMenu");
 import MenuItemSources = require("./menus/MenuItemSources");
 import MenuItemSources = require("./menus/MenuItemSources");
-import EditorEvents = require("../editor/EditorEvents");
+import EditorEvents = require("editor/EditorEvents");
 
 
 var IconTemporary = "ComponentBitmap";
 var IconTemporary = "ComponentBitmap";
 
 
@@ -56,8 +56,44 @@ class HierarchyFrame extends Atomic.UIWidget {
 
 
         });
         });
 
 
+        this.subscribeToEvent("ComponentAdded", (ev: Atomic.ComponentAddedEvent) => {
+
+            if (!ev.component || ev.component.typeName != "PrefabComponent") return;
+
+            var node = ev.node;
+
+            var itemID = this.nodeIDToItemID[node.id];
+
+            if (itemID) {
+
+                this.hierList.setItemTextSkin(node.id.toString(), "HierarchyPrefabText");
+
+            }
+
+        });
+
+        this.subscribeToEvent("ComponentRemoved", (ev: Atomic.ComponentRemovedEvent) => {
+
+            if (!ev.component || ev.component.typeName != "PrefabComponent") return;
+
+            var node = ev.node;
+
+            var itemID = this.nodeIDToItemID[node.id];
+
+            if (itemID) {
+
+                this.hierList.setItemTextSkin(node.id.toString(), "Folder");
+            }
+
+        });
+
         this.subscribeToEvent("TemporaryChanged", (ev: Atomic.TemporaryChangedEvent) => {
         this.subscribeToEvent("TemporaryChanged", (ev: Atomic.TemporaryChangedEvent) => {
 
 
+            // this can happen on a temporary status change on a non-scripted class instance
+            if (!ev.serializable) {
+                return;
+            }
+
             if (ev.serializable.typeName == "Node") {
             if (ev.serializable.typeName == "Node") {
 
 
                 var node = <Atomic.Node> ev.serializable;
                 var node = <Atomic.Node> ev.serializable;
@@ -159,8 +195,8 @@ class HierarchyFrame extends Atomic.UIWidget {
                 var node = this.scene.getNode(selectedId);
                 var node = this.scene.getNode(selectedId);
                 if (node) {
                 if (node) {
 
 
-                  node.removeAllComponents();
-                  node.remove();
+                    node.removeAllComponents();
+                    node.remove();
 
 
                 }
                 }
 
 
@@ -236,7 +272,7 @@ class HierarchyFrame extends Atomic.UIWidget {
 
 
             // create
             // create
             if (id == "menu create") {
             if (id == "menu create") {
-                if (!ToolCore.toolSystem.project) return;  
+                if (!ToolCore.toolSystem.project) return;
                 var src = MenuItemSources.getMenuItemSource("hierarchy create items");
                 var src = MenuItemSources.getMenuItemSource("hierarchy create items");
                 var menu = new Atomic.UIMenuWindow(data.target, "create popup");
                 var menu = new Atomic.UIMenuWindow(data.target, "create popup");
                 menu.show(src);
                 menu.show(src);
@@ -294,6 +330,12 @@ class HierarchyFrame extends Atomic.UIWidget {
 
 
         var childItemID = this.hierList.addChildItem(parentID, name, icon, node.id.toString());
         var childItemID = this.hierList.addChildItem(parentID, name, icon, node.id.toString());
 
 
+        if (node.getComponent("PrefabComponent")) {
+
+            this.hierList.setItemTextSkin(node.id.toString(), "HierarchyPrefabText");
+
+        }
+
         this.nodeIDToItemID[node.id] = childItemID;
         this.nodeIDToItemID[node.id] = childItemID;
 
 
         for (var i = 0; i < node.getNumChildren(false); i++) {
         for (var i = 0; i < node.getNumChildren(false); i++) {

+ 5 - 5
Script/AtomicEditor/ui/MainFrame.ts → Script/AtomicEditor/ui/frames/MainFrame.ts

@@ -3,13 +3,13 @@ import ResourceFrame = require("./ResourceFrame");
 import WelcomeFrame = require("./WelcomeFrame");
 import WelcomeFrame = require("./WelcomeFrame");
 import InspectorFrame = require("./inspector/InspectorFrame");
 import InspectorFrame = require("./inspector/InspectorFrame");
 import HierarchyFrame = require("./HierarchyFrame");
 import HierarchyFrame = require("./HierarchyFrame");
-import MainToolbar = require("./MainToolbar");
+import MainToolbar = require("ui//MainToolbar");
 
 
-import MessageModal = require("./modal/MessageModal");
-import UIEvents = require("./UIEvents");
+import MessageModal = require("../modal/MessageModal");
+import UIEvents = require("ui/UIEvents");
 
 
-import ScriptWidget = require("./ScriptWidget");
-import MainFrameMenu = require("./MainFrameMenu");
+import ScriptWidget = require("ui/ScriptWidget");
+import MainFrameMenu = require("./menus/MainFrameMenu");
 
 
 import MenuItemSources = require("./menus/MenuItemSources");
 import MenuItemSources = require("./menus/MenuItemSources");
 
 

+ 23 - 13
Script/AtomicEditor/ui/ProjectFrame.ts → Script/AtomicEditor/ui/frames/ProjectFrame.ts

@@ -1,9 +1,9 @@
 
 
 
 
-import ScriptWidget = require("./ScriptWidget");
-import Editor = require("../editor/Editor");
-import EditorEvents = require("../editor/EditorEvents");
-import ProjectFrameMenu = require("./ProjectFrameMenu");
+import ScriptWidget = require("ui/ScriptWidget");
+import Editor = require("editor/Editor");
+import EditorEvents = require("editor/EditorEvents");
+import ProjectFrameMenu = require("./menus/ProjectFrameMenu");
 import MenuItemSources = require("./menus/MenuItemSources");
 import MenuItemSources = require("./menus/MenuItemSources");
 
 
 class ProjectFrame extends ScriptWidget {
 class ProjectFrame extends ScriptWidget {
@@ -136,10 +136,10 @@ class ProjectFrame extends ScriptWidget {
 
 
             if (this.menu.handlePopupMenu(data.target, data.refid))
             if (this.menu.handlePopupMenu(data.target, data.refid))
                 return true;
                 return true;
-            
+
             // create
             // create
             if (id == "menu create") {
             if (id == "menu create") {
-                if (!ToolCore.toolSystem.project) return;  
+                if (!ToolCore.toolSystem.project) return;
                 var src = MenuItemSources.getMenuItemSource("project create items");
                 var src = MenuItemSources.getMenuItemSource("project create items");
                 var menu = new Atomic.UIMenuWindow(data.target, "create popup");
                 var menu = new Atomic.UIMenuWindow(data.target, "create popup");
                 menu.show(src);
                 menu.show(src);
@@ -254,12 +254,22 @@ class ProjectFrame extends ScriptWidget {
         if (dragObject.object && dragObject.object.typeName == "Node") {
         if (dragObject.object && dragObject.object.typeName == "Node") {
 
 
             var node = <Atomic.Node> dragObject.object;
             var node = <Atomic.Node> dragObject.object;
-            var destFilename = Atomic.addTrailingSlash(asset.path);
-            destFilename += node.name + ".prefab";
 
 
-            var file = new Atomic.File(destFilename, Atomic.FILE_WRITE);
-            node.saveXML(file);
-            file.close();
+            var prefabComponent = <Atomic.PrefabComponent> node.getComponent("PrefabComponent");
+
+            if (prefabComponent) {
+
+              prefabComponent.savePrefab();
+
+            }
+            else {
+                var destFilename = Atomic.addTrailingSlash(asset.path);
+                destFilename += node.name + ".prefab";
+
+                var file = new Atomic.File(destFilename, Atomic.FILE_WRITE);
+                node.saveXML(file);
+                file.close();
+            }
 
 
             this.rescan(asset);
             this.rescan(asset);
 
 
@@ -308,7 +318,7 @@ class ProjectFrame extends ScriptWidget {
 
 
         var container: Atomic.UILayout = <Atomic.UILayout> this.getWidget("contentcontainer");
         var container: Atomic.UILayout = <Atomic.UILayout> this.getWidget("contentcontainer");
         container.deleteAllChildren();
         container.deleteAllChildren();
-        
+
     }
     }
 
 
     private refreshContent(folder: ToolCore.Asset) {
     private refreshContent(folder: ToolCore.Asset) {
@@ -391,7 +401,7 @@ class ProjectFrame extends ScriptWidget {
         button.id = asset.guid;
         button.id = asset.guid;
         button.layoutParams = lp;
         button.layoutParams = lp;
         button.fontDescription = fd;
         button.fontDescription = fd;
-        button.text = asset.name;
+        button.text = asset.name + asset.extension;
         button.skinBg = "TBButton.flat";
         button.skinBg = "TBButton.flat";
         blayout.addChild(button);
         blayout.addChild(button);
 
 

+ 3 - 3
Script/AtomicEditor/ui/ResourceFrame.ts → Script/AtomicEditor/ui/frames/ResourceFrame.ts

@@ -1,6 +1,6 @@
-import ScriptWidget = require("./ScriptWidget");
-import EditorEvents = require("../editor/EditorEvents");
-import UIEvents = require("./UIEvents");
+import ScriptWidget = require("ui/ScriptWidget");
+import EditorEvents = require("editor/EditorEvents");
+import UIEvents = require("ui/UIEvents");
 
 
 // the root content of editor widgets (rootContentWidget property) are extended with an editor field
 // the root content of editor widgets (rootContentWidget property) are extended with an editor field
 // so we can access the editor they belong to from the widget itself
 // so we can access the editor they belong to from the widget itself

+ 4 - 4
Script/AtomicEditor/ui/WelcomeFrame.ts → Script/AtomicEditor/ui/frames/WelcomeFrame.ts

@@ -1,8 +1,8 @@
 
 
-import EditorEvents = require("../editor/EditorEvents");
-import EditorUI = require("./EditorUI");
-import ScriptWidget = require("./ScriptWidget");
-import Preferences = require("../editor/Preferences");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import ScriptWidget = require("ui/ScriptWidget");
+import Preferences = require("editor/Preferences");
 
 
 class WelcomeFrame extends ScriptWidget {
 class WelcomeFrame extends ScriptWidget {
 
 

+ 0 - 0
Script/AtomicEditor/ui/inspector/ArrayEditWidget.ts → Script/AtomicEditor/ui/frames/inspector/ArrayEditWidget.ts


+ 60 - 129
Script/AtomicEditor/ui/inspector/ComponentInspector.ts → Script/AtomicEditor/ui/frames/inspector/ComponentInspector.ts

@@ -1,8 +1,8 @@
 
 
-import ScriptWidget = require("../ScriptWidget");
+import ScriptWidget = require("ui/ScriptWidget");
 import DataBinding = require("./DataBinding");
 import DataBinding = require("./DataBinding");
 import InspectorUtils = require("./InspectorUtils");
 import InspectorUtils = require("./InspectorUtils");
-import EditorUI = require("../EditorUI");
+import EditorUI = require("ui/EditorUI");
 
 
 class ComponentInspector extends Atomic.UISection {
 class ComponentInspector extends Atomic.UISection {
 
 
@@ -123,15 +123,21 @@ class ComponentInspector extends Atomic.UISection {
 
 
 
 
         if (component.typeName == "JSComponent") {
         if (component.typeName == "JSComponent") {
-            this.addJSComponentUI(attrsVerticalLayout);
+            // auto expand JSComponents
+            this.value = 1;
         }
         }
 
 
+        if (component.typeName == "TileMap2D") {
+            this.addTilemap2DUI(attrsVerticalLayout);
+        }
+
+
         if (component.typeName == "StaticModel" || component.typeName == "AnimatedModel" || component.typeName == "Skybox") {
         if (component.typeName == "StaticModel" || component.typeName == "AnimatedModel" || component.typeName == "Skybox") {
             this.addModelUI(attrsVerticalLayout, component.typeName);
             this.addModelUI(attrsVerticalLayout, component.typeName);
         }
         }
 
 
-        if (component.typeName == "SoundSource" || component.typeName == "SoundSource3D") {
-            this.addSoundSourceUI(attrsVerticalLayout, component.typeName);
+        if (component.typeName == "StaticSprite2D" || component.typeName == "AnimatedSprite2D") {
+            this.addSpriteUI(attrsVerticalLayout, component.typeName);
         }
         }
 
 
 
 
@@ -164,29 +170,6 @@ class ComponentInspector extends Atomic.UISection {
 
 
     addPrefabUI(layout: Atomic.UILayout) {
     addPrefabUI(layout: Atomic.UILayout) {
 
 
-        // expand prefab
-        this.value = 1;
-
-        var fd = new Atomic.UIFontDescription();
-        fd.id = "Vera";
-        fd.size = 11;
-
-        var selectButton = new Atomic.UIButton();
-        selectButton.text = "Select Prefab";
-        selectButton.fontDescription = fd;
-
-        selectButton.onClick = () => {
-
-            var node = (<Atomic.PrefabComponent> this.component).getPrefabNode();
-
-            this.sendEvent("EditorActiveNodeChange", { node: node });
-
-            return true;
-
-        }
-
-        layout.addChild(selectButton);
-
     }
     }
 
 
     acceptAssetDrag(importerTypeName: string, ev: Atomic.DragEndedEvent): ToolCore.AssetImporter {
     acceptAssetDrag(importerTypeName: string, ev: Atomic.DragEndedEvent): ToolCore.AssetImporter {
@@ -207,79 +190,19 @@ class ComponentInspector extends Atomic.UISection {
 
 
     }
     }
 
 
-    addModelUI(layout: Atomic.UILayout, typeName: string) {
-
-        var staticModel = <Atomic.StaticModel> this.component;
-        var cacheModel = staticModel.model;
-
-        var o = InspectorUtils.createAttrEditFieldWithSelectButton("Model", layout);
-        var field = o.editField;
-        field.readOnly = true;
-
-        var select = o.selectButton;
-
-        select.onClick = () => {
-
-            EditorUI.getModelOps().showResourceSelection("Select Model", "ModelImporter", function(asset: ToolCore.Asset) {
-
-                staticModel.model = <Atomic.Model> Atomic.cache.getResource("Model", asset.cachePath + ".mdl");
-                field.text = asset.name;
-
-            });
-
-        }
-
-        if (cacheModel) {
-
-            var asset = ToolCore.assetDatabase.getAssetByCachePath(cacheModel.name);
-
-            if (asset) {
-
-                field.text = asset.name;
-
-            }
-
-        }
-
-        // handle dropping of model on field
-        field.subscribeToEvent(field, "DragEnded", (ev: Atomic.DragEndedEvent) => {
-
-            if (ev.target == field) {
-
-                var importer = this.acceptAssetDrag("ModelImporter", ev);
-
-                if (importer) {
-
-                    var modelImporter = <ToolCore.ModelImporter> importer;
-                    var asset = modelImporter.asset;
-
-                    // the model itself, not the node XML
-                    var model = <Atomic.Model> Atomic.cache.getResource("Model", asset.cachePath + ".mdl");
-
-                    if (model) {
+    createMaterialClosure(layout: Atomic.UILayout, staticModel: Atomic.StaticModel, index: number) {
 
 
-                        staticModel.model = model;
-                        ev.target.text = asset.name;
-
-                    }
-                }
-            }
-
-        });
-
-        // MATERIAL FIELD (single material, not multimaterial for now)
-
-        o = InspectorUtils.createAttrEditFieldWithSelectButton("Material", layout);
+        var o = InspectorUtils.createAttrEditFieldWithSelectButton("Material " + index, layout);
         var materialField = o.editField;
         var materialField = o.editField;
         materialField.readOnly = true;
         materialField.readOnly = true;
 
 
-        select = o.selectButton;
+        var select = o.selectButton;
 
 
         select.onClick = () => {
         select.onClick = () => {
 
 
             EditorUI.getModelOps().showResourceSelection("Select Material", "MaterialImporter", function(asset: ToolCore.Asset) {
             EditorUI.getModelOps().showResourceSelection("Select Material", "MaterialImporter", function(asset: ToolCore.Asset) {
 
 
-                staticModel.setMaterial(<Atomic.Material> Atomic.cache.getResource("Material", asset.path));
+                staticModel.setMaterialIndex(index, <Atomic.Material> Atomic.cache.getResource("Material", asset.path));
 
 
                 if (staticModel.getMaterial())
                 if (staticModel.getMaterial())
                     materialField.text = staticModel.getMaterial().name;
                     materialField.text = staticModel.getMaterial().name;
@@ -314,7 +237,7 @@ class ComponentInspector extends Atomic.UISection {
 
 
                     if (material) {
                     if (material) {
 
 
-                        staticModel.material = material;
+                        staticModel.setMaterialIndex(index, material);
                         ev.target.text = material.name;
                         ev.target.text = material.name;
 
 
                     }
                     }
@@ -326,28 +249,44 @@ class ComponentInspector extends Atomic.UISection {
 
 
     }
     }
 
 
-    addJSComponentUI(layout: Atomic.UILayout) {
+    addModelUI(layout: Atomic.UILayout, typeName: string) {
 
 
-        var js = <Atomic.JSComponent> this.component;
+        var staticModel = <Atomic.StaticModel> this.component;
+
+        var numGeometries = staticModel.numGeometries;
+        if (typeName == "Skybox") {
+            numGeometries = 1;
+        }
+
+        for (var x = 0; x < numGeometries; x++) {
+
+            this.createMaterialClosure(layout, staticModel, x);
+
+        }
+
+
+    }
 
 
-        // expand prefab
-        this.value = 1;
 
 
-        var o = InspectorUtils.createAttrEditFieldWithSelectButton("Script", layout);
+    addSpriteUI(layout: Atomic.UILayout, typeName: string) {
+
+        var spriteComponent = <Atomic.StaticSprite2D> this.component;
+
+        var o = InspectorUtils.createAttrEditFieldWithSelectButton("Sprite", layout);
         var field = o.editField;
         var field = o.editField;
         field.readOnly = true;
         field.readOnly = true;
-        field.text = js.componentFile ? js.componentFile.name : "";
+        field.text = spriteComponent.sprite ? spriteComponent.sprite.name : "";
 
 
         var select = o.selectButton;
         var select = o.selectButton;
 
 
         select.onClick = () => {
         select.onClick = () => {
 
 
-            EditorUI.getModelOps().showResourceSelection("Select JSComponent Script", "JavascriptImporter", function(asset: ToolCore.Asset) {
-
-                js.componentFile = <Atomic.JSComponentFile> Atomic.cache.getResource("JSComponentFile", asset.path);
+            // this should allow selecting of sprite sheets as well
+            EditorUI.getModelOps().showResourceSelection("Select Sprite", "TextureImporter", function(asset: ToolCore.Asset) {
 
 
-                if (js.componentFile)
-                    field.text = js.componentFile.name;
+                spriteComponent.sprite = <Atomic.Sprite2D> Atomic.cache.getResource("Sprite2D", asset.path);
+                if (spriteComponent.sprite)
+                    field.text = spriteComponent.sprite.name;
 
 
             });
             });
 
 
@@ -358,19 +297,13 @@ class ComponentInspector extends Atomic.UISection {
 
 
             if (ev.target == field) {
             if (ev.target == field) {
 
 
-                var importer = this.acceptAssetDrag("JavascriptImporter", ev);
+                var importer = this.acceptAssetDrag("TextureImporter", ev);
 
 
                 if (importer) {
                 if (importer) {
 
 
-                    var jsImporter = <ToolCore.JavascriptImporter> importer;
-
-                    if (jsImporter.isComponentFile()) {
-
-                        js.componentFile = <Atomic.JSComponentFile> Atomic.cache.getResource("JSComponentFile", importer.asset.path);
-                        if (js.componentFile)
-                            ev.target.text = js.componentFile.name;
-
-                    }
+                  spriteComponent.sprite = <Atomic.Sprite2D> Atomic.cache.getResource("Sprite2D", importer.asset.path);
+                  if (spriteComponent.sprite)
+                      field.text = spriteComponent.sprite.name;
 
 
                 }
                 }
             }
             }
@@ -380,26 +313,25 @@ class ComponentInspector extends Atomic.UISection {
 
 
     }
     }
 
 
+    addTilemap2DUI(layout: Atomic.UILayout) {
 
 
-    addSoundSourceUI(layout: Atomic.UILayout, typeName: string) {
-
-        var sndSource = <Atomic.SoundSource> this.component;
+        var tilemap = <Atomic.TileMap2D> this.component;
 
 
-        var o = InspectorUtils.createAttrEditFieldWithSelectButton("Sound", layout);
+        var o = InspectorUtils.createAttrEditFieldWithSelectButton("TMX File", layout);
         var field = o.editField;
         var field = o.editField;
         field.readOnly = true;
         field.readOnly = true;
-        field.text = sndSource.sound ? sndSource.sound.name : "";
+        field.text = tilemap.tmxFile ? tilemap.tmxFile.name : "";
 
 
         var select = o.selectButton;
         var select = o.selectButton;
 
 
         select.onClick = () => {
         select.onClick = () => {
 
 
-            EditorUI.getModelOps().showResourceSelection("Select Sound", "AudioImporter", function(asset: ToolCore.Asset) {
-
-                sndSource.sound = <Atomic.Sound> Atomic.cache.getResource("Sound", asset.path);
-                if (sndSource.sound)
-                    field.text = sndSource.sound.name;
+            // this should allow selecting of sprite sheets as well
+            EditorUI.getModelOps().showResourceSelection("Select TMX File", "TMXImporter", function(asset: ToolCore.Asset) {
 
 
+                tilemap.tmxFile = <Atomic.TmxFile2D> Atomic.cache.getResource("TmxFile2D", asset.path);
+                if (tilemap.tmxFile)
+                    field.text = tilemap.tmxFile.name;
             });
             });
 
 
         }
         }
@@ -409,20 +341,19 @@ class ComponentInspector extends Atomic.UISection {
 
 
             if (ev.target == field) {
             if (ev.target == field) {
 
 
-                var importer = this.acceptAssetDrag("AudioImporter", ev);
+                var importer = this.acceptAssetDrag("TextureImporter", ev);
 
 
                 if (importer) {
                 if (importer) {
 
 
-                    sndSource.sound = <Atomic.Sound> Atomic.cache.getResource("Sound", importer.asset.path);
-                    if (sndSource.sound)
-                        field.text = sndSource.sound.name;
+                  tilemap.tmxFile = <Atomic.TmxFile2D> Atomic.cache.getResource("TmxFile2D", importer.asset.path);
+                  if (tilemap.tmxFile)
+                      field.text = tilemap.tmxFile.name;
 
 
                 }
                 }
             }
             }
 
 
         });
         });
 
 
-
     }
     }
 
 
     addLightCascadeParametersUI(layout: Atomic.UILayout) {
     addLightCascadeParametersUI(layout: Atomic.UILayout) {

+ 13 - 1
Script/AtomicEditor/ui/inspector/CreateComponentButton.ts → Script/AtomicEditor/ui/frames/inspector/CreateComponentButton.ts

@@ -8,6 +8,17 @@ audioCreateSource.addItem(new Atomic.UIMenuItem("SoundListener", "SoundListener"
 audioCreateSource.addItem(new Atomic.UIMenuItem("SoundSource", "SoundSource"));
 audioCreateSource.addItem(new Atomic.UIMenuItem("SoundSource", "SoundSource"));
 audioCreateSource.addItem(new Atomic.UIMenuItem("SoundSource3D", "SoundSource3D"));
 audioCreateSource.addItem(new Atomic.UIMenuItem("SoundSource3D", "SoundSource3D"));
 
 
+var _2DCreateSource = new Atomic.UIMenuItemSource();
+_2DCreateSource.addItem(new Atomic.UIMenuItem("PhysicsWorld2D", "PhysicsWorld2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("StaticSprite2D", "StaticSprite2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("AnimatedSprite2D", "AnimatedSprite2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("PointLight2D", "PointLight2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("DirectionalLight2D", "DirectionalLight2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("RigidBody2D", "RigidBody2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("CollisionBox2D", "CollisionBox2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("CollisionCircle2D", "CollisionCircle2D"));
+_2DCreateSource.addItem(new Atomic.UIMenuItem("TileMap2D", "TileMap2D"));
+
 var geometryCreateSource = new Atomic.UIMenuItemSource();
 var geometryCreateSource = new Atomic.UIMenuItemSource();
 
 
 geometryCreateSource.addItem(new Atomic.UIMenuItem("StaticModel", "StaticModel"));
 geometryCreateSource.addItem(new Atomic.UIMenuItem("StaticModel", "StaticModel"));
@@ -47,7 +58,7 @@ var sceneCreateSource = new Atomic.UIMenuItemSource();
 
 
 sceneCreateSource.addItem(new Atomic.UIMenuItem("Camera", "Camera"));
 sceneCreateSource.addItem(new Atomic.UIMenuItem("Camera", "Camera"));
 sceneCreateSource.addItem(new Atomic.UIMenuItem("Light", "Light"));
 sceneCreateSource.addItem(new Atomic.UIMenuItem("Light", "Light"));
-sceneCreateSource.addItem(new Atomic.UIMenuItem("Zone", "create component"));
+sceneCreateSource.addItem(new Atomic.UIMenuItem("Zone", "Zone"));
 
 
 var subsystemCreateSource = new Atomic.UIMenuItemSource();
 var subsystemCreateSource = new Atomic.UIMenuItemSource();
 
 
@@ -59,6 +70,7 @@ var componentCreateSource = new Atomic.UIMenuItemSource();
 
 
 var sources = {
 var sources = {
     Audio: audioCreateSource,
     Audio: audioCreateSource,
+    "2D": _2DCreateSource,
     Geometry: geometryCreateSource,
     Geometry: geometryCreateSource,
     Logic: logicCreateSource,
     Logic: logicCreateSource,
     Navigation: navigationCreateSource,
     Navigation: navigationCreateSource,

+ 155 - 3
Script/AtomicEditor/ui/inspector/DataBinding.ts → Script/AtomicEditor/ui/frames/inspector/DataBinding.ts

@@ -1,3 +1,6 @@
+import InspectorUtils = require("./InspectorUtils");
+import EditorUI = require("ui/EditorUI");
+
 class DataBinding {
 class DataBinding {
 
 
     constructor(object: Atomic.Serializable, attrInfo: Atomic.AttributeInfo, widget: Atomic.UIWidget) {
     constructor(object: Atomic.Serializable, attrInfo: Atomic.AttributeInfo, widget: Atomic.UIWidget) {
@@ -93,7 +96,7 @@ class DataBinding {
             var lp = new Atomic.UILayoutParams();
             var lp = new Atomic.UILayoutParams();
             lp.width = 100;
             lp.width = 100;
 
 
-            for (var i:any = 0; i < 3; i++) {
+            for (var i: any = 0; i < 3; i++) {
                 var select = new Atomic.UIInlineSelect();
                 var select = new Atomic.UIInlineSelect();
                 select.id = String(i + 1);
                 select.id = String(i + 1);
                 select.fontDescription = fd;
                 select.fontDescription = fd;
@@ -114,7 +117,7 @@ class DataBinding {
             var lp = new Atomic.UILayoutParams();
             var lp = new Atomic.UILayoutParams();
             lp.width = 70;
             lp.width = 70;
 
 
-            for (var i:any = 0; i < 4; i++) {
+            for (var i: any = 0; i < 4; i++) {
 
 
                 var select = new Atomic.UIInlineSelect();
                 var select = new Atomic.UIInlineSelect();
                 select.id = String(i + 1);
                 select.id = String(i + 1);
@@ -124,6 +127,116 @@ class DataBinding {
                 layout.addChild(select);
                 layout.addChild(select);
             }
             }
 
 
+        } else if (attrInfo.type == Atomic.VAR_VECTOR2) {
+            var layout = new Atomic.UILayout();
+            widget = layout;
+            layout.spacing = 0;
+
+            var lp = new Atomic.UILayoutParams();
+            lp.width = 100;
+
+            for (var i: any = 0; i < 2; i++) {
+                var select = new Atomic.UIInlineSelect();
+                select.id = String(i + 1);
+                select.fontDescription = fd;
+                select.skinBg = "InspectorVectorAttrName";
+                select.setLimits(-10000000, 10000000);
+                var editlp = new Atomic.UILayoutParams();
+                editlp.minWidth = 60;
+                select.editFieldLayoutParams = editlp;
+                select.layoutParams = lp;
+                layout.addChild(select);
+            }
+
+        } else if (attrInfo.type == Atomic.VAR_RESOURCEREF && attrInfo.resourceTypeName) {
+
+            var importerName = ToolCore.assetDatabase.getResourceImporterName(attrInfo.resourceTypeName);
+
+            if (importerName) {
+
+                var parent = new Atomic.UILayout();
+                var o = InspectorUtils.createAttrEditFieldWithSelectButton("", parent);
+
+                parent.layoutSize = Atomic.UI_LAYOUT_SIZE_AVAILABLE;
+                parent.gravity = Atomic.UI_GRAVITY_LEFT_RIGHT;
+                parent.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION_GRAVITY;
+
+
+                var lp = new Atomic.UILayoutParams();
+                lp.width = 140;
+                o.editField.layoutParams = lp;
+                o.editField.readOnly = true;
+
+                // stuff editfield in so can be reference
+                parent["editField"] = o.editField;
+
+                var selectButton = o.selectButton;
+
+                selectButton.onClick = () => {
+
+                    EditorUI.getModelOps().showResourceSelection("Select " + attrInfo.resourceTypeName + " Resource", importerName, function(asset: ToolCore.Asset) {
+
+                        var resource = asset.resource;
+
+                        object.setAttribute(attrInfo.name, resource);
+
+                        if (resource) {
+
+                            // use the asset name instead of the cache name
+                            if (asset.importer.requiresCacheFile())
+                                o.editField.text = asset.name;
+                            else
+                                o.editField.text = resource.name;
+                        }
+                        else
+                            o.editField.text = "";
+
+
+                    });
+
+                }
+
+                // handle dropping of component on field
+                o.editField.subscribeToEvent(o.editField, "DragEnded", (ev: Atomic.DragEndedEvent) => {
+
+                    if (ev.target == o.editField) {
+
+                        var dragObject = ev.dragObject;
+
+                        var importer;
+
+                        if (dragObject.object && dragObject.object.typeName == "Asset") {
+
+                            var asset = <ToolCore.Asset> dragObject.object;
+
+                            if (asset.importerTypeName == importerName) {
+                                importer = asset.importer;
+                            }
+
+                        }
+
+                        if (importer) {
+
+                            var resource = asset.resource;
+                            object.setAttribute(attrInfo.name, resource);
+                            if (resource) {
+                                // use the asset name instead of the cache name
+                                if (asset.importer.requiresCacheFile())
+                                    o.editField.text = asset.name;
+                                else
+                                    o.editField.text = resource.name;
+                            }
+                            else
+                                o.editField.text = "";
+
+                        }
+                    }
+
+                });
+
+                widget = parent;
+            }
+
         }
         }
 
 
         if (widget) {
         if (widget) {
@@ -163,6 +276,18 @@ class DataBinding {
                     select.value = value[i];
                     select.value = value[i];
             }
             }
 
 
+        }
+        else if (attrInfo.type == Atomic.VAR_VECTOR2) {
+
+            var value = object.getAttribute(attrInfo.name);
+
+            for (var i = 0; i < 2; i++) {
+
+                var select = widget.getWidget((i + 1).toString());
+                if (select)
+                    select.value = value[i];
+            }
+
         }
         }
         else if (attrInfo.type == Atomic.VAR_QUATERNION) {
         else if (attrInfo.type == Atomic.VAR_QUATERNION) {
 
 
@@ -205,6 +330,20 @@ class DataBinding {
                     select.value = value[i];
                     select.value = value[i];
             }
             }
 
 
+        } else if (attrInfo.type == Atomic.VAR_RESOURCEREF && attrInfo.resourceTypeName) {
+
+            // for cached resources, use the asset name, otherwise use the resource path name
+            var resource = <Atomic.Resource> object.getAttribute(attrInfo.name);
+            var text = "";
+            if (resource) {
+                text = resource.name;
+                var asset = ToolCore.assetDatabase.getAssetByCachePath(resource.name);
+                if (asset)
+                  text = asset.name;
+            }
+
+            widget["editField"].text = text;
+
         }
         }
 
 
         this.widgetLocked = false;
         this.widgetLocked = false;
@@ -254,7 +393,19 @@ class DataBinding {
 
 
             object.setAttribute(attrInfo.name, value);
             object.setAttribute(attrInfo.name, value);
 
 
-        } else if (type == Atomic.VAR_QUATERNION && srcWidget) {
+        } else if (type == Atomic.VAR_VECTOR2 && srcWidget) {
+
+            var value = object.getAttribute(attrInfo.name);
+
+            if (srcWidget.id == "1")
+                value[0] = srcWidget.value;
+            else if (srcWidget.id == "2")
+                value[1] = srcWidget.value;
+
+            object.setAttribute(attrInfo.name, value);
+
+        }
+        else if (type == Atomic.VAR_QUATERNION && srcWidget) {
 
 
             var value = object.getAttribute(attrInfo.name);
             var value = object.getAttribute(attrInfo.name);
 
 
@@ -287,6 +438,7 @@ class DataBinding {
 
 
     }
     }
 
 
+
     handleWidgetEvent(ev: Atomic.UIWidgetEvent): boolean {
     handleWidgetEvent(ev: Atomic.UIWidgetEvent): boolean {
 
 
         if (this.objectLocked)
         if (this.objectLocked)

+ 2 - 2
Script/AtomicEditor/ui/inspector/InspectorFrame.ts → Script/AtomicEditor/ui/frames/inspector/InspectorFrame.ts

@@ -1,6 +1,6 @@
 
 
-import EditorEvents = require("../../editor/EditorEvents");
-import ScriptWidget = require("../ScriptWidget");
+import EditorEvents = require("editor/EditorEvents");
+import ScriptWidget = require("ui/ScriptWidget");
 import DataBinding = require("./DataBinding");
 import DataBinding = require("./DataBinding");
 
 
 // inspectors
 // inspectors

+ 4 - 2
Script/AtomicEditor/ui/inspector/InspectorUtils.ts → Script/AtomicEditor/ui/frames/inspector/InspectorUtils.ts

@@ -84,8 +84,10 @@ class InspectorUtils {
     var attrLayout = new Atomic.UILayout();
     var attrLayout = new Atomic.UILayout();
     attrLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP;
     attrLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP;
 
 
-    var _name = InspectorUtils.createAttrName(name);
-    attrLayout.addChild(_name);
+    if (name) {
+      var _name = InspectorUtils.createAttrName(name);
+      attrLayout.addChild(_name);
+    }
 
 
     var fieldLayout = new Atomic.UILayout();
     var fieldLayout = new Atomic.UILayout();
     fieldLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP;
     fieldLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP;

+ 1 - 1
Script/AtomicEditor/ui/inspector/InspectorWidget.ts → Script/AtomicEditor/ui/frames/inspector/InspectorWidget.ts

@@ -1,4 +1,4 @@
-import ScriptWidget = require("../ScriptWidget");
+import ScriptWidget = require("ui/ScriptWidget");
 
 
 class InspectorWidget extends ScriptWidget {
 class InspectorWidget extends ScriptWidget {
 
 

+ 7 - 4
Script/AtomicEditor/ui/inspector/MaterialInspector.ts → Script/AtomicEditor/ui/frames/inspector/MaterialInspector.ts

@@ -1,7 +1,7 @@
 
 
-import ScriptWidget = require("../ScriptWidget");
-import UIEvents = require("../UIEvents");
-import EditorUI = require("../EditorUI");
+import ScriptWidget = require("ui/ScriptWidget");
+import UIEvents = require("ui/UIEvents");
+import EditorUI = require("ui/EditorUI");
 
 
 import TextureSelector = require("./TextureSelector");
 import TextureSelector = require("./TextureSelector");
 
 
@@ -42,7 +42,10 @@ var techniqueLookup = {
     "Techniques/Diff.xml": "Diffuse",
     "Techniques/Diff.xml": "Diffuse",
     "Techniques/DiffEmissive.xml": "Diffuse Emissive",
     "Techniques/DiffEmissive.xml": "Diffuse Emissive",
     "Techniques/DiffNormal.xml": "Diffuse Normal",
     "Techniques/DiffNormal.xml": "Diffuse Normal",
-    "Techniques/DiffNormalSpec.xml": "Diffuse Normal Specular"
+    "Techniques/DiffNormalSpec.xml": "Diffuse Normal Specular",
+    "Techniques/DiffAlpha.xml": "Alpha",
+    "Techniques/DiffAlphaMask.xml": "Alpha Mask",
+    "Techniques/DiffAdd.xml": "Additive"
 }
 }
 
 
 var techniqueReverseLookup = {};
 var techniqueReverseLookup = {};

+ 0 - 0
Script/AtomicEditor/ui/inspector/ModelInspector.ts → Script/AtomicEditor/ui/frames/inspector/ModelInspector.ts


+ 10 - 5
Script/AtomicEditor/ui/inspector/NodeInspector.ts → Script/AtomicEditor/ui/frames/inspector/NodeInspector.ts

@@ -1,5 +1,5 @@
 
 
-import ScriptWidget = require("../ScriptWidget");
+import ScriptWidget = require("ui/ScriptWidget");
 import ComponentInspector = require("./ComponentInspector");
 import ComponentInspector = require("./ComponentInspector");
 import DataBinding = require("./DataBinding");
 import DataBinding = require("./DataBinding");
 import CreateComponentButton = require("./CreateComponentButton");
 import CreateComponentButton = require("./CreateComponentButton");
@@ -35,8 +35,8 @@ class NodeInspector extends ScriptWidget {
 
 
     getPrefabComponent(node: Atomic.Node): Atomic.PrefabComponent {
     getPrefabComponent(node: Atomic.Node): Atomic.PrefabComponent {
 
 
-        if (node.parent && node.parent.getComponent("PrefabComponent"))
-            return <Atomic.PrefabComponent> node.parent.getComponent("PrefabComponent");
+        if (node.getComponent("PrefabComponent"))
+            return <Atomic.PrefabComponent> node.getComponent("PrefabComponent");
 
 
         if (node.parent)
         if (node.parent)
             return this.getPrefabComponent(node.parent);
             return this.getPrefabComponent(node.parent);
@@ -47,7 +47,7 @@ class NodeInspector extends ScriptWidget {
 
 
     detectPrefab(node: Atomic.Node): boolean {
     detectPrefab(node: Atomic.Node): boolean {
 
 
-        if (node.parent && node.parent.getComponent("PrefabComponent"))
+        if (node.getComponent("PrefabComponent"))
             return true;
             return true;
 
 
         if (node.parent)
         if (node.parent)
@@ -230,9 +230,14 @@ class NodeInspector extends ScriptWidget {
 
 
         for (var i in components) {
         for (var i in components) {
 
 
+            var component = components[i];
+
+            //if (component.isTemporary())
+            //  continue;
+
             var ci = new ComponentInspector();
             var ci = new ComponentInspector();
 
 
-            ci.inspect(components[i]);
+            ci.inspect(component);
 
 
             nodeLayout.addChild(ci);
             nodeLayout.addChild(ci);
 
 

+ 0 - 0
Script/AtomicEditor/ui/inspector/TextureSelector.ts → Script/AtomicEditor/ui/frames/inspector/TextureSelector.ts


+ 4 - 4
Script/AtomicEditor/ui/HierarchyFrameMenu.ts → Script/AtomicEditor/ui/frames/menus/HierarchyFrameMenu.ts

@@ -1,8 +1,8 @@
 
 
-import strings = require("./EditorStrings");
-import EditorEvents = require("../editor/EditorEvents");
-import EditorUI = require("./EditorUI");
-import MenuItemSources = require("./menus/MenuItemSources");
+import strings = require("ui/EditorStrings");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import MenuItemSources = require("./MenuItemSources");
 
 
 class HierarchyFrameMenus extends Atomic.ScriptObject {
 class HierarchyFrameMenus extends Atomic.ScriptObject {
 
 

+ 4 - 4
Script/AtomicEditor/ui/MainFrameMenu.ts → Script/AtomicEditor/ui/frames/menus/MainFrameMenu.ts

@@ -1,8 +1,8 @@
 
 
-import strings = require("./EditorStrings");
-import EditorEvents = require("../editor/EditorEvents");
-import EditorUI = require("./EditorUI");
-import MenuItemSources = require("./menus/MenuItemSources");
+import strings = require("ui/EditorStrings");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import MenuItemSources = require("./MenuItemSources");
 
 
 class MainFrameMenu extends Atomic.ScriptObject {
 class MainFrameMenu extends Atomic.ScriptObject {
 
 

+ 3 - 3
Script/AtomicEditor/ui/menus/MenuItemSources.ts → Script/AtomicEditor/ui/frames/menus/MenuItemSources.ts

@@ -1,7 +1,7 @@
 
 
-import strings = require("../EditorStrings");
-import EditorEvents = require("../../editor/EditorEvents");
-import EditorUI = require("../EditorUI");
+import strings = require("ui/EditorStrings");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
 
 
 var UIMenuItemSource = Atomic.UIMenuItemSource;
 var UIMenuItemSource = Atomic.UIMenuItemSource;
 var UIMenuItem = Atomic.UIMenuItem;
 var UIMenuItem = Atomic.UIMenuItem;

+ 4 - 4
Script/AtomicEditor/ui/ProjectFrameMenu.ts → Script/AtomicEditor/ui/frames/menus/ProjectFrameMenu.ts

@@ -1,8 +1,8 @@
 
 
-import strings = require("./EditorStrings");
-import EditorEvents = require("../editor/EditorEvents");
-import EditorUI = require("./EditorUI");
-import MenuItemSources = require("./menus/MenuItemSources");
+import strings = require("ui/EditorStrings");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import MenuItemSources = require("./MenuItemSources");
 
 
 class ProjectFrameMenus extends Atomic.ScriptObject {
 class ProjectFrameMenus extends Atomic.ScriptObject {
 
 

+ 4 - 4
Script/AtomicEditor/ui/modal/ModalOps.ts

@@ -4,10 +4,10 @@ import About = require("./About");
 import NewProject = require("./NewProject");
 import NewProject = require("./NewProject");
 import CreateProject = require("./CreateProject");
 import CreateProject = require("./CreateProject");
 
 
-import EULAWindow = require("../license/EULAWindow");
-import ActivationWindow = require("../license/ActivationWindow");
-import ActivationSuccessWindow = require("../license/ActivationSuccessWindow");
-import ManageLicense = require("../license/ManageLicense");
+import EULAWindow = require("./license/EULAWindow");
+import ActivationWindow = require("./license/ActivationWindow");
+import ActivationSuccessWindow = require("./license/ActivationSuccessWindow");
+import ManageLicense = require("./license/ManageLicense");
 
 
 import ResourceSelection = require("./ResourceSelection");
 import ResourceSelection = require("./ResourceSelection");
 
 

+ 2 - 2
Script/AtomicEditor/ui/modal/UIResourceOps.ts

@@ -1,7 +1,7 @@
-import EditorEvents = require("../../editor/EditorEvents");
+import EditorEvents = require("editor/EditorEvents");
 import EditorUI = require("../EditorUI");
 import EditorUI = require("../EditorUI");
 import ModalWindow = require("./ModalWindow");
 import ModalWindow = require("./ModalWindow");
-import ResourceOps = require("../../resources/ResourceOps");
+import ResourceOps = require("resources/ResourceOps");
 
 
 export class ResourceDelete extends ModalWindow {
 export class ResourceDelete extends ModalWindow {
 
 

+ 3 - 3
Script/AtomicEditor/ui/license/ActivationSuccessWindow.ts → Script/AtomicEditor/ui/modal/license/ActivationSuccessWindow.ts

@@ -1,7 +1,7 @@
 
 
-import EditorEvents = require("../../editor/EditorEvents");
-import EditorUI = require("../EditorUI");
-import ModalWindow = require("../modal/ModalWindow");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import ModalWindow = require("../ModalWindow");
 
 
 class ActivationSuccessWindow extends ModalWindow {
 class ActivationSuccessWindow extends ModalWindow {
 
 

+ 4 - 4
Script/AtomicEditor/ui/license/ActivationWindow.ts → Script/AtomicEditor/ui/modal/license/ActivationWindow.ts

@@ -1,8 +1,8 @@
 
 
-import EditorEvents = require("../../editor/EditorEvents");
-import EditorUI = require("../EditorUI");
-import ModalWindow = require("../modal/ModalWindow");
-import ProgressModal = require("../modal/ProgressModal");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import ModalWindow = require("../ModalWindow");
+import ProgressModal = require("../ProgressModal");
 
 
 class ActivationWidow extends ModalWindow {
 class ActivationWidow extends ModalWindow {
 
 

+ 3 - 3
Script/AtomicEditor/ui/license/EULAWindow.ts → Script/AtomicEditor/ui/modal/license/EULAWindow.ts

@@ -1,7 +1,7 @@
 
 
-import EditorEvents = require("../../editor/EditorEvents");
-import EditorUI = require("../EditorUI");
-import ModalWindow = require("../modal/ModalWindow");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import ModalWindow = require("../ModalWindow");
 
 
 class EULAWindow extends ModalWindow {
 class EULAWindow extends ModalWindow {
 
 

+ 4 - 4
Script/AtomicEditor/ui/license/ManageLicense.ts → Script/AtomicEditor/ui/modal/license/ManageLicense.ts

@@ -1,8 +1,8 @@
 
 
-import EditorEvents = require("../../editor/EditorEvents");
-import EditorUI = require("../EditorUI");
-import ModalWindow = require("../modal/ModalWindow");
-import ProgressModal = require("../modal/ProgressModal");
+import EditorEvents = require("editor/EditorEvents");
+import EditorUI = require("ui/EditorUI");
+import ModalWindow = require("../ModalWindow");
+import ProgressModal = require("../ProgressModal");
 
 
 class ManageLicense extends ModalWindow {
 class ManageLicense extends ModalWindow {
 
 

+ 1 - 1
Script/Packages/Atomic/Atomic2D.json

@@ -14,7 +14,7 @@
 				 "Light2DGroup", "Light2D", "DirectionalLight2D", "PositionalLight2D", "PointLight2D"],
 				 "Light2DGroup", "Light2D", "DirectionalLight2D", "PositionalLight2D", "PointLight2D"],
 	"overloads" : {
 	"overloads" : {
 		"AnimatedSprite2D" : {
 		"AnimatedSprite2D" : {
-			"SetAnimation" : ["AnimationSet2D", "String", "LoopMode2D"]
+			"SetAnimation" : ["String", "LoopMode2D"]
 		},
 		},
 		"CollisionBox2D" : {
 		"CollisionBox2D" : {
 			"SetSize" : ["Vector2"]
 			"SetSize" : ["Vector2"]

+ 7 - 0
Script/Packages/Atomic/Atomic3D.json

@@ -17,6 +17,13 @@
 			"AnimationState" : ["AnimatedModel", "Animation"]
 			"AnimationState" : ["AnimatedModel", "Animation"]
 		}
 		}
 
 
+	},
+	"typescript_decl" : {
+
+		"StaticModel" : [
+			"setMaterialIndex(index:number, material:Material);"
+		]
 	}
 	}
 
 
+
 }
 }

+ 3 - 1
Script/Packages/Atomic/Scene.json

@@ -39,7 +39,9 @@
 			"getComponents(componentType?:string, recursive?:boolean):Component[];",
 			"getComponents(componentType?:string, recursive?:boolean):Component[];",
 			"getChildAtIndex(index:number):Node;",
 			"getChildAtIndex(index:number):Node;",
 			"createJSComponent(name:string, args?:{});",
 			"createJSComponent(name:string, args?:{});",
-			"getJSComponent(name:string):JSComponent;"
+			"getJSComponent(name:string):JSComponent;",
+			"createChildPrefab(childName:string, prefabPath:string):Node;",
+			"loadPrefab(prefabPath:string):boolean;"
 		],
 		],
 		"Scene" : [
 		"Scene" : [
 			"getMainCamera():Camera;"
 			"getMainCamera():Camera;"

+ 13 - 8
Script/TypeScript/Atomic.d.ts

@@ -1800,6 +1800,8 @@ declare module Atomic {
       getChildAtIndex(index:number):Node;
       getChildAtIndex(index:number):Node;
       createJSComponent(name:string, args?:{});
       createJSComponent(name:string, args?:{});
       getJSComponent(name:string):JSComponent;
       getJSComponent(name:string):JSComponent;
+      createChildPrefab(childName:string, prefabPath:string):Node;
+      loadPrefab(prefabPath:string):boolean;
 
 
    }
    }
 
 
@@ -1824,7 +1826,6 @@ declare module Atomic {
    export class PrefabComponent extends Component {
    export class PrefabComponent extends Component {
 
 
       prefabGUID: string;
       prefabGUID: string;
-      prefabNode: Node;
 
 
       // Construct.
       // Construct.
       constructor();
       constructor();
@@ -1834,7 +1835,6 @@ declare module Atomic {
       savePrefab(): boolean;
       savePrefab(): boolean;
       undoPrefab(): void;
       undoPrefab(): void;
       breakPrefab(): void;
       breakPrefab(): void;
-      getPrefabNode(): Node;
 
 
    }
    }
 
 
@@ -4292,6 +4292,7 @@ declare module Atomic {
       isInside(point: Vector3): boolean;
       isInside(point: Vector3): boolean;
       // Determines if the given local space point is within the model geometry.
       // Determines if the given local space point is within the model geometry.
       isInsideLocal(point: Vector3): boolean;
       isInsideLocal(point: Vector3): boolean;
+      setMaterialIndex(index:number, material:Material);
 
 
    }
    }
 
 
@@ -4565,8 +4566,8 @@ declare module Atomic {
       onSetEnabled(): void;
       onSetEnabled(): void;
       // Set speed.
       // Set speed.
       setSpeed(speed: number): void;
       setSpeed(speed: number): void;
-      // Set animation by animation set, name and loop mode.
-      setAnimation(animationSet: AnimationSet2D, name: string, loopMode?: LoopMode2D): void;
+      // Set animation by name and loop mode.
+      setAnimation(name: string, loopMode?: LoopMode2D): void;
       // Set animation set.
       // Set animation set.
       setAnimationSet(animationSet: AnimationSet2D): void;
       setAnimationSet(animationSet: AnimationSet2D): void;
       // Set loop mode.
       // Set loop mode.
@@ -5175,7 +5176,7 @@ declare module Atomic {
 
 
    export class Light2D extends Component {
    export class Light2D extends Component {
 
 
-      lightGroup: Light2DGroup;
+      lightGroupID: number;
       color: Color;
       color: Color;
       numRays: number;
       numRays: number;
       lightType: LightType2D;
       lightType: LightType2D;
@@ -5187,8 +5188,8 @@ declare module Atomic {
       // Construct.
       // Construct.
       constructor();
       constructor();
 
 
-      setLightGroup(group: Light2DGroup): void;
-      getLightGroup(): Light2DGroup;
+      setLightGroupID(id: number): void;
+      getLightGroupID(): number;
       getColor(): Color;
       getColor(): Color;
       setColor(color: Color): void;
       setColor(color: Color): void;
       updateVertices(): void;
       updateVertices(): void;
@@ -5246,17 +5247,20 @@ declare module Atomic {
 
 
       physicsWorld: PhysicsWorld2D;
       physicsWorld: PhysicsWorld2D;
       ambientColor: Color;
       ambientColor: Color;
+      lightGroupID: number;
       frustumBox: BoundingBox;
       frustumBox: BoundingBox;
 
 
       // Construct.
       // Construct.
       constructor();
       constructor();
 
 
-      setPhysicsWorld(physicsWorld: PhysicsWorld2D): void;
       getPhysicsWorld(): PhysicsWorld2D;
       getPhysicsWorld(): PhysicsWorld2D;
       addLight2D(light: Light2D): void;
       addLight2D(light: Light2D): void;
+      removeLight2D(light: Light2D): void;
       setDirty(): void;
       setDirty(): void;
       setAmbientColor(color: Color): void;
       setAmbientColor(color: Color): void;
       getAmbientColor(): Color;
       getAmbientColor(): Color;
+      setLightGroupID(id: number): void;
+      getLightGroupID(): number;
       getFrustumBox(): BoundingBox;
       getFrustumBox(): BoundingBox;
 
 
    }
    }
@@ -7121,6 +7125,7 @@ declare module Atomic {
       addRootItem(text: string, icon: string, id: string): number;
       addRootItem(text: string, icon: string, id: string): number;
       addChildItem(parentItemID: number, text: string, icon: string, id: string): number;
       addChildItem(parentItemID: number, text: string, icon: string, id: string): number;
       setItemText(id: string, text: string): void;
       setItemText(id: string, text: string): void;
+      setItemTextSkin(id: string, skin: string): void;
       setItemIcon(id: string, icon: string): void;
       setItemIcon(id: string, icon: string): void;
       deleteItemByID(id: string): void;
       deleteItemByID(id: string): void;
       setExpanded(itemID: number, value: boolean): void;
       setExpanded(itemID: number, value: boolean): void;

+ 3 - 0
Script/TypeScript/AtomicPlayer.d.ts

@@ -13,10 +13,13 @@ declare module AtomicPlayer {
 
 
    export class Player extends Atomic.AObject {
    export class Player extends Atomic.AObject {
 
 
+      currentScene: Atomic.Scene;
+
       // Construct.
       // Construct.
       constructor();
       constructor();
 
 
       loadScene(filename: string, camera?: Atomic.Camera): Atomic.Scene;
       loadScene(filename: string, camera?: Atomic.Camera): Atomic.Scene;
+      getCurrentScene(): Atomic.Scene;
 
 
    }
    }
 
 

+ 17 - 0
Script/TypeScript/AtomicWork.d.ts

@@ -127,6 +127,22 @@ declare module Atomic {
 
 
     }
     }
 
 
+    export interface ComponentAddedEvent {
+
+        scene: Atomic.Scene;
+        node: Atomic.Node;
+        component: Atomic.Component;
+
+    }
+
+    export interface ComponentRemovedEvent {
+
+        scene: Atomic.Scene;
+        node: Atomic.Node;
+        component: Atomic.Component;
+
+    }
+
     export interface IPCJSErrorEvent {
     export interface IPCJSErrorEvent {
 
 
         errorName: string;
         errorName: string;
@@ -144,6 +160,7 @@ declare module Atomic {
         mode: number; // AM_*
         mode: number; // AM_*
         defaultValue: string;
         defaultValue: string;
         enumNames: string[];
         enumNames: string[];
+        resourceTypeName: string;
 
 
     }
     }
 
 

+ 45 - 33
Script/TypeScript/ToolCore.d.ts

@@ -88,17 +88,6 @@ declare module ToolCore {
 
 
    }
    }
 
 
-   export class ProjectFile extends Atomic.AObject {
-
-      // Construct.
-      constructor();
-
-      save(project: Project): void;
-      load(project: Project): boolean;
-      writeNewProject(fullpath: string): void;
-
-   }
-
    export class Project extends Atomic.AObject {
    export class Project extends Atomic.AObject {
 
 
       resourcePath: string;
       resourcePath: string;
@@ -143,6 +132,17 @@ declare module ToolCore {
 
 
    }
    }
 
 
+   export class ProjectFile extends Atomic.AObject {
+
+      // Construct.
+      constructor();
+
+      save(project: Project): void;
+      load(project: Project): boolean;
+      writeNewProject(fullpath: string): void;
+
+   }
+
    export class Platform extends Atomic.AObject {
    export class Platform extends Atomic.AObject {
 
 
       name: string;
       name: string;
@@ -227,7 +227,7 @@ declare module ToolCore {
 
 
       load(assetPath: string): boolean;
       load(assetPath: string): boolean;
       getErrorMessage(): string;
       getErrorMessage(): string;
-      exportModel(outName: string, animName?: string, animationOnly?: boolean): void;
+      exportModel(outName: string, animName?: string, animationOnly?: boolean): boolean;
       setImportNode(node: Atomic.Node): void;
       setImportNode(node: Atomic.Node): void;
       setStartTime(startTime: number): void;
       setStartTime(startTime: number): void;
       setEndTime(endTime: number): void;
       setEndTime(endTime: number): void;
@@ -237,34 +237,15 @@ declare module ToolCore {
 
 
    }
    }
 
 
-   export class AssetDatabase extends Atomic.AObject {
-
-      cachePath: string;
-
-      // Construct.
-      constructor();
-
-      getAssetByGUID(guid: string): Asset;
-      getAssetByPath(path: string): Asset;
-      getAssetByCachePath(cachePath: string): Asset;
-      generateAssetGUID(): string;
-      registerGUID(guid: string): void;
-      getCachePath(): string;
-      deleteAsset(asset: Asset): void;
-      scan(): void;
-      getDotAssetFilename(path: string): string;
-      getFolderAssets(folder:string):ToolCore.Asset[];
-      getAssetsByImporterType(type:string):ToolCore.Asset[];
-
-   }
-
    export class Asset extends Atomic.AObject {
    export class Asset extends Atomic.AObject {
 
 
       guid: string;
       guid: string;
       name: string;
       name: string;
       path: string;
       path: string;
+      extension: string;
       relativePath: string;
       relativePath: string;
       cachePath: string;
       cachePath: string;
+      resource: Atomic.Resource;
       importerType: string;
       importerType: string;
       importerTypeName: string;
       importerTypeName: string;
       importer: AssetImporter;
       importer: AssetImporter;
@@ -282,9 +263,11 @@ declare module ToolCore {
       getGUID(): string;
       getGUID(): string;
       getName(): string;
       getName(): string;
       getPath(): string;
       getPath(): string;
+      getExtension(): string;
       // Get the path relative to project
       // Get the path relative to project
       getRelativePath(): string;
       getRelativePath(): string;
       getCachePath(): string;
       getCachePath(): string;
+      getResource(): Atomic.Resource;
       getImporterType(): string;
       getImporterType(): string;
       getImporterTypeName(): string;
       getImporterTypeName(): string;
       getImporter(): AssetImporter;
       getImporter(): AssetImporter;
@@ -303,9 +286,32 @@ declare module ToolCore {
 
 
    }
    }
 
 
+   export class AssetDatabase extends Atomic.AObject {
+
+      cachePath: string;
+
+      // Construct.
+      constructor();
+
+      getAssetByGUID(guid: string): Asset;
+      getAssetByPath(path: string): Asset;
+      getAssetByCachePath(cachePath: string): Asset;
+      generateAssetGUID(): string;
+      registerGUID(guid: string): void;
+      getCachePath(): string;
+      deleteAsset(asset: Asset): void;
+      scan(): void;
+      getResourceImporterName(resourceTypeName: string): string;
+      getDotAssetFilename(path: string): string;
+      getFolderAssets(folder:string):ToolCore.Asset[];
+      getAssetsByImporterType(type:string):ToolCore.Asset[];
+
+   }
+
    export class AssetImporter extends Atomic.AObject {
    export class AssetImporter extends Atomic.AObject {
 
 
       asset: Asset;
       asset: Asset;
+      resource: Atomic.Resource;
 
 
       // Construct.
       // Construct.
       constructor(asset: Asset);
       constructor(asset: Asset);
@@ -313,6 +319,7 @@ declare module ToolCore {
       setDefaults(): void;
       setDefaults(): void;
       preload(): boolean;
       preload(): boolean;
       getAsset(): Asset;
       getAsset(): Asset;
+      getResource(): Atomic.Resource;
       requiresCacheFile(): boolean;
       requiresCacheFile(): boolean;
 
 
    }
    }
@@ -328,11 +335,14 @@ declare module ToolCore {
 
 
    export class JavascriptImporter extends AssetImporter {
    export class JavascriptImporter extends AssetImporter {
 
 
+      resource: Atomic.Resource;
+
       // Construct.
       // Construct.
       constructor(asset: Asset);
       constructor(asset: Asset);
 
 
       setDefaults(): void;
       setDefaults(): void;
       isComponentFile(): boolean;
       isComponentFile(): boolean;
+      getResource(): Atomic.Resource;
 
 
    }
    }
 
 
@@ -368,6 +378,7 @@ declare module ToolCore {
       scale: number;
       scale: number;
       importAnimations: boolean;
       importAnimations: boolean;
       animationCount: number;
       animationCount: number;
+      resource: Atomic.Resource;
 
 
       // Construct.
       // Construct.
       constructor(asset: Asset);
       constructor(asset: Asset);
@@ -379,6 +390,7 @@ declare module ToolCore {
       setImportAnimations(importAnimations: boolean): void;
       setImportAnimations(importAnimations: boolean): void;
       getAnimationCount(): number;
       getAnimationCount(): number;
       setAnimationCount(count: number): void;
       setAnimationCount(count: number): void;
+      getResource(): Atomic.Resource;
       getAnimationInfo(index: number): AnimationImportInfo;
       getAnimationInfo(index: number): AnimationImportInfo;
 
 
    }
    }

+ 1 - 1
Source/Atomic/Atomic2D/CollisionShape2D.cpp

@@ -285,7 +285,7 @@ void CollisionShape2D::OnNodeSet(Node* node)
             rigidBody_->AddCollisionShape2D(this);
             rigidBody_->AddCollisionShape2D(this);
         }
         }
         else
         else
-            LOGERROR("No right body component in node, can not create collision shape");
+            LOGERROR("No rigid body component in node, can not create collision shape");
     }
     }
 }
 }
 
 

+ 1 - 1
Source/Atomic/Atomic2D/Constraint2D.cpp

@@ -130,7 +130,7 @@ void Constraint2D::OnNodeSet(Node* node)
         ownerBody_ = node->GetComponent<RigidBody2D>();
         ownerBody_ = node->GetComponent<RigidBody2D>();
         if (!ownerBody_)
         if (!ownerBody_)
         {
         {
-            LOGERROR("No right body component in node, can not create constraint");
+            LOGERROR("No rigid body component in node, can not create constraint");
             return;
             return;
         }
         }
     }
     }

+ 185 - 92
Source/Atomic/Atomic2D/Light2D.cpp

@@ -16,6 +16,7 @@
 #include "../Graphics/RenderPath.h"
 #include "../Graphics/RenderPath.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Technique.h"
 #include "../Graphics/Technique.h"
+#include "../Graphics/Zone.h"
 
 
 #include "../Atomic2D/RigidBody2D.h"
 #include "../Atomic2D/RigidBody2D.h"
 #include "../Atomic2D/Renderer2D.h"
 #include "../Atomic2D/Renderer2D.h"
@@ -27,20 +28,16 @@
 namespace Atomic
 namespace Atomic
 {
 {
 
 
-
-static Viewport* __fixmeViewport = NULL;
-void FixMeSetLight2DGroupViewport(Viewport *viewport)
-{
-    __fixmeViewport = viewport;
-}
-
 extern const char* ATOMIC2D_CATEGORY;
 extern const char* ATOMIC2D_CATEGORY;
 
 
 Light2D::Light2D(Context* context) : Component(context),
 Light2D::Light2D(Context* context) : Component(context),
+    lightgroupID_(0),
+    color_(Color::WHITE),
     castShadows_(false),
     castShadows_(false),
     softShadows_(false),
     softShadows_(false),
     softShadowLength_(2.5f),
     softShadowLength_(2.5f),
-    backtrace_(false)
+    backtrace_(false),
+    raysInitialized_(false)
 {
 {
     SetNumRays(32);
     SetNumRays(32);
 }
 }
@@ -52,9 +49,48 @@ Light2D::~Light2D()
 
 
 void Light2D::SetNumRays(int numRays)
 void Light2D::SetNumRays(int numRays)
 {
 {
+    raysInitialized_ = false;
     rays_.Resize(numRays);
     rays_.Resize(numRays);
 }
 }
 
 
+void Light2D::OnSceneSet(Scene* scene)
+{
+    if (scene && !context_->GetEditorContext())
+    {
+        PODVector<Light2DGroup*> lightgroups;
+        scene->GetComponents<Light2DGroup>(lightgroups, true);
+
+        lightgroup_ = 0;
+        for (unsigned i = 0; i < lightgroups.Size(); i++)
+        {
+            Light2DGroup* lightgroup = lightgroups.At(i);
+            if (lightgroup->GetLightGroupID() == lightgroupID_)
+            {
+                lightgroup_ = lightgroup;
+                lightgroup_->AddLight2D(this);
+                break;
+            }
+        }
+
+        if (lightgroup_.Null())
+        {
+            lightgroup_ = node_->CreateComponent<Light2DGroup>();
+            lightgroup_->SetTemporary(true);
+            lightgroup_->AddLight2D(this);
+        }
+    }
+    else
+    {
+        if (lightgroup_)
+        {
+            lightgroup_->RemoveLight2D(this);
+            lightgroup_ = 0;
+        }
+
+    }
+}
+
+
 void Light2D::OnSetEnabled()
 void Light2D::OnSetEnabled()
 {
 {
     Component::OnSetEnabled();
     Component::OnSetEnabled();
@@ -77,10 +113,23 @@ void Light2D::RegisterObject(Context* context)
 {
 {
     context->RegisterFactory<Light2D>(ATOMIC2D_CATEGORY);
     context->RegisterFactory<Light2D>(ATOMIC2D_CATEGORY);
     COPY_BASE_ATTRIBUTES(Component);
     COPY_BASE_ATTRIBUTES(Component);
+
+    ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("LightGroup", GetLightGroupID, SetLightGroupID, int, 0, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Cast Shadows", GetCastShadows, SetCastShadows, bool, false, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Num Rays", GetNumRays, SetNumRays, int, 32, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Soft Shadows", GetSoftShadows, SetSoftShadows, bool, false, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Soft Shadows Length", GetSoftShadowLength, SetSoftShadowLength, float, 2.5f, AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Backtrace", GetBacktrace, SetBacktrace, bool, false, AM_DEFAULT);
+
 }
 }
 
 
 void Light2D::CastRays()
 void Light2D::CastRays()
 {
 {
+    if (!raysInitialized_ || context_->GetEditorContext())
+        return;
+
     PhysicsWorld2D* physicsWorld = lightgroup_->GetPhysicsWorld();
     PhysicsWorld2D* physicsWorld = lightgroup_->GetPhysicsWorld();
 
 
     if (physicsWorld && castShadows_) {
     if (physicsWorld && castShadows_) {
@@ -155,14 +204,17 @@ void DirectionalLight2D::RegisterObject(Context* context)
 {
 {
     context->RegisterFactory<DirectionalLight2D>(ATOMIC2D_CATEGORY);
     context->RegisterFactory<DirectionalLight2D>(ATOMIC2D_CATEGORY);
     COPY_BASE_ATTRIBUTES(Light2D);
     COPY_BASE_ATTRIBUTES(Light2D);
+
+    ACCESSOR_ATTRIBUTE("Direction", GetDirection, SetDirection, float, -45.0f, AM_DEFAULT);
 }
 }
 
 
 void DirectionalLight2D::UpdateVertices()
 void DirectionalLight2D::UpdateVertices()
 {
 {
-    vertices_.Clear();
-
-    if (!lightgroup_ || !enabled_)
+    if (!lightgroup_ || !enabled_ || context_->GetEditorContext())
+    {
+        vertices_.Clear();
         return;
         return;
+    }
 
 
     const BoundingBox& frustumBox = lightgroup_->GetFrustumBox();
     const BoundingBox& frustumBox = lightgroup_->GetFrustumBox();
 
 
@@ -171,6 +223,10 @@ void DirectionalLight2D::UpdateVertices()
 
 
     float width = frustumBox.Size().x_;
     float width = frustumBox.Size().x_;
     float height = frustumBox.Size().y_;
     float height = frustumBox.Size().y_;
+
+    if (!width || !height)
+        return;
+
     float sizeOfScreen = width > height ? width : height;
     float sizeOfScreen = width > height ? width : height;
 
 
     float xAxelOffSet = sizeOfScreen * cos;
     float xAxelOffSet = sizeOfScreen * cos;
@@ -211,6 +267,7 @@ void DirectionalLight2D::UpdateVertices()
         ray.fraction_ = 0.0f;
         ray.fraction_ = 0.0f;
     }
     }
 
 
+    raysInitialized_ = true;
     CastRays();
     CastRays();
 
 
     Vertex2D vertex0;
     Vertex2D vertex0;
@@ -219,36 +276,50 @@ void DirectionalLight2D::UpdateVertices()
     Vertex2D vertex3;
     Vertex2D vertex3;
 
 
     vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt();
     vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt();
+    vertex0.uv_.x_ = 1.0f;
+    vertex2.uv_.x_ = 1.0 ;
+    vertex1.uv_.x_ = 1.0f;
+    vertex3.uv_.x_ = 1.0f;
+
+    int vertexCount = (rayNum - 1) * 6;
+
+    if (softShadows_ && castShadows_)
+        vertexCount *= 2;
+
+    if (vertices_.Size() != vertexCount)
+        vertices_.Resize(vertexCount);
+
+    Vertex2D* v = &vertices_[0];
 
 
     for (unsigned i = 0; i < rayNum - 1; i++) {
     for (unsigned i = 0; i < rayNum - 1; i++) {
 
 
         Light2DRay& ray0 = rays_[i];
         Light2DRay& ray0 = rays_[i];
         Light2DRay& ray1 = rays_[i + 1];
         Light2DRay& ray1 = rays_[i + 1];
 
 
-        vertex0.position_ = Vector3( ray0.start_.x_, ray0.start_.y_, 0.0f);
-        vertex1.position_ = Vector3( ray0.end_.x_, ray0.end_.y_, 0.0f);
-        vertex2.position_ = Vector3( ray1.start_.x_, ray1.start_.y_, 0.0f);
-        vertex3.position_ = Vector3( ray1.end_.x_, ray1.end_.y_, 0.0f);
+        vertex0.position_.x_ = ray0.start_.x_;
+        vertex0.position_.y_ = ray0.start_.y_;
 
 
-        vertex0.uv_.x_ = 1.0f;
-        vertex2.uv_.x_ = 1.0 ;
-        vertex1.uv_.x_ = 1.0f;
-        vertex3.uv_.x_ =  1.0f;
+        vertex1.position_.x_ = ray0.end_.x_;
+        vertex1.position_.y_ = ray0.end_.y_;
+
+        vertex2.position_.x_ = ray1.start_.x_;
+        vertex2.position_.y_ = ray1.start_.y_;
 
 
-        vertices_.Push(vertex0);
-        vertices_.Push(vertex1);
-        vertices_.Push(vertex3);
+        vertex3.position_.x_ = ray1.end_.x_;
+        vertex3.position_.y_ = ray1.end_.y_;
 
 
-        vertices_.Push(vertex0);
-        vertices_.Push(vertex3);
-        vertices_.Push(vertex2);
+        *v++ = vertex0;
+        *v++ = vertex1;
+        *v++ = vertex3;
+
+        *v++ = vertex0;
+        *v++ = vertex3;
+        *v++ = vertex2;
 
 
     }
     }
 
 
     if (softShadows_ && castShadows_)
     if (softShadows_ && castShadows_)
     {
     {
-        unsigned uambient = lightgroup_->GetAmbientColor().ToUInt();
-
         // THIS CAN BE OPTIMIZED!
         // THIS CAN BE OPTIMIZED!
         for (unsigned i = 0; i < rays_.Size() - 1; i++) {
         for (unsigned i = 0; i < rays_.Size() - 1; i++) {
 
 
@@ -280,13 +351,13 @@ void DirectionalLight2D::UpdateVertices()
             vertex1.uv_.x_ = 1.0;
             vertex1.uv_.x_ = 1.0;
             vertex2.uv_.x_ = 1.0;
             vertex2.uv_.x_ = 1.0;
 
 
-            vertices_.Push(vertex0);
-            vertices_.Push(vertex1);
-            vertices_.Push(vertex2);
+            *v++ = vertex0;
+            *v++ = vertex1;
+            *v++ = vertex2;
 
 
-            vertices_.Push(vertex0);
-            vertices_.Push(vertex2);
-            vertices_.Push(vertex3);
+            *v++ = vertex0;
+            *v++ = vertex2;
+            *v++ = vertex3;
 
 
         }
         }
 
 
@@ -307,15 +378,16 @@ PositionalLight2D::~PositionalLight2D()
 void PositionalLight2D::RegisterObject(Context* context)
 void PositionalLight2D::RegisterObject(Context* context)
 {
 {
     context->RegisterFactory<PositionalLight2D>(ATOMIC2D_CATEGORY);
     context->RegisterFactory<PositionalLight2D>(ATOMIC2D_CATEGORY);
-    COPY_BASE_ATTRIBUTES(Light2D);
+    COPY_BASE_ATTRIBUTES(Light2D);    
 }
 }
 
 
 void PositionalLight2D::UpdateVertices()
 void PositionalLight2D::UpdateVertices()
 {
 {
-    vertices_.Clear();
-
-    if (!lightgroup_ || !enabled_)
+    if (!lightgroup_ || !enabled_ || context_->GetEditorContext())
+    {
+        vertices_.Clear();
         return;
         return;
+    }
 
 
     CastRays();
     CastRays();
 
 
@@ -326,22 +398,37 @@ void PositionalLight2D::UpdateVertices()
 
 
     vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt();
     vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt();
 
 
+    int vertexCount = (rays_.Size() - 1 ) * 3;
+
+    if (softShadows_ && castShadows_)
+        vertexCount += (rays_.Size() - 1) * 6;
+
+    if (vertices_.Size() != vertexCount)
+        vertices_.Resize(vertexCount);
+
+    Vertex2D* v = &vertices_[0];
+
     for (unsigned i = 0; i < rays_.Size() - 1; i++) {
     for (unsigned i = 0; i < rays_.Size() - 1; i++) {
 
 
         Light2DRay& ray0 = rays_[i];
         Light2DRay& ray0 = rays_[i];
         Light2DRay& ray1 = rays_[i + 1];
         Light2DRay& ray1 = rays_[i + 1];
 
 
-        vertex0.position_ = Vector3( ray0.start_.x_, ray0.start_.y_, 0.0f);
-        vertex1.position_ = Vector3( ray0.end_.x_, ray0.end_.y_, 0.0f);
-        vertex2.position_ = Vector3( ray1.end_.x_, ray1.end_.y_, 0.0f);
+        vertex0.position_.x_ = ray0.start_.x_;
+        vertex0.position_.y_ = ray0.start_.y_;
+
+        vertex1.position_.x_ = ray0.end_.x_;
+        vertex1.position_.y_ = ray0.end_.y_;
+
+        vertex2.position_.x_ = ray1.end_.x_;
+        vertex2.position_.y_ = ray1.end_.y_;
 
 
         vertex0.uv_.x_ = 1.0f;
         vertex0.uv_.x_ = 1.0f;
         vertex1.uv_.x_ =  1.0f - ray0.fraction_;
         vertex1.uv_.x_ =  1.0f - ray0.fraction_;
         vertex2.uv_.x_ =  1.0f - ray1.fraction_;
         vertex2.uv_.x_ =  1.0f - ray1.fraction_;
 
 
-        vertices_.Push(vertex0);
-        vertices_.Push(vertex1);
-        vertices_.Push(vertex2);
+        *v++ = vertex0;
+        *v++ = vertex1;
+        *v++ = vertex2;
 
 
     }
     }
 
 
@@ -356,16 +443,17 @@ void PositionalLight2D::UpdateVertices()
             float s0 = (1.0f - ray0.fraction_);
             float s0 = (1.0f - ray0.fraction_);
             float s1 = (1.0f - ray1.fraction_);
             float s1 = (1.0f - ray1.fraction_);
 
 
-            vertex0.position_ = Vector3( ray0.end_.x_, ray0.end_.y_, 0.0f);
-
-            vertex1.position_ = Vector3( ray0.end_.x_ + s0 * softShadowLength_ * ray0.cos_,
-                                         (ray0.end_.y_ + s0 * softShadowLength_ * ray0.sin_), 0.0f);
+            vertex0.position_.x_ = ray0.end_.x_;
+            vertex0.position_.y_ = ray0.end_.y_;
 
 
+            vertex1.position_.x_ = ray0.end_.x_ + s0 * softShadowLength_ * ray0.cos_;
+            vertex1.position_.y_ = ray0.end_.y_ + s0 * softShadowLength_ * ray0.sin_;
 
 
-            vertex2.position_ = Vector3( ray1.end_.x_ + s1 * softShadowLength_ * ray1.cos_,
-                                         (ray1.end_.y_ + s1 * softShadowLength_ * ray1.sin_), 0.0f);
+            vertex2.position_.x_ = ray1.end_.x_ + s1 * softShadowLength_ * ray1.cos_;
+            vertex2.position_.y_ = ray1.end_.y_ + s1 * softShadowLength_ * ray1.sin_;
 
 
-            vertex3.position_ = Vector3( ray1.end_.x_, ray1.end_.y_, 0.0f);
+            vertex3.position_.x_ = ray1.end_.x_;
+            vertex3.position_.y_ = ray1.end_.y_;
 
 
             vertex1.uv_.x_ = 0;
             vertex1.uv_.x_ = 0;
             vertex2.uv_.x_ = 0;
             vertex2.uv_.x_ = 0;
@@ -375,13 +463,13 @@ void PositionalLight2D::UpdateVertices()
             vertex0.uv_.x_ = s0 * .65f;
             vertex0.uv_.x_ = s0 * .65f;
             vertex3.uv_.x_ = s1 * .65f;
             vertex3.uv_.x_ = s1 * .65f;
 
 
-            vertices_.Push(vertex0);
-            vertices_.Push(vertex1);
-            vertices_.Push(vertex2);
+            *v++ = vertex0;
+            *v++ = vertex1;
+            *v++ = vertex2;
 
 
-            vertices_.Push(vertex0);
-            vertices_.Push(vertex2);
-            vertices_.Push(vertex3);
+            *v++ = vertex0;
+            *v++ = vertex2;
+            *v++ = vertex3;
 
 
         }
         }
 
 
@@ -389,7 +477,7 @@ void PositionalLight2D::UpdateVertices()
 }
 }
 
 
 PointLight2D::PointLight2D(Context* context) : PositionalLight2D(context),
 PointLight2D::PointLight2D(Context* context) : PositionalLight2D(context),
-    radius_(1.0f)
+    radius_(4.0f)
 {
 {
     lightType_ = LIGHT2D_POINT;
     lightType_ = LIGHT2D_POINT;
 }
 }
@@ -403,18 +491,19 @@ void PointLight2D::RegisterObject(Context* context)
 {
 {
     context->RegisterFactory<PointLight2D>(ATOMIC2D_CATEGORY);
     context->RegisterFactory<PointLight2D>(ATOMIC2D_CATEGORY);
     COPY_BASE_ATTRIBUTES(PositionalLight2D);
     COPY_BASE_ATTRIBUTES(PositionalLight2D);
+
+    ACCESSOR_ATTRIBUTE("Radius", GetRadius, SetRadius, float, 4.0f, AM_DEFAULT);
 }
 }
 
 
 void PointLight2D::UpdateVertices()
 void PointLight2D::UpdateVertices()
 {
 {
-    vertices_.Clear();
+    const Node* lightNode = GetNode();
 
 
-    if (!lightgroup_ || !enabled_)
+    if (!lightgroup_ || !enabled_ || !lightNode || context_->GetEditorContext())
+    {
+        vertices_.Clear();
         return;
         return;
-
-    const PhysicsWorld2D* physicsWorld = lightgroup_->GetPhysicsWorld();
-
-    const Node* lightNode = GetNode();
+    }
 
 
     Vector2 start = lightNode->GetWorldPosition2D();
     Vector2 start = lightNode->GetWorldPosition2D();
 
 
@@ -430,6 +519,7 @@ void PointLight2D::UpdateVertices()
         ray.fraction_ = 1.0f;
         ray.fraction_ = 1.0f;
     }
     }
 
 
+    raysInitialized_ = true;
     PositionalLight2D::UpdateVertices();
     PositionalLight2D::UpdateVertices();
 
 
 }
 }
@@ -443,31 +533,28 @@ void Light2DGroup::RegisterObject(Context* context)
 
 
 
 
 
 
-void Light2DGroup::OnNodeSet(Node* node)
+void Light2DGroup::OnSceneSet(Scene* scene)
 {
 {
-    // Do not call Drawable2D::OnNodeSet(node)
 
 
-    if (node)
+    if (scene && node_ && !context_->GetEditorContext())
     {
     {
-        if (renderer_.Null())
-        {
-            renderer_ = node->GetOrCreateComponent<Renderer2D>();
-            renderer_->SetUseTris(true);
-        }
+        physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld2D>();
 
 
-        if (light2DMaterial_.Null())
-            CreateLight2DMaterial();
+        Zone* zone = scene->GetComponent<Zone>();
+        if (zone)
+            SetAmbientColor(zone->GetAmbientColor());
 
 
-        Scene* scene = GetScene();
-        if (scene)
-        {
-            if (IsEnabledEffective())
-                renderer_->AddDrawable(this);
-        }
+        renderer_ = node_->GetOrCreateComponent<Renderer2D>();
+        renderer_->SetTemporary(true);
+        renderer_->SetUseTris(true);
 
 
-        node->AddListener(this);
+        if (light2DMaterial_.Null())
+            CreateLight2DMaterial();
 
 
+        if (IsEnabledEffective())
+            renderer_->AddDrawable(this);
 
 
+        node_->AddListener(this);
     }
     }
     else
     else
     {
     {
@@ -478,6 +565,7 @@ void Light2DGroup::OnNodeSet(Node* node)
 }
 }
 
 
 Light2DGroup::Light2DGroup(Context* context) : Drawable2D(context),
 Light2DGroup::Light2DGroup(Context* context) : Drawable2D(context),
+    lightgroupID_(0),
     ambientColor_(0, 0, 0, 0),
     ambientColor_(0, 0, 0, 0),
     frustum_(0)
     frustum_(0)
 {
 {
@@ -492,7 +580,7 @@ Light2DGroup::~Light2DGroup()
 
 
     if (renderer)
     if (renderer)
     {
     {
-        Viewport* viewport = __fixmeViewport ? __fixmeViewport :  renderer->GetViewport(0);
+        Viewport* viewport = renderer->GetViewport(0);
         if (viewport)
         if (viewport)
         {
         {
             RenderPath* renderpath = viewport->GetRenderPath();
             RenderPath* renderpath = viewport->GetRenderPath();
@@ -502,8 +590,6 @@ Light2DGroup::~Light2DGroup()
 
 
     }
     }
 
 
-    __fixmeViewport = NULL;
-
 }
 }
 
 
 void Light2DGroup::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
 void Light2DGroup::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
@@ -568,21 +654,26 @@ void Light2DGroup::UpdateSourceBatches()
 
 
 void Light2DGroup::AddLight2D(Light2D* light)
 void Light2DGroup::AddLight2D(Light2D* light)
 {
 {
-    for (Vector<WeakPtr<Light2D> >::ConstIterator itr = lights_.Begin(); itr != lights_.End(); itr++)
-        if (*itr == light)
-            return;
+    Vector<WeakPtr<Light2D>>::Iterator itr = lights_.Find(WeakPtr<Light2D>(light));
 
 
-    light->SetLightGroup(this);
+    if (itr != lights_.End())
+        return;
 
 
     lights_.Push(WeakPtr<Light2D>(light));
     lights_.Push(WeakPtr<Light2D>(light));
 
 
 }
 }
 
 
-void Light2DGroup::SetPhysicsWorld(PhysicsWorld2D* physicsWorld)
+void Light2DGroup::RemoveLight2D(Light2D* light)
 {
 {
-    physicsWorld_ = physicsWorld;
+
+    Vector<WeakPtr<Light2D>>::Iterator itr = lights_.Find(WeakPtr<Light2D>(light));
+
+    if (itr != lights_.End())
+        lights_.Erase(itr);
+
 }
 }
 
 
+
 void Light2DGroup::SetAmbientColor(const Color& color)
 void Light2DGroup::SetAmbientColor(const Color& color)
 {
 {
     if (color == ambientColor_)
     if (color == ambientColor_)
@@ -594,7 +685,7 @@ void Light2DGroup::SetAmbientColor(const Color& color)
     // only on main viewport atm and viewport must first be set
     // only on main viewport atm and viewport must first be set
     if (renderer)
     if (renderer)
     {
     {
-        Viewport* viewport = __fixmeViewport ? __fixmeViewport :  renderer->GetViewport(0);
+        Viewport* viewport = renderer->GetViewport(0);
         if (viewport)
         if (viewport)
         {
         {
             RenderPath* renderpath = viewport->GetRenderPath();
             RenderPath* renderpath = viewport->GetRenderPath();
@@ -606,9 +697,11 @@ void Light2DGroup::SetAmbientColor(const Color& color)
 
 
 void Light2DGroup::CreateLight2DMaterial()
 void Light2DGroup::CreateLight2DMaterial()
 {
 {
+    if (context_->GetEditorContext())
+        return;
+
     Renderer* renderer = GetSubsystem<Renderer>();
     Renderer* renderer = GetSubsystem<Renderer>();
-    // only on main viewport atm and viewport must first be set
-    Viewport* viewport = __fixmeViewport ? __fixmeViewport :  renderer->GetViewport(0);
+    Viewport* viewport = renderer->GetViewport(0);
     RenderPath* renderpath = viewport->GetRenderPath();
     RenderPath* renderpath = viewport->GetRenderPath();
 
 
     RenderTargetInfo ntarget;
     RenderTargetInfo ntarget;

+ 18 - 9
Source/Atomic/Atomic2D/Light2D.h

@@ -42,18 +42,18 @@ public:
     /// Register object factory
     /// Register object factory
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
 
 
-    void SetLightGroup(Light2DGroup* group) { lightgroup_ = group; }
-    Light2DGroup* GetLightGroup() { return lightgroup_; }
+    void SetLightGroupID(int id) { lightgroupID_ = id; }
+    int GetLightGroupID() const { return lightgroupID_; }
 
 
     const Color& GetColor() const { return color_; }
     const Color& GetColor() const { return color_; }
     void SetColor(const Color& color) { color_ = color; }
     void SetColor(const Color& color) { color_ = color; }
 
 
-    void AddVertices(Vector<Vertex2D>& vertices);
+    void AddVertices(Vector<Vertex2D> &vertices);
 
 
     virtual void UpdateVertices() {}
     virtual void UpdateVertices() {}
 
 
     void SetNumRays(int numRays);
     void SetNumRays(int numRays);
-    unsigned GetNumRays() const { return rays_.Size(); }
+    int GetNumRays() const { return (int) rays_.Size(); }
 
 
     virtual void OnSetEnabled();
     virtual void OnSetEnabled();
 
 
@@ -73,15 +73,20 @@ public:
 
 
 protected:
 protected:
 
 
+    void OnSceneSet(Scene* scene);
+
     void CastRays();
     void CastRays();
 
 
+    int lightgroupID_;
     WeakPtr<Light2DGroup> lightgroup_;
     WeakPtr<Light2DGroup> lightgroup_;
+
     Color color_;
     Color color_;
     bool castShadows_;
     bool castShadows_;
     bool softShadows_;
     bool softShadows_;
     bool backtrace_;
     bool backtrace_;
     float softShadowLength_;
     float softShadowLength_;
     PODVector<Light2DRay> rays_;
     PODVector<Light2DRay> rays_;
+    bool raysInitialized_;
     Vector<Vertex2D> vertices_;
     Vector<Vertex2D> vertices_;
     LightType2D lightType_;
     LightType2D lightType_;
 };
 };
@@ -168,10 +173,11 @@ public:
     /// Register object factory. drawable2d must be registered first.
     /// Register object factory. drawable2d must be registered first.
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
 
 
-    void SetPhysicsWorld(PhysicsWorld2D* physicsWorld);
     PhysicsWorld2D* GetPhysicsWorld() { return physicsWorld_; }
     PhysicsWorld2D* GetPhysicsWorld() { return physicsWorld_; }
 
 
     void AddLight2D(Light2D* light);
     void AddLight2D(Light2D* light);
+    void RemoveLight2D(Light2D* light);
+
     Vector<WeakPtr<Light2D> >& GetLights() { return lights_; }
     Vector<WeakPtr<Light2D> >& GetLights() { return lights_; }
 
 
     void SetDirty() { /*verticesDirty_ = true;*/ }
     void SetDirty() { /*verticesDirty_ = true;*/ }
@@ -179,6 +185,9 @@ public:
     void SetAmbientColor(const Color& color);
     void SetAmbientColor(const Color& color);
     const Color& GetAmbientColor() { return ambientColor_; }
     const Color& GetAmbientColor() { return ambientColor_; }
 
 
+    void SetLightGroupID(int id) { lightgroupID_ = id; }
+    int GetLightGroupID() const { return lightgroupID_; }
+
     const BoundingBox& GetFrustumBox() const { return frustumBoundingBox_; }
     const BoundingBox& GetFrustumBox() const { return frustumBoundingBox_; }
 
 
 protected:
 protected:
@@ -186,22 +195,22 @@ protected:
     /// Recalculate the world-space bounding box.
     /// Recalculate the world-space bounding box.
     void OnWorldBoundingBoxUpdate();
     void OnWorldBoundingBoxUpdate();
 
 
-    void OnNodeSet(Node* node);
+    void OnSceneSet(Scene* scene);
 
 
     /// Handle draw order changed.
     /// Handle draw order changed.
     virtual void OnDrawOrderChanged();
     virtual void OnDrawOrderChanged();
     /// Update source batches.
     /// Update source batches.
     virtual void UpdateSourceBatches();
     virtual void UpdateSourceBatches();
 
 
-
 private:
 private:
 
 
-    Color ambientColor_;
     void HandleBeginRendering(StringHash eventType, VariantMap& eventData);
     void HandleBeginRendering(StringHash eventType, VariantMap& eventData);
     void HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData);
     void HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData);
-
     void CreateLight2DMaterial();
     void CreateLight2DMaterial();
 
 
+    int lightgroupID_;
+    Color ambientColor_;
+
     Vector<WeakPtr<Light2D> > lights_;
     Vector<WeakPtr<Light2D> > lights_;
 
 
     SharedPtr<Material> shadow2DMaterial_;
     SharedPtr<Material> shadow2DMaterial_;

+ 2 - 1
Source/Atomic/Atomic2D/RigidBody2D.cpp

@@ -39,11 +39,12 @@ namespace Atomic
 extern const char* ATOMIC2D_CATEGORY;
 extern const char* ATOMIC2D_CATEGORY;
 static const BodyType2D DEFAULT_BODYTYPE = BT_STATIC;
 static const BodyType2D DEFAULT_BODYTYPE = BT_STATIC;
 
 
+// ATOMIC: Make sure these match box2d order
 static const char* bodyTypeNames[] =
 static const char* bodyTypeNames[] =
 {
 {
     "Static",
     "Static",
-    "Dynamic",
     "Kinematic",
     "Kinematic",
+    "Dynamic",
     0
     0
 };
 };
 
 

+ 1 - 3
Source/Atomic/IO/File.cpp

@@ -535,11 +535,9 @@ void File::ReadText(String& text)
     if (!size_)
     if (!size_)
         return;
         return;
 
 
-    text.Resize(size_ + 1);
+    text.Resize(size_);
 
 
     Read((void*)text.CString(), size_);
     Read((void*)text.CString(), size_);
-
-    text[size_] = '\0';
 }
 }
 
 
 // ATOMIC BEGIN
 // ATOMIC BEGIN

+ 76 - 27
Source/Atomic/Scene/PrefabComponent.cpp

@@ -6,6 +6,7 @@
 #include <Atomic/Resource/ResourceEvents.h>
 #include <Atomic/Resource/ResourceEvents.h>
 
 
 #include <Atomic/Physics/RigidBody.h>
 #include <Atomic/Physics/RigidBody.h>
+#include <Atomic/Atomic2D/AnimatedSprite2D.h>
 
 
 #include "PrefabEvents.h"
 #include "PrefabEvents.h"
 #include "PrefabComponent.h"
 #include "PrefabComponent.h"
@@ -51,15 +52,53 @@ void PrefabComponent::LoadPrefabNode()
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     XMLFile* xmlfile = cache->GetResource<XMLFile>(prefabGUID_);
     XMLFile* xmlfile = cache->GetResource<XMLFile>(prefabGUID_);
 
 
-    prefabNode_->LoadXML(xmlfile->GetRoot());
-    prefabNode_->SetTemporary(true);
+    if (!xmlfile || !node_)
+        return;
+
+    bool temporary = IsTemporary();
+    unsigned id = GetID();
+
+    // We're going to be removed, so keep ourselves alive and
+    // a reference to node_ as we'll readd
+    SharedPtr<PrefabComponent> keepAlive(this);
+    SharedPtr<Node> node(node_);
+
+    // store original transform
+    Vector3 pos = node->GetPosition();
+    Quaternion rot = node->GetRotation();
+    Vector3 scale = node->GetScale();
+
+    node->LoadXML(xmlfile->GetRoot());
+
+    node->SetPosition(pos);
+    node->SetRotation(rot);
+    node->SetScale(scale);
+
+    // Get the root components of the load node
+    const Vector<SharedPtr<Component>>& rootComponents = node->GetComponents();
+
+    // set all loaded components to be temporary, set all loaded root components and
+    // direct children to temporary
+    for (unsigned i = 0; i < rootComponents.Size(); i++)
+    {
+        rootComponents.At(i)->SetTemporary(true);
+    }
+
+    const Vector<SharedPtr<Node> >& children = node->GetChildren();
+
+    for (unsigned i = 0; i < children.Size(); i++)
+    {
+        children.At(i)->SetTemporary(true);
+    }
 
 
-    prefabNode_->SetPosition(Vector3::ZERO);
-    prefabNode_->SetRotation(Quaternion::IDENTITY);
-    // prefabNode_->SetScale(Vector3::ONE);
+    // readd via stored node, which is the same as node_ after this add
+    this->SetTemporary(temporary);
+    node->AddComponent(this, id, REPLICATED);
 
 
+    // Get all the rigid bodies of the load node
     PODVector<RigidBody*> bodies;
     PODVector<RigidBody*> bodies;
-    prefabNode_->GetComponents<RigidBody>(bodies, true);
+    node_->GetComponents<RigidBody>(bodies, true);
+
     for (unsigned i = 0; i < bodies.Size(); i++)
     for (unsigned i = 0; i < bodies.Size(); i++)
     {
     {
         RigidBody* body = bodies[i];
         RigidBody* body = bodies[i];
@@ -73,14 +112,41 @@ void PrefabComponent::BreakPrefab()
     if (!node_ || !node_->GetScene())
     if (!node_ || !node_->GetScene())
         return;
         return;
 
 
-    SharedPtr<PrefabComponent> keepAlive(this);
+    // flip temporary root children and components to break prefab
+    const Vector<SharedPtr<Component>>& rootComponents = node_->GetComponents();
+    const Vector<SharedPtr<Node> >& children = node_->GetChildren();
+    PODVector<Node*> filterNodes;
+
+    for (unsigned i = 0; i < rootComponents.Size(); i++)
+    {
+        if (rootComponents[i]->IsTemporary())
+        {
+            rootComponents[i]->SetTemporary(false);
+
+            // Animated sprites contain a temporary node we don't want to save in the prefab
+            // it would be nice if this was general purpose because have to test this when
+            // saving a prefab as well
+
+            if (rootComponents[i]->GetType() == AnimatedSprite2D::GetTypeStatic())
+            {
+                AnimatedSprite2D* asprite = (AnimatedSprite2D*) rootComponents[i].Get();
+                if (asprite->GetRootNode())
+                    filterNodes.Push(asprite->GetRootNode());
+            }
+
+        }
+    }
 
 
-    if (prefabNode_.NotNull())
-        prefabNode_->SetTemporary(false);
+    for (unsigned i = 0; i < children.Size(); i++)
+    {
+        if (children[i]->IsTemporary() && !filterNodes.Contains(children[i].Get()))
+        {
+            children[i]->SetTemporary(false);
+        }
+    }
 
 
     node_->RemoveComponent(this);
     node_->RemoveComponent(this);
 
 
-
 }
 }
 
 
 void PrefabComponent::HandlePrefabChanged(StringHash eventType, VariantMap& eventData)
 void PrefabComponent::HandlePrefabChanged(StringHash eventType, VariantMap& eventData)
@@ -96,14 +162,7 @@ void PrefabComponent::HandlePrefabChanged(StringHash eventType, VariantMap& even
 
 
 void PrefabComponent::SetPrefabGUID(const String& guid)
 void PrefabComponent::SetPrefabGUID(const String& guid)
 {
 {
-    assert(prefabNode_.Null());
-
-    // ensure to use node_->CreateChild() so in scene, this may be fixed
-    // with update on https://github.com/urho3d/Urho3D/issues/748
-    assert(node_);
-
     prefabGUID_ = guid;
     prefabGUID_ = guid;
-    prefabNode_ = node_->CreateChild();
 
 
     if (prefabGUID_.Length())
     if (prefabGUID_.Length())
     {
     {
@@ -115,16 +174,6 @@ void PrefabComponent::SetPrefabGUID(const String& guid)
 void PrefabComponent::OnNodeSet(Node* node)
 void PrefabComponent::OnNodeSet(Node* node)
 {
 {
     Component::OnNodeSet(node);
     Component::OnNodeSet(node);
-
-
-    if (!node && prefabNode_.NotNull())
-    {
-        // a prefab node might not be temporary is prefab is broken{
-        if (prefabNode_->IsTemporary())
-            prefabNode_->Remove();
-
-        prefabNode_ = NULL;
-    }
 }
 }
 
 
 }
 }

+ 0 - 4
Source/Atomic/Scene/PrefabComponent.h

@@ -7,7 +7,6 @@
 namespace Atomic
 namespace Atomic
 {
 {
 
 
-/// Helper base class for user-defined game logic components that hooks up to update events and forwards them to virtual functions similar to ScriptInstance class.
 class PrefabComponent : public Component
 class PrefabComponent : public Component
 {
 {
     OBJECT(PrefabComponent);
     OBJECT(PrefabComponent);
@@ -29,8 +28,6 @@ public:
     void UndoPrefab();
     void UndoPrefab();
     void BreakPrefab();
     void BreakPrefab();
 
 
-    Node* GetPrefabNode() { return prefabNode_; }
-
 protected:
 protected:
 
 
     /// Handle scene node being assigned at creation.
     /// Handle scene node being assigned at creation.
@@ -43,7 +40,6 @@ private:
 
 
     void LoadPrefabNode();
     void LoadPrefabNode();
 
 
-    SharedPtr<Node> prefabNode_;
     String prefabGUID_;
     String prefabGUID_;
 
 
 };
 };

+ 34 - 1
Source/Atomic/UI/UIListView.cpp

@@ -61,6 +61,7 @@ public:
     }
     }
 
 
     void UpdateText(const String& text);
     void UpdateText(const String& text);
+    void UpdateTextSkin(const String& skin);
     void UpdateIcon(const String& icon);
     void UpdateIcon(const String& icon);
 
 
     ListViewItemSource* source_;
     ListViewItemSource* source_;
@@ -69,6 +70,7 @@ public:
     PODVector<ListViewItem*> children_;
     PODVector<ListViewItem*> children_;
     ListViewItemWidget* widget_;
     ListViewItemWidget* widget_;
     String icon_;
     String icon_;
+    String textSkin_;
 };
 };
 
 
 class ListViewItemWidget : public TBLayout
 class ListViewItemWidget : public TBLayout
@@ -89,6 +91,12 @@ public:
             icon_->SetSkinBg(TBIDC(icon.CString()));
             icon_->SetSkinBg(TBIDC(icon.CString()));
     }
     }
 
 
+    void UpdateTextSkin(const String& skin)
+    {
+        if (textField_)
+            textField_->SetSkinBg(TBIDC(skin.CString()));
+    }
+
 
 
 private:
 private:
     TBCheckBox* expandBox_;
     TBCheckBox* expandBox_;
@@ -126,6 +134,14 @@ void ListViewItem::UpdateIcon(const String& icon)
         widget_->UpdateIcon(icon);
         widget_->UpdateIcon(icon);
 }
 }
 
 
+void ListViewItem::UpdateTextSkin(const String& skin)
+{
+    textSkin_ = skin;
+    if (widget_)
+        widget_->UpdateTextSkin(skin);
+}
+
+
 ListViewItem* ListViewItem::AddChild(const char *text, const char* icon, const TBID &id)
 ListViewItem* ListViewItem::AddChild(const char *text, const char* icon, const TBID &id)
 {
 {
     ListViewItem* child = new ListViewItem(text, id, icon, source_);
     ListViewItem* child = new ListViewItem(text, id, icon, source_);
@@ -237,7 +253,8 @@ ListViewItemWidget::ListViewItemWidget(ListViewItem *item, ListViewItemSource *s
 
 
     TBTextField* tfield = textField_ = new TBTextField();
     TBTextField* tfield = textField_ = new TBTextField();
     tfield->SetIgnoreInput(true);
     tfield->SetIgnoreInput(true);
-    tfield->SetSkinBg(TBIDC("Folder"));
+
+    tfield->SetSkinBg(item->textSkin_.Length() ? TBIDC(item->textSkin_.CString()) : TBIDC("Folder"));
     tfield->SetText(item->str);
     tfield->SetText(item->str);
     tfield->SetFontDescription(fd);
     tfield->SetFontDescription(fd);
 
 
@@ -385,6 +402,22 @@ void UIListView::SetItemText(const String& id, const String& text)
 
 
 }
 }
 
 
+void UIListView::SetItemTextSkin(const String& id, const String& skin)
+{
+    TBID tbid(id.CString());
+
+    for (int i = 0; i <  source_->GetNumItems(); i++)
+    {
+        if (source_->GetItemID(i) == tbid)
+        {
+            ListViewItem* item = source_->GetItem(i);
+            item->UpdateTextSkin(skin);
+            return;
+        }
+    }
+
+}
+
 void UIListView::SetItemIcon(const String& id, const String& icon)
 void UIListView::SetItemIcon(const String& id, const String& icon)
 {
 {
     TBID tbid(id.CString());
     TBID tbid(id.CString());

+ 2 - 1
Source/Atomic/UI/UIListView.h

@@ -27,7 +27,8 @@ public:
 
 
 
 
     void SetItemText(const String& id, const String& text);
     void SetItemText(const String& id, const String& text);
-    void SetItemIcon(const String& id, const String& icon);
+    void SetItemTextSkin(const String& id, const String& skin);
+    void SetItemIcon(const String& id, const String& icon);    
     void DeleteItemByID(const String& id);
     void DeleteItemByID(const String& id);
 
 
     void SetExpanded(unsigned itemID, bool value);
     void SetExpanded(unsigned itemID, bool value);

+ 7 - 7
Source/AtomicEditor/Application/AEEditorApp.cpp

@@ -47,7 +47,7 @@ void AEEditorApp::Start()
 
 
     context_->RegisterSubsystem(new EditorMode(context_));
     context_->RegisterSubsystem(new EditorMode(context_));
 
 
-    vm_->SetModuleSearchPaths("AtomicEditor");
+    vm_->SetModuleSearchPaths("AtomicEditor/out");
 
 
     // Do not create bone structure by default when in the editor
     // Do not create bone structure by default when in the editor
     // this can be toggled temporarily, for example to setup an animation preview
     // this can be toggled temporarily, for example to setup an animation preview
@@ -67,17 +67,17 @@ void AEEditorApp::Start()
     jsapi_init_toolcore(vm_);
     jsapi_init_toolcore(vm_);
     jsapi_init_editor(vm_);
     jsapi_init_editor(vm_);
 
 
-    SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("AtomicEditor/main.js"));
+    SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("AtomicEditor/out/main.js"));
 
 
     if (file.Null())
     if (file.Null())
     {
     {
-        ErrorExit("Unable to load AtomicEditor/main.js");
+        ErrorExit("Unable to load AtomicEditor/out/main.js");
         return;
         return;
     }
     }
 
 
     if (!vm_->ExecuteFile(file))
     if (!vm_->ExecuteFile(file))
     {
     {
-        ErrorExit("Error executing AtomicEditor/main.js");
+        ErrorExit("Error executing AtomicEditor/out/main.js");
         return;
         return;
     }
     }
 
 
@@ -157,10 +157,10 @@ void AEEditorApp::HandleJSError(StringHash eventType, VariantMap& eventData)
     String errMessage = eventData[P_ERRORMESSAGE].GetString();
     String errMessage = eventData[P_ERRORMESSAGE].GetString();
     String errFilename = eventData[P_ERRORFILENAME].GetString();
     String errFilename = eventData[P_ERRORFILENAME].GetString();
     //String errStack = eventData[P_ERRORSTACK].GetString();
     //String errStack = eventData[P_ERRORSTACK].GetString();
-    int errLineNumber = eventData[P_ERRORLINENUMBER].GetInt();
+    int errLineNumber = vm_->GetRealLineNumber("AtomicEditor/out/" + errFilename, eventData[P_ERRORLINENUMBER].GetInt());
+    
+    String errorString = ToString("%s - %s - Line: %i", errFilename.CString(), errMessage.CString(), errLineNumber);
 
 
-    String errorString = ToString("%s - %s - Line: %i",
-                                  errFilename.CString(), errMessage.CString(), errLineNumber);
 
 
     ErrorExit(errorString);
     ErrorExit(errorString);
 
 

+ 35 - 10
Source/AtomicEditor/Editors/SceneEditor3D/SceneView3D.cpp

@@ -36,8 +36,13 @@
 #include <ToolCore/Assets/Asset.h>
 #include <ToolCore/Assets/Asset.h>
 #include <ToolCore/Assets/AssetDatabase.h>
 #include <ToolCore/Assets/AssetDatabase.h>
 #include <ToolCore/Assets/ModelImporter.h>
 #include <ToolCore/Assets/ModelImporter.h>
-
 #include <ToolCore/Assets/PrefabImporter.h>
 #include <ToolCore/Assets/PrefabImporter.h>
+#include <ToolCore/Assets/SpriterImporter.h>
+#include <ToolCore/Assets/TextureImporter.h>
+
+#include <Atomic/Atomic2D/Sprite2D.h>
+#include <Atomic/Atomic2D/AnimationSet2D.h>
+#include <Atomic/Atomic2D/AnimatedSprite2D.h>
 
 
 #include "../../EditorMode/AEEditorEvents.h"
 #include "../../EditorMode/AEEditorEvents.h"
 
 
@@ -490,12 +495,10 @@ void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventD
             dragNode_ = scene_->CreateChild(asset->GetName());
             dragNode_ = scene_->CreateChild(asset->GetName());
             PrefabComponent* pc = dragNode_->CreateComponent<PrefabComponent>();
             PrefabComponent* pc = dragNode_->CreateComponent<PrefabComponent>();
             pc->SetPrefabGUID(asset->GetGUID());
             pc->SetPrefabGUID(asset->GetGUID());
-            dragNode_->SetName(asset->GetName());
-
         }
         }
         else if (importerType == ModelImporter::GetTypeNameStatic())
         else if (importerType == ModelImporter::GetTypeNameStatic())
         {
         {
-            dragNode_ = scene_->CreateChild(asset->GetName());
+            dragNode_ = scene_->CreateChild();
 
 
             SharedPtr<File> file(new File(context_, asset->GetCachePath()));
             SharedPtr<File> file(new File(context_, asset->GetCachePath()));
             SharedPtr<XMLFile> xml(new XMLFile(context_));
             SharedPtr<XMLFile> xml(new XMLFile(context_));
@@ -505,18 +508,40 @@ void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventD
 
 
             dragNode_->LoadXML(xml->GetRoot());
             dragNode_->LoadXML(xml->GetRoot());
             dragNode_->SetName(asset->GetName());
             dragNode_->SetName(asset->GetName());
+        }
+        else if (importerType == SpriterImporter::GetTypeNameStatic())
+        {
+            AnimationSet2D* animationSet = GetSubsystem<ResourceCache>()->GetResource<AnimationSet2D>(asset->GetPath());
+
+            String animationName;
+
+            if (animationSet && animationSet->GetNumAnimations())
+            {
+                animationName = animationSet->GetAnimation(0)->GetName();
+            }
 
 
-            /*
             dragNode_ = scene_->CreateChild(asset->GetName());
             dragNode_ = scene_->CreateChild(asset->GetName());
-            preloadResourceScene_ = new Scene(context_);
 
 
-            SharedPtr<File> file(new File(context_, asset->GetCachePath()));
+            AnimatedSprite2D* sprite = dragNode_->CreateComponent<AnimatedSprite2D>();
+
+            if (!animationName.Length())
+                sprite->SetAnimationSet(animationSet);
+            else
+                sprite->SetAnimation(animationSet, animationName);
+
+        }
+        else if (importerType == TextureImporter::GetTypeNameStatic())
+        {
+            dragNode_ = scene_->CreateChild(asset->GetName());
+
+            Sprite2D* spriteGraphic = GetSubsystem<ResourceCache>()->GetResource<Sprite2D>(asset->GetPath());
 
 
-            preloadResourceScene_->LoadAsyncXML(file, LOAD_RESOURCES_ONLY);
-            dragAssetGUID_ = asset->GetGUID();
-            */
+            StaticSprite2D* sprite = dragNode_->CreateComponent<StaticSprite2D>();
+
+            sprite->SetSprite(spriteGraphic);
         }
         }
 
 
+
         if (dragNode_.NotNull())
         if (dragNode_.NotNull())
         {
         {
             Input* input = GetSubsystem<Input>();
             Input* input = GetSubsystem<Input>();

+ 23 - 0
Source/AtomicJS/Javascript/JSAPI.cpp

@@ -2,6 +2,9 @@
 // Please see LICENSE.md in repository root for license information
 // Please see LICENSE.md in repository root for license information
 // https://github.com/AtomicGameEngine/AtomicGameEngine
 // https://github.com/AtomicGameEngine/AtomicGameEngine
 
 
+#include <Atomic/Core/Context.h>
+#include <Atomic/Resource/ResourceCache.h>
+
 #include "JSAPI.h"
 #include "JSAPI.h"
 #include "JSVM.h"
 #include "JSVM.h"
 
 
@@ -292,6 +295,16 @@ void js_to_variant(duk_context* ctx, int variantIdx, Variant &v)
         return;
         return;
     }
     }
 
 
+    // object check after array
+    if (duk_is_object(ctx, variantIdx))
+    {
+        RefCounted* o = js_to_class_instance<RefCounted>(ctx, variantIdx, 0);
+        if (o)
+            v = o;
+        return;
+    }
+
+
 }
 }
 
 
 
 
@@ -380,6 +393,9 @@ void js_push_variant(duk_context *ctx, const Variant& v)
     Vector3 vector3 = Vector3::ZERO;
     Vector3 vector3 = Vector3::ZERO;
     Vector4 vector4 = Vector4::ZERO;
     Vector4 vector4 = Vector4::ZERO;
     Color color = Color::BLACK;
     Color color = Color::BLACK;
+    Resource* resource = NULL;
+    ResourceCache* cache = NULL;
+    ResourceRef resourceRef;
 
 
     switch (type)
     switch (type)
     {
     {
@@ -419,6 +435,13 @@ void js_push_variant(duk_context *ctx, const Variant& v)
 
 
         break;
         break;
 
 
+    case VAR_RESOURCEREF:
+        resourceRef = v.GetResourceRef();
+        cache = JSVM::GetJSVM(ctx)->GetContext()->GetSubsystem<ResourceCache>();
+        resource = cache->GetResource(resourceRef.type_, resourceRef.name_);
+        js_push_class_object_instance(ctx, resource);
+        break;
+
     case VAR_BOOL:
     case VAR_BOOL:
         duk_push_boolean(ctx, v.GetBool() ? 1 : 0);
         duk_push_boolean(ctx, v.GetBool() ? 1 : 0);
         break;
         break;

+ 6 - 0
Source/AtomicJS/Javascript/JSAtomic.cpp

@@ -21,6 +21,9 @@
 #include "JSCore.h"
 #include "JSCore.h"
 #include "JSFileSystem.h"
 #include "JSFileSystem.h"
 #include "JSGraphics.h"
 #include "JSGraphics.h"
+#ifdef ATOMIC_3D
+#include "JSAtomic3D.h"
+#endif
 #include "JSIO.h"
 #include "JSIO.h"
 #include "JSUIAPI.h"
 #include "JSUIAPI.h"
 #include "JSScene.h"
 #include "JSScene.h"
@@ -258,6 +261,9 @@ void jsapi_init_atomic(JSVM* vm)
     jsapi_init_network(vm);
     jsapi_init_network(vm);
 #endif
 #endif
     jsapi_init_graphics(vm);
     jsapi_init_graphics(vm);
+#ifdef ATOMIC_3D
+    jsapi_init_atomic3d(vm);
+#endif
     jsapi_init_ui(vm);
     jsapi_init_ui(vm);
     jsapi_init_scene(vm);
     jsapi_init_scene(vm);
 
 

+ 38 - 0
Source/AtomicJS/Javascript/JSAtomic3D.cpp

@@ -0,0 +1,38 @@
+
+#include <Atomic/Atomic3D/StaticModel.h>
+
+#include "JSAtomic3D.h"
+
+namespace Atomic
+{
+
+
+static int StaticModel_SetMaterialIndex(duk_context* ctx) {
+
+    unsigned index = (unsigned) duk_require_number(ctx, 0);
+    Material* material = js_to_class_instance<Material>(ctx, 1, 0);
+
+    duk_push_this(ctx);
+
+    // event receiver
+    StaticModel* model = js_to_class_instance<StaticModel>(ctx, -1, 0);
+
+
+    model->SetMaterial(index, material);
+
+
+    return 0;
+}
+
+void jsapi_init_atomic3d(JSVM* vm)
+{
+    duk_context* ctx = vm->GetJSContext();
+
+    js_class_get_prototype(ctx, "Atomic", "StaticModel");
+    duk_push_c_function(ctx, StaticModel_SetMaterialIndex, 2);
+    duk_put_prop_string(ctx, -2, "setMaterialIndex");
+    duk_pop(ctx); // pop AObject prototype
+
+}
+
+}

+ 16 - 0
Source/AtomicJS/Javascript/JSAtomic3D.h

@@ -0,0 +1,16 @@
+// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
+// Please see LICENSE.md in repository root for license information
+// https://github.com/AtomicGameEngine/AtomicGameEngine
+
+#pragma once
+
+#include "JSAPI.h"
+
+namespace Atomic
+{
+
+class JSVM;
+
+void jsapi_init_atomic3d(JSVM* vm);
+
+}

+ 4 - 1
Source/AtomicJS/Javascript/JSComponent.cpp

@@ -165,6 +165,9 @@ void JSComponent::SetUpdateEventMask(unsigned char mask)
 
 
 void JSComponent::UpdateReferences(bool remove)
 void JSComponent::UpdateReferences(bool remove)
 {
 {
+    if (context_->GetEditorContext())
+        return;
+
     duk_context* ctx = vm_->GetJSContext();
     duk_context* ctx = vm_->GetJSContext();
 
 
     int top = duk_get_top(ctx);
     int top = duk_get_top(ctx);
@@ -390,7 +393,7 @@ void JSComponent::OnNodeSet(Node* node)
 {
 {
     if (node)
     if (node)
     {
     {
-
+        UpdateReferences();
     }
     }
     else
     else
     {
     {

+ 48 - 17
Source/AtomicJS/Javascript/JSComponentFile.cpp

@@ -203,8 +203,8 @@ bool JSComponentFile::BeginLoad(Deserializer& source)
     if (!InitModule())
     if (!InitModule())
         return false;
         return false;
 
 
-    // TODO: cache these for player builds
-    // FIXME: this won't work with obfusication or minimization
+    // TODO: move the inspector field parsing to the JavascriptImporter
+    // which will work with obfusication, minimization, or bytecode dumps
 
 
     unsigned dataSize = source.GetSize();
     unsigned dataSize = source.GetSize();
     if (!dataSize && !source.GetName().Empty())
     if (!dataSize && !source.GetName().Empty())
@@ -234,7 +234,7 @@ bool JSComponentFile::BeginLoad(Deserializer& source)
 
 
             if (line.StartsWith("inspectorFields"))
             if (line.StartsWith("inspectorFields"))
             {
             {
-                eval = line;
+                eval = line + "\n";
                 if (line.Contains("}"))
                 if (line.Contains("}"))
                 {
                 {
                     valid = true;
                     valid = true;
@@ -243,7 +243,7 @@ bool JSComponentFile::BeginLoad(Deserializer& source)
             }
             }
             else if (line.StartsWith("this.inspectorFields"))
             else if (line.StartsWith("this.inspectorFields"))
             {
             {
-                eval = line.Substring(5);
+                eval = line.Substring(5) + "\n";
                 if (line.Contains("}"))
                 if (line.Contains("}"))
                 {
                 {
                     valid = true;
                     valid = true;
@@ -252,7 +252,7 @@ bool JSComponentFile::BeginLoad(Deserializer& source)
             }
             }
             else if (line.StartsWith("var inspectorFields"))
             else if (line.StartsWith("var inspectorFields"))
             {
             {
-                eval = line.Substring(4);
+                eval = line.Substring(4) + "\n";
                 if (line.Contains("}"))
                 if (line.Contains("}"))
                 {
                 {
                     valid = true;
                     valid = true;
@@ -263,7 +263,7 @@ bool JSComponentFile::BeginLoad(Deserializer& source)
         }
         }
         else
         else
         {
         {
-            eval += line;
+            eval += line + "\n";
         }
         }
 
 
         if (line.Contains("}") && eval.Length())
         if (line.Contains("}") && eval.Length())
@@ -321,23 +321,54 @@ bool JSComponentFile::BeginLoad(Deserializer& source)
                     }
                     }
                     else if (duk_is_array(ctx, -1))
                     else if (duk_is_array(ctx, -1))
                     {
                     {
-                        if (duk_get_length(ctx, -1) > 0)
+                        int length = duk_get_length(ctx, -1);
+
+                        if (length > 0)
                         {
                         {
+
                             duk_get_prop_index(ctx, -1, 0);
                             duk_get_prop_index(ctx, -1, 0);
 
 
-                            // TODO: class types
-                            variantType = (VariantType) ((int)duk_require_number(ctx, -1));
+                            // resource ref detection
+                            if (duk_is_string(ctx, -1))
+                            {
+                                const char* classname = duk_to_string(ctx, -1);
 
 
-                            duk_pop(ctx);
-                        }
+                                duk_pop(ctx);
 
 
-                        if (duk_get_length(ctx, -1) > 1)
-                        {
-                            duk_get_prop_index(ctx, -1, 1);
-                            // default value
-                            js_to_variant(ctx, -1, defaultValue);
+                                const char* name = NULL;
+
+                                if (length > 1)
+                                {
+                                    duk_get_prop_index(ctx, -1, 1);
+                                    name = duk_require_string(ctx, -1);
+                                    duk_pop(ctx);
+
+                                }
+
+                                ResourceRef resourceRef(classname);
+                                if (name)
+                                    resourceRef.name_ = name;
+
+                                variantType = VAR_RESOURCEREF;
+                                defaultValue = resourceRef;
+
+                            }
+                            else
+                            {
+                                variantType = (VariantType) ((int)duk_require_number(ctx, -1));
+
+                                duk_pop(ctx);
+
+                                if (length > 1)
+                                {
+                                    duk_get_prop_index(ctx, -1, 1);
+                                    // default value
+                                    js_to_variant(ctx, -1, defaultValue);
+                                    duk_pop(ctx);
+                                }
+
+                            }
 
 
-                            duk_pop(ctx);
                         }
                         }
 
 
                     }
                     }

+ 1 - 0
Source/AtomicJS/Javascript/JSComponentFile.h

@@ -44,6 +44,7 @@ public:
     static void RegisterObject(Context* context);
     static void RegisterObject(Context* context);
 
 
     const HashMap<String, VariantType>& GetFields() const { return fields_; }
     const HashMap<String, VariantType>& GetFields() const { return fields_; }
+    const VariantMap& GetDefaultFieldValues() const { return defaultFieldValues_; }
 
 
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     virtual bool BeginLoad(Deserializer& source);
     virtual bool BeginLoad(Deserializer& source);

+ 1 - 0
Source/AtomicJS/Javascript/JSRequire.cpp

@@ -133,6 +133,7 @@ namespace Atomic
             vm->SetLastModuleSearchFile(jsfile->GetFullPath());
             vm->SetLastModuleSearchFile(jsfile->GetFullPath());
             String source;
             String source;
             jsfile->ReadText(source);
             jsfile->ReadText(source);
+            source.Append('\n');
             duk_push_string(ctx, source.CString());
             duk_push_string(ctx, source.CString());
             return 1;
             return 1;
         }
         }

+ 49 - 5
Source/AtomicJS/Javascript/JSScene.cpp

@@ -3,11 +3,17 @@
 // https://github.com/AtomicGameEngine/AtomicGameEngine
 // https://github.com/AtomicGameEngine/AtomicGameEngine
 
 
 #include <Atomic/Resource/ResourceCache.h>
 #include <Atomic/Resource/ResourceCache.h>
+#include <Atomic/Resource/XMLFile.h>
 #include <Atomic/IO/File.h>
 #include <Atomic/IO/File.h>
 #include <Atomic/Scene/Node.h>
 #include <Atomic/Scene/Node.h>
 #include <Atomic/Scene/Scene.h>
 #include <Atomic/Scene/Scene.h>
+#include <Atomic/Scene/PrefabComponent.h>
 #include <Atomic/Graphics/Camera.h>
 #include <Atomic/Graphics/Camera.h>
 
 
+#ifdef ATOMIC_3D
+#include <Atomic/Physics/RigidBody.h>
+#endif
+
 #include "JSScene.h"
 #include "JSScene.h"
 #include "JSComponent.h"
 #include "JSComponent.h"
 #include "JSVM.h"
 #include "JSVM.h"
@@ -155,8 +161,8 @@ static int Node_GetComponents(duk_context* ctx)
 
 
     for (unsigned i = 0; i < dest.Size(); i++)
     for (unsigned i = 0; i < dest.Size(); i++)
     {
     {
-        js_push_class_object_instance(ctx, dest[i], "Component");
-        duk_put_prop_index(ctx, -2, i);
+        if (js_push_class_object_instance(ctx, dest[i], "Component"))
+            duk_put_prop_index(ctx, -2, i);
     }
     }
 
 
     return 1;
     return 1;
@@ -193,6 +199,43 @@ static int Node_SaveXML(duk_context* ctx)
     return 1;
     return 1;
 }
 }
 
 
+static int Node_LoadPrefab(duk_context* ctx)
+{
+    const char* prefabName = duk_require_string(ctx, 0);
+
+    duk_push_this(ctx);
+    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
+
+    PrefabComponent* prefabComponent = node->CreateComponent<PrefabComponent>();
+    prefabComponent->SetPrefabGUID(prefabName);
+
+    duk_push_boolean(ctx, 1);
+    return 1;
+
+}
+
+static int Node_CreateChildPrefab(duk_context* ctx)
+{
+    const char* childName = duk_require_string(ctx, 0);
+    const char* prefabName = duk_require_string(ctx, 1);
+
+    duk_push_this(ctx);
+    Node* parent = js_to_class_instance<Node>(ctx, -1, 0);
+
+    Node* node = parent->CreateChild();
+
+    PrefabComponent* prefabComponent = node->CreateComponent<PrefabComponent>();
+    prefabComponent->SetPrefabGUID(prefabName);
+
+    // override what node name is in prefab
+    node->SetName(childName);
+
+    js_push_class_object_instance(ctx, node, "Node");
+
+    return 1;
+
+}
+
 
 
 static int Scene_LoadXML(duk_context* ctx)
 static int Scene_LoadXML(duk_context* ctx)
 {
 {
@@ -250,8 +293,6 @@ static int Scene_GetMainCamera(duk_context* ctx)
 
 
 }
 }
 
 
-
-
 void jsapi_init_scene(JSVM* vm)
 void jsapi_init_scene(JSVM* vm)
 {
 {
     duk_context* ctx = vm->GetJSContext();
     duk_context* ctx = vm->GetJSContext();
@@ -273,7 +314,10 @@ void jsapi_init_scene(JSVM* vm)
     duk_put_prop_string(ctx, -2, "getChildAtIndex");
     duk_put_prop_string(ctx, -2, "getChildAtIndex");
     duk_push_c_function(ctx, Node_SaveXML, 1);
     duk_push_c_function(ctx, Node_SaveXML, 1);
     duk_put_prop_string(ctx, -2, "saveXML");
     duk_put_prop_string(ctx, -2, "saveXML");
-
+    duk_push_c_function(ctx, Node_LoadPrefab, 1);
+    duk_put_prop_string(ctx, -2, "loadPrefab");
+    duk_push_c_function(ctx, Node_CreateChildPrefab, 2);
+    duk_put_prop_string(ctx, -2, "createChildPrefab");
     duk_pop(ctx);
     duk_pop(ctx);
 
 
     js_class_get_prototype(ctx, "Atomic", "Scene");
     js_class_get_prototype(ctx, "Atomic", "Scene");

+ 69 - 0
Source/AtomicJS/Javascript/JSSceneSerializable.cpp

@@ -108,6 +108,22 @@ static int Serializable_SetAttribute(duk_context* ctx)
     {
     {
         v = (int) v.GetFloat();
         v = (int) v.GetFloat();
     }
     }
+    else if (variantType == VAR_RESOURCEREF)
+    {
+        RefCounted* ref = v.GetPtr();
+
+        if (ref && ref->IsObject())
+        {
+            Object* o = (Object*) ref;
+
+            // TODO: calling code must ensure we are a resource, can this be done here?
+            Resource* resource = (Resource*) o;
+
+            v = ResourceRef(resource->GetType(), resource->GetName());
+
+        }
+
+    }
 
 
     if (isAttr)
     if (isAttr)
     {
     {
@@ -182,6 +198,25 @@ static int Serializable_GetAttribute(duk_context* ctx)
     return 1;
     return 1;
 }
 }
 
 
+static const String& GetResourceRefClassName(Context* context, const ResourceRef& ref)
+{
+    const HashMap<StringHash, SharedPtr<ObjectFactory>>& factories = context->GetObjectFactories();
+
+    HashMap<StringHash, SharedPtr<ObjectFactory>>::ConstIterator itr = factories.Begin();
+
+    while (itr != factories.End())
+    {
+        if (itr->first_ == ref.type_)
+        {
+            return itr->second_->GetTypeName();
+        }
+
+        itr++;
+    }
+
+    return String::EMPTY;
+}
+
 
 
 static int Serializable_GetAttributes(duk_context* ctx)
 static int Serializable_GetAttributes(duk_context* ctx)
 {
 {
@@ -218,6 +253,22 @@ static int Serializable_GetAttributes(duk_context* ctx)
             duk_push_number(ctx, (double) attr->type_);
             duk_push_number(ctx, (double) attr->type_);
             duk_put_prop_string(ctx, -2, "type");
             duk_put_prop_string(ctx, -2, "type");
 
 
+            if (attr->type_ == VAR_RESOURCEREF)
+            {
+                if (attr->defaultValue_.GetType() == VAR_RESOURCEREF)
+                {
+                    const ResourceRef& ref = attr->defaultValue_.GetResourceRef();
+                    const String& typeName = GetResourceRefClassName(serial->GetContext(), ref);
+
+                    if (typeName.Length())
+                    {
+                        duk_push_string(ctx, typeName.CString());
+                        duk_put_prop_string(ctx, -2, "resourceTypeName");
+
+                    }
+                }
+            }
+
             duk_push_string(ctx, attr->name_.CString());
             duk_push_string(ctx, attr->name_.CString());
             duk_put_prop_string(ctx, -2, "name");
             duk_put_prop_string(ctx, -2, "name");
 
 
@@ -260,6 +311,8 @@ static int Serializable_GetAttributes(duk_context* ctx)
 
 
         if (file)
         if (file)
         {
         {
+
+            const VariantMap& defaultFieldValues = file->GetDefaultFieldValues();
             const HashMap<String, VariantType>& fields =  file->GetFields();
             const HashMap<String, VariantType>& fields =  file->GetFields();
 
 
             if (fields.Size())
             if (fields.Size())
@@ -272,6 +325,22 @@ static int Serializable_GetAttributes(duk_context* ctx)
                     duk_push_number(ctx, (double) itr->second_);
                     duk_push_number(ctx, (double) itr->second_);
                     duk_put_prop_string(ctx, -2, "type");
                     duk_put_prop_string(ctx, -2, "type");
 
 
+                    if (itr->second_ == VAR_RESOURCEREF && defaultFieldValues.Contains(itr->first_))
+                    {
+                        if (defaultFieldValues[itr->first_]->GetType() == VAR_RESOURCEREF)
+                        {
+                            const ResourceRef& ref = defaultFieldValues[itr->first_]->GetResourceRef();
+                            const String& typeName = GetResourceRefClassName(serial->GetContext(), ref);
+
+                            if (typeName.Length())
+                            {
+                                duk_push_string(ctx, typeName.CString());
+                                duk_put_prop_string(ctx, -2, "resourceTypeName");
+
+                            }
+                        }
+                    }
+
                     duk_push_string(ctx, itr->first_.CString());
                     duk_push_string(ctx, itr->first_.CString());
                     duk_put_prop_string(ctx, -2, "name");
                     duk_put_prop_string(ctx, -2, "name");
 
 

+ 46 - 0
Source/AtomicJS/Javascript/JSVM.cpp

@@ -247,6 +247,50 @@ void JSVM::SendJSErrorEvent(const String& filename)
 
 
 }
 }
 
 
+int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {
+    int realLineNumber = lineNumber;
+    String path = fileName;
+    if (!path.EndsWith(".js.map"))
+        path += ".js.map";
+    if (path.EndsWith(".js")) {
+        return realLineNumber;
+    }
+    SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
+    //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
+    if (mapFile.Null()) 
+    {
+        return realLineNumber;
+    }    
+    String map;
+    mapFile->ReadText(map);
+    int top = duk_get_top(ctx_);
+    duk_get_global_string(ctx_, "require");
+    duk_push_string(ctx_, "AtomicEditor/Script/jsutils");
+    if (duk_pcall(ctx_, 1))
+    {
+        printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
+        duk_set_top(ctx_, top);
+        return false;
+    }
+
+    duk_get_prop_string(ctx_, -1, "getRealLineNumber");
+    duk_push_string(ctx_, map.CString());
+    duk_push_int(ctx_, lineNumber);
+    bool ok = true;
+    if (duk_pcall(ctx_, 2))
+    {
+        ok = false;
+        printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
+    }
+    else
+    {
+        realLineNumber = duk_to_int(ctx_, -1);
+    }
+    duk_set_top(ctx_, top);
+
+    return realLineNumber;
+}
+
 bool JSVM::ExecuteScript(const String& scriptPath)
 bool JSVM::ExecuteScript(const String& scriptPath)
 {
 {
     String path = scriptPath;
     String path = scriptPath;
@@ -266,6 +310,7 @@ bool JSVM::ExecuteScript(const String& scriptPath)
     String source;
     String source;
 
 
     file->ReadText(source);
     file->ReadText(source);
+    source.Append('\n');
 
 
     duk_push_string(ctx_, file->GetFullPath().CString());
     duk_push_string(ctx_, file->GetFullPath().CString());
     if (duk_eval_raw(ctx_, source.CString(), 0,
     if (duk_eval_raw(ctx_, source.CString(), 0,
@@ -291,6 +336,7 @@ bool JSVM::ExecuteFile(File *file)
     String source;
     String source;
 
 
     file->ReadText(source);
     file->ReadText(source);
+    source.Append('\n');
 
 
     duk_push_string(ctx_, file->GetFullPath().CString());
     duk_push_string(ctx_, file->GetFullPath().CString());
     if (duk_eval_raw(ctx_, source.CString(), 0,
     if (duk_eval_raw(ctx_, source.CString(), 0,

+ 9 - 2
Source/AtomicJS/Javascript/JSVM.h

@@ -162,6 +162,8 @@ public:
 
 
     void SendJSErrorEvent(const String& filename = String::EMPTY);
     void SendJSErrorEvent(const String& filename = String::EMPTY);
 
 
+    int GetRealLineNumber(const String& fileName, const int lineNumber);
+
 private:
 private:
 
 
     void SubscribeToEvents();
     void SubscribeToEvents();
@@ -229,8 +231,13 @@ inline bool js_push_class_object_instance(duk_context* ctx, const RefCounted *in
     duk_push_pointer(ctx, (void*) instance->GetClassID());
     duk_push_pointer(ctx, (void*) instance->GetClassID());
     duk_get_prop(ctx, -2);
     duk_get_prop(ctx, -2);
 
 
-    // if this is tripped, means the class hasn't been registered and shouldn't be trying to push it
-    assert(duk_is_object(ctx, -1));
+    // if not an object, this instance isn't not a scriptable class
+    // reset top and return false
+    if (!duk_is_object(ctx, -1))
+    {
+        duk_set_top(ctx, top);
+        return false;
+    }
 
 
     duk_get_prop_index(ctx, -1, 0);
     duk_get_prop_index(ctx, -1, 0);
     const char* package = duk_require_string(ctx, -1);
     const char* package = duk_require_string(ctx, -1);

+ 15 - 2
Source/AtomicPlayer/Player.cpp

@@ -1,5 +1,8 @@
 
 
 #include <Atomic/IO/Log.h>
 #include <Atomic/IO/Log.h>
+
+#include <Atomic/Input/InputEvents.h>
+
 #include <Atomic/Resource/ResourceCache.h>
 #include <Atomic/Resource/ResourceCache.h>
 #include <Atomic/Graphics/Renderer.h>
 #include <Atomic/Graphics/Renderer.h>
 #include <Atomic/Graphics/Camera.h>
 #include <Atomic/Graphics/Camera.h>
@@ -14,6 +17,8 @@ Player::Player(Context* context) :
 {
 {
     viewport_ = new Viewport(context_);
     viewport_ = new Viewport(context_);
     GetSubsystem<Renderer>()->SetViewport(0, viewport_);
     GetSubsystem<Renderer>()->SetViewport(0, viewport_);
+
+    SubscribeToEvent(E_EXITREQUESTED, HANDLER(Player, HandleExitRequested));
 }
 }
 
 
 Player::~Player()
 Player::~Player()
@@ -21,6 +26,13 @@ Player::~Player()
 
 
 }
 }
 
 
+void Player::HandleExitRequested(StringHash eventType, VariantMap& eventData)
+{
+    currentScene_ = 0;
+    viewport_ = 0;
+
+}
+
 Scene* Player::LoadScene(const String& filename, Camera *camera)
 Scene* Player::LoadScene(const String& filename, Camera *camera)
 {
 {
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     ResourceCache* cache = GetSubsystem<ResourceCache>();
@@ -31,14 +43,15 @@ Scene* Player::LoadScene(const String& filename, Camera *camera)
         return 0;
         return 0;
     }
     }
 
 
-    Scene* scene = new Scene(context_);
+    SharedPtr<Scene> scene(new Scene(context_));
 
 
     if (!scene->LoadXML(*file))
     if (!scene->LoadXML(*file))
     {
     {
-        scene->ReleaseRef();
         return 0;
         return 0;
     }
     }
 
 
+    currentScene_ = scene;
+
     if(!camera)
     if(!camera)
     {
     {
         PODVector<Node*> cameraNodes;
         PODVector<Node*> cameraNodes;

+ 7 - 0
Source/AtomicPlayer/Player.h

@@ -23,8 +23,15 @@ public:
 
 
     Scene* LoadScene(const String& filename, Camera* camera = NULL);
     Scene* LoadScene(const String& filename, Camera* camera = NULL);
 
 
+    Scene* GetCurrentScene() { return currentScene_; }
+
 private:
 private:
 
 
+    void HandleExitRequested(StringHash eventType, VariantMap& eventData);
+
+    // Strong reference
+    SharedPtr<Scene> currentScene_;
+
     SharedPtr<Viewport> viewport_;
     SharedPtr<Viewport> viewport_;
 
 
 };
 };

+ 2 - 2
Source/AtomicTool/AtomicTool.cpp

@@ -271,8 +271,8 @@ void AtomicTool::Start()
 
 
         if (!tsystem->LoadProject(projectFile))
         if (!tsystem->LoadProject(projectFile))
         {
         {
-            ErrorExit(ToString("Failed to load project: %s", projectFile.CString()));
-            return;
+            //ErrorExit(ToString("Failed to load project: %s", projectFile.CString()));
+            //return;
         }
         }
 
 
         // Set the build path
         // Set the build path

+ 3191 - 0
Source/ThirdParty/Duktape/duk_config.h

@@ -0,0 +1,3191 @@
+/*
+ *  Determine platform features, select feature selection defines
+ *  (e.g. _XOPEN_SOURCE), include system headers, and define DUK_USE_xxx
+ *  defines which are (only) checked in Duktape internal code for
+ *  activated features.  Duktape feature selection is based on automatic
+ *  feature detection, user supplied DUK_OPT_xxx defines, and optionally
+ *  a "duk_custom.h" user header (if DUK_OPT_HAVE_CUSTOM_H is defined).
+ *
+ *  When compiling Duktape, DUK_COMPILING_DUKTAPE is set, and this file
+ *  is included before any system headers are included.  Feature selection
+ *  defines (e.g. _XOPEN_SOURCE) are defined here before any system headers
+ *  are included (which is a requirement for system headers to work correctly).
+ *  This file is responsible for including all system headers and contains
+ *  all platform dependent cruft in general.  When compiling user code,
+ *  DUK_COMPILING_DUKTAPE is not defined, and we must avoid e.g. defining
+ *  unnecessary feature selection defines.
+ *
+ *  The general order of handling:
+ *    - Compiler feature detection (require no includes)
+ *    - Intermediate platform detection (-> easier platform defines)
+ *    - Platform detection, system includes, byte order detection, etc
+ *    - ANSI C wrappers (e.g. DUK_MEMCMP), wrappers for constants, etc
+ *    - DUK_USE_xxx defines are resolved based on input defines
+ *    - Duktape Date provider settings
+ *    - Final sanity checks
+ *
+ *  DUK_F_xxx are internal feature detection macros which should not be
+ *  used outside this header.
+ *
+ *  Useful resources:
+ *
+ *    http://sourceforge.net/p/predef/wiki/Home/
+ *    http://sourceforge.net/p/predef/wiki/Architectures/
+ *    http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
+ *    http://en.wikipedia.org/wiki/C_data_types#Fixed-width_integer_types
+ *
+ *  Preprocessor defines available in a particular GCC:
+ *
+ *    gcc -dM -E - </dev/null   # http://www.brain-dump.org/blog/entry/107
+ */
+
+#ifndef DUK_CONFIG_H_INCLUDED
+#define DUK_CONFIG_H_INCLUDED
+
+/*
+ *  Compiler features
+ */
+
+#undef DUK_F_C99
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
+#define DUK_F_C99
+#endif
+
+#undef DUK_F_CPP
+#if defined(__cplusplus)
+#define DUK_F_CPP
+#endif
+
+#undef DUK_F_CPP11
+#if defined(__cplusplus) && (__cplusplus >= 201103L)
+#define DUK_F_CPP11
+#endif
+
+/*
+ *  Provides the duk_rdtsc() inline function (if available), limited to
+ *  GCC C99.
+ *
+ *  See: http://www.mcs.anl.gov/~kazutomo/rdtsc.html
+ */
+
+/* XXX: more accurate detection of what gcc versions work; more inline
+ * asm versions for other compilers.
+ */
+#if defined(__GNUC__) && defined(__i386__) && defined(DUK_F_C99) && \
+    !defined(__cplusplus) /* unsigned long long not standard */
+static __inline__ unsigned long long duk_rdtsc(void) {
+	unsigned long long int x;
+	__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
+	return x;
+}
+#define DUK_USE_RDTSC()  duk_rdtsc()
+#elif defined(__GNUC__) && defined(__x86_64__) && defined(DUK_F_C99) && \
+    !defined(__cplusplus) /* unsigned long long not standard */
+static __inline__ unsigned long long duk_rdtsc(void) {
+	unsigned hi, lo;
+	__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
+	return ((unsigned long long) lo) | (((unsigned long long) hi) << 32);
+}
+#define DUK_USE_RDTSC()  duk_rdtsc()
+#else
+/* not available */
+#undef DUK_USE_RDTSC
+#endif
+
+/*
+ *  Intermediate platform, architecture, and compiler detection.  These are
+ *  hopelessly intertwined - e.g. architecture defines depend on compiler etc.
+ *
+ *  Provide easier defines for platforms and compilers which are often tricky
+ *  or verbose to detect.  The intent is not to provide intermediate defines for
+ *  all features; only if existing feature defines are inconvenient.
+ */
+
+/* Intel x86 (32-bit) */
+#if defined(i386) || defined(__i386) || defined(__i386__) || \
+    defined(__i486__) || defined(__i586__) || defined(__i686__) || \
+    defined(__IA32__) || defined(_M_IX86) || defined(__X86__) || \
+    defined(_X86_) || defined(__THW_INTEL__) || defined(__I86__)
+#define DUK_F_X86
+#endif
+
+/* AMD64 (64-bit) */
+#if defined(__amd64__) || defined(__amd64) || \
+    defined(__x86_64__) || defined(__x86_64) || \
+    defined(_M_X64) || defined(_M_AMD64)
+#define DUK_F_X64
+#endif
+
+/* X32: 64-bit with 32-bit pointers (allows packed tvals).  X32 support is
+ * not very mature yet.
+ *
+ * https://sites.google.com/site/x32abi/
+ */
+#if defined(DUK_F_X64) && \
+    (defined(_ILP32) || defined(__ILP32__))
+#define DUK_F_X32
+/* define only one of: DUK_F_X86, DUK_F_X32, or DUK_F_X64 */
+#undef DUK_F_X64
+#undef DUK_F_X86
+#endif
+
+/* ARM */
+#if defined(__arm__) || defined(__thumb__) || defined(_ARM) || defined(_M_ARM)
+#define DUK_F_ARM
+#endif
+
+/* MIPS */
+/* Related defines: __MIPSEB__, __MIPSEL__, __mips_isa_rev, __LP64__ */
+#if defined(__mips__) || defined(mips) || defined(_MIPS_ISA) || \
+    defined(_R3000) || defined(_R4000) || defined(_R5900) || \
+    defined(_MIPS_ISA_MIPS1) || defined(_MIPS_ISA_MIPS2) || \
+    defined(_MIPS_ISA_MIPS3) || defined(_MIPS_ISA_MIPS4) || \
+    defined(__mips) || defined(__MIPS__)
+#define DUK_F_MIPS
+#if defined(__LP64__) || defined(__mips64) || defined(__mips64__) || \
+    defined(__mips_n64)
+#define DUK_F_MIPS64
+#else
+#define DUK_F_MIPS32
+#endif
+#endif
+
+/* SuperH */
+#if defined(__sh__) || \
+    defined(__sh1__) || defined(__SH1__) || \
+    defined(__sh2__) || defined(__SH2__) || \
+    defined(__sh3__) || defined(__SH3__) || \
+    defined(__sh4__) || defined(__SH4__) || \
+    defined(__sh5__) || defined(__SH5__)
+#define DUK_F_SUPERH
+#endif
+
+/* Motorola 68K.  Not defined by VBCC, so user must define one of these
+ * manually when using VBCC.
+ */
+#if defined(__m68k__) || defined(M68000) || defined(__MC68K__)
+#define DUK_F_M68K
+#endif
+
+/* Linux */
+#if defined(__linux) || defined(__linux__) || defined(linux)
+#define DUK_F_LINUX
+#endif
+
+/* FreeBSD */
+#if defined(__FreeBSD__) || defined(__FreeBSD)
+#define DUK_F_FREEBSD
+#endif
+
+/* NetBSD */
+#if defined(__NetBSD__) || defined(__NetBSD)
+#define DUK_F_NETBSD
+#endif
+
+/* OpenBSD */
+#if defined(__OpenBSD__) || defined(__OpenBSD)
+#define DUK_F_OPENBSD
+#endif
+
+/* BSD variant */
+#if defined(DUK_F_FREEBSD) || defined(DUK_F_NETBSD) || defined(DUK_F_OPENBSD) || \
+    defined(__bsdi__) || defined(__DragonFly__)
+#define DUK_F_BSD
+#endif
+
+/* Generic Unix (includes Cygwin) */
+#if defined(__unix) || defined(__unix__) || defined(unix) || \
+    defined(DUK_F_LINUX) || defined(DUK_F_BSD)
+#define DUK_F_UNIX
+#endif
+
+/* Cygwin */
+#if defined(__CYGWIN__)
+#define DUK_F_CYGWIN
+#endif
+
+/* Windows (32-bit or above) */
+#if defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64) || \
+    defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__)
+#define DUK_F_WINDOWS
+#endif
+
+#if defined(__APPLE__)
+#define DUK_F_APPLE
+#endif
+
+/* Atari ST TOS. __TOS__ defined by PureC (which doesn't work as a target now
+ * because int is 16-bit, to be fixed).  No platform define in VBCC apparently,
+ * so to use with VBCC, user must define '__TOS__' manually.
+  */
+#if defined(__TOS__)
+#define DUK_F_TOS
+#endif
+
+/* AmigaOS.  Neither AMIGA nor __amigaos__ is defined on VBCC, so user must
+ * define 'AMIGA' manually.
+ */
+#if defined(AMIGA) || defined(__amigaos__)
+#define DUK_F_AMIGAOS
+#endif
+
+/* Flash player (e.g. Crossbridge) */
+#if defined(__FLASHPLAYER__)
+#define DUK_F_FLASHPLAYER
+#endif
+
+/* Emscripten (provided explicitly by user), improve if possible */
+#if defined(EMSCRIPTEN)
+#define DUK_F_EMSCRIPTEN
+#endif
+
+/* QNX */
+#if defined(__QNX__)
+#define DUK_F_QNX
+#endif
+
+/* TI-Nspire (using Ndless) */
+#if defined(_TINSPIRE)
+#define DUK_F_TINSPIRE
+#endif
+
+/* GCC and GCC version convenience define. */
+#if defined(__GNUC__)
+#define DUK_F_GCC
+#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__)
+/* Convenience, e.g. gcc 4.5.1 == 40501; http://stackoverflow.com/questions/6031819/emulating-gccs-builtin-unreachable */
+#define DUK_F_GCC_VERSION  (__GNUC__ * 10000L + __GNUC_MINOR__ * 100L + __GNUC_PATCHLEVEL__)
+#else
+#error cannot figure out gcc version
+#endif
+#endif
+
+/* Clang */
+#if defined(__clang__)
+#define DUK_F_CLANG
+/* It seems clang also defines __GNUC__, so undo the GCC detection. */
+#if defined(DUK_F_GCC)
+#undef DUK_F_GCC
+#endif
+#if defined(DUK_F_GCC_VERSION)
+#undef DUK_F_GCC_VERSION
+#endif
+#endif
+
+/* MSVC */
+#if defined(_MSC_VER)
+/* MSVC preprocessor defines: http://msdn.microsoft.com/en-us/library/b0084kay.aspx
+ * _MSC_FULL_VER includes the build number, but it has at least two formats, see e.g.
+ * BOOST_MSVC_FULL_VER in http://www.boost.org/doc/libs/1_52_0/boost/config/compiler/visualc.hpp
+ */
+#define DUK_F_MSVC
+#if defined(_MSC_FULL_VER)
+#if (_MSC_FULL_VER > 100000000)
+#define DUK_F_MSVC_FULL_VER _MSC_FULL_VER
+#else
+#define DUK_F_MSCV_FULL_VER (_MSC_FULL_VER * 10)
+#endif
+#endif
+#endif  /* _MSC_VER */
+
+/* MinGW */
+#if defined(__MINGW32__) || defined(__MINGW64__)
+/* NOTE: Also GCC flags are detected (DUK_F_GCC etc). */
+#define DUK_F_MINGW
+#endif
+
+/* BCC (Bruce's C compiler): this is a "torture target" for compilation */
+#if defined(__BCC__) || defined(__BCC_VERSION__)
+#define DUK_F_BCC
+#endif
+
+#if defined(__VBCC__)
+#define DUK_F_VBCC
+#endif
+
+/*
+ *  Platform detection, system includes, Date provider selection.
+ *
+ *  Feature selection (e.g. _XOPEN_SOURCE) must happen before any system
+ *  headers are included.  This header should avoid providing any feature
+ *  selection defines when compiling user code (only when compiling Duktape
+ *  itself).  If a feature selection option is required for user code to
+ *  compile correctly (e.g. it is needed for type detection), it should
+ *  probably be -checked- here, not defined here.
+ *
+ *  Date provider selection seems a bit out-of-place here, but since
+ *  the date headers and provider functions are heavily platform
+ *  specific, there's little point in duplicating the platform if-else
+ *  ladder.  All platform specific Date provider functions are in
+ *  duk_bi_date.c; here we provide appropriate #defines to enable them,
+ *  and include all the necessary system headers so that duk_bi_date.c
+ *  compiles.  Date "providers" are:
+ *
+ *    NOW = getting current time (required)
+ *    TZO = getting local time offset (required)
+ *    PRS = parse datetime (optional)
+ *    FMT = format datetime (optional)
+ *
+ *  There's a lot of duplication here, unfortunately, because many
+ *  platforms have similar (but not identical) headers, Date providers,
+ *  etc.  The duplication could be removed by more complicated nested
+ *  #ifdefs, but it would then be more difficult to make fixes which
+ *  affect only a specific platform.
+ *
+ *  XXX: add a way to provide custom functions to provide the critical
+ *  primitives; this would be convenient when porting to unknown platforms
+ *  (rather than muck with Duktape internals).
+ */
+
+#if defined(DUK_COMPILING_DUKTAPE) && \
+ (defined(DUK_F_LINUX) || defined(DUK_F_EMSCRIPTEN))
+/* A more recent Emscripten (2014-05) seems to lack "linux" environment
+ * defines, so check for Emscripten explicitly.
+ */
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE  200809L
+#endif
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE      /* e.g. getdate_r */
+#endif
+#ifndef _XOPEN_SOURCE
+#define _XOPEN_SOURCE    /* e.g. strptime */
+#endif
+#endif
+
+#if defined(DUK_F_QNX) && defined(DUK_COMPILING_DUKTAPE)
+/* See: /opt/qnx650/target/qnx6/usr/include/sys/platform.h */
+#define _XOPEN_SOURCE    600
+#define _POSIX_C_SOURCE  200112L
+#endif
+
+#undef DUK_F_MSVC_CRT_SECURE
+#if defined(DUK_F_WINDOWS) && defined(_MSC_VER)
+/* http://msdn.microsoft.com/en-us/library/8ef0s5kh.aspx
+ * http://msdn.microsoft.com/en-us/library/wd3wzwts.aspx
+ * Seem to be available since VS2005.
+ */
+#if (_MSC_VER >= 1400)
+/* VS2005+, secure CRT functions are preferred.  Windows Store applications
+ * (and probably others) should use these.
+ */
+#define DUK_F_MSVC_CRT_SECURE
+#endif
+#if (_MSC_VER < 1700)
+/* VS2012+ has stdint.h, < VS2012 does not (but it's available for download). */
+#define DUK_F_NO_STDINT_H
+#endif
+/* Initial fix: disable secure CRT related warnings when compiling Duktape
+ * itself (must be defined before including Windows headers).  Don't define
+ * for user code including duktape.h.
+ */
+#if defined(DUK_COMPILING_DUKTAPE) && !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#endif  /* DUK_F_WINDOWS && _MSC_VER */
+
+#if defined(DUK_F_TOS) || defined(DUK_F_BCC)
+#define DUK_F_NO_STDINT_H
+#endif
+
+/* Workaround for older C++ compilers before including <inttypes.h>,
+ * see e.g.: https://sourceware.org/bugzilla/show_bug.cgi?id=15366
+ */
+#if defined(__cplusplus) && !defined(__STDC_LIMIT_MACROS)
+#define __STDC_LIMIT_MACROS
+#endif
+#if defined(__cplusplus) && !defined(__STDC_CONSTANT_MACROS)
+#define __STDC_CONSTANT_MACROS
+#endif
+
+#if defined(__APPLE__)
+/* Mac OSX, iPhone, Darwin */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <TargetConditionals.h>
+#include <architecture/byte_order.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_OPENBSD)
+/* http://www.monkey.org/openbsd/archive/ports/0401/msg00089.html */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#include <sys/endian.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_BSD)
+/* other BSD */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#include <sys/endian.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_TOS)
+/* Atari ST TOS */
+#define DUK_USE_DATE_NOW_TIME
+#define DUK_USE_DATE_TZO_GMTIME
+/* no parsing (not an error) */
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <limits.h>
+#include <time.h>
+#elif defined(DUK_F_AMIGAOS)
+#if defined(DUK_F_M68K)
+/* AmigaOS on M68k */
+#define DUK_USE_DATE_NOW_TIME
+#define DUK_USE_DATE_TZO_GMTIME
+/* no parsing (not an error) */
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <limits.h>
+#include <time.h>
+#else
+#error AmigaOS but not M68K, not supported now
+#endif
+#elif defined(DUK_F_WINDOWS)
+/* Windows 32-bit and 64-bit are currently the same. */
+/* MSVC does not have sys/param.h */
+#define DUK_USE_DATE_NOW_WINDOWS
+#define DUK_USE_DATE_TZO_WINDOWS
+/* Note: PRS and FMT are intentionally left undefined for now.  This means
+ * there is no platform specific date parsing/formatting but there is still
+ * the ISO 8601 standard format.
+ */
+#include <windows.h>
+#include <limits.h>
+// ATOMIC BEGIN
+#ifdef GetObject
+#undef GetObject
+#endif
+#ifdef MessageBox
+#undef MessageBox
+#endif
+#ifdef GetMessage
+#undef GetMessage
+#endif
+#ifdef FindText
+#undef FindText
+#endif
+// ATOMIC END
+#elif defined(DUK_F_FLASHPLAYER)
+/* Crossbridge */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <endian.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_QNX)
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_TINSPIRE)
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_LINUX)
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#if defined(DUK_F_BCC)
+/* no endian.h */
+#else
+#include <endian.h>
+#endif  /* DUK_F_BCC */
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(__posix)
+/* POSIX */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#include <endian.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#elif defined(DUK_F_CYGWIN)
+/* Cygwin -- don't use strptime() for now */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#include <endian.h>
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#else
+/* Other UNIX, hopefully others */
+#define DUK_USE_DATE_NOW_GETTIMEOFDAY
+#define DUK_USE_DATE_TZO_GMTIME_R
+#define DUK_USE_DATE_PRS_STRPTIME
+#define DUK_USE_DATE_FMT_STRFTIME
+#include <sys/types.h>
+#if defined(DUK_F_BCC)
+/* no endian.h */
+#else
+#include <endian.h>
+#endif  /* DUK_F_BCC */
+#include <limits.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <time.h>
+#endif
+
+/* Shared includes */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>  /* varargs */
+#include <setjmp.h>
+#include <stddef.h>  /* e.g. ptrdiff_t */
+#if defined(DUK_F_NO_STDINT_H)
+/* stdint.h not available */
+#else
+/* Technically C99 (C++11) but found in many systems.  Note the workaround
+ * above for some C++ compilers (__STDC_LIMIT_MACROS etc).
+ */
+#include <stdint.h>
+#endif
+#include <math.h>
+
+#if (defined(DUK_F_C99) || defined(DUK_F_CPP11)) && \
+    !defined(DUK_F_BCC)
+/* ULL / LL preprocessor constants should be avoided because they're not
+ * always available.  With suitable options, some compilers will support
+ * 64-bit integer types but won't support ULL / LL preprocessor constants.
+ * Assume C99/C++11 environments have these.  However, BCC is nominally
+ * C99 but doesn't support these constants.
+ */
+#define DUK_F_ULL_CONSTS
+#endif
+
+/*
+ *  Detection for specific libc variants (like uclibc) and other libc specific
+ *  features.  Potentially depends on the #includes above.
+ */
+
+#if defined(__UCLIBC__)
+#define DUK_F_UCLIBC
+#endif
+
+/*
+ *  Wrapper typedefs and constants for integer types, also sanity check types.
+ *
+ *  C99 typedefs are quite good but not always available, and we want to avoid
+ *  forcibly redefining the C99 typedefs.  So, there are Duktape wrappers for
+ *  all C99 typedefs and Duktape code should only use these typedefs.  Type
+ *  detection when C99 is not supported is best effort and may end up detecting
+ *  some types incorrectly.
+ *
+ *  Pointer sizes are a portability problem: pointers to different types may
+ *  have a different size and function pointers are very difficult to manage
+ *  portably.
+ *
+ *  http://en.wikipedia.org/wiki/C_data_types#Fixed-width_integer_types
+ *
+ *  Note: there's an interesting corner case when trying to define minimum
+ *  signed integer value constants which leads to the current workaround of
+ *  defining e.g. -0x80000000 as (-0x7fffffffL - 1L).  See doc/code-issues.txt
+ *  for a longer discussion.
+ *
+ *  Note: avoid typecasts and computations in macro integer constants as they
+ *  can then no longer be used in macro relational expressions (such as
+ *  #if DUK_SIZE_MAX < 0xffffffffUL).  There is internal code which relies on
+ *  being able to compare DUK_SIZE_MAX against a limit.
+ */
+
+/* XXX: add feature options to force basic types from outside? */
+
+#if !defined(INT_MAX)
+#error INT_MAX not defined
+#endif
+
+/* Check that architecture is two's complement, standard C allows e.g.
+ * INT_MIN to be -2**31+1 (instead of -2**31).
+ */
+#if defined(INT_MAX) && defined(INT_MIN)
+#if INT_MAX != -(INT_MIN + 1)
+#error platform does not seem complement of two
+#endif
+#else
+#error cannot check complement of two
+#endif
+
+/* Pointer size determination based on architecture.
+ * XXX: unsure about BCC correctness.
+ */
+#if defined(DUK_F_X86) || defined(DUK_F_X32) || \
+    defined(DUK_F_BCC) || defined(ANDROID) || \
+    (defined(__WORDSIZE) && (__WORDSIZE == 32))
+#define DUK_F_32BIT_PTRS
+#elif defined(DUK_F_X64) || \
+      (defined(__WORDSIZE) && (__WORDSIZE == 64))
+#define DUK_F_64BIT_PTRS
+#else
+/* not sure, not needed with C99 anyway */
+#endif
+
+/* Intermediate define for 'have inttypes.h' */
+#undef DUK_F_HAVE_INTTYPES
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
+    !(defined(DUK_F_AMIGAOS) && defined(DUK_F_VBCC))
+/* vbcc + AmigaOS has C99 but no inttypes.h */
+#define DUK_F_HAVE_INTTYPES
+#elif defined(__cplusplus) && (__cplusplus >= 201103L)
+/* C++11 apparently ratified stdint.h */
+#define DUK_F_HAVE_INTTYPES
+#endif
+
+/* Basic integer typedefs and limits, preferably from inttypes.h, otherwise
+ * through automatic detection.
+ */
+#if defined(DUK_F_HAVE_INTTYPES)
+/* C99 or compatible */
+
+#define DUK_F_HAVE_64BIT
+#include <inttypes.h>
+
+typedef uint8_t duk_uint8_t;
+typedef int8_t duk_int8_t;
+typedef uint16_t duk_uint16_t;
+typedef int16_t duk_int16_t;
+typedef uint32_t duk_uint32_t;
+typedef int32_t duk_int32_t;
+typedef uint64_t duk_uint64_t;
+typedef int64_t duk_int64_t;
+typedef uint_least8_t duk_uint_least8_t;
+typedef int_least8_t duk_int_least8_t;
+typedef uint_least16_t duk_uint_least16_t;
+typedef int_least16_t duk_int_least16_t;
+typedef uint_least32_t duk_uint_least32_t;
+typedef int_least32_t duk_int_least32_t;
+typedef uint_least64_t duk_uint_least64_t;
+typedef int_least64_t duk_int_least64_t;
+typedef uint_fast8_t duk_uint_fast8_t;
+typedef int_fast8_t duk_int_fast8_t;
+typedef uint_fast16_t duk_uint_fast16_t;
+typedef int_fast16_t duk_int_fast16_t;
+typedef uint_fast32_t duk_uint_fast32_t;
+typedef int_fast32_t duk_int_fast32_t;
+typedef uint_fast64_t duk_uint_fast64_t;
+typedef int_fast64_t duk_int_fast64_t;
+typedef uintptr_t duk_uintptr_t;
+typedef intptr_t duk_intptr_t;
+typedef uintmax_t duk_uintmax_t;
+typedef intmax_t duk_intmax_t;
+
+#define DUK_UINT8_MIN         0
+#define DUK_UINT8_MAX         UINT8_MAX
+#define DUK_INT8_MIN          INT8_MIN
+#define DUK_INT8_MAX          INT8_MAX
+#define DUK_UINT_LEAST8_MIN   0
+#define DUK_UINT_LEAST8_MAX   UINT_LEAST8_MAX
+#define DUK_INT_LEAST8_MIN    INT_LEAST8_MIN
+#define DUK_INT_LEAST8_MAX    INT_LEAST8_MAX
+#define DUK_UINT_FAST8_MIN    0
+#define DUK_UINT_FAST8_MAX    UINT_FAST8_MAX
+#define DUK_INT_FAST8_MIN     INT_FAST8_MIN
+#define DUK_INT_FAST8_MAX     INT_FAST8_MAX
+#define DUK_UINT16_MIN        0
+#define DUK_UINT16_MAX        UINT16_MAX
+#define DUK_INT16_MIN         INT16_MIN
+#define DUK_INT16_MAX         INT16_MAX
+#define DUK_UINT_LEAST16_MIN  0
+#define DUK_UINT_LEAST16_MAX  UINT_LEAST16_MAX
+#define DUK_INT_LEAST16_MIN   INT_LEAST16_MIN
+#define DUK_INT_LEAST16_MAX   INT_LEAST16_MAX
+#define DUK_UINT_FAST16_MIN   0
+#define DUK_UINT_FAST16_MAX   UINT_FAST16_MAX
+#define DUK_INT_FAST16_MIN    INT_FAST16_MIN
+#define DUK_INT_FAST16_MAX    INT_FAST16_MAX
+#define DUK_UINT32_MIN        0
+#define DUK_UINT32_MAX        UINT32_MAX
+#define DUK_INT32_MIN         INT32_MIN
+#define DUK_INT32_MAX         INT32_MAX
+#define DUK_UINT_LEAST32_MIN  0
+#define DUK_UINT_LEAST32_MAX  UINT_LEAST32_MAX
+#define DUK_INT_LEAST32_MIN   INT_LEAST32_MIN
+#define DUK_INT_LEAST32_MAX   INT_LEAST32_MAX
+#define DUK_UINT_FAST32_MIN   0
+#define DUK_UINT_FAST32_MAX   UINT_FAST32_MAX
+#define DUK_INT_FAST32_MIN    INT_FAST32_MIN
+#define DUK_INT_FAST32_MAX    INT_FAST32_MAX
+#define DUK_UINT64_MIN        0
+#define DUK_UINT64_MAX        UINT64_MAX
+#define DUK_INT64_MIN         INT64_MIN
+#define DUK_INT64_MAX         INT64_MAX
+#define DUK_UINT_LEAST64_MIN  0
+#define DUK_UINT_LEAST64_MAX  UINT_LEAST64_MAX
+#define DUK_INT_LEAST64_MIN   INT_LEAST64_MIN
+#define DUK_INT_LEAST64_MAX   INT_LEAST64_MAX
+#define DUK_UINT_FAST64_MIN   0
+#define DUK_UINT_FAST64_MAX   UINT_FAST64_MAX
+#define DUK_INT_FAST64_MIN    INT_FAST64_MIN
+#define DUK_INT_FAST64_MAX    INT_FAST64_MAX
+
+#define DUK_UINTPTR_MIN       0
+#define DUK_UINTPTR_MAX       UINTPTR_MAX
+#define DUK_INTPTR_MIN        INTPTR_MIN
+#define DUK_INTPTR_MAX        INTPTR_MAX
+
+#define DUK_UINTMAX_MIN       0
+#define DUK_UINTMAX_MAX       UINTMAX_MAX
+#define DUK_INTMAX_MIN        INTMAX_MIN
+#define DUK_INTMAX_MAX        INTMAX_MAX
+
+#define DUK_SIZE_MIN          0
+#define DUK_SIZE_MAX          SIZE_MAX
+#undef DUK_SIZE_MAX_COMPUTED
+
+#else  /* C99 types */
+
+/* When C99 types are not available, we use heuristic detection to get
+ * the basic 8, 16, 32, and (possibly) 64 bit types.  The fast/least
+ * types are then assumed to be exactly the same for now: these could
+ * be improved per platform but C99 types are very often now available.
+ * 64-bit types are not available on all platforms; this is OK at least
+ * on 32-bit platforms.
+ *
+ * This detection code is necessarily a bit hacky and can provide typedefs
+ * and defines that won't work correctly on some exotic platform.
+ */
+
+#if (defined(CHAR_BIT) && (CHAR_BIT == 8)) || \
+    (defined(UCHAR_MAX) && (UCHAR_MAX == 255))
+typedef unsigned char duk_uint8_t;
+typedef signed char duk_int8_t;
+#else
+#error cannot detect 8-bit type
+#endif
+
+#if defined(USHRT_MAX) && (USHRT_MAX == 65535UL)
+typedef unsigned short duk_uint16_t;
+typedef signed short duk_int16_t;
+#elif defined(UINT_MAX) && (UINT_MAX == 65535UL)
+/* On some platforms int is 16-bit but long is 32-bit (e.g. PureC) */
+typedef unsigned int duk_uint16_t;
+typedef signed int duk_int16_t;
+#else
+#error cannot detect 16-bit type
+#endif
+
+#if defined(UINT_MAX) && (UINT_MAX == 4294967295UL)
+typedef unsigned int duk_uint32_t;
+typedef signed int duk_int32_t;
+#elif defined(ULONG_MAX) && (ULONG_MAX == 4294967295UL)
+/* On some platforms int is 16-bit but long is 32-bit (e.g. PureC) */
+typedef unsigned long duk_uint32_t;
+typedef signed long duk_int32_t;
+#else
+#error cannot detect 32-bit type
+#endif
+
+/* 64-bit type detection is a bit tricky.
+ *
+ * ULLONG_MAX is a standard define.  __LONG_LONG_MAX__ and __ULONG_LONG_MAX__
+ * are used by at least GCC (even if system headers don't provide ULLONG_MAX).
+ * Some GCC variants may provide __LONG_LONG_MAX__ but not __ULONG_LONG_MAX__.
+ *
+ * ULL / LL constants are rejected / warned about by some compilers, even if
+ * the compiler has a 64-bit type and the compiler/system headers provide an
+ * unsupported constant (ULL/LL)!  Try to avoid using ULL / LL constants.
+ * As a side effect we can only check that e.g. ULONG_MAX is larger than 32
+ * bits but can't be sure it is exactly 64 bits.  Self tests will catch such
+ * cases.
+ */
+#undef DUK_F_HAVE_64BIT
+#if !defined(DUK_F_HAVE_64BIT) && defined(ULONG_MAX)
+#if (ULONG_MAX > 4294967295UL)
+#define DUK_F_HAVE_64BIT
+typedef unsigned long duk_uint64_t;
+typedef signed long duk_int64_t;
+#endif
+#endif
+#if !defined(DUK_F_HAVE_64BIT) && defined(ULLONG_MAX)
+#if (ULLONG_MAX > 4294967295UL)
+#define DUK_F_HAVE_64BIT
+typedef unsigned long long duk_uint64_t;
+typedef signed long long duk_int64_t;
+#endif
+#endif
+#if !defined(DUK_F_HAVE_64BIT) && defined(__ULONG_LONG_MAX__)
+#if (__ULONG_LONG_MAX__ > 4294967295UL)
+#define DUK_F_HAVE_64BIT
+typedef unsigned long long duk_uint64_t;
+typedef signed long long duk_int64_t;
+#endif
+#endif
+#if !defined(DUK_F_HAVE_64BIT) && defined(__LONG_LONG_MAX__)
+#if (__LONG_LONG_MAX__ > 2147483647L)
+#define DUK_F_HAVE_64BIT
+typedef unsigned long long duk_uint64_t;
+typedef signed long long duk_int64_t;
+#endif
+#endif
+#if !defined(DUK_F_HAVE_64BIT) && \
+    (defined(DUK_F_MINGW) || defined(DUK_F_MSVC))
+/* Both MinGW and MSVC have a 64-bit type. */
+#define DUK_F_HAVE_64BIT
+typedef unsigned long duk_uint64_t;
+typedef signed long duk_int64_t;
+#endif
+#if !defined(DUK_F_HAVE_64BIT)
+/* cannot detect 64-bit type, not always needed so don't error */
+#endif
+
+typedef duk_uint8_t duk_uint_least8_t;
+typedef duk_int8_t duk_int_least8_t;
+typedef duk_uint16_t duk_uint_least16_t;
+typedef duk_int16_t duk_int_least16_t;
+typedef duk_uint32_t duk_uint_least32_t;
+typedef duk_int32_t duk_int_least32_t;
+typedef duk_uint8_t duk_uint_fast8_t;
+typedef duk_int8_t duk_int_fast8_t;
+typedef duk_uint16_t duk_uint_fast16_t;
+typedef duk_int16_t duk_int_fast16_t;
+typedef duk_uint32_t duk_uint_fast32_t;
+typedef duk_int32_t duk_int_fast32_t;
+#if defined(DUK_F_HAVE_64BIT)
+typedef duk_uint64_t duk_uint_least64_t;
+typedef duk_int64_t duk_int_least64_t;
+typedef duk_uint64_t duk_uint_fast64_t;
+typedef duk_int64_t duk_int_fast64_t;
+#endif
+#if defined(DUK_F_HAVE_64BIT)
+typedef duk_uint64_t duk_uintmax_t;
+typedef duk_int64_t duk_intmax_t;
+#else
+typedef duk_uint32_t duk_uintmax_t;
+typedef duk_int32_t duk_intmax_t;
+#endif
+
+/* Note: the funny looking computations for signed minimum 16-bit, 32-bit, and
+ * 64-bit values are intentional as the obvious forms (e.g. -0x80000000L) are
+ * -not- portable.  See code-issues.txt for a detailed discussion.
+ */
+#define DUK_UINT8_MIN         0UL
+#define DUK_UINT8_MAX         0xffUL
+#define DUK_INT8_MIN          (-0x80L)
+#define DUK_INT8_MAX          0x7fL
+#define DUK_UINT_LEAST8_MIN   0UL
+#define DUK_UINT_LEAST8_MAX   0xffUL
+#define DUK_INT_LEAST8_MIN    (-0x80L)
+#define DUK_INT_LEAST8_MAX    0x7fL
+#define DUK_UINT_FAST8_MIN    0UL
+#define DUK_UINT_FAST8_MAX    0xffUL
+#define DUK_INT_FAST8_MIN     (-0x80L)
+#define DUK_INT_FAST8_MAX     0x7fL
+#define DUK_UINT16_MIN        0UL
+#define DUK_UINT16_MAX        0xffffUL
+#define DUK_INT16_MIN         (-0x7fffL - 1L)
+#define DUK_INT16_MAX         0x7fffL
+#define DUK_UINT_LEAST16_MIN  0UL
+#define DUK_UINT_LEAST16_MAX  0xffffUL
+#define DUK_INT_LEAST16_MIN   (-0x7fffL - 1L)
+#define DUK_INT_LEAST16_MAX   0x7fffL
+#define DUK_UINT_FAST16_MIN   0UL
+#define DUK_UINT_FAST16_MAX   0xffffUL
+#define DUK_INT_FAST16_MIN    (-0x7fffL - 1L)
+#define DUK_INT_FAST16_MAX    0x7fffL
+#define DUK_UINT32_MIN        0UL
+#define DUK_UINT32_MAX        0xffffffffUL
+#define DUK_INT32_MIN         (-0x7fffffffL - 1L)
+#define DUK_INT32_MAX         0x7fffffffL
+#define DUK_UINT_LEAST32_MIN  0UL
+#define DUK_UINT_LEAST32_MAX  0xffffffffUL
+#define DUK_INT_LEAST32_MIN   (-0x7fffffffL - 1L)
+#define DUK_INT_LEAST32_MAX   0x7fffffffL
+#define DUK_UINT_FAST32_MIN   0UL
+#define DUK_UINT_FAST32_MAX   0xffffffffUL
+#define DUK_INT_FAST32_MIN    (-0x7fffffffL - 1L)
+#define DUK_INT_FAST32_MAX    0x7fffffffL
+
+/* 64-bit constants.  Since LL / ULL constants are not always available,
+ * use computed values.  These values can't be used in preprocessor
+ * comparisons; flag them as such.
+ */
+#if defined(DUK_F_HAVE_64BIT)
+#define DUK_UINT64_MIN        ((duk_uint64_t) 0)
+#define DUK_UINT64_MAX        ((duk_uint64_t) -1)
+#define DUK_INT64_MIN         ((duk_int64_t) (~(DUK_UINT64_MAX >> 1)))
+#define DUK_INT64_MAX         ((duk_int64_t) (DUK_UINT64_MAX >> 1))
+#define DUK_UINT_LEAST64_MIN  DUK_UINT64_MIN
+#define DUK_UINT_LEAST64_MAX  DUK_UINT64_MAX
+#define DUK_INT_LEAST64_MIN   DUK_INT64_MIN
+#define DUK_INT_LEAST64_MAX   DUK_INT64_MAX
+#define DUK_UINT_FAST64_MIN   DUK_UINT64_MIN
+#define DUK_UINT_FAST64_MAX   DUK_UINT64_MAX
+#define DUK_INT_FAST64_MIN    DUK_INT64_MIN
+#define DUK_INT_FAST64_MAX    DUK_INT64_MAX
+#define DUK_UINT64_MIN_COMPUTED
+#define DUK_UINT64_MAX_COMPUTED
+#define DUK_INT64_MIN_COMPUTED
+#define DUK_INT64_MAX_COMPUTED
+#define DUK_UINT_LEAST64_MIN_COMPUTED
+#define DUK_UINT_LEAST64_MAX_COMPUTED
+#define DUK_INT_LEAST64_MIN_COMPUTED
+#define DUK_INT_LEAST64_MAX_COMPUTED
+#define DUK_UINT_FAST64_MIN_COMPUTED
+#define DUK_UINT_FAST64_MAX_COMPUTED
+#define DUK_INT_FAST64_MIN_COMPUTED
+#define DUK_INT_FAST64_MAX_COMPUTED
+#endif
+
+#if defined(DUK_F_HAVE_64BIT)
+#define DUK_UINTMAX_MIN       DUK_UINT64_MIN
+#define DUK_UINTMAX_MAX       DUK_UINT64_MAX
+#define DUK_INTMAX_MIN        DUK_INT64_MIN
+#define DUK_INTMAX_MAX        DUK_INT64_MAX
+#define DUK_UINTMAX_MIN_COMPUTED
+#define DUK_UINTMAX_MAX_COMPUTED
+#define DUK_INTMAX_MIN_COMPUTED
+#define DUK_INTMAX_MAX_COMPUTED
+#else
+#define DUK_UINTMAX_MIN       0UL
+#define DUK_UINTMAX_MAX       0xffffffffUL
+#define DUK_INTMAX_MIN        (-0x7fffffffL - 1L)
+#define DUK_INTMAX_MAX        0x7fffffffL
+#endif
+
+/* This detection is not very reliable. */
+#if defined(DUK_F_32BIT_PTRS)
+typedef duk_int32_t duk_intptr_t;
+typedef duk_uint32_t duk_uintptr_t;
+#define DUK_UINTPTR_MIN       DUK_UINT32_MIN
+#define DUK_UINTPTR_MAX       DUK_UINT32_MAX
+#define DUK_INTPTR_MIN        DUK_INT32_MIN
+#define DUK_INTPTR_MAX        DUK_INT32_MAX
+#elif defined(DUK_F_64BIT_PTRS) && defined(DUK_F_HAVE_64BIT)
+typedef duk_int64_t duk_intptr_t;
+typedef duk_uint64_t duk_uintptr_t;
+#define DUK_UINTPTR_MIN       DUK_UINT64_MIN
+#define DUK_UINTPTR_MAX       DUK_UINT64_MAX
+#define DUK_INTPTR_MIN        DUK_INT64_MIN
+#define DUK_INTPTR_MAX        DUK_INT64_MAX
+#define DUK_UINTPTR_MIN_COMPUTED
+#define DUK_UINTPTR_MAX_COMPUTED
+#define DUK_INTPTR_MIN_COMPUTED
+#define DUK_INTPTR_MAX_COMPUTED
+#else
+#error cannot determine intptr type
+#endif
+
+/* SIZE_MAX may be missing so use an approximate value for it. */
+#undef DUK_SIZE_MAX_COMPUTED
+#if !defined(SIZE_MAX)
+#define DUK_SIZE_MAX_COMPUTED
+#define SIZE_MAX              ((size_t) (-1))
+#endif
+#define DUK_SIZE_MIN          0
+#define DUK_SIZE_MAX          SIZE_MAX
+
+#endif  /* C99 types */
+
+/* A few types are assumed to always exist. */
+typedef size_t duk_size_t;
+typedef ptrdiff_t duk_ptrdiff_t;
+
+/* The best type for an "all around int" in Duktape internals is "at least
+ * 32 bit signed integer" which is most convenient.  Same for unsigned type.
+ * Prefer 'int' when large enough, as it is almost always a convenient type.
+ */
+#if defined(UINT_MAX) && (UINT_MAX >= 0xffffffffUL)
+typedef int duk_int_t;
+typedef unsigned int duk_uint_t;
+#define DUK_INT_MIN           INT_MIN
+#define DUK_INT_MAX           INT_MAX
+#define DUK_UINT_MIN          0
+#define DUK_UINT_MAX          UINT_MAX
+#else
+typedef duk_int_fast32_t duk_int_t;
+typedef duk_uint_fast32_t duk_uint_t;
+#define DUK_INT_MIN           DUK_INT_FAST32_MIN
+#define DUK_INT_MAX           DUK_INT_FAST32_MAX
+#define DUK_UINT_MIN          DUK_UINT_FAST32_MIN
+#define DUK_UINT_MAX          DUK_UINT_FAST32_MAX
+#endif
+
+/* Same as 'duk_int_t' but guaranteed to be a 'fast' variant if this
+ * distinction matters for the CPU.  These types are used mainly in the
+ * executor where it might really matter.
+ */
+typedef duk_int_fast32_t duk_int_fast_t;
+typedef duk_uint_fast32_t duk_uint_fast_t;
+#define DUK_INT_FAST_MIN      DUK_INT_FAST32_MIN
+#define DUK_INT_FAST_MAX      DUK_INT_FAST32_MAX
+#define DUK_UINT_FAST_MIN     DUK_UINT_FAST32_MIN
+#define DUK_UINT_FAST_MAX     DUK_UINT_FAST32_MAX
+
+/* Small integers (16 bits or more) can fall back to the 'int' type, but
+ * have a typedef so they are marked "small" explicitly.
+ */
+typedef int duk_small_int_t;
+typedef unsigned int duk_small_uint_t;
+#define DUK_SMALL_INT_MIN     INT_MIN
+#define DUK_SMALL_INT_MAX     INT_MAX
+#define DUK_SMALL_UINT_MIN    0
+#define DUK_SMALL_UINT_MAX    UINT_MAX
+
+/* Fast variants of small integers, again for really fast paths like the
+ * executor.
+ */
+typedef duk_int_fast16_t duk_small_int_fast_t;
+typedef duk_uint_fast16_t duk_small_uint_fast_t;
+#define DUK_SMALL_INT_FAST_MIN    DUK_INT_FAST16_MIN
+#define DUK_SMALL_INT_FAST_MAX    DUK_INT_FAST16_MAX
+#define DUK_SMALL_UINT_FAST_MIN   DUK_UINT_FAST16_MIN
+#define DUK_SMALL_UINT_FAST_MAX   DUK_UINT_FAST16_MAX
+
+/* Boolean values are represented with the platform 'int'. */
+typedef duk_small_int_t duk_bool_t;
+#define DUK_BOOL_MIN              DUK_SMALL_INT_MIN
+#define DUK_BOOL_MAX              DUK_SMALL_INT_MAX
+
+/* Index values must have at least 32-bit signed range. */
+typedef duk_int_t duk_idx_t;
+#define DUK_IDX_MIN               DUK_INT_MIN
+#define DUK_IDX_MAX               DUK_INT_MAX
+
+/* Array index values, could be exact 32 bits.
+ * Currently no need for signed duk_arridx_t.
+ */
+typedef duk_uint_t duk_uarridx_t;
+#define DUK_UARRIDX_MIN           DUK_UINT_MIN
+#define DUK_UARRIDX_MAX           DUK_UINT_MAX
+
+/* Duktape/C function return value, platform int is enough for now to
+ * represent 0, 1, or negative error code.  Must be compatible with
+ * assigning truth values (e.g. duk_ret_t rc = (foo == bar);).
+ */
+typedef duk_small_int_t duk_ret_t;
+#define DUK_RET_MIN               DUK_SMALL_INT_MIN
+#define DUK_RET_MAX               DUK_SMALL_INT_MAX
+
+/* Error codes are represented with platform int.  High bits are used
+ * for flags and such, so 32 bits are needed.
+ */
+typedef duk_int_t duk_errcode_t;
+#define DUK_ERRCODE_MIN           DUK_INT_MIN
+#define DUK_ERRCODE_MAX           DUK_INT_MAX
+
+/* Codepoint type.  Must be 32 bits or more because it is used also for
+ * internal codepoints.  The type is signed because negative codepoints
+ * are used as internal markers (e.g. to mark EOF or missing argument).
+ * (X)UTF-8/CESU-8 encode/decode take and return an unsigned variant to
+ * ensure duk_uint32_t casts back and forth nicely.  Almost everything
+ * else uses the signed one.
+ */
+typedef duk_int_t duk_codepoint_t;
+typedef duk_uint_t duk_ucodepoint_t;
+#define DUK_CODEPOINT_MIN         DUK_INT_MIN
+#define DUK_CODEPOINT_MAX         DUK_INT_MAX
+#define DUK_UCODEPOINT_MIN        DUK_UINT_MIN
+#define DUK_UCODEPOINT_MAX        DUK_UINT_MAX
+
+/* IEEE float/double typedef. */
+typedef float duk_float_t;
+typedef double duk_double_t;
+
+/* We're generally assuming that we're working on a platform with a 32-bit
+ * address space.  If DUK_SIZE_MAX is a typecast value (which is necessary
+ * if SIZE_MAX is missing), the check must be avoided because the
+ * preprocessor can't do a comparison.
+ */
+#if !defined(DUK_SIZE_MAX)
+#error DUK_SIZE_MAX is undefined, probably missing SIZE_MAX
+#elif !defined(DUK_SIZE_MAX_COMPUTED)
+#if DUK_SIZE_MAX < 0xffffffffUL
+/* On some systems SIZE_MAX can be smaller than max unsigned 32-bit value
+ * which seems incorrect if size_t is (at least) an unsigned 32-bit type.
+ * However, it doesn't seem useful to error out compilation if this is the
+ * case.
+ */
+#endif
+#endif
+
+/* Type for public API calls. */
+typedef struct duk_hthread duk_context;
+
+/*
+ *  Check whether we should use 64-bit integers
+ */
+
+/* Quite incomplete now.  Use 64-bit types if detected (C99 or other detection)
+ * unless they are known to be unreliable.  For instance, 64-bit types are
+ * available on VBCC but seem to misbehave.
+ */
+#if defined(DUK_F_HAVE_64BIT) && !defined(DUK_F_VBCC)
+#define DUK_USE_64BIT_OPS
+#else
+#undef DUK_USE_64BIT_OPS
+#endif
+
+/*
+ *  Alignment requirement and support for unaligned accesses
+ *
+ *  Assume unaligned accesses are not supported unless specifically allowed
+ *  in the target platform.  Some platforms may support unaligned accesses
+ *  but alignment to 4 or 8 may still be desirable.
+ */
+
+#undef DUK_USE_UNALIGNED_ACCESSES_POSSIBLE
+#undef DUK_USE_ALIGN_BY
+
+#if defined(DUK_F_EMSCRIPTEN)
+/* Required on at least some targets, so use whenever Emscripten used,
+ * regardless of compilation target.
+ */
+#define DUK_USE_ALIGN_BY 8
+#elif defined(DUK_F_ARM)
+#define DUK_USE_ALIGN_BY 4
+#elif defined(DUK_F_MIPS32)
+/* Based on 'make checkalign' there are no alignment requirements on
+ * Linux MIPS except for doubles, which need align by 4.  Alignment
+ * requirements vary based on target though.
+ */
+#define DUK_USE_ALIGN_BY 4
+#elif defined(DUK_F_MIPS64)
+/* Good default is a bit arbitrary because alignment requirements
+ * depend on target.  See https://github.com/svaarala/duktape/issues/102.
+ */
+#define DUK_USE_ALIGN_BY 8
+#elif defined(DUK_F_SUPERH)
+/* Based on 'make checkalign' there are no alignment requirements on
+ * Linux SH4, but align by 4 is probably a good basic default.
+ */
+#define DUK_USE_ALIGN_BY 4
+#elif defined(DUK_F_X86) || defined(DUK_F_X32) || defined(DUK_F_X64) || \
+      defined(DUK_F_BCC)
+/* XXX: This is technically not guaranteed because it's possible to configure
+ * an x86 to require aligned accesses with Alignment Check (AC) flag.
+ */
+#define DUK_USE_ALIGN_BY 1
+#define DUK_USE_UNALIGNED_ACCESSES_POSSIBLE
+#else
+/* Unknown, use safe default */
+#define DUK_USE_ALIGN_BY 8
+#endif
+
+/* User forced alignment to 4 or 8. */
+#if defined(DUK_OPT_FORCE_ALIGN)
+#undef DUK_USE_ALIGN_BY
+#undef DUK_USE_UNALIGNED_ACCESSES_POSSIBLE
+#if (DUK_OPT_FORCE_ALIGN == 4)
+#define DUK_USE_ALIGN_BY 4
+#elif (DUK_OPT_FORCE_ALIGN == 8)
+#define DUK_USE_ALIGN_BY 8
+#else
+#error invalid DUK_OPT_FORCE_ALIGN value
+#endif
+#endif
+
+/* Compiler specific hackery needed to force struct size to match aligment,
+ * see e.g. duk_hbuffer.h.
+ *
+ * http://stackoverflow.com/questions/11130109/c-struct-size-alignment
+ * http://stackoverflow.com/questions/10951039/specifying-64-bit-alignment
+ */
+#if defined(DUK_F_MSVC)
+#define DUK_USE_PACK_MSVC_PRAGMA
+#elif defined(DUK_F_GCC)
+#define DUK_USE_PACK_GCC_ATTR
+#elif defined(DUK_F_CLANG)
+#define DUK_USE_PACK_CLANG_ATTR
+#else
+#define DUK_USE_PACK_DUMMY_MEMBER
+#endif
+
+#ifdef DUK_USE_UNALIGNED_ACCESSES_POSSIBLE
+#define DUK_USE_HASHBYTES_UNALIGNED_U32_ACCESS
+#else
+#undef DUK_USE_HASHBYTES_UNALIGNED_U32_ACCESS
+#endif
+
+/* Object property allocation layout has implications for memory and code
+ * footprint and generated code size/speed.  The best layout also depends
+ * on whether the platform has alignment requirements or benefits from
+ * having mostly aligned accesses.
+ */
+#undef DUK_USE_HOBJECT_LAYOUT_1
+#undef DUK_USE_HOBJECT_LAYOUT_2
+#undef DUK_USE_HOBJECT_LAYOUT_3
+#if defined(DUK_USE_UNALIGNED_ACCESSES_POSSIBLE) && (DUK_USE_ALIGN_BY == 1)
+/* On platforms without any alignment issues, layout 1 is preferable
+ * because it compiles to slightly less code and provides direct access
+ * to property keys.
+ */
+#define DUK_USE_HOBJECT_LAYOUT_1
+#else
+/* On other platforms use layout 2, which requires some padding but
+ * is a bit more natural than layout 3 in ordering the entries.  Layout
+ * 3 is currently not used.
+ */
+#define DUK_USE_HOBJECT_LAYOUT_2
+#endif
+
+/*
+ *  Byte order and double memory layout detection
+ *
+ *  Endianness detection is a major portability hassle because the macros
+ *  and headers are not standardized.  There's even variance across UNIX
+ *  platforms.  Even with "standard" headers, details like underscore count
+ *  varies between platforms, e.g. both __BYTE_ORDER and _BYTE_ORDER are used
+ *  (Crossbridge has a single underscore, for instance).
+ *
+ *  The checks below are structured with this in mind: several approaches are
+ *  used, and at the end we check if any of them worked.  This allows generic
+ *  approaches to be tried first, and platform/compiler specific hacks tried
+ *  last.  As a last resort, the user can force a specific endianness, as it's
+ *  not likely that automatic detection will work on the most exotic platforms.
+ *
+ *  Duktape supports little and big endian machines.  There's also support
+ *  for a hybrid used by some ARM machines where integers are little endian
+ *  but IEEE double values use a mixed order (12345678 -> 43218765).  This
+ *  byte order for doubles is referred to as "mixed endian".
+ */
+
+#undef DUK_F_BYTEORDER
+#undef DUK_USE_BYTEORDER_FORCED
+
+/* DUK_F_BYTEORDER is set as an intermediate value when detection
+ * succeeds, to one of:
+ *   1 = little endian
+ *   2 = mixed (arm hybrid) endian
+ *   3 = big endian
+ */
+
+/* For custom platforms allow user to define byteorder explicitly.
+ * Since endianness headers are not standardized, this is a useful
+ * workaround for custom platforms for which endianness detection
+ * is not directly supported.  Perhaps custom hardware is used and
+ * user cannot submit upstream patches.
+ */
+#if defined(DUK_OPT_FORCE_BYTEORDER)
+#if (DUK_OPT_FORCE_BYTEORDER == 1)
+#define DUK_F_BYTEORDER 1
+#elif (DUK_OPT_FORCE_BYTEORDER == 2)
+#define DUK_F_BYTEORDER 2
+#elif (DUK_OPT_FORCE_BYTEORDER == 3)
+#define DUK_F_BYTEORDER 3
+#else
+#error invalid DUK_OPT_FORCE_BYTEORDER value
+#endif
+#define DUK_USE_BYTEORDER_FORCED
+#endif  /* DUK_OPT_FORCE_BYTEORDER */
+
+/* More or less standard endianness predefines provided by header files.
+ * The ARM hybrid case is detected by assuming that __FLOAT_WORD_ORDER
+ * will be big endian, see: http://lists.mysql.com/internals/443.
+ */
+#if !defined(DUK_F_BYTEORDER)
+#if defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN) || \
+    defined(_BYTE_ORDER) && defined(_LITTLE_ENDIAN) && (_BYTE_ORDER == _LITTLE_ENDIAN) || \
+    defined(__LITTLE_ENDIAN__)
+/* Integer little endian */
+#if defined(__FLOAT_WORD_ORDER) && defined(__LITTLE_ENDIAN) && (__FLOAT_WORD_ORDER == __LITTLE_ENDIAN) || \
+    defined(_FLOAT_WORD_ORDER) && defined(_LITTLE_ENDIAN) && (_FLOAT_WORD_ORDER == _LITTLE_ENDIAN)
+#define DUK_F_BYTEORDER 1
+#elif defined(__FLOAT_WORD_ORDER) && defined(__BIG_ENDIAN) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) || \
+      defined(_FLOAT_WORD_ORDER) && defined(_BIG_ENDIAN) && (_FLOAT_WORD_ORDER == _BIG_ENDIAN)
+#define DUK_F_BYTEORDER 2
+#elif !defined(__FLOAT_WORD_ORDER) && !defined(_FLOAT_WORD_ORDER)
+/* Float word order not known, assume not a hybrid. */
+#define DUK_F_BYTEORDER 1
+#else
+/* byte order is little endian but cannot determine IEEE double word order */
+#endif  /* float word order */
+#elif defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN) || \
+      defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && (_BYTE_ORDER == _BIG_ENDIAN) || \
+      defined(__BIG_ENDIAN__)
+/* Integer big endian */
+#if defined(__FLOAT_WORD_ORDER) && defined(__BIG_ENDIAN) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) || \
+    defined(_FLOAT_WORD_ORDER) && defined(_BIG_ENDIAN) && (_FLOAT_WORD_ORDER == _BIG_ENDIAN)
+#define DUK_F_BYTEORDER 3
+#elif !defined(__FLOAT_WORD_ORDER) && !defined(_FLOAT_WORD_ORDER)
+/* Float word order not known, assume not a hybrid. */
+#define DUK_F_BYTEORDER 3
+#else
+/* byte order is big endian but cannot determine IEEE double word order */
+#endif  /* float word order */
+#else
+/* cannot determine byte order */
+#endif  /* integer byte order */
+#endif  /* !defined(DUK_F_BYTEORDER) */
+
+/* GCC and Clang provide endianness defines as built-in predefines, with
+ * leading and trailing double underscores (e.g. __BYTE_ORDER__).  See
+ * output of "make gccpredefs" and "make clangpredefs".  Clang doesn't
+ * seem to provide __FLOAT_WORD_ORDER__.
+ * http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
+ */
+#if !defined(DUK_F_BYTEORDER) && defined(__BYTE_ORDER__)
+#if defined(__ORDER_LITTLE_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
+/* Integer little endian */
+#if defined(__FLOAT_WORD_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \
+    (__FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__)
+#define DUK_F_BYTEORDER 1
+#elif defined(__FLOAT_WORD_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \
+      (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__)
+#define DUK_F_BYTEORDER 2
+#elif !defined(__FLOAT_WORD_ORDER__)
+/* Float word order not known, assume not a hybrid. */
+#define DUK_F_BYTEORDER 1
+#else
+/* byte order is little endian but cannot determine IEEE double word order */
+#endif  /* float word order */
+#elif defined(__ORDER_BIG_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
+/* Integer big endian */
+#if defined(__FLOAT_WORD_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \
+    (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__)
+#define DUK_F_BYTEORDER 3
+#elif !defined(__FLOAT_WORD_ORDER__)
+/* Float word order not known, assume not a hybrid. */
+#define DUK_F_BYTEORDER 3
+#else
+/* byte order is big endian but cannot determine IEEE double word order */
+#endif  /* float word order */
+#else
+/* cannot determine byte order; __ORDER_PDP_ENDIAN__ is related to 32-bit
+ * integer ordering and is not relevant
+ */
+#endif  /* integer byte order */
+#endif  /* !defined(DUK_F_BYTEORDER) && defined(__BYTE_ORDER__) */
+
+/* Atari ST TOS */
+#if !defined(DUK_F_BYTEORDER) && defined(DUK_F_TOS)
+#define DUK_F_BYTEORDER 3
+#endif
+
+/* AmigaOS on M68k */
+#if !defined(DUK_F_BYTEORDER) && defined(DUK_F_AMIGAOS)
+#if defined(DUK_F_M68K)
+#define DUK_F_BYTEORDER 3
+#endif
+#endif
+
+/* On Windows, assume we're little endian.  Even Itanium which has a
+ * configurable endianness runs little endian in Windows.
+ */
+#if !defined(DUK_F_BYTEORDER) && defined(DUK_F_WINDOWS)
+/* XXX: verify that Windows on ARM is little endian for floating point
+ * values too.
+ */
+#define DUK_F_BYTEORDER 1
+#endif  /* Windows */
+
+/* Crossbridge should work with the standard byteorder #ifdefs.  It doesn't
+ * provide _FLOAT_WORD_ORDER but the standard approach now covers that case
+ * too.  This has been left here just in case.
+ */
+#if !defined(DUK_F_BYTEORDER) && defined(DUK_F_FLASHPLAYER)
+#define DUK_F_BYTEORDER 1
+#endif
+
+/* QNX gcc cross compiler seems to define e.g. __LITTLEENDIAN__ or __BIGENDIAN__:
+ *  $ /opt/qnx650/host/linux/x86/usr/bin/i486-pc-nto-qnx6.5.0-gcc -dM -E - </dev/null | grep -ni endian
+ *  67:#define __LITTLEENDIAN__ 1
+ *  $ /opt/qnx650/host/linux/x86/usr/bin/mips-unknown-nto-qnx6.5.0-gcc -dM -E - </dev/null | grep -ni endian
+ *  81:#define __BIGENDIAN__ 1
+ *  $ /opt/qnx650/host/linux/x86/usr/bin/arm-unknown-nto-qnx6.5.0-gcc -dM -E - </dev/null | grep -ni endian
+ *  70:#define __LITTLEENDIAN__ 1
+ */
+#if !defined(DUK_F_BYTEORDER) && defined(DUK_F_QNX)
+/* XXX: ARM hybrid? */
+#if defined(__LITTLEENDIAN__)
+#define DUK_F_BYTEORDER 1
+#elif defined(__BIGENDIAN__)
+#define DUK_F_BYTEORDER 3
+#endif
+#endif
+
+/* Bruce's C Compiler (BCC), assume we're on x86. */
+#if !defined(DUK_F_BYTEORDER) && defined(DUK_F_BCC)
+#define DUK_F_BYTEORDER 1
+#endif
+
+/* Check whether or not byte order detection worked based on the intermediate
+ * define, and define final values.  If detection failed, #error out.
+ */
+#if defined(DUK_F_BYTEORDER)
+#if (DUK_F_BYTEORDER == 1)
+#define DUK_USE_INTEGER_LE
+#define DUK_USE_DOUBLE_LE
+#elif (DUK_F_BYTEORDER == 2)
+#define DUK_USE_INTEGER_LE  /* integer endianness is little on purpose */
+#define DUK_USE_DOUBLE_ME
+#elif (DUK_F_BYTEORDER == 3)
+#define DUK_USE_INTEGER_BE
+#define DUK_USE_DOUBLE_BE
+#else
+#error unsupported: byte order detection failed (internal error, should not happen)
+#endif  /* byte order */
+#else
+#error unsupported: byte order detection failed
+#endif  /* defined(DUK_F_BYTEORDER) */
+
+/*
+ *  Check whether or not a packed duk_tval representation is possible.
+ *  What's basically required is that pointers are 32-bit values
+ *  (sizeof(void *) == 4).  Best effort check, not always accurate.
+ *  If guess goes wrong, crashes may result; self tests also verify
+ *  the guess.
+ */
+
+#undef DUK_USE_PACKED_TVAL_POSSIBLE
+
+/* Strict C99 case: DUK_UINTPTR_MAX (= UINTPTR_MAX) should be very reliable */
+#if !defined(DUK_USE_PACKED_TVAL_POSSIBLE) && defined(DUK_F_HAVE_INTTYPES) && defined(DUK_UINTPTR_MAX)
+#if (DUK_UINTPTR_MAX <= 0xffffffffUL)
+#define DUK_USE_PACKED_TVAL_POSSIBLE
+#endif
+#endif
+
+/* Non-C99 case, still relying on DUK_UINTPTR_MAX, as long as it is not a computed value */
+#if !defined(DUK_USE_PACKED_TVAL_POSSIBLE) && defined(DUK_UINTPTR_MAX) && !defined(DUK_UINTPTR_MAX_COMPUTED)
+#if (DUK_UINTPTR_MAX <= 0xffffffffUL)
+#define DUK_USE_PACKED_TVAL_POSSIBLE
+#endif
+#endif
+
+/* DUK_SIZE_MAX (= SIZE_MAX) is often reliable */
+#if !defined(DUK_USE_PACKED_TVAL_POSSIBLE) && defined(DUK_SIZE_MAX) && !defined(DUK_SIZE_MAX_COMPUTED)
+#if DUK_SIZE_MAX <= 0xffffffffUL
+#define DUK_USE_PACKED_TVAL_POSSIBLE
+#endif
+#endif
+
+/* M68K: packed always possible */
+#if !defined(DUK_USE_PACKED_TVAL_POSSIBLE) && defined(DUK_F_M68K)
+#define DUK_USE_PACKED_TVAL_POSSIBLE
+#endif
+
+/* With Emscripten, force unpacked duk_tval just to be safe, as it seems to
+ * break at least on Firefox (probably IEEE double arithmetic is not 100%
+ * supported, especially for NaNs).
+ */
+#if defined(DUK_USE_PACKED_TVAL_POSSIBLE) && defined(DUK_F_EMSCRIPTEN)
+#undef DUK_USE_PACKED_TVAL_POSSIBLE
+#endif
+
+/* Microsoft Visual Studio 2010 on x64 fails the above rules and tries to
+ * use a packed type.  Force unpacked on x64 in general.
+ */
+#if defined(DUK_USE_PACKED_TVAL_POSSIBLE) && defined(DUK_F_X64)
+#undef DUK_USE_PACKED_TVAL_POSSIBLE
+#endif
+
+/* GCC/clang inaccurate math would break compliance and probably duk_tval,
+ * so refuse to compile.  Relax this if -ffast-math is tested to work.
+ */
+#if defined(__FAST_MATH__)
+#error __FAST_MATH__ defined, refusing to compile
+#endif
+
+/*
+ *  Detection of double constants and math related functions.  Availability
+ *  of constants and math functions is a significant porting concern.
+ *
+ *  INFINITY/HUGE_VAL is problematic on GCC-3.3: it causes an overflow warning
+ *  and there is no pragma in GCC-3.3 to disable it.  Using __builtin_inf()
+ *  avoids this problem for some reason.
+ */
+
+#define DUK_DOUBLE_2TO32     4294967296.0
+#define DUK_DOUBLE_2TO31     2147483648.0
+
+#undef DUK_USE_COMPUTED_INFINITY
+#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION < 40600)
+/* GCC older than 4.6: avoid overflow warnings related to using INFINITY */
+#define DUK_DOUBLE_INFINITY  (__builtin_inf())
+#elif defined(INFINITY)
+#define DUK_DOUBLE_INFINITY  ((double) INFINITY)
+#elif !defined(DUK_F_VBCC) && !defined(DUK_F_MSVC) && !defined(DUK_F_BCC)
+#define DUK_DOUBLE_INFINITY  (1.0 / 0.0)
+#else
+/* In VBCC (1.0 / 0.0) results in a warning and 0.0 instead of infinity.
+ * Use a computed infinity (initialized when a heap is created at the
+ * latest).
+ */
+extern double duk_computed_infinity;
+#define DUK_USE_COMPUTED_INFINITY
+#define DUK_DOUBLE_INFINITY  duk_computed_infinity
+#endif
+
+#undef DUK_USE_COMPUTED_NAN
+#if defined(NAN)
+#define DUK_DOUBLE_NAN       NAN
+#elif !defined(DUK_F_VBCC) && !defined(DUK_F_MSVC) && !defined(DUK_F_BCC)
+#define DUK_DOUBLE_NAN       (0.0 / 0.0)
+#else
+/* In VBCC (0.0 / 0.0) results in a warning and 0.0 instead of NaN.
+ * In MSVC (VS2010 Express) (0.0 / 0.0) results in a compile error.
+ * Use a computed NaN (initialized when a heap is created at the
+ * latest).
+ */
+extern double duk_computed_nan;
+#define DUK_USE_COMPUTED_NAN
+#define DUK_DOUBLE_NAN       duk_computed_nan
+#endif
+
+/* Many platforms are missing fpclassify() and friends, so use replacements
+ * if necessary.  The replacement constants (FP_NAN etc) can be anything but
+ * match Linux constants now.
+ */
+#undef DUK_USE_REPL_FPCLASSIFY
+#undef DUK_USE_REPL_SIGNBIT
+#undef DUK_USE_REPL_ISFINITE
+#undef DUK_USE_REPL_ISNAN
+#undef DUK_USE_REPL_ISINF
+
+/* Complex condition broken into separate parts. */
+#undef DUK_F_USE_REPL_ALL
+#if !(defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO) && \
+      defined(FP_SUBNORMAL) && defined(FP_NORMAL))
+/* Missing some obvious constants. */
+#define DUK_F_USE_REPL_ALL
+#elif defined(DUK_F_AMIGAOS) && defined(DUK_F_VBCC)
+/* VBCC is missing the built-ins even in C99 mode (perhaps a header issue) */
+#define DUK_F_USE_REPL_ALL
+#elif defined(DUK_F_FREEBSD) && defined(DUK_F_CLANG)
+/* Placeholder fix for (detection is wider than necessary):
+ * http://llvm.org/bugs/show_bug.cgi?id=17788
+ */
+#define DUK_F_USE_REPL_ALL
+#elif defined(DUK_F_UCLIBC)
+/* At least some uclibc versions have broken floating point math.  For
+ * example, fpclassify() can incorrectly classify certain NaN formats.
+ * To be safe, use replacements.
+ */
+#define DUK_F_USE_REPL_ALL
+#endif
+
+#if defined(DUK_F_USE_REPL_ALL)
+#define DUK_USE_REPL_FPCLASSIFY
+#define DUK_USE_REPL_SIGNBIT
+#define DUK_USE_REPL_ISFINITE
+#define DUK_USE_REPL_ISNAN
+#define DUK_USE_REPL_ISINF
+#define DUK_FPCLASSIFY       duk_repl_fpclassify
+#define DUK_SIGNBIT          duk_repl_signbit
+#define DUK_ISFINITE         duk_repl_isfinite
+#define DUK_ISNAN            duk_repl_isnan
+#define DUK_ISINF            duk_repl_isinf
+#define DUK_FP_NAN           0
+#define DUK_FP_INFINITE      1
+#define DUK_FP_ZERO          2
+#define DUK_FP_SUBNORMAL     3
+#define DUK_FP_NORMAL        4
+#else
+#define DUK_FPCLASSIFY       fpclassify
+#define DUK_SIGNBIT          signbit
+#define DUK_ISFINITE         isfinite
+#define DUK_ISNAN            isnan
+#define DUK_ISINF            isinf
+#define DUK_FP_NAN           FP_NAN
+#define DUK_FP_INFINITE      FP_INFINITE
+#define DUK_FP_ZERO          FP_ZERO
+#define DUK_FP_SUBNORMAL     FP_SUBNORMAL
+#define DUK_FP_NORMAL        FP_NORMAL
+#endif
+
+#if defined(DUK_F_USE_REPL_ALL)
+#undef DUK_F_USE_REPL_ALL
+#endif
+
+/* Some math functions are C99 only.  This is also an issue with some
+ * embedded environments using uclibc where uclibc has been configured
+ * not to provide some functions.  For now, use replacements whenever
+ * using uclibc.
+ */
+#undef DUK_USE_MATH_FMIN
+#undef DUK_USE_MATH_FMAX
+#undef DUK_USE_MATH_ROUND
+#if defined(DUK_F_UCLIBC)
+/* uclibc may be missing these */
+#elif defined(DUK_F_AMIGAOS) && defined(DUK_F_VBCC)
+/* vbcc + AmigaOS may be missing these */
+#elif !defined(DUK_F_C99) && !defined(DUK_F_CPP11)
+/* build is not C99 or C++11, play it safe */
+#else
+/* C99 or C++11, no known issues */
+#define DUK_USE_MATH_FMIN
+#define DUK_USE_MATH_FMAX
+#define DUK_USE_MATH_ROUND
+#endif
+
+/* These functions don't currently need replacement but are wrapped for
+ * completeness.  Because these are used as function pointers, they need
+ * to be defined as concrete C functions (not macros).
+ */
+#define DUK_FABS             fabs
+#define DUK_FMIN             fmin
+#define DUK_FMAX             fmax
+#define DUK_FLOOR            floor
+#define DUK_CEIL             ceil
+#define DUK_FMOD             fmod
+#define DUK_POW              pow
+#define DUK_ACOS             acos
+#define DUK_ASIN             asin
+#define DUK_ATAN             atan
+#define DUK_ATAN2            atan2
+#define DUK_SIN              sin
+#define DUK_COS              cos
+#define DUK_TAN              tan
+#define DUK_EXP              exp
+#define DUK_LOG              log
+#define DUK_SQRT             sqrt
+
+/* NetBSD 6.0 x86 (at least) has a few problems with pow() semantics,
+ * see test-bug-netbsd-math-pow.js.  Use NetBSD specific workaround.
+ * (This might be a wider problem; if so, generalize the define name.)
+ */
+#undef DUK_USE_POW_NETBSD_WORKAROUND
+#if defined(DUK_F_NETBSD)
+#define DUK_USE_POW_NETBSD_WORKAROUND
+#endif
+
+/* Rely as little as possible on compiler behavior for NaN comparison,
+ * signed zero handling, etc.  Currently never activated but may be needed
+ * for broken compilers.
+ */
+#undef DUK_USE_PARANOID_MATH
+
+/* There was a curious bug where test-bi-date-canceling.js would fail e.g.
+ * on 64-bit Ubuntu, gcc-4.8.1, -m32, and no -std=c99.  Some date computations
+ * using doubles would be optimized which then broke some corner case tests.
+ * The problem goes away by adding 'volatile' to the datetime computations.
+ * Not sure what the actual triggering conditions are, but using this on
+ * non-C99 systems solves the known issues and has relatively little cost
+ * on other platforms.  See bugs/issue-2e9d9c2d761dabaf8136c0897b91a270d1a47147.yaml.
+ */
+#undef DUK_USE_PARANOID_DATE_COMPUTATION
+#if !defined(DUK_F_C99)
+#define DUK_USE_PARANOID_DATE_COMPUTATION
+#endif
+
+/*
+ *  ANSI C string/memory function wrapper defines to allow easier workarounds.
+ *  Also convenience macros like DUK_MEMZERO which may be mapped to existing
+ *  platform function to zero memory (like the deprecated bzero).
+ *
+ *  For instance, some platforms don't support zero-size memcpy correctly,
+ *  some arcane uclibc versions have a buggy memcpy (but working memmove)
+ *  and so on.  Such broken platforms can be dealt with here.
+ *
+ *  NOTE: ANSI C (various versions) and some implementations require that the
+ *  pointer arguments to memset(), memcpy(), and memmove() be valid values
+ *  even when byte size is 0 (even a NULL pointer is considered invalid in
+ *  this context).  Zero-size operations as such are allowed, as long as their
+ *  pointer arguments point to a valid memory area.  The DUK_MEMSET(),
+ *  DUK_MEMCPY(), and DUK_MEMMOVE() macros require this same behavior, i.e.:
+ *  (1) pointers must be valid and non-NULL, (2) zero size must otherwise be
+ *  allowed.  If these are not fulfilled, a macro wrapper is needed.
+ *
+ *    http://stackoverflow.com/questions/5243012/is-it-guaranteed-to-be-safe-to-perform-memcpy0-0-0
+ *    http://lists.cs.uiuc.edu/pipermail/llvmdev/2007-October/011065.html
+ *
+ *  Not sure what's the required behavior when a pointer points just past the
+ *  end of a buffer, which often happens in practice (e.g. zero size memmoves).
+ *  For example, if allocation size is 3, the following pointer would not
+ *  technically point to a valid memory byte:
+ *
+ *    <-- alloc -->
+ *    | 0 | 1 | 2 | .....
+ *                  ^-- p=3, points after last valid byte (2)
+ *
+ *  If this is a practical issue, wrappers are again needed.
+ */
+
+typedef FILE duk_file;
+#define DUK_STDIN       stdin
+#define DUK_STDOUT      stdout
+#define DUK_STDERR      stderr
+
+/* Special naming to avoid conflict with e.g. DUK_FREE() in duk_heap.h
+ * (which is unfortunately named).
+ */
+#define DUK_ANSI_MALLOC      malloc
+#define DUK_ANSI_REALLOC     realloc
+#define DUK_ANSI_CALLOC      calloc
+#define DUK_ANSI_FREE        free
+
+/* Old uclibcs have a broken memcpy so use memmove instead (this is overly
+ * wide now on purpose):
+ * http://lists.uclibc.org/pipermail/uclibc-cvs/2008-October/025511.html
+ */
+#if defined(DUK_F_UCLIBC)
+#define DUK_MEMCPY       memmove
+#else
+#define DUK_MEMCPY       memcpy
+#endif
+
+#define DUK_MEMMOVE      memmove
+#define DUK_MEMCMP       memcmp
+#define DUK_MEMSET       memset
+#define DUK_STRLEN       strlen
+#define DUK_STRCMP       strcmp
+#define DUK_STRNCMP      strncmp
+#define DUK_PRINTF       printf
+#define DUK_FPRINTF      fprintf
+#define DUK_SPRINTF      sprintf
+
+#if defined(DUK_F_MSVC)
+/* _snprintf() does NOT NUL terminate on truncation, but Duktape code never
+ * assumes that.
+ * http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
+ */
+#define DUK_SNPRINTF     _snprintf
+#else
+#define DUK_SNPRINTF     snprintf
+#endif
+
+#define DUK_VSPRINTF     vsprintf
+
+#if defined(DUK_F_MSVC)
+#if (_MSC_VER < 1600)
+/* Older MSVC version are missing vsnprintf() but have _vsnprintf(). */
+#define DUK_VSNPRINTF    _vsnprintf
+#else
+#define DUK_VSNPRINTF    vsnprintf
+#endif
+#else
+#define DUK_VSNPRINTF    vsnprintf
+#endif  /* DUK_F_MSVC */
+
+#define DUK_SSCANF       sscanf
+#define DUK_VSSCANF      vsscanf
+#define DUK_FOPEN        fopen
+#define DUK_FCLOSE       fclose
+#define DUK_FREAD        fread
+#define DUK_FWRITE       fwrite
+#define DUK_FSEEK        fseek
+#define DUK_FTELL        ftell
+#define DUK_FFLUSH       fflush
+#define DUK_FPUTC        fputc
+
+#define DUK_MEMZERO(p,n) \
+	DUK_MEMSET((p), 0, (n))
+
+/*
+ *  Vararg macro wrappers.  We need va_copy() which is defined in C99 / C++11,
+ *  so an awkward replacement is needed for pre-C99 / pre-C++11 environments.
+ *  This will quite likely need portability hacks for some non-C99 environments.
+ */
+
+#if defined(DUK_F_C99) || defined(DUK_F_CPP11)
+/* C99 / C++11 and above: rely on va_copy() which is required.
+ * Omit parenthesis on macro right side on purpose to minimize differences
+ * to direct use.
+ */
+#define DUK_VA_COPY(dest,src) va_copy(dest,src)
+#elif defined(DUK_F_GCC) || defined(DUK_F_CLANG)
+/* GCC: assume we have __va_copy() in non-C99 mode, which should be correct
+ * for even quite old GCC versions.  Clang matches GCC behavior.
+ */
+#define DUK_VA_COPY(dest,src) __va_copy(dest,src)
+#else
+/* Pre-C99: va_list type is implementation dependent.  This replacement
+ * assumes it is a plain value so that a simple assignment will work.
+ * This is not the case on all platforms (it may be a single-array element,
+ * for instance).
+ */
+#define DUK_VA_COPY(dest,src) do { (dest) = (src); } while (0)
+#endif
+
+/*
+ *  Miscellaneous ANSI C or other platform wrappers.
+ */
+
+#define DUK_ABORT        abort
+#define DUK_EXIT         exit
+
+/*
+ *  Avoiding platform function pointers.
+ *
+ *  On some platforms built-in functions may be implemented as macros or
+ *  inline functions, so they can't be necessarily addressed by function
+ *  pointers.  This is certainly the case with some platform "polyfills"
+ *  which provide missing C99/C++11 functions through macros, and may be
+ *  the case with VS2013 (see GH-17).
+ */
+
+/* This is now the default: the cost in footprint is negligible. */
+#define DUK_USE_AVOID_PLATFORM_FUNCPTRS
+
+/*
+ *  Macro hackery to convert e.g. __LINE__ to a string without formatting,
+ *  see: http://stackoverflow.com/questions/240353/convert-a-preprocessor-token-to-a-string
+ */
+
+#define DUK_F_STRINGIFY_HELPER(x)  #x
+#define DUK_MACRO_STRINGIFY(x)  DUK_F_STRINGIFY_HELPER(x)
+
+/*
+ *  Cause segfault macro.
+ *
+ *  This is optionally used by panic handling to cause the program to segfault
+ *  (instead of e.g. abort()) on panic.  Valgrind will then indicate the C
+ *  call stack leading to the panic.
+ */
+
+#define DUK_CAUSE_SEGFAULT()  do { \
+		*((volatile duk_uint32_t *) NULL) = (duk_uint32_t) 0xdeadbeefUL; \
+	} while (0)
+
+/*
+ *  Macro for suppressing warnings for potentially unreferenced variables.
+ *  The variables can be actually unreferenced or unreferenced in some
+ *  specific cases only; for instance, if a variable is only debug printed,
+ *  it is unreferenced when debug printing is disabled.
+ *
+ *  (Introduced here because it's potentially compiler specific.)
+ */
+
+#define DUK_UNREF(x)  do { \
+		(void) (x); \
+	} while (0)
+
+/*
+ *  DUK_NORETURN: macro for declaring a 'noreturn' function.
+ *  Unfortunately the noreturn declaration may appear in various
+ *  places of a function declaration, so the solution is to wrap
+ *  the entire declaration inside the macro.  Compiler support
+ *  for using a noreturn declaration on function pointers varies;
+ *  this macro must only be used for actual function declarations.
+ *
+ *  http://gcc.gnu.org/onlinedocs/gcc-4.3.2//gcc/Function-Attributes.html
+ *  http://clang.llvm.org/docs/LanguageExtensions.html
+ */
+
+#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 20500L)
+/* since gcc-2.5 */
+#define DUK_NORETURN(decl)  decl __attribute__((noreturn))
+#elif defined(__clang__)
+/* syntax same as gcc */
+#define DUK_NORETURN(decl)  decl __attribute__((noreturn))
+#elif defined(DUK_F_MSVC)
+/* http://msdn.microsoft.com/en-us/library/aa235362(VS.60).aspx */
+#define DUK_NORETURN(decl)  __declspec(noreturn) decl
+#else
+/* Don't know how to declare a noreturn function, so don't do it; this
+ * may cause some spurious compilation warnings (e.g. "variable used
+ * uninitialized").
+ */
+#define DUK_NORETURN(decl)  decl
+#endif
+
+/*
+ *  Macro for stating that a certain line cannot be reached.
+ *
+ *  http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Other-Builtins.html#Other-Builtins
+ *  http://clang.llvm.org/docs/LanguageExtensions.html
+ */
+
+#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40500L)
+/* since gcc-4.5 */
+#define DUK_UNREACHABLE()  do { __builtin_unreachable(); } while(0)
+#elif defined(__clang__) && defined(__has_builtin)
+#if __has_builtin(__builtin_unreachable)
+/* same as gcc */
+#define DUK_UNREACHABLE()  do { __builtin_unreachable(); } while(0)
+#endif
+#else
+/* unknown */
+#endif
+
+#if !defined(DUK_UNREACHABLE)
+/* Don't know how to declare unreachable point, so don't do it; this
+ * may cause some spurious compilation warnings (e.g. "variable used
+ * uninitialized").
+ */
+#define DUK_UNREACHABLE()  /* unreachable */
+#endif
+
+/*
+ *  Likely and unlikely branches.  Using these is not at all a clear cut case,
+ *  so the selection is a two-step process: (1) DUK_USE_BRANCH_HINTS is set
+ *  if the architecture, compiler etc make it useful to use the hints, and (2)
+ *  a separate check determines how to do them.
+ *
+ *  These macros expect the argument to be a relational expression with an
+ *  integer value.  If used with pointers, you should use an explicit check
+ *  like:
+ *
+ *    if (DUK_LIKELY(ptr != NULL)) { ... }
+ *
+ *  instead of:
+ *
+ *    if (DUK_LIKELY(ptr)) { ... }
+ *
+ *  http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html  (__builtin_expect)
+ */
+
+/* pretty much a placeholder now */
+#if defined(DUK_F_GCC)
+#define DUK_USE_BRANCH_HINTS
+#elif defined(DUK_F_CLANG)
+#define DUK_USE_BRANCH_HINTS
+#else
+#undef DUK_USE_BRANCH_HINTS
+#endif
+
+#if defined(DUK_USE_BRANCH_HINTS)
+#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40500L)
+/* GCC: test not very accurate; enable only in relatively recent builds
+ * because of bugs in gcc-4.4 (http://lists.debian.org/debian-gcc/2010/04/msg00000.html)
+ */
+#define DUK_LIKELY(x)    __builtin_expect((x), 1)
+#define DUK_UNLIKELY(x)  __builtin_expect((x), 0)
+#elif defined(DUK_F_CLANG)
+#define DUK_LIKELY(x)    __builtin_expect((x), 1)
+#define DUK_UNLIKELY(x)  __builtin_expect((x), 0)
+#endif
+#endif  /* DUK_USE_BRANCH_HINTS */
+
+#if !defined(DUK_LIKELY)
+#define DUK_LIKELY(x)    (x)
+#endif
+#if !defined(DUK_UNLIKELY)
+#define DUK_UNLIKELY(x)  (x)
+#endif
+
+/*
+ *  Function inlining control
+ *
+ *  DUK_NOINLINE: avoid inlining a function.
+ *  DUK_INLINE: suggest inlining a function.
+ *  DUK_ALWAYS_INLINE: force inlining for critical functions.
+ *
+ *  Apply to function definition only (not declaration).
+ */
+
+#if defined(DUK_F_CLANG) && (defined(DUK_F_C99) || defined(DUK_F_CPP11))
+#define DUK_NOINLINE        __attribute__((noinline))
+#define DUK_INLINE          inline
+#define DUK_ALWAYS_INLINE   inline __attribute__((always_inline))
+#elif defined(DUK_F_GCC) && defined(DUK_F_GCC_VERSION) && (defined(DUK_F_C99) || defined(DUK_F_CPP11))
+#if (DUK_F_GCC_VERSION >= 30101)
+#define DUK_NOINLINE        __attribute__((noinline))
+#define DUK_INLINE          inline
+#define DUK_ALWAYS_INLINE   inline __attribute__((always_inline))
+#endif
+#endif
+
+#if !defined(DUK_NOINLINE)
+#define DUK_NOINLINE       /*nop*/
+#define DUK_INLINE         /*nop*/
+#define DUK_ALWAYS_INLINE  /*nop*/
+#endif
+
+/*
+ *  Symbol visibility macros
+ *
+ *  To avoid C++ declaration issues (see GH-63):
+ *
+ *    - Don't use DUK_LOCAL_DECL for local -data symbols- so that you don't
+ *      end up with both a "static" declaration and a definition.
+ *
+ *    - Wrap any DUK_INTERNAL_DECL with a '#if !defined(DUK_SINGLE_FILE)'
+ *      so that the internal declarations (which would map to "static" in
+ *      a single file distribution) get dropped.
+ */
+
+/* XXX: user override for these? user override for just using the default visibility macros? */
+/* XXX: separate macros for function and data may be necessary at some point. */
+
+#if defined(DUK_F_GCC_VERSION)
+#if (DUK_F_GCC_VERSION >= 40000) && !(defined(DUK_F_MINGW) || defined(DUK_F_CYGWIN))
+/* Might work on earlier versions too but limit to GCC 4+.
+ * MinGW should use Windows specific __declspec or no visibility attributes at all,
+ * otherwise: "warning: visibility attribute not supported in this configuration; ignored".
+ * Same applies to Cygwin GCC.
+ */
+#define DUK_F_GCC_SYMBOL_VISIBILITY
+#endif
+#endif
+#if defined(DUK_F_CLANG) && !defined(DUK_F_GCC_SYMBOL_VISIBILITY)
+#define DUK_F_GCC_SYMBOL_VISIBILITY
+#endif
+#if defined(DUK_OPT_DLL_BUILD) && defined(_WIN32) && (defined(_MSC_VER) || defined(__GNUC__))
+/* __declspec(dllexport) and __declspec(dllimport) only for Windows DLL build.
+ * MSVC: any minimum version?
+ * MinGW: no minimum version, even gcc-2.95.3 supported dllimport/dllexport.
+*/
+#define DUK_F_MSVC_DLL_SYMBOL_VISIBILITY
+#endif
+
+#if defined(DUK_F_GCC_SYMBOL_VISIBILITY)
+/* GCC 4+ visibility attributes. */
+#define DUK_EXTERNAL_DECL  __attribute__ ((visibility("default"))) extern
+#define DUK_EXTERNAL       __attribute__ ((visibility("default")))
+#if defined(DUK_SINGLE_FILE)
+#define DUK_INTERNAL_DECL  static
+#define DUK_INTERNAL       static
+#else
+#define DUK_INTERNAL_DECL  __attribute__ ((visibility("hidden"))) extern
+#define DUK_INTERNAL       __attribute__ ((visibility("hidden")))
+#endif
+#elif defined(DUK_F_MSVC_DLL_SYMBOL_VISIBILITY)
+/* MSVC dllexport/dllimport: appropriate __declspec depends on whether we're
+ * compiling Duktape or the application.
+ */
+#if defined(DUK_COMPILING_DUKTAPE)
+#define DUK_EXTERNAL_DECL  extern __declspec(dllexport)
+#define DUK_EXTERNAL       __declspec(dllexport)
+#else
+#define DUK_EXTERNAL_DECL  extern __declspec(dllimport)
+#define DUK_EXTERNAL       should_not_happen
+#endif
+#if defined(DUK_SINGLE_FILE)
+#define DUK_INTERNAL_DECL  static
+#define DUK_INTERNAL       static
+#else
+#define DUK_INTERNAL_DECL  extern
+#define DUK_INTERNAL       /*empty*/
+#endif
+#else
+/* Default visibility. */
+#define DUK_EXTERNAL_DECL  extern
+#define DUK_EXTERNAL       /*empty*/
+#if defined(DUK_SINGLE_FILE)
+#define DUK_INTERNAL_DECL  static
+#define DUK_INTERNAL       static
+#else  /* DUK_SINGLE_FILE */
+#define DUK_INTERNAL_DECL  extern
+#define DUK_INTERNAL       /*empty*/
+#endif
+#endif
+
+/* For now, these are shared. */
+#define DUK_LOCAL_DECL     static
+#define DUK_LOCAL          static
+
+/*
+ *  __FILE__, __LINE__, __func__ are wrapped.  Especially __func__ is a
+ *  problem because it is not available even in some compilers which try
+ *  to be C99 compatible (e.g. VBCC with -c99 option).
+ */
+
+#define DUK_FILE_MACRO  __FILE__
+
+#define DUK_LINE_MACRO  __LINE__
+
+#if !defined(DUK_F_VBCC) && !defined(DUK_F_MSVC)
+#define DUK_FUNC_MACRO  __func__
+#else
+#define DUK_FUNC_MACRO  "unknown"
+#endif
+
+/*
+ *  Byteswap macros
+ *
+ *  These are here so that inline assembly or other platform functions can be
+ *  used if available.
+ */
+
+#define DUK_BSWAP32(x) \
+	((((duk_uint32_t) (x)) >> 24) | \
+	 ((((duk_uint32_t) (x)) >> 8) & 0xff00UL) | \
+	 ((((duk_uint32_t) (x)) << 8) & 0xff0000UL) | \
+	 (((duk_uint32_t) (x)) << 24))
+
+#define DUK_BSWAP16(x) \
+	((duk_uint16_t) (x) >> 8) | \
+	((duk_uint16_t) (x) << 8)
+
+/*
+ *  Architecture string, human readable value exposed in Duktape.env
+ */
+
+#if defined(DUK_F_X86)
+#define DUK_USE_ARCH_STRING "x86"
+#elif defined(DUK_F_X32)
+#define DUK_USE_ARCH_STRING "x32"
+#elif defined(DUK_F_X64)
+#define DUK_USE_ARCH_STRING "x64"
+#elif defined(DUK_F_ARM)
+#define DUK_USE_ARCH_STRING "arm"
+#elif defined(DUK_F_MIPS32)
+#define DUK_USE_ARCH_STRING "mips32"
+#elif defined(DUK_F_MIPS64)
+#define DUK_USE_ARCH_STRING "mips64"
+#elif defined(DUK_F_SUPERH)
+#define DUK_USE_ARCH_STRING "sh"
+#elif defined(DUK_F_M68K)
+#define DUK_USE_ARCH_STRING "m68k"
+#elif defined(DUK_F_FLASHPLAYER)
+#define DUK_USE_ARCH_STRING "flashplayer"
+#elif defined(DUK_F_EMSCRIPTEN)
+#define DUK_USE_ARCH_STRING "emscripten"
+#else
+#define DUK_USE_ARCH_STRING "unknown"
+#endif
+
+/*
+ *  OS string, human readable value exposed in Duktape.env
+ */
+
+#if defined(DUK_F_LINUX)
+#define DUK_USE_OS_STRING "linux"
+#elif defined(__APPLE__)
+/* http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor */
+#if TARGET_IPHONE_SIMULATOR
+#define DUK_USE_OS_STRING "iphone-sim"
+#elif TARGET_OS_IPHONE
+#define DUK_USE_OS_STRING "iphone"
+#elif TARGET_OS_MAC
+#define DUK_USE_OS_STRING "ios"
+#else
+#define DUK_USE_OS_STRING "ios-unknown"
+#endif
+#elif defined(DUK_F_FREEBSD)
+#define DUK_USE_OS_STRING "freebsd"
+#elif defined(DUK_F_OPENBSD)
+#define DUK_USE_OS_STRING "openbsd"
+#elif defined(DUK_F_NETBSD)
+#define DUK_USE_OS_STRING "netbsd"
+#elif defined(DUK_F_BSD)
+#define DUK_USE_OS_STRING "bsd"
+#elif defined(DUK_F_UNIX)
+#define DUK_USE_OS_STRING "unix"
+#elif defined(DUK_F_WINDOWS)
+#define DUK_USE_OS_STRING "windows"
+#elif defined(DUK_F_TOS)
+#define DUK_USE_OS_STRING "tos"
+#elif defined(DUK_F_AMIGAOS)
+#define DUK_USE_OS_STRING "amigaos"
+#elif defined(DUK_F_QNX)
+#define DUK_USE_OS_STRING "qnx"
+#elif defined(DUK_F_TINSPIRE)
+#define DUK_USE_OS_STRING "tinspire"
+#else
+#define DUK_USE_OS_STRING "unknown"
+#endif
+
+/*
+ *  Compiler string, human readable value exposed in Duktape.env
+ */
+
+#if defined(DUK_F_MINGW)
+#define DUK_USE_COMPILER_STRING "mingw"
+#elif defined(DUK_F_GCC)
+#if defined(DUK_F_CPP)
+#define DUK_USE_COMPILER_STRING "g++"
+#else
+#define DUK_USE_COMPILER_STRING "gcc"
+#endif
+#elif defined(DUK_F_CLANG)
+#define DUK_USE_COMPILER_STRING "clang"
+#elif defined(DUK_F_MSVC)
+#define DUK_USE_COMPILER_STRING "msvc"
+#elif defined(DUK_F_VBCC)
+#define DUK_USE_COMPILER_STRING "vbcc"
+#else
+#define DUK_USE_COMPILER_STRING "unknown"
+#endif
+
+/*
+ *  Long control transfer, setjmp/longjmp or alternatives
+ *
+ *  Signal mask is not saved (when that can be communicated to the platform)
+ */
+
+/* dummy non-zero value to be used as an argument for longjmp(), see man longjmp */
+#define DUK_LONGJMP_DUMMY_VALUE  1
+
+#if defined(DUK_OPT_SETJMP)
+#define DUK_USE_SETJMP
+#elif defined(DUK_OPT_UNDERSCORE_SETJMP)
+#define DUK_USE_UNDERSCORE_SETJMP
+#elif defined(DUK_OPT_SIGSETJMP)
+#define DUK_USE_SIGSETJMP
+#elif defined(__APPLE__)
+/* Use _setjmp() on Apple by default, see GH-55. */
+#define DUK_USE_UNDERSCORE_SETJMP
+#else
+/* The most portable default is setjmp(). */
+#define DUK_USE_SETJMP
+#endif
+
+#if defined(DUK_USE_UNDERSCORE_SETJMP)
+#define DUK_SETJMP(jb)        _setjmp((jb))
+#define DUK_LONGJMP(jb)       _longjmp((jb), DUK_LONGJMP_DUMMY_VALUE)
+#elif defined(DUK_USE_SIGSETJMP)
+#define DUK_SETJMP(jb)        sigsetjmp((jb), 0 /*savesigs*/)
+#define DUK_LONGJMP(jb)       siglongjmp((jb), DUK_LONGJMP_DUMMY_VALUE)
+#elif defined(DUK_USE_SETJMP)
+#define DUK_SETJMP(jb)        setjmp((jb))
+#define DUK_LONGJMP(jb)       longjmp((jb), DUK_LONGJMP_DUMMY_VALUE)
+#else
+#error internal error
+#endif
+
+/*
+ *  Target info string
+ */
+
+#if defined(DUK_OPT_TARGET_INFO)
+#define DUK_USE_TARGET_INFO DUK_OPT_TARGET_INFO
+#else
+#define DUK_USE_TARGET_INFO "unknown"
+#endif
+
+/*
+ *  Speed/size and other performance options
+ */
+
+/* Use fast ("inline") refcount operations instead of calling out to helpers
+ * by default.  The difference in binary size is small (~1kB on x64).
+ */
+#define DUK_USE_FAST_REFCOUNT_DEFAULT
+
+/* Assert for valstack space but don't check for it in non-assert build.
+ * Valstack overruns (writing beyond checked space) is memory unsafe and
+ * potentially a segfault.  Produces a smaller and faster binary.
+ * (In practice the speed difference is small with -O3 so default to
+ * safer behavior for now.)
+ */
+#undef DUK_USE_VALSTACK_UNSAFE
+
+/* Catch-all flag which can be used to choose between variant algorithms
+ * where a speed-size tradeoff exists (e.g. lookup tables).  When it really
+ * matters, specific use flags may be appropriate.
+ */
+#define DUK_USE_PREFER_SIZE
+
+/* Use a sliding window for lexer; slightly larger footprint, slightly faster. */
+#define DUK_USE_LEXER_SLIDING_WINDOW
+
+/*
+ *  Tagged type representation (duk_tval)
+ */
+
+#undef DUK_USE_PACKED_TVAL
+#undef DUK_USE_FULL_TVAL
+
+#if defined(DUK_USE_PACKED_TVAL_POSSIBLE) && !defined(DUK_OPT_NO_PACKED_TVAL)
+#define DUK_USE_PACKED_TVAL
+#endif
+
+/* Support for 48-bit signed integer duk_tval with transparent semantics. */
+#undef DUK_USE_FASTINT
+#if defined(DUK_OPT_FASTINT)
+#if !defined(DUK_F_HAVE_64BIT)
+#error DUK_OPT_FASTINT requires 64-bit integer type support at the moment
+#endif
+#define DUK_USE_FASTINT
+#endif
+
+/*
+ *  Memory management options
+ */
+
+#define DUK_USE_REFERENCE_COUNTING
+#define DUK_USE_DOUBLE_LINKED_HEAP
+#define DUK_USE_MARK_AND_SWEEP
+#define DUK_USE_MS_STRINGTABLE_RESIZE
+
+#if defined(DUK_OPT_NO_REFERENCE_COUNTING)
+#undef DUK_USE_REFERENCE_COUNTING
+#undef DUK_USE_DOUBLE_LINKED_HEAP
+/* XXX: undef DUK_USE_MS_STRINGTABLE_RESIZE as it is more expensive
+ * with more frequent mark-and-sweeps?
+ */
+#endif
+
+#if defined(DUK_OPT_NO_MARK_AND_SWEEP)
+#undef DUK_USE_MARK_AND_SWEEP
+#endif
+
+#if defined(DUK_USE_MARK_AND_SWEEP)
+#define DUK_USE_VOLUNTARY_GC
+#if defined(DUK_OPT_NO_VOLUNTARY_GC)
+#undef DUK_USE_VOLUNTARY_GC
+#endif
+#endif
+
+#if !defined(DUK_USE_MARK_AND_SWEEP) && !defined(DUK_USE_REFERENCE_COUNTING)
+#error must have either mark-and-sweep or reference counting enabled
+#endif
+
+#if defined(DUK_OPT_NO_MS_STRINGTABLE_RESIZE)
+#undef DUK_USE_MS_STRINGTABLE_RESIZE
+#endif
+
+#undef DUK_USE_GC_TORTURE
+#if defined(DUK_OPT_GC_TORTURE)
+#define DUK_USE_GC_TORTURE
+#endif
+
+/*
+ *  String table options
+ */
+
+#if defined(DUK_OPT_STRTAB_CHAIN) && defined(DUK_OPT_STRTAB_CHAIN_SIZE)
+/* Low memory algorithm: separate chaining using arrays, fixed size hash */
+#define DUK_USE_STRTAB_CHAIN
+#define DUK_USE_STRTAB_CHAIN_SIZE  DUK_OPT_STRTAB_CHAIN_SIZE
+#else
+/* Default algorithm: open addressing (probing) */
+#define DUK_USE_STRTAB_PROBE
+#endif
+
+/*
+ *  Error handling options
+ */
+
+#define DUK_USE_AUGMENT_ERROR_CREATE
+#define DUK_USE_AUGMENT_ERROR_THROW
+#define DUK_USE_TRACEBACKS
+#define DUK_USE_ERRCREATE
+#define DUK_USE_ERRTHROW
+
+#define DUK_USE_VERBOSE_ERRORS
+
+#if defined(DUK_OPT_NO_AUGMENT_ERRORS)
+#undef DUK_USE_AUGMENT_ERROR_CREATE
+#undef DUK_USE_AUGMENT_ERROR_THROW
+#undef DUK_USE_TRACEBACKS
+#undef DUK_USE_ERRCREATE
+#undef DUK_USE_ERRTHROW
+#elif defined(DUK_OPT_NO_TRACEBACKS)
+#undef DUK_USE_TRACEBACKS
+#endif
+
+#if defined(DUK_OPT_NO_VERBOSE_ERRORS)
+#undef DUK_USE_VERBOSE_ERRORS
+#endif
+
+#if defined(DUK_USE_TRACEBACKS)
+#if defined(DUK_OPT_TRACEBACK_DEPTH)
+#define DUK_USE_TRACEBACK_DEPTH  DUK_OPT_TRACEBACK_DEPTH
+#else
+#define DUK_USE_TRACEBACK_DEPTH  10
+#endif
+#endif
+
+/* Include messages in executor internal errors. */
+#define DUK_USE_VERBOSE_EXECUTOR_ERRORS
+
+/*
+ *  Execution and debugger options
+ */
+
+#undef DUK_USE_INTERRUPT_COUNTER
+#if defined(DUK_OPT_INTERRUPT_COUNTER)
+#define DUK_USE_INTERRUPT_COUNTER
+#endif
+
+#undef DUK_USE_EXEC_TIMEOUT_CHECK
+#if defined(DUK_OPT_EXEC_TIMEOUT_CHECK)
+#define DUK_USE_EXEC_TIMEOUT_CHECK(udata)  DUK_OPT_EXEC_TIMEOUT_CHECK((udata))
+#endif
+
+#undef DUK_USE_DEBUGGER_SUPPORT
+#if defined(DUK_OPT_DEBUGGER_SUPPORT)
+#define DUK_USE_DEBUGGER_SUPPORT
+#endif
+
+#undef DUK_USE_DEBUGGER_FWD_PRINTALERT
+#if defined(DUK_OPT_DEBUGGER_SUPPORT) && defined(DUK_OPT_DEBUGGER_FWD_PRINTALERT)
+#define DUK_USE_DEBUGGER_FWD_PRINTALERT
+#endif
+
+#undef DUK_USE_DEBUGGER_FWD_LOGGING
+#if defined(DUK_OPT_DEBUGGER_SUPPORT) && defined(DUK_OPT_DEBUGGER_FWD_LOGGING)
+#define DUK_USE_DEBUGGER_FWD_LOGGING
+#endif
+
+/* DumpHeap is optional because it's not always needed and has a relatively
+ * large footprint.
+ */
+#undef DUK_USE_DEBUGGER_DUMPHEAP
+#if defined(DUK_OPT_DEBUGGER_DUMPHEAP)
+#define DUK_USE_DEBUGGER_DUMPHEAP
+#endif
+
+/* Debugger transport read/write torture. */
+#undef DUK_USE_DEBUGGER_TRANSPORT_TORTURE
+#if defined(DUK_OPT_DEBUGGER_TRANSPORT_TORTURE)
+#define DUK_USE_DEBUGGER_TRANSPORT_TORTURE
+#endif
+
+/* For opcodes with indirect indices, check final index against stack size.
+ * This should not be necessary because the compiler is trusted, and we don't
+ * bound check non-indirect indices either.
+ */
+#undef DUK_USE_EXEC_INDIRECT_BOUND_CHECK
+#if defined(DUK_OPT_DEBUG) || defined(DUK_OPT_ASSERTIONS)
+/* Enabled with debug/assertions just so that any issues can be caught. */
+#define DUK_USE_EXEC_INDIRECT_BOUND_CHECK
+#endif
+
+/*
+ *  Debug printing and assertion options
+ */
+
+#undef DUK_USE_DEBUG
+#undef DUK_USE_DPRINT
+#undef DUK_USE_DDPRINT
+#undef DUK_USE_DDDPRINT
+#undef DUK_USE_DPRINT_RDTSC
+#undef DUK_USE_ASSERTIONS
+
+/* Global debug enable.  Compile must be clean on C99 regardless of whether or
+ * not debugging is enabled.  On non-C99 platforms compile should be clean with
+ * debugging disabled but may produce warnings with debugging enabled (related
+ * to debug macro hackery and such).
+ */
+#if defined(DUK_OPT_DEBUG)
+#define DUK_USE_DEBUG
+#endif
+
+#if defined(DUK_OPT_DEBUG) && defined(DUK_OPT_DPRINT)
+#define DUK_USE_DPRINT
+#endif
+#if defined(DUK_OPT_DEBUG) && defined(DUK_OPT_DDPRINT)
+#define DUK_USE_DDPRINT
+#endif
+#if defined(DUK_OPT_DEBUG) && defined(DUK_OPT_DDDPRINT)
+#define DUK_USE_DDDPRINT
+#endif
+
+#undef DUK_USE_DPRINT_COLORS
+#if defined(DUK_OPT_DPRINT_COLORS)
+#define DUK_USE_DPRINT_COLORS
+#endif
+
+#if defined(DUK_USE_RDTSC) && defined(DUK_OPT_DPRINT_RDTSC)
+#define DUK_USE_DPRINT_RDTSC
+#else
+#undef DUK_USE_DPRINT_RDTSC
+#endif
+
+#if defined(DUK_OPT_ASSERTIONS)
+#define DUK_USE_ASSERTIONS
+#endif
+
+/* The static buffer for debug printing is quite large by default, so there
+ * is an option to shrink it manually for constrained builds.
+ */
+#if defined(DUK_OPT_DEBUG_BUFSIZE)
+#define DUK_USE_DEBUG_BUFSIZE  DUK_OPT_DEBUG_BUFSIZE
+#else
+#define DUK_USE_DEBUG_BUFSIZE  65536L
+#endif
+
+/*
+ *  Ecmascript features / compliance options
+ */
+
+#if defined(DUK_F_BCC)
+/* Math built-in is stubbed out on BCC to allow compiler torture testing. */
+#else
+#define DUK_USE_MATH_BUILTIN
+#endif
+
+#define DUK_USE_STRICT_DECL
+#if defined(DUK_OPT_NO_STRICT_DECL)
+#undef DUK_USE_STRICT_DECL
+#endif
+
+#define DUK_USE_REGEXP_SUPPORT
+#if defined(DUK_OPT_NO_REGEXP_SUPPORT)
+#undef DUK_USE_REGEXP_SUPPORT
+#endif
+
+#undef DUK_USE_STRICT_UTF8_SOURCE
+#if defined(DUK_OPT_STRICT_UTF8_SOURCE)
+#define DUK_USE_STRICT_UTF8_SOURCE
+#endif
+
+#define DUK_USE_OCTAL_SUPPORT
+#if defined(DUK_OPT_NO_OCTAL_SUPPORT)
+#undef DUK_USE_OCTAL_SUPPORT
+#endif
+
+#define DUK_USE_SOURCE_NONBMP
+#if defined(DUK_OPT_NO_SOURCE_NONBMP)
+#undef DUK_USE_SOURCE_NONBMP
+#endif
+
+#define DUK_USE_BROWSER_LIKE
+#if defined(DUK_OPT_NO_BROWSER_LIKE)
+#undef DUK_USE_BROWSER_LIKE
+#endif
+
+/* E5/E5.1 Section B features. */
+#define DUK_USE_SECTION_B
+#if defined(DUK_OPT_NO_SECTION_B)
+#undef DUK_USE_SECTION_B
+#endif
+
+/* Non-standard regexp parsing features. */
+#define DUK_USE_NONSTD_REGEXP_DOLLAR_ESCAPE
+
+/* Treat function statements (function declarations outside top level of
+ * Program or FunctionBody) same as normal function declarations.  This is
+ * also V8 behavior.  See test-dev-func-decl-outside-top.js.
+ */
+#define DUK_USE_NONSTD_FUNC_STMT
+#if defined(DUK_OPT_NO_NONSTD_FUNC_STMT)
+#undef DUK_USE_NONSTD_FUNC_STMT
+#endif
+
+/* Array.prototype.splice() non-standard but real world compatible behavior
+ * when deleteCount is omitted.
+ */
+#define DUK_USE_NONSTD_ARRAY_SPLICE_DELCOUNT
+#if defined(DUK_OPT_NO_NONSTD_ARRAY_SPLICE_DELCOUNT)
+#undef DUK_USE_NONSTD_ARRAY_SPLICE_DELCOUNT
+#endif
+
+/* Array.prototype.concat() non-standard but real world compatible behavior
+ * for non-existent trailing elements.
+ */
+#define DUK_USE_NONSTD_ARRAY_CONCAT_TRAILER
+#if defined(DUK_OPT_NO_NONSTD_ARRAY_CONCAT_TRAILER)
+#undef DUK_USE_NONSTD_ARRAY_CONCAT_TRAILER
+#endif
+
+/* Array.prototype.map() non-standard but real world compatible behavior
+ * for non-existent trailing elements.
+ */
+#define DUK_USE_NONSTD_ARRAY_MAP_TRAILER
+#if defined(DUK_OPT_NO_NONSTD_ARRAY_MAP_TRAILER)
+#undef DUK_USE_NONSTD_ARRAY_MAP_TRAILER
+#endif
+
+/* Non-standard 'caller' property for function instances, see
+ * test-bi-function-nonstd-caller-prop.js.
+ */
+#undef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
+#if defined(DUK_OPT_NONSTD_FUNC_CALLER_PROPERTY)
+#define DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
+#endif
+
+/* Non-standard Object.prototype.__proto__ (ES6), see
+ * test-bi-object-proto-__proto__.js.
+ */
+#define DUK_USE_ES6_OBJECT_PROTO_PROPERTY
+#if defined(DUK_OPT_NO_ES6_OBJECT_PROTO_PROPERTY)
+#undef DUK_USE_ES6_OBJECT_PROTO_PROPERTY
+#endif
+
+/* Non-standard Object.setPrototypeOf (ES6), see
+ * test-bi-object-setprototypeof.js.
+ */
+#define DUK_USE_ES6_OBJECT_SETPROTOTYPEOF
+#if defined(DUK_OPT_NO_ES6_OBJECT_SETPROTOTYPEOF)
+#undef DUK_USE_ES6_OBJECT_SETPROTOTYPEOF
+#endif
+
+/* ES6 Proxy object (subset for now). */
+#define DUK_USE_ES6_PROXY
+#if defined(DUK_OPT_NO_ES6_PROXY)
+#undef DUK_USE_ES6_PROXY
+#endif
+
+/* Record pc-to-line information. */
+#define DUK_USE_PC2LINE
+#if defined(DUK_OPT_NO_PC2LINE)
+#undef DUK_USE_PC2LINE
+#endif
+
+/* Non-standard function 'source' property. */
+#undef DUK_USE_NONSTD_FUNC_SOURCE_PROPERTY
+#if defined(DUK_OPT_NONSTD_FUNC_SOURCE_PROPERTY)
+#define DUK_USE_NONSTD_FUNC_SOURCE_PROPERTY
+#endif
+
+/* CommonJS modules */
+#define DUK_USE_COMMONJS_MODULES
+#if defined(DUK_OPT_NO_COMMONJS_MODULES)
+#undef DUK_USE_COMMONJS_MODULES
+#endif
+
+/* Additional key argument to setter/getter calls when triggered by property
+ * accesses.
+ */
+
+#define DUK_USE_NONSTD_GETTER_KEY_ARGUMENT
+#define DUK_USE_NONSTD_SETTER_KEY_ARGUMENT
+#if defined(DUK_OPT_NO_NONSTD_ACCESSOR_KEY_ARGUMENT)
+#undef DUK_USE_NONSTD_GETTER_KEY_ARGUMENT
+#undef DUK_USE_NONSTD_SETTER_KEY_ARGUMENT
+#endif
+
+/* JSON escaping of U+2028 and U+2029.
+ */
+
+#define DUK_USE_NONSTD_JSON_ESC_U2028_U2029
+#if defined(DUK_OPT_NO_NONSTD_JSON_ESC_U2028_U2029)
+#undef DUK_USE_NONSTD_JSON_ESC_U2028_U2029
+#endif
+
+/* Allow 32-bit codepoints in String.fromCharCode. */
+#define DUK_USE_NONSTD_STRING_FROMCHARCODE_32BIT
+#if defined(DUK_OPT_NO_NONSTD_STRING_FROMCHARCODE_32BIT)
+#undef DUK_USE_NONSTD_STRING_FROMCHARCODE_32BIT
+#endif
+
+/* Non-standard array fast path write behavior: when writing to numeric
+ * indexes of an Array instance, assume Array.prototype doesn't have
+ * conflicting properties (e.g. a non-writable property "7").
+ */
+#define DUK_USE_NONSTD_ARRAY_WRITE
+#if defined(DUK_OPT_NO_NONSTD_ARRAY_WRITE)
+#undef DUK_USE_NONSTD_ARRAY_WRITE
+#endif
+
+/*
+ *  Optional C API options
+ */
+
+#define DUK_USE_BYTECODE_DUMP_SUPPORT
+#if defined(DUK_OPT_NO_BYTECODE_DUMP_SUPPORT)
+#undef DUK_USE_BYTECODE_DUMP_SUPPORT
+#endif
+
+/*
+ *  Tailcalls
+ */
+
+/* Tailcalls are enabled by default.  The non-standard function 'caller'
+ * property feature conflicts with tailcalls quite severely so tailcalls
+ * are disabled if the 'caller' property is enabled.
+ */
+#define DUK_USE_TAILCALL
+#if defined(DUK_USE_NONSTD_FUNC_CALLER_PROPERTY)
+#undef DUK_USE_TAILCALL
+#endif
+
+/*
+ *  Deep vs. shallow stack.
+ *
+ *  Some embedded platforms have very shallow stack (e.g. 64kB); default to
+ *  a shallow stack on unknown platforms or known embedded platforms.
+ */
+
+#if defined(DUK_F_LINUX) || defined(DUK_F_BSD) || defined(DUK_F_WINDOWS) || \
+    defined(DUK_F_APPLE) || defined(DUK_OPT_DEEP_C_STACK)
+#define DUK_USE_DEEP_C_STACK
+#else
+#undef DUK_USE_DEEP_C_STACK
+#endif
+
+/*
+ *  Ecmascript compiler
+ */
+
+/* Ensure final bytecode never exceeds a certain byte size and never uses
+ * line numbers above a certain limit.  This ensures that there is no need
+ * to deal with unbounded ranges in e.g. pc2line data structures.  For now,
+ * limits are set so that signed 32-bit values can represent line number
+ * and byte offset with room to spare.
+ */
+#define DUK_USE_ESBC_LIMITS
+#define DUK_USE_ESBC_MAX_LINENUMBER  0x7fff0000L
+#define DUK_USE_ESBC_MAX_BYTES       0x7fff0000L
+
+#undef DUK_USE_SHUFFLE_TORTURE
+#if defined(DUK_OPT_SHUFFLE_TORTURE)
+#define DUK_USE_SHUFFLE_TORTURE
+#endif
+
+/*
+ *  User panic handler, panic exit behavior for default panic handler
+ */
+
+#undef DUK_USE_PANIC_HANDLER
+#if defined(DUK_OPT_PANIC_HANDLER)
+#define DUK_USE_PANIC_HANDLER(code,msg) DUK_OPT_PANIC_HANDLER((code),(msg))
+#endif
+
+#undef DUK_USE_PANIC_ABORT
+#undef DUK_USE_PANIC_EXIT
+#undef DUK_USE_PANIC_SEGFAULT
+
+#if defined(DUK_OPT_SEGFAULT_ON_PANIC)
+#define DUK_USE_PANIC_SEGFAULT
+#else
+#define DUK_USE_PANIC_ABORT
+#endif
+
+/*
+ *  File I/O support.  This is now used in a few API calls to e.g. push
+ *  a string from file contents or eval a file.  For portability it must
+ *  be possible to disable I/O altogether.
+ */
+
+#undef DUK_USE_FILE_IO
+#if !defined(DUK_OPT_NO_FILE_IO)
+#define DUK_USE_FILE_IO
+#endif
+
+/*
+ *  Optional run-time self tests executed when a heap is created.  Some
+ *  platform/compiler issues cannot be determined at compile time.  One
+ *  particular example is the bug described in misc/clang_aliasing.c.
+ */
+
+#undef DUK_USE_SELF_TESTS
+#if defined(DUK_OPT_SELF_TESTS)
+#define DUK_USE_SELF_TESTS
+#endif
+
+/* Double aliasing testcase fails when Emscripten-generated code is run
+ * on Firefox.  This is not fatal because it only affects packed duk_tval
+ * which we avoid with Emscripten.
+ */
+#undef DUK_USE_NO_DOUBLE_ALIASING_SELFTEST
+#if defined(DUK_F_EMSCRIPTEN)
+#define DUK_USE_NO_DOUBLE_ALIASING_SELFTEST
+#endif
+
+/*
+ *  Codecs
+ */
+
+#define DUK_USE_JX
+#if defined(DUK_OPT_NO_JX)
+#undef DUK_USE_JX
+#endif
+
+#define DUK_USE_JC
+#if defined(DUK_OPT_NO_JC)
+#undef DUK_USE_JC
+#endif
+
+/*
+ *  InitJS code
+ */
+
+/* Always use the built-in InitJS code for now. */
+#define DUK_USE_BUILTIN_INITJS
+
+/* User provided InitJS. */
+#undef DUK_USE_USER_INITJS
+#if defined(DUK_OPT_USER_INITJS)
+#define DUK_USE_USER_INITJS (DUK_OPT_USER_INITJS)
+#endif
+
+/*
+ *  External string data support
+ *
+ *  Allow duk_hstrings to store data also behind an external pointer (see
+ *  duk_hstring_external).  This increases code size slightly but is useful
+ *  in low memory environments where memory is more limited than flash.
+ */
+
+#undef DUK_USE_HSTRING_EXTDATA
+#if defined(DUK_OPT_EXTERNAL_STRINGS)
+#define DUK_USE_HSTRING_EXTDATA
+#endif
+
+#undef DUK_USE_EXTSTR_INTERN_CHECK
+#if defined(DUK_OPT_EXTERNAL_STRINGS) && defined(DUK_OPT_EXTSTR_INTERN_CHECK)
+#define DUK_USE_EXTSTR_INTERN_CHECK(udata,ptr,len) DUK_OPT_EXTSTR_INTERN_CHECK((udata), (ptr), (len))
+#endif
+
+#undef DUK_USE_EXTSTR_FREE
+#if defined(DUK_OPT_EXTERNAL_STRINGS) && defined(DUK_OPT_EXTSTR_FREE)
+#define DUK_USE_EXTSTR_FREE(udata,ptr) DUK_OPT_EXTSTR_FREE((udata), (ptr))
+#endif
+
+/*
+ *  Lightweight functions
+ */
+
+/* Force built-ins to use lightfunc function pointers when possible.  This
+ * makes the built-in functions non-compliant with respect to their property
+ * values and such, but is very useful in low memory environments (can save
+ * around 14kB of initial RAM footprint).
+ */
+#undef DUK_USE_LIGHTFUNC_BUILTINS
+#if defined(DUK_OPT_LIGHTFUNC_BUILTINS)
+#define DUK_USE_LIGHTFUNC_BUILTINS
+#endif
+
+/*
+ *  Pointer compression and 16-bit header fields for low memory environments
+ */
+
+#undef DUK_USE_HEAPPTR16
+#undef DUK_USE_HEAPPTR_ENC16
+#undef DUK_USE_HEAPPTR_DEC16
+#if defined(DUK_OPT_HEAPPTR16) && defined(DUK_OPT_HEAPPTR_ENC16) && defined(DUK_OPT_HEAPPTR_DEC16)
+#define DUK_USE_HEAPPTR16
+#define DUK_USE_HEAPPTR_ENC16(udata,ptr) DUK_OPT_HEAPPTR_ENC16((udata),(ptr))
+#define DUK_USE_HEAPPTR_DEC16(udata,ptr) DUK_OPT_HEAPPTR_DEC16((udata),(ptr))
+#endif
+
+#undef DUK_USE_DATAPTR16
+#undef DUK_USE_DATAPTR_ENC16
+#undef DUK_USE_DATAPTR_DEC16
+#if defined(DUK_OPT_DATAPTR16) && defined(DUK_OPT_DATAPTR_ENC16) && defined(DUK_OPT_DATAPTR_DEC16)
+#define DUK_USE_DATAPTR16
+#define DUK_USE_DATAPTR_ENC16(udata,ptr) DUK_OPT_DATAPTR_ENC16((udata),(ptr))
+#define DUK_USE_DATAPTR_DEC16(udata,ptr) DUK_OPT_DATAPTR_DEC16((udata),(ptr))
+#endif
+
+#undef DUK_USE_FUNCPTR16
+#undef DUK_USE_FUNCPTR_ENC16
+#undef DUK_USE_FUNCPTR_DEC16
+#if defined(DUK_OPT_FUNCPTR16) && defined(DUK_OPT_FUNCPTR_ENC16) && defined(DUK_OPT_FUNCPTR_DEC16)
+#define DUK_USE_FUNCPTR16
+#define DUK_USE_FUNCPTR_ENC16(udata,ptr) DUK_OPT_FUNCPTR_ENC16((udata),(ptr))
+#define DUK_USE_FUNCPTR_DEC16(udata,ptr) DUK_OPT_FUNCPTR_DEC16((udata),(ptr))
+#endif
+
+#undef DUK_USE_REFCOUNT16
+#if defined(DUK_OPT_REFCOUNT16)
+#define DUK_USE_REFCOUNT16
+#endif
+
+#undef DUK_USE_STRHASH16
+#if defined(DUK_OPT_STRHASH16)
+#define DUK_USE_STRHASH16
+#endif
+
+#undef DUK_USE_STRLEN16
+#if defined(DUK_OPT_STRLEN16)
+#define DUK_USE_STRLEN16
+#endif
+
+#undef DUK_USE_BUFLEN16
+#if defined(DUK_OPT_BUFLEN16)
+#define DUK_USE_BUFLEN16
+#endif
+
+#undef DUK_USE_OBJSIZES16
+#if defined(DUK_OPT_OBJSIZES16)
+#define DUK_USE_OBJSIZES16
+#endif
+
+/* For now, hash part is dropped if and only if 16-bit object fields are used. */
+#define DUK_USE_HOBJECT_HASH_PART
+#if defined(DUK_USE_OBJSIZES16)
+#undef DUK_USE_HOBJECT_HASH_PART
+#endif
+
+/*
+ *  Miscellaneous
+ */
+
+/* Convenience define: 32-bit pointers.  32-bit platforms are an important
+ * footprint optimization target, and this define allows e.g. struct sizes
+ * to be organized for compactness.
+ */
+#undef DUK_USE_32BIT_PTRS
+#if defined(DUK_UINTPTR_MAX) && !defined(DUK_UINTPTR_MAX_COMPUTED)
+#if DUK_UINTPTR_MAX <= 0xffffffffUL
+#define DUK_USE_32BIT_PTRS
+#endif
+#endif
+
+#define DUK_USE_PROVIDE_DEFAULT_ALLOC_FUNCTIONS
+#undef DUK_USE_EXPLICIT_NULL_INIT
+
+#if !defined(DUK_USE_PACKED_TVAL)
+#define DUK_USE_EXPLICIT_NULL_INIT
+#endif
+
+#define DUK_USE_ZERO_BUFFER_DATA
+#if defined(DUK_OPT_NO_ZERO_BUFFER_DATA)
+#undef DUK_USE_ZERO_BUFFER_DATA
+#endif
+
+#undef DUK_USE_VARIADIC_MACROS
+#if defined(DUK_F_C99) || (defined(DUK_F_CPP11) && defined(__GNUC__))
+#define DUK_USE_VARIADIC_MACROS
+#endif
+#if defined(_MSC_VER) && !defined(DUK_USE_VARIADIC_MACROS)
+#if (_MSC_VER >= 1400)
+/* VS2005+ should have variadic macros even when they're not C99. */
+#define DUK_USE_VARIADIC_MACROS
+#endif
+#endif
+
+/*
+ *  Variable size array initialization.
+ *
+ *  Variable size array at the end of a structure is nonportable.
+ *  There are three alternatives:
+ *
+ *    1) C99 (flexible array member): char buf[]
+ *    2) Compiler specific (e.g. GCC): char buf[0]
+ *    3) Portable but wastes memory / complicates allocation: char buf[1]
+ */
+
+/* XXX: Currently unused, only hbuffer.h needed this at some point. */
+#undef DUK_USE_FLEX_C99
+#undef DUK_USE_FLEX_ZEROSIZE
+#undef DUK_USE_FLEX_ONESIZE
+#if defined(DUK_F_C99)
+#define DUK_USE_FLEX_C99
+#elif defined(__GNUC__)
+#define DUK_USE_FLEX_ZEROSIZE
+#else
+#define DUK_USE_FLEX_ONESIZE
+#endif
+
+/*
+ *  GCC pragmas
+ */
+
+/* XXX: GCC pragma inside a function fails in some earlier GCC versions (e.g. gcc 4.5).
+ * This is very approximate but allows clean builds for development right now.
+ */
+/* http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html */
+#if defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)
+#define DUK_USE_GCC_PRAGMAS
+#else
+#undef DUK_USE_GCC_PRAGMAS
+#endif
+
+/*
+ *  Date provider selection
+ *
+ *  User may define DUK_USE_DATE_GET_NOW() etc directly, in which case we'll
+ *  rely on an external provider.  If this is not done, revert to previous
+ *  behavior and use Unix/Windows built-in provider.
+ */
+
+#if defined(DUK_COMPILING_DUKTAPE)
+
+#if defined(DUK_USE_DATE_GET_NOW)
+/* External provider already defined. */
+#elif defined(DUK_USE_DATE_NOW_GETTIMEOFDAY)
+DUK_INTERNAL_DECL duk_double_t duk_bi_date_get_now_gettimeofday(duk_context *ctx);
+#define DUK_USE_DATE_GET_NOW(ctx)            duk_bi_date_get_now_gettimeofday((ctx))
+#elif defined(DUK_USE_DATE_NOW_TIME)
+DUK_INTERNAL_DECL duk_double_t duk_bi_date_get_now_time(duk_context *ctx);
+#define DUK_USE_DATE_GET_NOW(ctx)            duk_bi_date_get_now_time((ctx))
+#elif defined(DUK_USE_DATE_NOW_WINDOWS)
+DUK_INTERNAL_DECL duk_double_t duk_bi_date_get_now_windows(duk_context *ctx);
+#define DUK_USE_DATE_GET_NOW(ctx)            duk_bi_date_get_now_windows((ctx))
+#else
+#error no provider for DUK_USE_DATE_GET_NOW()
+#endif
+
+#if defined(DUK_USE_DATE_GET_LOCAL_TZOFFSET)
+/* External provider already defined. */
+#elif defined(DUK_USE_DATE_TZO_GMTIME_R) || defined(DUK_USE_DATE_TZO_GMTIME)
+DUK_INTERNAL_DECL duk_int_t duk_bi_date_get_local_tzoffset_gmtime(duk_double_t d);
+#define DUK_USE_DATE_GET_LOCAL_TZOFFSET(d)   duk_bi_date_get_local_tzoffset_gmtime((d))
+#elif defined(DUK_USE_DATE_TZO_WINDOWS)
+DUK_INTERNAL_DECL duk_int_t duk_bi_date_get_local_tzoffset_windows(duk_double_t d);
+#define DUK_USE_DATE_GET_LOCAL_TZOFFSET(d)   duk_bi_date_get_local_tzoffset_windows((d))
+#else
+#error no provider for DUK_USE_DATE_GET_LOCAL_TZOFFSET()
+#endif
+
+#if defined(DUK_USE_DATE_PARSE_STRING)
+/* External provider already defined. */
+#elif defined(DUK_USE_DATE_PRS_STRPTIME)
+DUK_INTERNAL_DECL duk_bool_t duk_bi_date_parse_string_strptime(duk_context *ctx, const char *str);
+#define DUK_USE_DATE_PARSE_STRING(ctx,str)   duk_bi_date_parse_string_strptime((ctx), (str))
+#elif defined(DUK_USE_DATE_PRS_GETDATE)
+DUK_INTERNAL_DECL duk_bool_t duk_bi_date_parse_string_getdate(duk_context *ctx, const char *str);
+#define DUK_USE_DATE_PARSE_STRING(ctx,str)   duk_bi_date_parse_string_getdate((ctx), (str))
+#else
+/* No provider for DUK_USE_DATE_PARSE_STRING(), fall back to ISO 8601 only. */
+#endif
+
+#if defined(DUK_USE_DATE_FORMAT_STRING)
+/* External provider already defined. */
+#elif defined(DUK_USE_DATE_FMT_STRFTIME)
+DUK_INTERNAL_DECL duk_bool_t duk_bi_date_format_parts_strftime(duk_context *ctx, duk_int_t *parts, duk_int_t tzoffset, duk_small_uint_t flags);
+#define DUK_USE_DATE_FORMAT_STRING(ctx,parts,tzoffset,flags) \
+	duk_bi_date_format_parts_strftime((ctx), (parts), (tzoffset), (flags))
+#else
+/* No provider for DUK_USE_DATE_FORMAT_STRING(), fall back to ISO 8601 only. */
+#endif
+
+#endif  /* DUK_COMPILING_DUKTAPE */
+
+/*
+ *  User declarations
+ */
+
+#if defined(DUK_OPT_DECLARE)
+#define DUK_USE_USER_DECLARE() DUK_OPT_DECLARE
+#else
+#define DUK_USE_USER_DECLARE() /* no user declarations */
+#endif
+
+/*
+ *  Autogenerated defaults
+ */
+
+#undef DUK_USE_DATE_PRS_GETDATE
+#undef DUK_USE_INTEGER_ME
+#define DUK_USE_JSON_DECNUMBER_FASTPATH
+#define DUK_USE_JSON_DECSTRING_FASTPATH
+#define DUK_USE_JSON_EATWHITE_FASTPATH
+#define DUK_USE_JSON_QUOTESTRING_FASTPATH
+// #undef DUK_USE_JSON_STRINGIFY_FASTPATH
+
+/*
+ *  Alternative customization header
+ *
+ *  If you want to modify the final DUK_USE_xxx flags directly (without
+ *  using the available DUK_OPT_xxx flags), define DUK_OPT_HAVE_CUSTOM_H
+ *  and tweak the final flags there.
+ */
+
+#if defined(DUK_OPT_HAVE_CUSTOM_H)
+#include "duk_custom.h"
+#endif
+
+/*
+ *  You may add overriding #define/#undef directives below for
+ *  customization.  You of course cannot un-#include or un-typedef
+ *  anything; these require direct changes above.
+ */
+
+/* __OVERRIDE_DEFINES__ */
+
+/*
+ *  Sanity check for the final effective internal defines.  Also
+ *  double checks user tweaks made by an optional duk_custom.h header.
+ */
+
+/*
+ *  Deprecated feature options.
+ *
+ *  Catch so that user more easily notices and updates build.
+ */
+
+#if defined(DUK_OPT_NO_FUNC_STMT)
+#error DUK_OPT_NO_FUNC_STMT is deprecated, use DUK_OPT_NO_NONSTD_FUNC_STMT
+#endif
+
+#if defined(DUK_OPT_FUNC_NONSTD_CALLER_PROPERTY)
+#error DUK_OPT_FUNC_NONSTD_CALLER_PROPERTY is deprecated, use DUK_OPT_NONSTD_FUNC_CALLER_PROPERTY
+#endif
+
+#if defined(DUK_OPT_FUNC_NONSTD_SOURCE_PROPERTY)
+#error DUK_OPT_FUNC_NONSTD_SOURCE_PROPERTY is deprecated, use DUK_OPT_NONSTD_FUNC_SOURCE_PROPERTY
+#endif
+
+#if defined(DUK_OPT_NO_ARRAY_SPLICE_NONSTD_DELCOUNT)
+#error DUK_OPT_NO_ARRAY_SPLICE_NONSTD_DELCOUNT is deprecated, use DUK_OPT_NO_NONSTD_ARRAY_SPLICE_DELCOUNT
+#endif
+
+#if defined(DUK_OPT_NO_OBJECT_ES6_PROTO_PROPERTY)
+#error DUK_OPT_NO_OBJECT_ES6_PROTO_PROPERTY is deprecated, use DUK_OPT_NO_ES6_OBJECT_PROTO_PROPERTY
+#endif
+
+#if defined(DUK_OPT_NO_OBJECT_ES6_SETPROTOTYPEOF)
+#error DUK_OPT_NO_OBJECT_ES6_SETPROTOTYPEOF is deprecated, use DUK_OPT_NO_ES6_OBJECT_SETPROTOTYPEOF
+#endif
+
+#if defined(DUK_OPT_NO_JSONX)
+#error DUK_OPT_NO_JSONX is deprecated, use DUK_OPT_NO_JX
+#endif
+
+#if defined(DUK_OPT_NO_JSONC)
+#error DUK_OPT_NO_JSONC is deprecated, use DUK_OPT_NO_JC
+#endif
+
+/*
+ *  Debug print consistency
+ */
+
+#if defined(DUK_USE_DPRINT) && !defined(DUK_USE_DEBUG)
+#error DUK_USE_DPRINT without DUK_USE_DEBUG
+#endif
+
+#if defined(DUK_USE_DDPRINT) && !defined(DUK_USE_DEBUG)
+#error DUK_USE_DDPRINT without DUK_USE_DEBUG
+#endif
+
+#if defined(DUK_USE_DDDPRINT) && !defined(DUK_USE_DEBUG)
+#error DUK_USE_DDDPRINT without DUK_USE_DEBUG
+#endif
+
+#if defined(DUK_USE_HEAPPTR16) && defined(DUK_USE_DEBUG)
+/* Debug code doesn't have access to 'heap' so it cannot decode pointers. */
+#error debug printing cannot currently be used with heap pointer compression
+#endif
+
+/*
+ *  Debugger consistency
+ */
+
+#if defined(DUK_USE_DEBUGGER_SUPPORT)
+#if !defined(DUK_USE_INTERRUPT_COUNTER)
+#error DUK_USE_INTERRUPT_COUNTER is needed when debugger support is enabled
+#endif
+#if !defined(DUK_USE_PC2LINE)
+#error DUK_USE_PC2LINE is needed when debugger support is enabled
+#endif
+#endif
+
+/*
+ *  Garbage collection consistency
+ */
+
+#if defined(DUK_USE_REFERENCE_COUNTING) && !defined(DUK_USE_DOUBLE_LINKED_HEAP)
+#error DUK_USE_REFERENCE_COUNTING defined without DUK_USE_DOUBLE_LINKED_HEAP
+#endif
+
+#if defined(DUK_USE_GC_TORTURE) && !defined(DUK_USE_MARK_AND_SWEEP)
+#error DUK_USE_GC_TORTURE defined without DUK_USE_MARK_AND_SWEEP
+#endif
+
+/*
+ *  Low memory feature consistency
+ */
+
+#if defined(DUK_USE_OBJSIZES16)
+#if defined(DUK_USE_HOBJECT_HASH_PART)
+#error DUK_USE_OBJSIZES16 assumes DUK_USE_HOBJECT_HASH_PART is not defined
+#endif
+#endif
+
+#if defined(DUK_USE_STRTAB_CHAIN) && defined(DUK_USE_STRTAB_PROBE)
+#error both DUK_USE_STRTAB_CHAIN and DUK_USE_STRTAB_PROBE defined
+#endif
+#if !defined(DUK_USE_STRTAB_CHAIN) && !defined(DUK_USE_STRTAB_PROBE)
+#error neither DUK_USE_STRTAB_CHAIN nor DUK_USE_STRTAB_PROBE is defined
+#endif
+
+#endif  /* DUK_CONFIG_H_INCLUDED */

File diff suppressed because it is too large
+ 674 - 138
Source/ThirdParty/Duktape/duktape.c


File diff suppressed because it is too large
+ 101 - 3069
Source/ThirdParty/Duktape/duktape.h


+ 25 - 1
Source/ToolCore/Assets/Asset.cpp

@@ -15,6 +15,8 @@
 #include "TextureImporter.h"
 #include "TextureImporter.h"
 #include "PrefabImporter.h"
 #include "PrefabImporter.h"
 #include "JavascriptImporter.h"
 #include "JavascriptImporter.h"
+#include "SpriterImporter.h"
+#include "TMXImporter.h"
 
 
 #include "AssetEvents.h"
 #include "AssetEvents.h"
 #include "Asset.h"
 #include "Asset.h"
@@ -230,7 +232,7 @@ bool Asset::CreateImporter()
     }
     }
     else
     else
     {
     {
-        String ext = GetExtension(path_);
+        String ext = Atomic::GetExtension(path_);
 
 
         name_ = GetFileName(path_);
         name_ = GetFileName(path_);
 
 
@@ -265,6 +267,14 @@ bool Asset::CreateImporter()
         {
         {
             importer_ = new MaterialImporter(context_, this);
             importer_ = new MaterialImporter(context_, this);
         }
         }
+        else if (ext == ".scml")
+        {
+            importer_ = new SpriterImporter(context_, this);
+        }
+        else if (ext == ".tmx")
+        {
+            importer_ = new TMXImporter(context_, this);
+        }
         else if (textureFormats.Contains(ext))
         else if (textureFormats.Contains(ext))
         {
         {
             importer_ = new TextureImporter(context_, this);
             importer_ = new TextureImporter(context_, this);
@@ -287,6 +297,12 @@ String Asset::GetCachePath() const
     return cachePath;
     return cachePath;
 }
 }
 
 
+String Asset::GetExtension() const
+{
+
+    return Atomic::GetExtension(path_);
+
+}
 
 
 bool Asset::SetPath(const String& path)
 bool Asset::SetPath(const String& path)
 {
 {
@@ -327,4 +343,12 @@ bool Asset::SetPath(const String& path)
 
 
 }
 }
 
 
+Resource* Asset::GetResource()
+{
+    if (importer_)
+        return importer_->GetResource();
+
+    return 0;
+}
+
 }
 }

+ 4 - 0
Source/ToolCore/Assets/Asset.h

@@ -2,6 +2,7 @@
 #pragma once
 #pragma once
 
 
 #include <Atomic/Core/Object.h>
 #include <Atomic/Core/Object.h>
+#include <Atomic/Resource/Resource.h>
 
 
 #include "AssetImporter.h"
 #include "AssetImporter.h"
 
 
@@ -32,10 +33,13 @@ public:
     const String& GetGUID() const { return guid_; }
     const String& GetGUID() const { return guid_; }
     const String& GetName() const { return name_; }
     const String& GetName() const { return name_; }
     const String& GetPath() const { return path_; }
     const String& GetPath() const { return path_; }
+    String GetExtension() const;
     /// Get the path relative to project
     /// Get the path relative to project
     String GetRelativePath();
     String GetRelativePath();
     String GetCachePath() const;
     String GetCachePath() const;
 
 
+    Resource* GetResource();
+
     const StringHash GetImporterType() { return importer_.Null() ? String::EMPTY : importer_->GetType(); }
     const StringHash GetImporterType() { return importer_.Null() ? String::EMPTY : importer_->GetType(); }
     const String& GetImporterTypeName() { return importer_.Null() ? String::EMPTY : importer_->GetTypeName(); }
     const String& GetImporterTypeName() { return importer_.Null() ? String::EMPTY : importer_->GetTypeName(); }
 
 

+ 22 - 0
Source/ToolCore/Assets/AssetDatabase.cpp

@@ -92,6 +92,9 @@ Asset* AssetDatabase::GetAssetByCachePath(const String& cachePath)
 {
 {
     List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
     List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
 
 
+    if (!cachePath.StartsWith("Cache/"))
+        return 0;
+
     String cacheFilename = GetFileName(cachePath);
     String cacheFilename = GetFileName(cachePath);
 
 
     while (itr != assets_.End())
     while (itr != assets_.End())
@@ -478,5 +481,24 @@ void AssetDatabase::HandleFileChanged(StringHash eventType, VariantMap& eventDat
     }
     }
 }
 }
 
 
+String AssetDatabase::GetResourceImporterName(const String& resourceTypeName)
+{
+    // TODO: have resource type register themselves
+    if (resourceTypeToImporterType_.Empty())
+    {
+        resourceTypeToImporterType_["Sound"] = "AudioImporter";
+        resourceTypeToImporterType_["Model"] = "ModelImporter";
+        resourceTypeToImporterType_["JSComponentFile"] = "JavascriptImporter";
+
+
+    }
+
+    if (!resourceTypeToImporterType_.Contains(resourceTypeName))
+        return String::EMPTY;
+
+    return resourceTypeToImporterType_[resourceTypeName];
+
+}
+
 
 
 }
 }

+ 4 - 0
Source/ToolCore/Assets/AssetDatabase.h

@@ -36,6 +36,8 @@ public:
 
 
     void GetFolderAssets(String folder, PODVector<Asset*>& assets) const;
     void GetFolderAssets(String folder, PODVector<Asset*>& assets) const;
 
 
+    String GetResourceImporterName(const String& resourceTypeName);
+
     void GetAssetsByImporterType(StringHash type, PODVector<Asset*>& assets) const;
     void GetAssetsByImporterType(StringHash type, PODVector<Asset*>& assets) const;
 
 
     void GetDirtyAssets(PODVector<Asset*>& assets);
     void GetDirtyAssets(PODVector<Asset*>& assets);
@@ -60,6 +62,8 @@ private:
     SharedPtr<Project> project_;
     SharedPtr<Project> project_;
     List<SharedPtr<Asset>> assets_;
     List<SharedPtr<Asset>> assets_;
 
 
+    HashMap<StringHash, String> resourceTypeToImporterType_;
+
     Vector<String> usedGUID_;
     Vector<String> usedGUID_;
 
 
 };
 };

+ 2 - 0
Source/ToolCore/Assets/AssetImporter.h

@@ -34,6 +34,8 @@ public:
 
 
     Asset* GetAsset() { return asset_; }
     Asset* GetAsset() { return asset_; }
 
 
+    virtual Resource* GetResource() { return 0; }
+
     bool RequiresCacheFile() const { return requiresCacheFile_; }
     bool RequiresCacheFile() const { return requiresCacheFile_; }
 
 
 protected:
 protected:

+ 17 - 0
Source/ToolCore/Assets/JavascriptImporter.cpp

@@ -4,10 +4,13 @@
 #include <Atomic/Resource/ResourceCache.h>
 #include <Atomic/Resource/ResourceCache.h>
 #include <Atomic/Resource/Image.h>
 #include <Atomic/Resource/Image.h>
 
 
+#include <AtomicJS/Javascript/JSComponentFile.h>
+
 #include "Asset.h"
 #include "Asset.h"
 #include "AssetDatabase.h"
 #include "AssetDatabase.h"
 #include "JavascriptImporter.h"
 #include "JavascriptImporter.h"
 
 
+
 namespace ToolCore
 namespace ToolCore
 {
 {
 
 
@@ -76,5 +79,19 @@ bool JavascriptImporter::SaveSettingsInternal()
     return true;
     return true;
 }
 }
 
 
+Resource* JavascriptImporter::GetResource()
+{
+    if (!isComponentFile_)
+        return 0;
+
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+
+    JSComponentFile* jsc = cache->GetResource<JSComponentFile>(asset_->GetPath());
+
+    return jsc;
+
+}
+
+
 
 
 }
 }

+ 2 - 0
Source/ToolCore/Assets/JavascriptImporter.h

@@ -19,6 +19,8 @@ public:
 
 
     bool IsComponentFile() { return isComponentFile_; }
     bool IsComponentFile() { return isComponentFile_; }
 
 
+    Resource* GetResource();
+
 protected:
 protected:
 
 
     bool Import();
     bool Import();

+ 11 - 0
Source/ToolCore/Assets/ModelImporter.cpp

@@ -7,6 +7,7 @@
 
 
 #include <Atomic/Atomic3D/AnimationController.h>
 #include <Atomic/Atomic3D/AnimationController.h>
 #include <Atomic/Atomic3D/Animation.h>
 #include <Atomic/Atomic3D/Animation.h>
+#include <Atomic/Atomic3D/Model.h>
 
 
 #include <Atomic/Resource/ResourceCache.h>
 #include <Atomic/Resource/ResourceCache.h>
 
 
@@ -294,5 +295,15 @@ bool ModelImporter::SaveSettingsInternal()
     return true;
     return true;
 }
 }
 
 
+Resource* ModelImporter::GetResource()
+{
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+
+    Model* model = cache->GetResource<Model>(asset_->GetCachePath() + ".mdl");
+
+    return model;
+
+}
+
 
 
 }
 }

+ 2 - 0
Source/ToolCore/Assets/ModelImporter.h

@@ -63,6 +63,8 @@ public:
     unsigned GetAnimationCount();
     unsigned GetAnimationCount();
     void SetAnimationCount(unsigned count);
     void SetAnimationCount(unsigned count);
 
 
+    Resource* GetResource();
+
     AnimationImportInfo* GetAnimationInfo(unsigned index) { return animationInfo_[index]; }
     AnimationImportInfo* GetAnimationInfo(unsigned index) { return animationInfo_[index]; }
 
 
 protected:
 protected:

+ 70 - 1
Source/ToolCore/Assets/PrefabImporter.cpp

@@ -4,6 +4,7 @@
 #include <Atomic/Scene/Scene.h>
 #include <Atomic/Scene/Scene.h>
 #include <Atomic/Scene/PrefabEvents.h>
 #include <Atomic/Scene/PrefabEvents.h>
 #include <Atomic/Scene/PrefabComponent.h>
 #include <Atomic/Scene/PrefabComponent.h>
+#include <Atomic/Atomic2D/AnimatedSprite2D.h>
 #include <Atomic/IO/FileSystem.h>
 #include <Atomic/IO/FileSystem.h>
 
 
 #include "Asset.h"
 #include "Asset.h"
@@ -49,16 +50,84 @@ void PrefabImporter::HandlePrefabSave(StringHash eventType, VariantMap& eventDat
     if (component->GetPrefabGUID() != asset_->GetGUID())
     if (component->GetPrefabGUID() != asset_->GetGUID())
         return;
         return;
 
 
-    Node* node = component->GetPrefabNode();
+    Node* node = component->GetNode();
+
+    if (!node)
+        return;
+
+    // flip temporary root children and components to not be temporary for save
+    const Vector<SharedPtr<Component>>& rootComponents = node->GetComponents();
+    const Vector<SharedPtr<Node> >& children = node->GetChildren();
+
+    PODVector<Component*> tempComponents;
+    PODVector<Node*> tempChildren;
+    PODVector<Node*> filterNodes;
+
+    for (unsigned i = 0; i < rootComponents.Size(); i++)
+    {
+        if (rootComponents[i]->IsTemporary())
+        {
+            rootComponents[i]->SetTemporary(false);
+            tempComponents.Push(rootComponents[i]);
+
+            // Animated sprites contain a temporary node we don't want to save in the prefab
+            // it would be nice if this was general purpose because have to test this when
+            // breaking node as well
+            if (rootComponents[i]->GetType() == AnimatedSprite2D::GetTypeStatic())
+            {
+                AnimatedSprite2D* asprite = (AnimatedSprite2D*) rootComponents[i].Get();
+                if (asprite->GetRootNode())
+                    filterNodes.Push(asprite->GetRootNode());
+            }
+
+        }
+    }
+
+    for (unsigned i = 0; i < children.Size(); i++)
+    {
+        if (filterNodes.Contains(children[i].Get()))
+            continue;
+
+        if (children[i]->IsTemporary())
+        {
+            children[i]->SetTemporary(false);
+            tempChildren.Push(children[i]);
+        }
+    }
+
+    // store original transform
+    Vector3 pos = node->GetPosition();
+    Quaternion rot = node->GetRotation();
+    Vector3 scale = node->GetScale();
 
 
     node->SetPosition(Vector3::ZERO);
     node->SetPosition(Vector3::ZERO);
     node->SetRotation(Quaternion::IDENTITY);
     node->SetRotation(Quaternion::IDENTITY);
     node->SetScale(Vector3::ONE);
     node->SetScale(Vector3::ONE);
 
 
+    component->SetTemporary(true);
+
     SharedPtr<File> file(new File(context_, asset_->GetPath(), FILE_WRITE));
     SharedPtr<File> file(new File(context_, asset_->GetPath(), FILE_WRITE));
     node->SaveXML(*file);
     node->SaveXML(*file);
     file->Close();
     file->Close();
 
 
+    component->SetTemporary(false);
+
+    // restore
+    node->SetPosition(pos);
+    node->SetRotation(rot);
+    node->SetScale(scale);
+
+    for (unsigned i = 0; i < tempComponents.Size(); i++)
+    {
+        tempComponents[i]->SetTemporary(true);
+    }
+
+    for (unsigned i = 0; i < tempChildren.Size(); i++)
+    {
+        tempChildren[i]->SetTemporary(true);
+    }
+
+
     FileSystem* fs = GetSubsystem<FileSystem>();
     FileSystem* fs = GetSubsystem<FileSystem>();
     fs->Copy(asset_->GetPath(), asset_->GetCachePath());
     fs->Copy(asset_->GetPath(), asset_->GetCachePath());
 
 

+ 53 - 0
Source/ToolCore/Assets/SpriterImporter.cpp

@@ -0,0 +1,53 @@
+
+#include <Atomic/Resource/ResourceCache.h>
+#include <Atomic/Resource/Image.h>
+
+#include "Asset.h"
+#include "AssetDatabase.h"
+#include "SpriterImporter.h"
+
+namespace ToolCore
+{
+
+SpriterImporter::SpriterImporter(Context* context, Asset *asset) : AssetImporter(context, asset)
+{
+
+}
+
+SpriterImporter::~SpriterImporter()
+{
+
+}
+
+void SpriterImporter::SetDefaults()
+{
+    AssetImporter::SetDefaults();
+}
+
+bool SpriterImporter::Import()
+{
+    return true;
+}
+
+bool SpriterImporter::LoadSettingsInternal()
+{
+    if (!AssetImporter::LoadSettingsInternal())
+        return false;
+
+    JSONValue import = jsonRoot_.GetChild("SpriterImporter", JSON_OBJECT);
+
+    return true;
+}
+
+bool SpriterImporter::SaveSettingsInternal()
+{
+    if (!AssetImporter::SaveSettingsInternal())
+        return false;
+
+    JSONValue import = jsonRoot_.CreateChild("SpriterImporter");
+
+    return true;
+}
+
+
+}

+ 29 - 0
Source/ToolCore/Assets/SpriterImporter.h

@@ -0,0 +1,29 @@
+
+#pragma once
+
+#include "AssetImporter.h"
+
+namespace ToolCore
+{
+
+class SpriterImporter : public AssetImporter
+{
+    OBJECT(SpriterImporter);
+
+public:
+    /// Construct.
+    SpriterImporter(Context* context, Asset* asset);
+    virtual ~SpriterImporter();
+
+    virtual void SetDefaults();
+
+protected:
+
+    bool Import();
+
+    virtual bool LoadSettingsInternal();
+    virtual bool SaveSettingsInternal();
+
+};
+
+}

+ 53 - 0
Source/ToolCore/Assets/TMXImporter.cpp

@@ -0,0 +1,53 @@
+
+#include <Atomic/Resource/ResourceCache.h>
+#include <Atomic/Resource/Image.h>
+
+#include "Asset.h"
+#include "AssetDatabase.h"
+#include "TMXImporter.h"
+
+namespace ToolCore
+{
+
+TMXImporter::TMXImporter(Context* context, Asset *asset) : AssetImporter(context, asset)
+{
+
+}
+
+TMXImporter::~TMXImporter()
+{
+
+}
+
+void TMXImporter::SetDefaults()
+{
+    AssetImporter::SetDefaults();
+}
+
+bool TMXImporter::Import()
+{
+    return true;
+}
+
+bool TMXImporter::LoadSettingsInternal()
+{
+    if (!AssetImporter::LoadSettingsInternal())
+        return false;
+
+    JSONValue import = jsonRoot_.GetChild("TMXImporter", JSON_OBJECT);
+
+    return true;
+}
+
+bool TMXImporter::SaveSettingsInternal()
+{
+    if (!AssetImporter::SaveSettingsInternal())
+        return false;
+
+    JSONValue import = jsonRoot_.CreateChild("TMXImporter");
+
+    return true;
+}
+
+
+}

+ 29 - 0
Source/ToolCore/Assets/TMXImporter.h

@@ -0,0 +1,29 @@
+
+#pragma once
+
+#include "AssetImporter.h"
+
+namespace ToolCore
+{
+
+class TMXImporter : public AssetImporter
+{
+    OBJECT(TMXImporter);
+
+public:
+    /// Construct.
+    TMXImporter(Context* context, Asset* asset);
+    virtual ~TMXImporter();
+
+    virtual void SetDefaults();
+
+protected:
+
+    bool Import();
+
+    virtual bool LoadSettingsInternal();
+    virtual bool SaveSettingsInternal();
+
+};
+
+}

+ 5 - 5
Source/ToolCore/Command/ImportCmd.cpp

@@ -51,9 +51,9 @@ bool ImportCmd::Parse(const Vector<String>& arguments, unsigned startIndex, Stri
 
 
 void ImportCmd::Run()
 void ImportCmd::Run()
 {
 {
-    //ToolSystem* tsystem = GetSubsystem<ToolSystem>();
-    //Project* project = tsystem->GetProject();
-    //String resourcePath = project->GetResourcePath();
+    ToolSystem* tsystem = GetSubsystem<ToolSystem>();
+    Project* project = tsystem->GetProject();
+    String resourcePath = project->GetResourcePath();
 
 
     String ext = GetExtension(assetFilename_);
     String ext = GetExtension(assetFilename_);
 
 
@@ -75,8 +75,8 @@ void ImportCmd::Run()
 
 
         SharedPtr<JSONSceneProcess> sceneProcess;
         SharedPtr<JSONSceneProcess> sceneProcess;
         sceneProcess = new JSONSceneProcess(context_, jimporter);
         sceneProcess = new JSONSceneProcess(context_, jimporter);
-        //sceneProcess->Process(resourcePath);
-        //sceneProcess->Write();
+        sceneProcess->Process(resourcePath);
+        sceneProcess->Write();
     }
     }
     else
     else
     {
     {

+ 1 - 1
Source/ToolCore/Command/ImportCmd.h

@@ -20,7 +20,7 @@ public:
     bool Parse(const Vector<String>& arguments, unsigned startIndex, String& errorMsg);
     bool Parse(const Vector<String>& arguments, unsigned startIndex, String& errorMsg);
     void Run();
     void Run();
 
 
-    bool RequiresProjectLoad() { return false; }
+    bool RequiresProjectLoad() { return true; }
 
 
 private:
 private:
 
 

+ 2 - 0
Source/ToolCore/Import/JSONSceneImporter.cpp

@@ -585,6 +585,8 @@ bool JSONSceneImporter::ParseMaterials(const rapidjson::Value& value)
                     else if (!strcmp(oitr->name.GetString(), "shader"))
                     else if (!strcmp(oitr->name.GetString(), "shader"))
                     {
                     {
                         shader = oitr->value.GetString();
                         shader = oitr->value.GetString();
+
+                        shader.Replace("Legacy Shaders/", "");
                     }
                     }
                     else if (!strcmp(oitr->name.GetString(), "mainTexture"))
                     else if (!strcmp(oitr->name.GetString(), "mainTexture"))
                     {
                     {

Some files were not shown because too many files changed in this diff