Procházet zdrojové kódy

More work on improving documentation for Doxygen generation.

BearishSun před 9 roky
rodič
revize
0a448db0af
100 změnil soubory, kde provedl 14036 přidání a 13893 odebrání
  1. 70 68
      Source/BansheeCore/Include/BsCBoxCollider.h
  2. 84 82
      Source/BansheeCore/Include/BsCCapsuleCollider.h
  3. 162 160
      Source/BansheeCore/Include/BsCCharacterController.h
  4. 4 2
      Source/BansheeCore/Include/BsCCollider.h
  5. 122 120
      Source/BansheeCore/Include/BsCD6Joint.h
  6. 94 92
      Source/BansheeCore/Include/BsCDistanceJoint.h
  7. 55 53
      Source/BansheeCore/Include/BsCFixedJoint.h
  8. 83 81
      Source/BansheeCore/Include/BsCHingeJoint.h
  9. 134 132
      Source/BansheeCore/Include/BsCJoint.h
  10. 67 65
      Source/BansheeCore/Include/BsCMeshCollider.h
  11. 74 72
      Source/BansheeCore/Include/BsCPlaneCollider.h
  12. 271 269
      Source/BansheeCore/Include/BsCRigidbody.h
  13. 76 74
      Source/BansheeCore/Include/BsCSliderJoint.h
  14. 70 68
      Source/BansheeCore/Include/BsCSphereCollider.h
  15. 70 68
      Source/BansheeCore/Include/BsCSphericalJoint.h
  16. 311 309
      Source/BansheeCore/Include/BsCharacterController.h
  17. 4 2
      Source/BansheeCore/Include/BsCollider.h
  18. 429 429
      Source/BansheeCore/Include/BsCommonTypes.h
  19. 124 124
      Source/BansheeCore/Include/BsComponent.h
  20. 299 297
      Source/BansheeCore/Include/BsCoreObject.h
  21. 95 93
      Source/BansheeCore/Include/BsCoreObjectCore.h
  22. 7 2
      Source/BansheeCore/Include/BsCorePrerequisites.h
  23. 1 1
      Source/BansheeCore/Include/BsCoreSceneManager.h
  24. 185 185
      Source/BansheeCore/Include/BsD6Joint.h
  25. 1 1
      Source/BansheeCore/Include/BsFCollider.h
  26. 76 76
      Source/BansheeCore/Include/BsFJoint.h
  27. 99 97
      Source/BansheeCore/Include/BsFont.h
  28. 171 167
      Source/BansheeCore/Include/BsFontDesc.h
  29. 120 118
      Source/BansheeCore/Include/BsGameObject.h
  30. 305 301
      Source/BansheeCore/Include/BsGameObjectHandle.h
  31. 56 56
      Source/BansheeCore/Include/BsGpuParamDesc.h
  32. 245 245
      Source/BansheeCore/Include/BsGpuProgram.h
  33. 143 143
      Source/BansheeCore/Include/BsGpuProgramManager.h
  34. 75 75
      Source/BansheeCore/Include/BsHString.h
  35. 161 161
      Source/BansheeCore/Include/BsHardwareBuffer.h
  36. 104 101
      Source/BansheeCore/Include/BsHingeJoint.h
  37. 11 8
      Source/BansheeCore/Include/BsImporter.h
  38. 249 247
      Source/BansheeCore/Include/BsInput.h
  39. 9 4
      Source/BansheeCore/Include/BsInputFwd.h
  40. 325 323
      Source/BansheeCore/Include/BsJoint.h
  41. 302 302
      Source/BansheeCore/Include/BsMaterialParam.h
  42. 396 396
      Source/BansheeCore/Include/BsMaterialParams.h
  43. 231 231
      Source/BansheeCore/Include/BsMeshHeap.h
  44. 87 84
      Source/BansheeCore/Include/BsMeshUtility.h
  45. 2 1
      Source/BansheeCore/Include/BsParamBlocks.h
  46. 1 1
      Source/BansheeCore/Include/BsPass.h
  47. 595 593
      Source/BansheeCore/Include/BsPhysics.h
  48. 86 84
      Source/BansheeCore/Include/BsPhysicsMaterial.h
  49. 4 2
      Source/BansheeCore/Include/BsPhysicsMesh.h
  50. 382 380
      Source/BansheeCore/Include/BsPixelData.h
  51. 229 229
      Source/BansheeCore/Include/BsPixelUtil.h
  52. 449 449
      Source/BansheeCore/Include/BsPlatform.h
  53. 96 94
      Source/BansheeCore/Include/BsPrefab.h
  54. 422 422
      Source/BansheeCore/Include/BsProfilerCPU.h
  55. 181 179
      Source/BansheeCore/Include/BsProfilerGPU.h
  56. 224 224
      Source/BansheeCore/Include/BsRasterizerState.h
  57. 1 1
      Source/BansheeCore/Include/BsRenderAPI.h
  58. 207 207
      Source/BansheeCore/Include/BsRenderTarget.h
  59. 301 298
      Source/BansheeCore/Include/BsRenderWindow.h
  60. 401 399
      Source/BansheeCore/Include/BsResourceHandle.h
  61. 87 87
      Source/BansheeCore/Include/BsResourceListenerManager.h
  62. 4 2
      Source/BansheeCore/Include/BsResources.h
  63. 367 365
      Source/BansheeCore/Include/BsRigidbody.h
  64. 4 2
      Source/BansheeCore/Include/BsSceneObject.h
  65. 6 3
      Source/BansheeCore/Include/BsShader.h
  66. 51 49
      Source/BansheeCore/Include/BsShaderInclude.h
  67. 34 34
      Source/BansheeCore/Include/BsShaderIncludeImporter.h
  68. 84 84
      Source/BansheeCore/Include/BsSpecificImporter.h
  69. 334 332
      Source/BansheeCore/Include/BsStringTable.h
  70. 1 1
      Source/BansheeCore/Include/BsTextData.h
  71. 470 470
      Source/BansheeCore/Include/BsTexture.h
  72. 99 99
      Source/BansheeCore/Include/BsTextureView.h
  73. 230 230
      Source/BansheeCore/Include/BsVertexDeclaration.h
  74. 112 112
      Source/BansheeCore/Include/BsVideoModeInfo.h
  75. 1 1
      Source/BansheeD3D11RenderAPI/Include/BsD3D11Driver.h
  76. 1 1
      Source/BansheeD3D11RenderAPI/Include/BsD3D11GpuBufferView.h
  77. 5 0
      Source/BansheeEditor/Include/BsEditorPrerequisites.h
  78. 4 2
      Source/BansheeEditor/Include/BsEditorWidget.h
  79. 92 90
      Source/BansheeEditor/Include/BsGUIColor.h
  80. 254 252
      Source/BansheeEditor/Include/BsGUIFieldBase.h
  81. 103 101
      Source/BansheeEditor/Include/BsGUIFloatField.h
  82. 104 102
      Source/BansheeEditor/Include/BsGUIIntField.h
  83. 111 111
      Source/BansheeEditor/Include/BsGUIStatusBar.h
  84. 211 209
      Source/BansheeEditor/Include/BsGUITextField.h
  85. 5 3
      Source/BansheeEditor/Include/BsGUITreeView.h
  86. 5 3
      Source/BansheeEditor/Include/BsGizmoManager.h
  87. 165 165
      Source/BansheeEditor/Include/BsHandleSlider.h
  88. 67 67
      Source/BansheeEditor/Include/BsHandleSliderLine.h
  89. 74 74
      Source/BansheeEditor/Include/BsModalWindow.h
  90. 55 55
      Source/BansheeEditor/Include/BsProjectLibraryEntries.h
  91. 139 139
      Source/BansheeEditor/Include/BsSceneGrid.h
  92. 118 116
      Source/BansheeEngine/Include/BsCGUIWidget.h
  93. 4 2
      Source/BansheeEngine/Include/BsCamera.h
  94. 77 75
      Source/BansheeEngine/Include/BsGUIButton.h
  95. 117 115
      Source/BansheeEngine/Include/BsGUIButtonBase.h
  96. 4 2
      Source/BansheeEngine/Include/BsGUIElement.h
  97. 332 330
      Source/BansheeEngine/Include/BsGUIElementBase.h
  98. 266 264
      Source/BansheeEngine/Include/BsGUIInputBox.h
  99. 106 104
      Source/BansheeEngine/Include/BsGUILabel.h
  100. 95 93
      Source/BansheeEngine/Include/BsGUILayout.h

+ 70 - 68
Source/BansheeCore/Include/BsCBoxCollider.h

@@ -1,69 +1,71 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsBoxCollider.h"
-#include "BsCCollider.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	BoxCollider
-	 *
-	 * Wraps BoxCollider as a Component.
-	 */
-    class BS_CORE_EXPORT CBoxCollider : public CCollider
-    {
-    public:
-		CBoxCollider(const HSceneObject& parent, const Vector3& extents = Vector3::ONE);
-
-		/** @copydoc BoxCollider::setExtents */
-		void setExtents(const Vector3& extents);
-
-		/** @copydoc BoxCollider::getExtents */
-		Vector3 getExtents() const { return mExtents; }
-
-		/** Sets the position of the box shape, relative to the component's scene object. */
-		void setCenter(const Vector3& center);
-
-		/** Gets the position of the box shape, relative to the component's scene object. */
-		Vector3 getCenter() const { return mLocalPosition; }
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the box collider that this component wraps. */
-		BoxCollider* _getInternal() const { return static_cast<BoxCollider*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CCollider::createInternal */
-		SPtr<Collider> createInternal() override;
-
-    protected:
-		Vector3 mExtents;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CBoxColliderRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CBoxCollider() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsBoxCollider.h"
+#include "BsCCollider.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	BoxCollider
+	 *
+	 * Wraps BoxCollider as a Component.
+	 */
+    class BS_CORE_EXPORT CBoxCollider : public CCollider
+    {
+    public:
+		CBoxCollider(const HSceneObject& parent, const Vector3& extents = Vector3::ONE);
+
+		/** @copydoc BoxCollider::setExtents */
+		void setExtents(const Vector3& extents);
+
+		/** @copydoc BoxCollider::getExtents */
+		Vector3 getExtents() const { return mExtents; }
+
+		/** Sets the position of the box shape, relative to the component's scene object. */
+		void setCenter(const Vector3& center);
+
+		/** Gets the position of the box shape, relative to the component's scene object. */
+		Vector3 getCenter() const { return mLocalPosition; }
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the box collider that this component wraps. */
+		BoxCollider* _getInternal() const { return static_cast<BoxCollider*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CCollider::createInternal */
+		SPtr<Collider> createInternal() override;
+
+    protected:
+		Vector3 mExtents;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CBoxColliderRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CBoxCollider() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 84 - 82
Source/BansheeCore/Include/BsCCapsuleCollider.h

@@ -1,83 +1,85 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsCapsuleCollider.h"
-#include "BsCCollider.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	CapsuleCollider
-	 *
-	 * Wraps CapsuleCollider as a Component.
-	 */
-    class BS_CORE_EXPORT CCapsuleCollider : public CCollider
-    {
-    public:
-		CCapsuleCollider(const HSceneObject& parent, float radius = 1.0f, float halfHeight = 0.5f);
-
-		/** Sets the normal vector of the capsule. It determines how is the capsule oriented. */
-		void setNormal(const Vector3& normal);
-
-		/** Gets the normal vector of the capsule. It determines how is the capsule oriented. */
-		Vector3 getNormal() const { return mNormal; }
-
-		/** Sets the position of the capsule shape, relative to the component's scene object. */
-		void setCenter(const Vector3& center);
-
-		/** Gets the position of the capsule shape, relative to the component's scene object. */
-		Vector3 getCenter() const { return mLocalPosition; }
-
-		/** @copydoc CapsuleCollider::setHalfHeight() */
-		void setHalfHeight(float halfHeight);
-
-		/** @copydoc CapsuleCollider::getHalfHeight() */
-		float getHalfHeight() const { return mHalfHeight; }
-
-		/** @copydoc CapsuleCollider::setRadius() */
-		void setRadius(float radius);
-
-		/** @copydoc CapsuleCollider::getRadius() */
-		float getRadius() const { return mRadius; }
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the capsule collider that this component wraps. */
-		CapsuleCollider* _getInternal() const { return static_cast<CapsuleCollider*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CCollider::createInternal */
-		SPtr<Collider> createInternal() override;
-
-    protected:
-		Vector3 mNormal = Vector3::UNIT_Y;
-		float mRadius = 1.0f;
-		float mHalfHeight = 0.5f;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CCapsuleColliderRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CCapsuleCollider() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsCapsuleCollider.h"
+#include "BsCCollider.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	CapsuleCollider
+	 *
+	 * Wraps CapsuleCollider as a Component.
+	 */
+    class BS_CORE_EXPORT CCapsuleCollider : public CCollider
+    {
+    public:
+		CCapsuleCollider(const HSceneObject& parent, float radius = 1.0f, float halfHeight = 0.5f);
+
+		/** Sets the normal vector of the capsule. It determines how is the capsule oriented. */
+		void setNormal(const Vector3& normal);
+
+		/** Gets the normal vector of the capsule. It determines how is the capsule oriented. */
+		Vector3 getNormal() const { return mNormal; }
+
+		/** Sets the position of the capsule shape, relative to the component's scene object. */
+		void setCenter(const Vector3& center);
+
+		/** Gets the position of the capsule shape, relative to the component's scene object. */
+		Vector3 getCenter() const { return mLocalPosition; }
+
+		/** @copydoc CapsuleCollider::setHalfHeight() */
+		void setHalfHeight(float halfHeight);
+
+		/** @copydoc CapsuleCollider::getHalfHeight() */
+		float getHalfHeight() const { return mHalfHeight; }
+
+		/** @copydoc CapsuleCollider::setRadius() */
+		void setRadius(float radius);
+
+		/** @copydoc CapsuleCollider::getRadius() */
+		float getRadius() const { return mRadius; }
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the capsule collider that this component wraps. */
+		CapsuleCollider* _getInternal() const { return static_cast<CapsuleCollider*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CCollider::createInternal */
+		SPtr<Collider> createInternal() override;
+
+    protected:
+		Vector3 mNormal = Vector3::UNIT_Y;
+		float mRadius = 1.0f;
+		float mHalfHeight = 0.5f;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CCapsuleColliderRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CCapsuleCollider() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 162 - 160
Source/BansheeCore/Include/BsCCharacterController.h

@@ -1,161 +1,163 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsCharacterController.h"
-#include "BsComponent.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	CharacterController
-	 *
-	 * Wraps CharacterController as a Component.
-	 */
-    class BS_CORE_EXPORT CCharacterController : public Component
-    {
-    public:
-		CCharacterController(const HSceneObject& parent);
-
-		/** @copydoc CharacterController::move */
-		inline CharacterCollisionFlags move(const Vector3& displacement);
-
-		/** @copydoc CharacterController::getFootPosition */
-		inline Vector3 getFootPosition() const;
-
-		/** @copydoc CharacterController::setFootPosition */
-		inline void setFootPosition(const Vector3& position);
-
-		/** @copydoc CharacterController::getRadius */
-		float getRadius() const { return mDesc.radius; }
-
-		/** @copydoc CharacterController::setRadius */
-		inline void setRadius(float radius);
-
-		/** @copydoc CharacterController::getHeight */
-		float getHeight() const { return mDesc.height; }
-
-		/** @copydoc CharacterController::setHeight */
-		inline void setHeight(float height);
-
-		/** @copydoc CharacterController::getUp */
-		Vector3 getUp() const { return mDesc.up; }
-
-		/** @copydoc CharacterController::setUp */
-		inline void setUp(const Vector3& up);
-
-		/** @copydoc CharacterController::getClimbingMode */
-		CharacterClimbingMode getClimbingMode() const { return mDesc.climbingMode; }
-
-		/** @copydoc CharacterController::setClimbingMode */
-		inline void setClimbingMode(CharacterClimbingMode mode);
-
-		/** @copydoc CharacterController::getNonWalkableMode */
-		CharacterNonWalkableMode getNonWalkableMode() const { return mDesc.nonWalkableMode; }
-
-		/** @copydoc CharacterController::setNonWalkableMode */
-		inline void setNonWalkableMode(CharacterNonWalkableMode mode);
-
-		/** @copydoc CharacterController::getMinMoveDistance */
-		float getMinMoveDistance() const { return mDesc.minMoveDistance; }
-
-		/** @copydoc CharacterController::setMinMoveDistance */
-		inline void setMinMoveDistance(float value);
-
-		/** @copydoc CharacterController::getContactOffset */
-		float getContactOffset() const { return mDesc.contactOffset; }
-
-		/** @copydoc CharacterController::setContactOffset */
-		inline void setContactOffset(float value);
-
-		/** @copydoc CharacterController::getStepOffset */
-		inline float getStepOffset() const { return mDesc.stepOffset; }
-
-		/** @copydoc CharacterController::setStepOffset */
-		inline void setStepOffset(float value);
-
-		/** @copydoc CharacterController::getSlopeLimit */
-		Radian getSlopeLimit() const { return mDesc.slopeLimit; }
-
-		/** @copydoc CharacterController::setSlopeLimit */
-		inline void setSlopeLimit(Radian value);
-
-		/** @copydoc CharacterController::getLayer */
-		UINT64 getLayer() const { return mLayer; }
-
-		/** @copydoc CharacterController::setLayer */
-		inline void setLayer(UINT64 layer);
-
-		/** @copydoc CharacterController::onColliderHit */
-		Event<void(const ControllerColliderCollision&)> onColliderHit;
-
-		/** @copydoc CharacterController::onControllerHit */
-		Event<void(const ControllerControllerCollision&)> onControllerHit;
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the character controller that this component wraps. */
-		CharacterController* _getInternal() const { return static_cast<CharacterController*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc Component::onInitialized() */
-		void onInitialized() override;
-
-		/** @copydoc Component::onDestroyed() */
-		void onDestroyed() override;
-
-		/** @copydoc Component::onDisabled() */
-		void onDisabled() override;
-
-		/** @copydoc Component::onEnabled() */
-		void onEnabled() override;
-
-		/** @copydoc Component::onTransformChanged() */
-		void onTransformChanged(TransformChangedFlags flags) override;
-
-    protected:
-		/** Updates the position by copying it from the controller to the component's scene object. */
-		void updatePositionFromController();
-
-		/** Updates the dimensions of the controller by taking account scale of the parent scene object. */
-		void updateDimensions();
-
-		/** Destroys the internal character controller representation. */
-		void destroyInternal();
-
-		/** Triggered when the internal controller hits a collider. */
-		void triggerOnColliderHit(const ControllerColliderCollision& value);
-
-		/** Triggered when the internal controller hits another controller. */
-		void triggerOnControllerHit(const ControllerControllerCollision& value);
-
-		SPtr<CharacterController> mInternal;
-		CHAR_CONTROLLER_DESC mDesc;
-		UINT64 mLayer = 1;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CCharacterControllerRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CCharacterController() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsCharacterController.h"
+#include "BsComponent.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	CharacterController
+	 *
+	 * Wraps CharacterController as a Component.
+	 */
+    class BS_CORE_EXPORT CCharacterController : public Component
+    {
+    public:
+		CCharacterController(const HSceneObject& parent);
+
+		/** @copydoc CharacterController::move */
+		inline CharacterCollisionFlags move(const Vector3& displacement);
+
+		/** @copydoc CharacterController::getFootPosition */
+		inline Vector3 getFootPosition() const;
+
+		/** @copydoc CharacterController::setFootPosition */
+		inline void setFootPosition(const Vector3& position);
+
+		/** @copydoc CharacterController::getRadius */
+		float getRadius() const { return mDesc.radius; }
+
+		/** @copydoc CharacterController::setRadius */
+		inline void setRadius(float radius);
+
+		/** @copydoc CharacterController::getHeight */
+		float getHeight() const { return mDesc.height; }
+
+		/** @copydoc CharacterController::setHeight */
+		inline void setHeight(float height);
+
+		/** @copydoc CharacterController::getUp */
+		Vector3 getUp() const { return mDesc.up; }
+
+		/** @copydoc CharacterController::setUp */
+		inline void setUp(const Vector3& up);
+
+		/** @copydoc CharacterController::getClimbingMode */
+		CharacterClimbingMode getClimbingMode() const { return mDesc.climbingMode; }
+
+		/** @copydoc CharacterController::setClimbingMode */
+		inline void setClimbingMode(CharacterClimbingMode mode);
+
+		/** @copydoc CharacterController::getNonWalkableMode */
+		CharacterNonWalkableMode getNonWalkableMode() const { return mDesc.nonWalkableMode; }
+
+		/** @copydoc CharacterController::setNonWalkableMode */
+		inline void setNonWalkableMode(CharacterNonWalkableMode mode);
+
+		/** @copydoc CharacterController::getMinMoveDistance */
+		float getMinMoveDistance() const { return mDesc.minMoveDistance; }
+
+		/** @copydoc CharacterController::setMinMoveDistance */
+		inline void setMinMoveDistance(float value);
+
+		/** @copydoc CharacterController::getContactOffset */
+		float getContactOffset() const { return mDesc.contactOffset; }
+
+		/** @copydoc CharacterController::setContactOffset */
+		inline void setContactOffset(float value);
+
+		/** @copydoc CharacterController::getStepOffset */
+		inline float getStepOffset() const { return mDesc.stepOffset; }
+
+		/** @copydoc CharacterController::setStepOffset */
+		inline void setStepOffset(float value);
+
+		/** @copydoc CharacterController::getSlopeLimit */
+		Radian getSlopeLimit() const { return mDesc.slopeLimit; }
+
+		/** @copydoc CharacterController::setSlopeLimit */
+		inline void setSlopeLimit(Radian value);
+
+		/** @copydoc CharacterController::getLayer */
+		UINT64 getLayer() const { return mLayer; }
+
+		/** @copydoc CharacterController::setLayer */
+		inline void setLayer(UINT64 layer);
+
+		/** @copydoc CharacterController::onColliderHit */
+		Event<void(const ControllerColliderCollision&)> onColliderHit;
+
+		/** @copydoc CharacterController::onControllerHit */
+		Event<void(const ControllerControllerCollision&)> onControllerHit;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the character controller that this component wraps. */
+		CharacterController* _getInternal() const { return static_cast<CharacterController*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc Component::onInitialized() */
+		void onInitialized() override;
+
+		/** @copydoc Component::onDestroyed() */
+		void onDestroyed() override;
+
+		/** @copydoc Component::onDisabled() */
+		void onDisabled() override;
+
+		/** @copydoc Component::onEnabled() */
+		void onEnabled() override;
+
+		/** @copydoc Component::onTransformChanged() */
+		void onTransformChanged(TransformChangedFlags flags) override;
+
+    protected:
+		/** Updates the position by copying it from the controller to the component's scene object. */
+		void updatePositionFromController();
+
+		/** Updates the dimensions of the controller by taking account scale of the parent scene object. */
+		void updateDimensions();
+
+		/** Destroys the internal character controller representation. */
+		void destroyInternal();
+
+		/** Triggered when the internal controller hits a collider. */
+		void triggerOnColliderHit(const ControllerColliderCollision& value);
+
+		/** Triggered when the internal controller hits another controller. */
+		void triggerOnControllerHit(const ControllerControllerCollision& value);
+
+		SPtr<CharacterController> mInternal;
+		CHAR_CONTROLLER_DESC mDesc;
+		UINT64 mLayer = 1;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CCharacterControllerRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CCharacterController() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 4 - 2
Source/BansheeCore/Include/BsCCollider.h

@@ -84,12 +84,14 @@ namespace BansheeEngine
 		/** @copydoc Collider::onCollisionEnd */
 		Event<void(const CollisionData&)> onCollisionEnd;
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/** Returns the Collider implementation wrapped by this component. */
 		Collider* _getInternal() const { return mInternal.get(); }
 
-		/** @endcond */
+		/** @} */
 
 		/************************************************************************/
 		/* 						COMPONENT OVERRIDES                      		*/

+ 122 - 120
Source/BansheeCore/Include/BsCD6Joint.h

@@ -1,121 +1,123 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsD6Joint.h"
-#include "BsCJoint.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	D6Joint
-	 *
-	 * Wraps D6Joint as a Component.
-	 */
-    class BS_CORE_EXPORT CD6Joint : public CJoint
-    {
-    public:
-		CD6Joint(const HSceneObject& parent);
-
-		/** @copydoc D6Joint::getMotion */
-		inline D6Joint::Motion getMotion(D6Joint::Axis axis) const;
-
-		/** @copydoc D6Joint::setMotion */
-		inline void setMotion(D6Joint::Axis axis, D6Joint::Motion motion);
-
-		/** @copydoc D6Joint::getTwist */
-		inline Radian getTwist() const;
-
-		/** @copydoc D6Joint::getSwingY */
-		inline Radian getSwingY() const;
-
-		/** @copydoc D6Joint::getSwingZ */
-		inline Radian getSwingZ() const;
-
-		/** @copydoc D6Joint::getLimitLinear */
-		inline LimitLinear getLimitLinear() const;
-
-		/** @copydoc D6Joint::setLimitLinear */
-		inline void setLimitLinear(const LimitLinear& limit);
-
-		/** @copydoc D6Joint::getLimitTwist */
-		inline LimitAngularRange getLimitTwist() const;
-
-		/** @copydoc D6Joint::setLimitTwist */
-		inline void setLimitTwist(const LimitAngularRange& limit);
-
-		/** @copydoc D6Joint::getLimitSwing */
-		inline LimitConeRange getLimitSwing() const;
-
-		/** @copydoc D6Joint::setLimitSwing */
-		inline void setLimitSwing(const LimitConeRange& limit);
-
-		/** @copydoc D6Joint::getDrive */
-		inline D6Joint::Drive getDrive(D6Joint::DriveType type) const;
-
-		/** @copydoc D6Joint::setDrive */
-		inline void setDrive(D6Joint::DriveType type, const D6Joint::Drive& drive);
-
-		/** @copydoc D6Joint::getDrivePosition */
-		inline Vector3 getDrivePosition() const;
-
-		/** @copydoc D6Joint::getDriveRotation */
-		inline Quaternion getDriveRotation() const;
-
-		/** @copydoc D6Joint::setDriveTransform */
-		inline void setDriveTransform(const Vector3& position, const Quaternion& rotation);
-
-		/** @copydoc D6Joint::getDriveLinearVelocity */
-		inline Vector3 getDriveLinearVelocity() const;
-
-		/** @copydoc D6Joint::getDriveAngularVelocity */
-		inline Vector3 getDriveAngularVelocity() const;
-
-		/** @copydoc D6Joint::setDriveVelocity */
-		inline void setDriveVelocity(const Vector3& linear, const Vector3& angular);
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the D6 joint that this component wraps. */
-		D6Joint* _getInternal() const { return static_cast<D6Joint*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CJoint::createInternal */
-		SPtr<Joint> createInternal() override;
-
-		D6Joint::Motion mMotion[(UINT32)D6Joint::Axis::Count];
-		D6Joint::Drive mDrive[(UINT32)D6Joint::DriveType::Count];
-		LimitLinear mLimitLinear;
-		LimitAngularRange mLimitTwist;
-		LimitConeRange mLimitSwing;
-		Vector3 mDrivePosition;
-		Quaternion mDriveRotation;
-		Vector3 mDriveLinearVelocity;
-		Vector3 mDriveAngularVelocity;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CD6JointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CD6Joint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsD6Joint.h"
+#include "BsCJoint.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	D6Joint
+	 *
+	 * Wraps D6Joint as a Component.
+	 */
+    class BS_CORE_EXPORT CD6Joint : public CJoint
+    {
+    public:
+		CD6Joint(const HSceneObject& parent);
+
+		/** @copydoc D6Joint::getMotion */
+		inline D6Joint::Motion getMotion(D6Joint::Axis axis) const;
+
+		/** @copydoc D6Joint::setMotion */
+		inline void setMotion(D6Joint::Axis axis, D6Joint::Motion motion);
+
+		/** @copydoc D6Joint::getTwist */
+		inline Radian getTwist() const;
+
+		/** @copydoc D6Joint::getSwingY */
+		inline Radian getSwingY() const;
+
+		/** @copydoc D6Joint::getSwingZ */
+		inline Radian getSwingZ() const;
+
+		/** @copydoc D6Joint::getLimitLinear */
+		inline LimitLinear getLimitLinear() const;
+
+		/** @copydoc D6Joint::setLimitLinear */
+		inline void setLimitLinear(const LimitLinear& limit);
+
+		/** @copydoc D6Joint::getLimitTwist */
+		inline LimitAngularRange getLimitTwist() const;
+
+		/** @copydoc D6Joint::setLimitTwist */
+		inline void setLimitTwist(const LimitAngularRange& limit);
+
+		/** @copydoc D6Joint::getLimitSwing */
+		inline LimitConeRange getLimitSwing() const;
+
+		/** @copydoc D6Joint::setLimitSwing */
+		inline void setLimitSwing(const LimitConeRange& limit);
+
+		/** @copydoc D6Joint::getDrive */
+		inline D6Joint::Drive getDrive(D6Joint::DriveType type) const;
+
+		/** @copydoc D6Joint::setDrive */
+		inline void setDrive(D6Joint::DriveType type, const D6Joint::Drive& drive);
+
+		/** @copydoc D6Joint::getDrivePosition */
+		inline Vector3 getDrivePosition() const;
+
+		/** @copydoc D6Joint::getDriveRotation */
+		inline Quaternion getDriveRotation() const;
+
+		/** @copydoc D6Joint::setDriveTransform */
+		inline void setDriveTransform(const Vector3& position, const Quaternion& rotation);
+
+		/** @copydoc D6Joint::getDriveLinearVelocity */
+		inline Vector3 getDriveLinearVelocity() const;
+
+		/** @copydoc D6Joint::getDriveAngularVelocity */
+		inline Vector3 getDriveAngularVelocity() const;
+
+		/** @copydoc D6Joint::setDriveVelocity */
+		inline void setDriveVelocity(const Vector3& linear, const Vector3& angular);
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the D6 joint that this component wraps. */
+		D6Joint* _getInternal() const { return static_cast<D6Joint*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CJoint::createInternal */
+		SPtr<Joint> createInternal() override;
+
+		D6Joint::Motion mMotion[(UINT32)D6Joint::Axis::Count];
+		D6Joint::Drive mDrive[(UINT32)D6Joint::DriveType::Count];
+		LimitLinear mLimitLinear;
+		LimitAngularRange mLimitTwist;
+		LimitConeRange mLimitSwing;
+		Vector3 mDrivePosition;
+		Quaternion mDriveRotation;
+		Vector3 mDriveLinearVelocity;
+		Vector3 mDriveAngularVelocity;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CD6JointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CD6Joint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 94 - 92
Source/BansheeCore/Include/BsCDistanceJoint.h

@@ -1,93 +1,95 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsDistanceJoint.h"
-#include "BsCJoint.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	DistanceJoint
-	 *
-	 * Wraps DistanceJoint as a Component.
-	 */
-    class BS_CORE_EXPORT CDistanceJoint : public CJoint
-    {
-    public:
-		CDistanceJoint(const HSceneObject& parent);
-
-		/** @copydoc DistanceJoint::getDistance */
-		inline float getDistance() const;
-
-		/** @copydoc DistanceJoint::getMinDistance */
-		inline float getMinDistance() const;
-
-		/** @copydoc DistanceJoint::setMinDistance */
-		inline void setMinDistance(float value);
-
-		/** @copydoc DistanceJoint::getMaxDistance */
-		inline float getMaxDistance() const;
-
-		/** @copydoc DistanceJoint::setMaxDistance */
-		inline void setMaxDistance(float value);
-
-		/** @copydoc DistanceJoint::getTolerance */
-		inline float getTolerance() const;
-
-		/** @copydoc DistanceJoint::setTolerance */
-		inline void setTolerance(float value);
-
-		/** @copydoc DistanceJoint::getSpring */
-		inline Spring getSpring() const;
-
-		/** @copydoc DistanceJoint::setSpring */
-		inline void setSpring(const Spring& value);
-
-		/** @copydoc DistanceJoint::setFlag */
-		inline void setFlag(DistanceJoint::Flag flag, bool enabled);
-
-		/** @copydoc DistanceJoint::hasFlag */
-		inline bool hasFlag(DistanceJoint::Flag flag) const;
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the distance joint that this component wraps. */
-		DistanceJoint* _getInternal() const { return static_cast<DistanceJoint*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CJoint::createInternal */
-		SPtr<Joint> createInternal() override;
-
-		float mMinDistance = 0.0f;
-		float mMaxDistance = 0.0f;
-		float mTolerance = 0.25f;
-		Spring mSpring;
-		DistanceJoint::Flag mFlag = (DistanceJoint::Flag)0;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CDistanceJointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CDistanceJoint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsDistanceJoint.h"
+#include "BsCJoint.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	DistanceJoint
+	 *
+	 * Wraps DistanceJoint as a Component.
+	 */
+    class BS_CORE_EXPORT CDistanceJoint : public CJoint
+    {
+    public:
+		CDistanceJoint(const HSceneObject& parent);
+
+		/** @copydoc DistanceJoint::getDistance */
+		inline float getDistance() const;
+
+		/** @copydoc DistanceJoint::getMinDistance */
+		inline float getMinDistance() const;
+
+		/** @copydoc DistanceJoint::setMinDistance */
+		inline void setMinDistance(float value);
+
+		/** @copydoc DistanceJoint::getMaxDistance */
+		inline float getMaxDistance() const;
+
+		/** @copydoc DistanceJoint::setMaxDistance */
+		inline void setMaxDistance(float value);
+
+		/** @copydoc DistanceJoint::getTolerance */
+		inline float getTolerance() const;
+
+		/** @copydoc DistanceJoint::setTolerance */
+		inline void setTolerance(float value);
+
+		/** @copydoc DistanceJoint::getSpring */
+		inline Spring getSpring() const;
+
+		/** @copydoc DistanceJoint::setSpring */
+		inline void setSpring(const Spring& value);
+
+		/** @copydoc DistanceJoint::setFlag */
+		inline void setFlag(DistanceJoint::Flag flag, bool enabled);
+
+		/** @copydoc DistanceJoint::hasFlag */
+		inline bool hasFlag(DistanceJoint::Flag flag) const;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the distance joint that this component wraps. */
+		DistanceJoint* _getInternal() const { return static_cast<DistanceJoint*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CJoint::createInternal */
+		SPtr<Joint> createInternal() override;
+
+		float mMinDistance = 0.0f;
+		float mMaxDistance = 0.0f;
+		float mTolerance = 0.25f;
+		Spring mSpring;
+		DistanceJoint::Flag mFlag = (DistanceJoint::Flag)0;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CDistanceJointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CDistanceJoint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 55 - 53
Source/BansheeCore/Include/BsCFixedJoint.h

@@ -1,54 +1,56 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsFixedJoint.h"
-#include "BsCJoint.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	FixedJoint
-	 *
-	 * Wraps FixedJoint as a Component.
-	 */
-    class BS_CORE_EXPORT CFixedJoint : public CJoint
-    {
-    public:
-		CFixedJoint(const HSceneObject& parent);
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the fixed joint that this component wraps. */
-		FixedJoint* _getInternal() const { return static_cast<FixedJoint*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CJoint::createInternal */
-		SPtr<Joint> createInternal() override;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CFixedJointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CFixedJoint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsFixedJoint.h"
+#include "BsCJoint.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	FixedJoint
+	 *
+	 * Wraps FixedJoint as a Component.
+	 */
+    class BS_CORE_EXPORT CFixedJoint : public CJoint
+    {
+    public:
+		CFixedJoint(const HSceneObject& parent);
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the fixed joint that this component wraps. */
+		FixedJoint* _getInternal() const { return static_cast<FixedJoint*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CJoint::createInternal */
+		SPtr<Joint> createInternal() override;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CFixedJointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CFixedJoint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 83 - 81
Source/BansheeCore/Include/BsCHingeJoint.h

@@ -1,82 +1,84 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsHingeJoint.h"
-#include "BsCJoint.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	HingeJoint
-	 *
-	 * Wraps HingeJoint as a Component.
-	 */
-    class BS_CORE_EXPORT CHingeJoint : public CJoint
-    {
-    public:
-		CHingeJoint(const HSceneObject& parent);
-
-		/** @copydoc HingeJoint::getAngle */
-		inline Radian getAngle() const;
-
-		/** @copydoc HingeJoint::getSpeed */
-		inline float getSpeed() const;
-
-		/** @copydoc HingeJoint::getLimit */
-		inline LimitAngularRange getLimit() const;
-
-		/** @copydoc HingeJoint::setLimit */
-		inline void setLimit(const LimitAngularRange& limit);
-
-		/** @copydoc HingeJoint::getDrive */
-		inline HingeJoint::Drive getDrive() const;
-
-		/** @copydoc HingeJoint::setDrive */
-		inline void setDrive(const HingeJoint::Drive& drive);
-
-		/** @copydoc HingeJoint::setFlag */
-		inline void setFlag(HingeJoint::Flag flag, bool enabled);
-
-		/** @copydoc HingeJoint::hasFlag */
-		inline bool hasFlag(HingeJoint::Flag flag) const;
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the hinge joint that this component wraps. */
-		HingeJoint* _getInternal() const { return static_cast<HingeJoint*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CJoint::createInternal */
-		SPtr<Joint> createInternal() override;
-
-		HingeJoint::Flag mFlag = (HingeJoint::Flag)0;
-		HingeJoint::Drive mDrive;
-		LimitAngularRange mLimit;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CHingeJointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CHingeJoint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsHingeJoint.h"
+#include "BsCJoint.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	HingeJoint
+	 *
+	 * Wraps HingeJoint as a Component.
+	 */
+    class BS_CORE_EXPORT CHingeJoint : public CJoint
+    {
+    public:
+		CHingeJoint(const HSceneObject& parent);
+
+		/** @copydoc HingeJoint::getAngle */
+		inline Radian getAngle() const;
+
+		/** @copydoc HingeJoint::getSpeed */
+		inline float getSpeed() const;
+
+		/** @copydoc HingeJoint::getLimit */
+		inline LimitAngularRange getLimit() const;
+
+		/** @copydoc HingeJoint::setLimit */
+		inline void setLimit(const LimitAngularRange& limit);
+
+		/** @copydoc HingeJoint::getDrive */
+		inline HingeJoint::Drive getDrive() const;
+
+		/** @copydoc HingeJoint::setDrive */
+		inline void setDrive(const HingeJoint::Drive& drive);
+
+		/** @copydoc HingeJoint::setFlag */
+		inline void setFlag(HingeJoint::Flag flag, bool enabled);
+
+		/** @copydoc HingeJoint::hasFlag */
+		inline bool hasFlag(HingeJoint::Flag flag) const;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the hinge joint that this component wraps. */
+		HingeJoint* _getInternal() const { return static_cast<HingeJoint*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CJoint::createInternal */
+		SPtr<Joint> createInternal() override;
+
+		HingeJoint::Flag mFlag = (HingeJoint::Flag)0;
+		HingeJoint::Drive mDrive;
+		LimitAngularRange mLimit;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CHingeJointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CHingeJoint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 134 - 132
Source/BansheeCore/Include/BsCJoint.h

@@ -1,133 +1,135 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsJoint.h"
-#include "BsComponent.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	Joint
-	 *
-	 * Wraps Joint as a Component.
-	 */
-    class BS_CORE_EXPORT CJoint : public Component
-    {
-    public:
-		CJoint(const HSceneObject& parent);
-		virtual ~CJoint() {}
-
-		/** @copydoc Joint::getBody */
-		inline HRigidbody getBody(JointBody body) const;
-
-		/** @copydoc Joint::setBody */
-		inline void setBody(JointBody body, const HRigidbody& value);
-
-		/** @copydoc Joint::getPosition */
-		inline Vector3 getPosition(JointBody body) const;
-
-		/** @copydoc Joint::getRotation */
-		inline Quaternion getRotation(JointBody body) const;
-
-		/** @copydoc Joint::setTransform */
-		inline void setTransform(JointBody body, const Vector3& position, const Quaternion& rotation);
-
-		/** @copydoc Joint::getBreakForce */
-		inline float getBreakForce() const;
-
-		/** @copydoc Joint::setBreakForce */
-		inline void setBreakForce(float force);
-
-		/** @copydoc Joint::getBreakTorque */
-		inline float getBreakTorque() const;
-
-		/** @copydoc Joint::setBreakToque */
-		inline void setBreakToque(float torque);
-
-		/** @copydoc Joint::getEnableCollision */
-		inline bool getEnableCollision() const;
-
-		/** @copydoc Joint::setEnableCollision */
-		inline void setEnableCollision(bool value);
-
-		/** @copydoc Joint::onJointBreak */
-		Event<void()> onJointBreak;
-
-		/** @cond INTERNAL */
-
-		/** Returns the Joint implementation wrapped by this component. */
-		Joint* _getInternal() const { return mInternal.get(); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc Component::onInitialized() */
-		void onInitialized() override;
-
-		/** @copydoc Component::onDestroyed() */
-		void onDestroyed() override;
-
-		/** @copydoc Component::onDisabled() */
-		void onDisabled() override;
-
-		/** @copydoc Component::onEnabled() */
-		void onEnabled() override;
-
-		/** @copydoc Component::onTransformChanged() */
-		void onTransformChanged(TransformChangedFlags flags) override;
-
-    protected:
-		friend class CRigidbody;
-
-		/** Creates the internal representation of the Joint for use by the component. */
-		virtual SPtr<Joint> createInternal() = 0;
-
-		/** Creates the internal representation of the Joint and restores the values saved by the Component. */
-		virtual void restoreInternal();
-
-		/** Destroys the internal joint representation. */
-		void destroyInternal();
-
-		/** Notifies the joint that one of the attached rigidbodies moved and that its transform needs updating. */
-		void notifyRigidbodyMoved(const HRigidbody& body);
-
-		/** Updates the local transform for the specified body attached to the joint. */
-		void updateTransform(JointBody body);
-
-		/** Triggered when the joint constraint gets broken. */
-		void triggerOnJointBroken();
-
-		SPtr<Joint> mInternal;
-
-		HRigidbody mBodies[2];
-		Vector3 mPositions[2];
-		Quaternion mRotations[2];
-		float mBreakForce = FLT_MAX;
-		float mBreakTorque = FLT_MAX;
-		bool mEnableCollision = false;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CJointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CJoint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsJoint.h"
+#include "BsComponent.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	Joint
+	 *
+	 * Wraps Joint as a Component.
+	 */
+    class BS_CORE_EXPORT CJoint : public Component
+    {
+    public:
+		CJoint(const HSceneObject& parent);
+		virtual ~CJoint() {}
+
+		/** @copydoc Joint::getBody */
+		inline HRigidbody getBody(JointBody body) const;
+
+		/** @copydoc Joint::setBody */
+		inline void setBody(JointBody body, const HRigidbody& value);
+
+		/** @copydoc Joint::getPosition */
+		inline Vector3 getPosition(JointBody body) const;
+
+		/** @copydoc Joint::getRotation */
+		inline Quaternion getRotation(JointBody body) const;
+
+		/** @copydoc Joint::setTransform */
+		inline void setTransform(JointBody body, const Vector3& position, const Quaternion& rotation);
+
+		/** @copydoc Joint::getBreakForce */
+		inline float getBreakForce() const;
+
+		/** @copydoc Joint::setBreakForce */
+		inline void setBreakForce(float force);
+
+		/** @copydoc Joint::getBreakTorque */
+		inline float getBreakTorque() const;
+
+		/** @copydoc Joint::setBreakToque */
+		inline void setBreakToque(float torque);
+
+		/** @copydoc Joint::getEnableCollision */
+		inline bool getEnableCollision() const;
+
+		/** @copydoc Joint::setEnableCollision */
+		inline void setEnableCollision(bool value);
+
+		/** @copydoc Joint::onJointBreak */
+		Event<void()> onJointBreak;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** Returns the Joint implementation wrapped by this component. */
+		Joint* _getInternal() const { return mInternal.get(); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc Component::onInitialized() */
+		void onInitialized() override;
+
+		/** @copydoc Component::onDestroyed() */
+		void onDestroyed() override;
+
+		/** @copydoc Component::onDisabled() */
+		void onDisabled() override;
+
+		/** @copydoc Component::onEnabled() */
+		void onEnabled() override;
+
+		/** @copydoc Component::onTransformChanged() */
+		void onTransformChanged(TransformChangedFlags flags) override;
+
+    protected:
+		friend class CRigidbody;
+
+		/** Creates the internal representation of the Joint for use by the component. */
+		virtual SPtr<Joint> createInternal() = 0;
+
+		/** Creates the internal representation of the Joint and restores the values saved by the Component. */
+		virtual void restoreInternal();
+
+		/** Destroys the internal joint representation. */
+		void destroyInternal();
+
+		/** Notifies the joint that one of the attached rigidbodies moved and that its transform needs updating. */
+		void notifyRigidbodyMoved(const HRigidbody& body);
+
+		/** Updates the local transform for the specified body attached to the joint. */
+		void updateTransform(JointBody body);
+
+		/** Triggered when the joint constraint gets broken. */
+		void triggerOnJointBroken();
+
+		SPtr<Joint> mInternal;
+
+		HRigidbody mBodies[2];
+		Vector3 mPositions[2];
+		Quaternion mRotations[2];
+		float mBreakForce = FLT_MAX;
+		float mBreakTorque = FLT_MAX;
+		bool mEnableCollision = false;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CJointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CJoint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 67 - 65
Source/BansheeCore/Include/BsCMeshCollider.h

@@ -1,66 +1,68 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsMeshCollider.h"
-#include "BsCCollider.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	MeshCollider
-	 *
-	 * Wraps MeshCollider as a Component.
-	 */
-    class BS_CORE_EXPORT CMeshCollider : public CCollider
-    {
-    public:
-		CMeshCollider(const HSceneObject& parent);
-
-		/** @copydoc MeshCollider::setMesh */
-		void setMesh(const HPhysicsMesh& mesh);
-
-		/** @copydoc MeshCollider::getMesh */
-		HPhysicsMesh getMesh() const { return mMesh; }
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the mesh collider that this component wraps. */
-		MeshCollider* _getInternal() const { return static_cast<MeshCollider*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CCollider::createInternal */
-		SPtr<Collider> createInternal() override;
-
-		/** @copydoc CPlaneCollider::isValidParent */
-		bool isValidParent(const HRigidbody& parent) const override;
-
-    protected:
-		HPhysicsMesh mMesh;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CMeshColliderRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CMeshCollider() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsMeshCollider.h"
+#include "BsCCollider.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	MeshCollider
+	 *
+	 * Wraps MeshCollider as a Component.
+	 */
+    class BS_CORE_EXPORT CMeshCollider : public CCollider
+    {
+    public:
+		CMeshCollider(const HSceneObject& parent);
+
+		/** @copydoc MeshCollider::setMesh */
+		void setMesh(const HPhysicsMesh& mesh);
+
+		/** @copydoc MeshCollider::getMesh */
+		HPhysicsMesh getMesh() const { return mMesh; }
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the mesh collider that this component wraps. */
+		MeshCollider* _getInternal() const { return static_cast<MeshCollider*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CCollider::createInternal */
+		SPtr<Collider> createInternal() override;
+
+		/** @copydoc CPlaneCollider::isValidParent */
+		bool isValidParent(const HRigidbody& parent) const override;
+
+    protected:
+		HPhysicsMesh mMesh;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CMeshColliderRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CMeshCollider() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 74 - 72
Source/BansheeCore/Include/BsCPlaneCollider.h

@@ -1,73 +1,75 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPlaneCollider.h"
-#include "BsCCollider.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	PlaneCollider
-	 *
-	 * Wraps PlaneCollider as a Component.
-	 */
-    class BS_CORE_EXPORT CPlaneCollider : public CCollider
-    {
-    public:
-		CPlaneCollider(const HSceneObject& parent);
-
-		/** Sets the normal vector of the plane. It determines how is the plane oriented. */
-		void setNormal(const Vector3& normal);
-
-		/** Gets the normal vector of the plane. It determines how is the plane oriented. */
-		Vector3 getNormal() const { return mNormal; }
-
-		/** Sets the distance of the plane from the local origin, along its normal vector. */
-		void setDistance(float distance);
-
-		/** Gets the distance of the plane from the local origin, along its normal vector. */
-		float getDistance() const { return mDistance; }
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the plane collider that this component wraps. */
-		PlaneCollider* _getInternal() const { return static_cast<PlaneCollider*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CCollider::createInternal */
-		SPtr<Collider> createInternal() override;
-
-		/** @copydoc CPlaneCollider::isValidParent */
-		bool isValidParent(const HRigidbody& parent) const override;
-
-    protected:
-		Vector3 mNormal = Vector3::UNIT_X;
-		float mDistance = 0.0f;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CPlaneColliderRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CPlaneCollider() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPlaneCollider.h"
+#include "BsCCollider.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	PlaneCollider
+	 *
+	 * Wraps PlaneCollider as a Component.
+	 */
+    class BS_CORE_EXPORT CPlaneCollider : public CCollider
+    {
+    public:
+		CPlaneCollider(const HSceneObject& parent);
+
+		/** Sets the normal vector of the plane. It determines how is the plane oriented. */
+		void setNormal(const Vector3& normal);
+
+		/** Gets the normal vector of the plane. It determines how is the plane oriented. */
+		Vector3 getNormal() const { return mNormal; }
+
+		/** Sets the distance of the plane from the local origin, along its normal vector. */
+		void setDistance(float distance);
+
+		/** Gets the distance of the plane from the local origin, along its normal vector. */
+		float getDistance() const { return mDistance; }
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the plane collider that this component wraps. */
+		PlaneCollider* _getInternal() const { return static_cast<PlaneCollider*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CCollider::createInternal */
+		SPtr<Collider> createInternal() override;
+
+		/** @copydoc CPlaneCollider::isValidParent */
+		bool isValidParent(const HRigidbody& parent) const override;
+
+    protected:
+		Vector3 mNormal = Vector3::UNIT_X;
+		float mDistance = 0.0f;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CPlaneColliderRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CPlaneCollider() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 271 - 269
Source/BansheeCore/Include/BsCRigidbody.h

@@ -1,270 +1,272 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsRigidbody.h"
-#include "BsComponent.h"
-#include "BsVector3.h"
-#include "BsQuaternion.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	Rigidbody
-	 *
-	 * Wraps Rigidbody as a Component. Colliders that are on the same scene object as the rigidbody, or on child scene 
-	 * objects are automatically considered as part of the rigidbody.
-	 */
-	class BS_CORE_EXPORT CRigidbody : public Component
-	{
-	public:
-		CRigidbody(const HSceneObject& parent);
-
-		/** @copydoc Rigidbody::move */
-		inline void move(const Vector3& position);
-
-		/** @copydoc Rigidbody::rotate */
-		inline void rotate(const Quaternion& rotation);
-
-		/** @copydoc Rigidbody::setMass */
-		inline void setMass(float mass);
-
-		/** @copydoc Rigidbody::getMass */
-		float getMass() const { return mMass; };
-
-		/** @copydoc Rigidbody::setIsKinematic */
-		inline void setIsKinematic(bool kinematic);
-
-		/** @copydoc Rigidbody::getIsKinematic */
-		bool getIsKinematic() const { return mIsKinematic; }
-
-		/** @copydoc Rigidbody::isSleeping */
-		inline bool isSleeping() const;
-
-		/** @copydoc Rigidbody::sleep */
-		inline void sleep();
-
-		/** @copydoc Rigidbody::wakeUp */
-		inline void wakeUp();
-
-		/** @copydoc Rigidbody::setSleepThreshold */
-		inline void setSleepThreshold(float threshold);
-
-		/** @copydoc Rigidbody::getSleepThreshold */
-		float getSleepThreshold() const { return mSleepThreshold; }
-
-		/** @copydoc Rigidbody::setUseGravity */
-		inline void setUseGravity(bool gravity);
-
-		/** @copydoc Rigidbody::getUseGravity */
-		bool getUseGravity() const { return mUseGravity; }
-
-		/** @copydoc Rigidbody::setVelocity */
-		inline void setVelocity(const Vector3& velocity);
-
-		/** @copydoc Rigidbody::getVelocity */
-		inline Vector3 getVelocity() const;
-
-		/** @copydoc Rigidbody::setAngularVelocity */
-		inline void setAngularVelocity(const Vector3& velocity);
-
-		/** @copydoc Rigidbody::getAngularVelocity */
-		inline Vector3 getAngularVelocity() const;
-
-		/** @copydoc Rigidbody::setDrag */
-		inline void setDrag(float drag);
-
-		/** @copydoc Rigidbody::getDrag */
-		float getDrag() const { return mLinearDrag; }
-
-		/** @copydoc Rigidbody::setAngularDrag */
-		inline void setAngularDrag(float drag);
-
-		/** @copydoc Rigidbody::getAngularDrag */
-		float getAngularDrag() const { return mAngularDrag; }
-
-		/** @copydoc Rigidbody::setInertiaTensor */
-		inline void setInertiaTensor(const Vector3& tensor);
-
-		/** @copydoc Rigidbody::getInertiaTensor */
-		inline Vector3 getInertiaTensor() const;
-
-		/** @copydoc Rigidbody::setMaxAngularVelocity */
-		inline void setMaxAngularVelocity(float maxVelocity);
-
-		/** @copydoc Rigidbody::getMaxAngularVelocity */
-		float getMaxAngularVelocity() const { return mMaxAngularVelocity; }
-
-		/** @copydoc Rigidbody::setCenterOfMass */
-		inline void setCenterOfMass(const Vector3& position, const Quaternion& rotation);
-
-		/** @copydoc Rigidbody::getCenterOfMassPosition */
-		inline  Vector3 getCenterOfMassPosition() const;
-
-		/** @copydoc Rigidbody::getCenterOfMassRotation */
-		inline Quaternion getCenterOfMassRotation() const;
-
-		/** @copydoc Rigidbody::setPositionSolverCount */
-		inline void setPositionSolverCount(UINT32 count);
-
-		/** @copydoc Rigidbody::getPositionSolverCount */
-		UINT32 getPositionSolverCount() const { return mPositionSolverCount; }
-
-		/** @copydoc Rigidbody::setVelocitySolverCount */
-		inline void setVelocitySolverCount(UINT32 count);
-
-		/** @copydoc Rigidbody::getVelocitySolverCount */
-		UINT32 getVelocitySolverCount() const { return mVelocitySolverCount; }
-
-		/** @copydoc Rigidbody::setInterpolationMode */
-		void setInterpolationMode(Rigidbody::InterpolationMode value);
-
-		/** @copydoc Rigidbody::getInterpolationMode */
-		Rigidbody::InterpolationMode getInterpolationMode(Rigidbody::InterpolationMode value) const 
-			{ return mInterpolationMode; }
-
-		/** Sets a value that determines which (if any) collision events are reported. */
-		inline void setCollisionReportMode(CollisionReportMode mode);
-
-		/** Gets a value that determines which (if any) collision events are reported. */
-		CollisionReportMode getCollisionReportMode() const { return mCollisionReportMode; }
-
-		/** @copydoc Rigidbody::setFlags */
-		inline void setFlags(Rigidbody::Flag flags);
-
-		/** @copydoc Rigidbody::getFlags */
-		Rigidbody::Flag getFlags() const { return mFlags; }
-
-		/** @copydoc Rigidbody::addForce */
-		inline void addForce(const Vector3& force, ForceMode mode = ForceMode::Force);
-
-		/** @copydoc Rigidbody::addTorque */
-		inline void addTorque(const Vector3& torque, ForceMode mode = ForceMode::Force);
-
-		/** @copydoc Rigidbody::addForceAtPoint */
-		inline void addForceAtPoint(const Vector3& force, const Vector3& position,
-			PointForceMode mode = PointForceMode::Force);
-
-		/** @copydoc Rigidbody::getVelocityAtPoint */
-		inline Vector3 getVelocityAtPoint(const Vector3& point) const;
-
-		/** @copydoc Rigidbody::onCollisionBegin */
-		Event<void(const CollisionData&)> onCollisionBegin;
-
-		/** @copydoc Rigidbody::onCollisionStay */
-		Event<void(const CollisionData&)> onCollisionStay;
-
-		/** @copydoc Rigidbody::onCollisionEnd */
-		Event<void(const CollisionData&)> onCollisionEnd;
-
-		/** @cond INTERNAL */
-
-		/** Returns the Rigidbody implementation wrapped by this component. */
-		Rigidbody* _getInternal() const { return mInternal.get(); }
-
-		/** Sets that joint that this rigidbody is attached to. Allows the rigidbody to notify the joint when it moves. */
-		void _setJoint(const HJoint& joint) { mParentJoint = joint; }
-
-		/** @copydoc Rigidbody::_updateMassDistribution */
-		inline void _updateMassDistribution();
-
-		/** @endcond */
-	protected:
-		friend class CCollider;
-
-		/** 
-		 * Searches child scene objects for Collider components and attaches them to the rigidbody. Make sure to call
-		 * clearColliders() if you need to clear old colliders first. 
-		 */
-		void updateColliders();
-
-		/** Unregisters all child colliders from the Rigidbody. */
-		void clearColliders();
-
-		/** 
-		 * Registers a new collider with the Rigidbody. This collider will then be used to calculate Rigidbody's geometry
-         * used for collisions, and optionally (depending on set flags) total mass, inertia tensors and center of mass.
-		 */
-		void addCollider(const HCollider& collider);
-
-		/** Unregisters the collider from the Rigidbody. */
-		void removeCollider(const HCollider& collider);
-
-		/** Checks if the rigidbody is nested under another rigidbody, and throws out a warning if so. */
-		void checkForNestedRigibody();
-
-		/** Appends Component referenes for the colliders to the collision data. */
-		void processCollisionData(CollisionData& data);
-
-		/** Destroys the internal rigidbody representation. */
-		void destroyInternal();
-
-		/** Triggered when the internal rigidbody begins touching another object. */
-		void triggerOnCollisionBegin(const CollisionData& data);
-
-		/** Triggered when the internal rigidbody continues touching another object. */
-		void triggerOnCollisionStay(const CollisionData& data);
-
-		/** Triggered when the internal rigidbody ends touching another object. */
-		void triggerOnCollisionEnd(const CollisionData& data);
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc Component::onInitialized() */
-		void onInitialized() override;
-
-		/** @copydoc Component::onDestroyed() */
-		void onDestroyed() override;
-
-		/** @copydoc Component::onDisabled() */
-		void onDisabled() override;
-
-		/** @copydoc Component::onEnabled() */
-		void onEnabled() override;
-
-		/** @copydoc Component::onTransformChanged() */
-		void onTransformChanged(TransformChangedFlags flags) override;
-
-		SPtr<Rigidbody> mInternal;
-		Vector<HCollider> mChildren;
-		HJoint mParentJoint;
-
-		UINT32 mPositionSolverCount = 4;
-		UINT32 mVelocitySolverCount = 1;
-		Rigidbody::Flag mFlags = (Rigidbody::Flag)((UINT32)Rigidbody::Flag::AutoTensors | (UINT32)Rigidbody::Flag::AutoMass);
-		Rigidbody::InterpolationMode mInterpolationMode = Rigidbody::InterpolationMode::None;
-		CollisionReportMode mCollisionReportMode = CollisionReportMode::None;
-		Vector3 mCMassPosition;
-		Quaternion mCMassRotation;
-		Vector3 mInertiaTensor;
-		float mMass = 0.0f;
-		float mMaxAngularVelocity = 1.0f;
-		float mLinearDrag = 0.0f;
-		float mAngularDrag = 0.0f;
-		float mSleepThreshold = 0.0f;
-		bool mUseGravity = true;
-		bool mIsKinematic = false;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CRigidbodyRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CRigidbody() {} // Serialization only
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsRigidbody.h"
+#include "BsComponent.h"
+#include "BsVector3.h"
+#include "BsQuaternion.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	Rigidbody
+	 *
+	 * Wraps Rigidbody as a Component. Colliders that are on the same scene object as the rigidbody, or on child scene 
+	 * objects are automatically considered as part of the rigidbody.
+	 */
+	class BS_CORE_EXPORT CRigidbody : public Component
+	{
+	public:
+		CRigidbody(const HSceneObject& parent);
+
+		/** @copydoc Rigidbody::move */
+		inline void move(const Vector3& position);
+
+		/** @copydoc Rigidbody::rotate */
+		inline void rotate(const Quaternion& rotation);
+
+		/** @copydoc Rigidbody::setMass */
+		inline void setMass(float mass);
+
+		/** @copydoc Rigidbody::getMass */
+		float getMass() const { return mMass; };
+
+		/** @copydoc Rigidbody::setIsKinematic */
+		inline void setIsKinematic(bool kinematic);
+
+		/** @copydoc Rigidbody::getIsKinematic */
+		bool getIsKinematic() const { return mIsKinematic; }
+
+		/** @copydoc Rigidbody::isSleeping */
+		inline bool isSleeping() const;
+
+		/** @copydoc Rigidbody::sleep */
+		inline void sleep();
+
+		/** @copydoc Rigidbody::wakeUp */
+		inline void wakeUp();
+
+		/** @copydoc Rigidbody::setSleepThreshold */
+		inline void setSleepThreshold(float threshold);
+
+		/** @copydoc Rigidbody::getSleepThreshold */
+		float getSleepThreshold() const { return mSleepThreshold; }
+
+		/** @copydoc Rigidbody::setUseGravity */
+		inline void setUseGravity(bool gravity);
+
+		/** @copydoc Rigidbody::getUseGravity */
+		bool getUseGravity() const { return mUseGravity; }
+
+		/** @copydoc Rigidbody::setVelocity */
+		inline void setVelocity(const Vector3& velocity);
+
+		/** @copydoc Rigidbody::getVelocity */
+		inline Vector3 getVelocity() const;
+
+		/** @copydoc Rigidbody::setAngularVelocity */
+		inline void setAngularVelocity(const Vector3& velocity);
+
+		/** @copydoc Rigidbody::getAngularVelocity */
+		inline Vector3 getAngularVelocity() const;
+
+		/** @copydoc Rigidbody::setDrag */
+		inline void setDrag(float drag);
+
+		/** @copydoc Rigidbody::getDrag */
+		float getDrag() const { return mLinearDrag; }
+
+		/** @copydoc Rigidbody::setAngularDrag */
+		inline void setAngularDrag(float drag);
+
+		/** @copydoc Rigidbody::getAngularDrag */
+		float getAngularDrag() const { return mAngularDrag; }
+
+		/** @copydoc Rigidbody::setInertiaTensor */
+		inline void setInertiaTensor(const Vector3& tensor);
+
+		/** @copydoc Rigidbody::getInertiaTensor */
+		inline Vector3 getInertiaTensor() const;
+
+		/** @copydoc Rigidbody::setMaxAngularVelocity */
+		inline void setMaxAngularVelocity(float maxVelocity);
+
+		/** @copydoc Rigidbody::getMaxAngularVelocity */
+		float getMaxAngularVelocity() const { return mMaxAngularVelocity; }
+
+		/** @copydoc Rigidbody::setCenterOfMass */
+		inline void setCenterOfMass(const Vector3& position, const Quaternion& rotation);
+
+		/** @copydoc Rigidbody::getCenterOfMassPosition */
+		inline  Vector3 getCenterOfMassPosition() const;
+
+		/** @copydoc Rigidbody::getCenterOfMassRotation */
+		inline Quaternion getCenterOfMassRotation() const;
+
+		/** @copydoc Rigidbody::setPositionSolverCount */
+		inline void setPositionSolverCount(UINT32 count);
+
+		/** @copydoc Rigidbody::getPositionSolverCount */
+		UINT32 getPositionSolverCount() const { return mPositionSolverCount; }
+
+		/** @copydoc Rigidbody::setVelocitySolverCount */
+		inline void setVelocitySolverCount(UINT32 count);
+
+		/** @copydoc Rigidbody::getVelocitySolverCount */
+		UINT32 getVelocitySolverCount() const { return mVelocitySolverCount; }
+
+		/** @copydoc Rigidbody::setInterpolationMode */
+		void setInterpolationMode(Rigidbody::InterpolationMode value);
+
+		/** @copydoc Rigidbody::getInterpolationMode */
+		Rigidbody::InterpolationMode getInterpolationMode(Rigidbody::InterpolationMode value) const 
+			{ return mInterpolationMode; }
+
+		/** Sets a value that determines which (if any) collision events are reported. */
+		inline void setCollisionReportMode(CollisionReportMode mode);
+
+		/** Gets a value that determines which (if any) collision events are reported. */
+		CollisionReportMode getCollisionReportMode() const { return mCollisionReportMode; }
+
+		/** @copydoc Rigidbody::setFlags */
+		inline void setFlags(Rigidbody::Flag flags);
+
+		/** @copydoc Rigidbody::getFlags */
+		Rigidbody::Flag getFlags() const { return mFlags; }
+
+		/** @copydoc Rigidbody::addForce */
+		inline void addForce(const Vector3& force, ForceMode mode = ForceMode::Force);
+
+		/** @copydoc Rigidbody::addTorque */
+		inline void addTorque(const Vector3& torque, ForceMode mode = ForceMode::Force);
+
+		/** @copydoc Rigidbody::addForceAtPoint */
+		inline void addForceAtPoint(const Vector3& force, const Vector3& position,
+			PointForceMode mode = PointForceMode::Force);
+
+		/** @copydoc Rigidbody::getVelocityAtPoint */
+		inline Vector3 getVelocityAtPoint(const Vector3& point) const;
+
+		/** @copydoc Rigidbody::onCollisionBegin */
+		Event<void(const CollisionData&)> onCollisionBegin;
+
+		/** @copydoc Rigidbody::onCollisionStay */
+		Event<void(const CollisionData&)> onCollisionStay;
+
+		/** @copydoc Rigidbody::onCollisionEnd */
+		Event<void(const CollisionData&)> onCollisionEnd;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** Returns the Rigidbody implementation wrapped by this component. */
+		Rigidbody* _getInternal() const { return mInternal.get(); }
+
+		/** Sets that joint that this rigidbody is attached to. Allows the rigidbody to notify the joint when it moves. */
+		void _setJoint(const HJoint& joint) { mParentJoint = joint; }
+
+		/** @copydoc Rigidbody::_updateMassDistribution */
+		inline void _updateMassDistribution();
+
+		/** @} */
+	protected:
+		friend class CCollider;
+
+		/** 
+		 * Searches child scene objects for Collider components and attaches them to the rigidbody. Make sure to call
+		 * clearColliders() if you need to clear old colliders first. 
+		 */
+		void updateColliders();
+
+		/** Unregisters all child colliders from the Rigidbody. */
+		void clearColliders();
+
+		/** 
+		 * Registers a new collider with the Rigidbody. This collider will then be used to calculate Rigidbody's geometry
+         * used for collisions, and optionally (depending on set flags) total mass, inertia tensors and center of mass.
+		 */
+		void addCollider(const HCollider& collider);
+
+		/** Unregisters the collider from the Rigidbody. */
+		void removeCollider(const HCollider& collider);
+
+		/** Checks if the rigidbody is nested under another rigidbody, and throws out a warning if so. */
+		void checkForNestedRigibody();
+
+		/** Appends Component referenes for the colliders to the collision data. */
+		void processCollisionData(CollisionData& data);
+
+		/** Destroys the internal rigidbody representation. */
+		void destroyInternal();
+
+		/** Triggered when the internal rigidbody begins touching another object. */
+		void triggerOnCollisionBegin(const CollisionData& data);
+
+		/** Triggered when the internal rigidbody continues touching another object. */
+		void triggerOnCollisionStay(const CollisionData& data);
+
+		/** Triggered when the internal rigidbody ends touching another object. */
+		void triggerOnCollisionEnd(const CollisionData& data);
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc Component::onInitialized() */
+		void onInitialized() override;
+
+		/** @copydoc Component::onDestroyed() */
+		void onDestroyed() override;
+
+		/** @copydoc Component::onDisabled() */
+		void onDisabled() override;
+
+		/** @copydoc Component::onEnabled() */
+		void onEnabled() override;
+
+		/** @copydoc Component::onTransformChanged() */
+		void onTransformChanged(TransformChangedFlags flags) override;
+
+		SPtr<Rigidbody> mInternal;
+		Vector<HCollider> mChildren;
+		HJoint mParentJoint;
+
+		UINT32 mPositionSolverCount = 4;
+		UINT32 mVelocitySolverCount = 1;
+		Rigidbody::Flag mFlags = (Rigidbody::Flag)((UINT32)Rigidbody::Flag::AutoTensors | (UINT32)Rigidbody::Flag::AutoMass);
+		Rigidbody::InterpolationMode mInterpolationMode = Rigidbody::InterpolationMode::None;
+		CollisionReportMode mCollisionReportMode = CollisionReportMode::None;
+		Vector3 mCMassPosition;
+		Quaternion mCMassRotation;
+		Vector3 mInertiaTensor;
+		float mMass = 0.0f;
+		float mMaxAngularVelocity = 1.0f;
+		float mLinearDrag = 0.0f;
+		float mAngularDrag = 0.0f;
+		float mSleepThreshold = 0.0f;
+		bool mUseGravity = true;
+		bool mIsKinematic = false;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CRigidbodyRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CRigidbody() {} // Serialization only
+	};
+
+	/** @} */
 }

+ 76 - 74
Source/BansheeCore/Include/BsCSliderJoint.h

@@ -1,75 +1,77 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsSliderJoint.h"
-#include "BsCJoint.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	SliderJoint
-	 *
-	 * Wraps SliderJoint as a Component.
-	 */
-    class BS_CORE_EXPORT CSliderJoint : public CJoint
-    {
-    public:
-		CSliderJoint(const HSceneObject& parent);
-
-		/** @copydoc SliderJoint::getPosition */
-		inline float getPosition() const;
-
-		/** @copydoc SliderJoint::getSpeed */
-		inline float getSpeed() const;
-
-		/** @copydoc SliderJoint::getLimit */
-		inline LimitLinearRange getLimit() const;
-
-		/** @copydoc SliderJoint::setLimit */
-		inline void setLimit(const LimitLinearRange& limit);
-
-		/** @copydoc SliderJoint::setFlag */
-		inline void setFlag(SliderJoint::Flag flag, bool enabled);
-
-		/** @copydoc SliderJoint::hasFlag */
-		inline bool hasFlag(SliderJoint::Flag flag) const;
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the slider joint that this component wraps. */
-		SliderJoint* _getInternal() const { return static_cast<SliderJoint*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CJoint::createInternal */
-		SPtr<Joint> createInternal() override;
-
-		SliderJoint::Flag mFlag = (SliderJoint::Flag)0;
-		LimitLinearRange mLimit;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CSliderJointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CSliderJoint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsSliderJoint.h"
+#include "BsCJoint.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	SliderJoint
+	 *
+	 * Wraps SliderJoint as a Component.
+	 */
+    class BS_CORE_EXPORT CSliderJoint : public CJoint
+    {
+    public:
+		CSliderJoint(const HSceneObject& parent);
+
+		/** @copydoc SliderJoint::getPosition */
+		inline float getPosition() const;
+
+		/** @copydoc SliderJoint::getSpeed */
+		inline float getSpeed() const;
+
+		/** @copydoc SliderJoint::getLimit */
+		inline LimitLinearRange getLimit() const;
+
+		/** @copydoc SliderJoint::setLimit */
+		inline void setLimit(const LimitLinearRange& limit);
+
+		/** @copydoc SliderJoint::setFlag */
+		inline void setFlag(SliderJoint::Flag flag, bool enabled);
+
+		/** @copydoc SliderJoint::hasFlag */
+		inline bool hasFlag(SliderJoint::Flag flag) const;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the slider joint that this component wraps. */
+		SliderJoint* _getInternal() const { return static_cast<SliderJoint*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CJoint::createInternal */
+		SPtr<Joint> createInternal() override;
+
+		SliderJoint::Flag mFlag = (SliderJoint::Flag)0;
+		LimitLinearRange mLimit;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CSliderJointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CSliderJoint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 70 - 68
Source/BansheeCore/Include/BsCSphereCollider.h

@@ -1,69 +1,71 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsSphereCollider.h"
-#include "BsCCollider.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	SphereCollider
-	 *
-	 * Wraps SphereCollider as a Component.
-	 */
-    class BS_CORE_EXPORT CSphereCollider : public CCollider
-    {
-    public:
-		CSphereCollider(const HSceneObject& parent, float radius = 1.0f);
-
-		/** @copydoc SphereCollider::setRadius */
-		void setRadius(float radius);
-
-		/** @copydoc SphereCollider::getRadius */
-		float getRadius() const { return mRadius; }
-
-		/** Sets the position of the sphere shape, relative to the component's scene object. */
-		void setCenter(const Vector3& center);
-
-		/** Gets the position of the sphere shape, relative to the component's scene object. */
-		Vector3 getCenter() const { return mLocalPosition; }
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the sphere collider that this component wraps. */
-		SphereCollider* _getInternal() const { return static_cast<SphereCollider*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CCollider::createInternal */
-		SPtr<Collider> createInternal() override;
-
-    protected:
-		float mRadius;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CSphereColliderRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CSphereCollider() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsSphereCollider.h"
+#include "BsCCollider.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	SphereCollider
+	 *
+	 * Wraps SphereCollider as a Component.
+	 */
+    class BS_CORE_EXPORT CSphereCollider : public CCollider
+    {
+    public:
+		CSphereCollider(const HSceneObject& parent, float radius = 1.0f);
+
+		/** @copydoc SphereCollider::setRadius */
+		void setRadius(float radius);
+
+		/** @copydoc SphereCollider::getRadius */
+		float getRadius() const { return mRadius; }
+
+		/** Sets the position of the sphere shape, relative to the component's scene object. */
+		void setCenter(const Vector3& center);
+
+		/** Gets the position of the sphere shape, relative to the component's scene object. */
+		Vector3 getCenter() const { return mLocalPosition; }
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the sphere collider that this component wraps. */
+		SphereCollider* _getInternal() const { return static_cast<SphereCollider*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CCollider::createInternal */
+		SPtr<Collider> createInternal() override;
+
+    protected:
+		float mRadius;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CSphereColliderRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CSphereCollider() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 70 - 68
Source/BansheeCore/Include/BsCSphericalJoint.h

@@ -1,69 +1,71 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsSphericalJoint.h"
-#include "BsCJoint.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Components-Core
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	SphericalJoint
-	 *
-	 * Wraps SphericalJoint as a Component.
-	 */
-    class BS_CORE_EXPORT CSphericalJoint : public CJoint
-    {
-    public:
-		CSphericalJoint(const HSceneObject& parent);
-
-		/** @copydoc SphericalJoint::getLimit */
-		inline LimitConeRange getLimit() const;
-
-		/** @copydoc SphericalJoint::setLimit */
-		inline void setLimit(const LimitConeRange& limit);
-
-		/** @copydoc SphericalJoint::setFlag */
-		inline void setFlag(SphericalJoint::Flag flag, bool enabled);
-
-		/** @copydoc SphericalJoint::hasFlag */
-		inline bool hasFlag(SphericalJoint::Flag flag) const;
-
-		/** @cond INTERNAL */
-
-	    /**	Returns the spherical joint that this component wraps. */
-		SphericalJoint* _getInternal() const { return static_cast<SphericalJoint*>(mInternal.get()); }
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 						COMPONENT OVERRIDES                      		*/
-		/************************************************************************/
-	protected:
-		friend class SceneObject;
-
-		/** @copydoc CJoint::createInternal */
-		SPtr<Joint> createInternal() override;
-
-		SphericalJoint::Flag mFlag = (SphericalJoint::Flag)0;
-		LimitConeRange mLimit;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CSphericalJointRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		CSphericalJoint() {} // Serialization only
-     };
-
-	 /** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsSphericalJoint.h"
+#include "BsCJoint.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Components-Core
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	SphericalJoint
+	 *
+	 * Wraps SphericalJoint as a Component.
+	 */
+    class BS_CORE_EXPORT CSphericalJoint : public CJoint
+    {
+    public:
+		CSphericalJoint(const HSceneObject& parent);
+
+		/** @copydoc SphericalJoint::getLimit */
+		inline LimitConeRange getLimit() const;
+
+		/** @copydoc SphericalJoint::setLimit */
+		inline void setLimit(const LimitConeRange& limit);
+
+		/** @copydoc SphericalJoint::setFlag */
+		inline void setFlag(SphericalJoint::Flag flag, bool enabled);
+
+		/** @copydoc SphericalJoint::hasFlag */
+		inline bool hasFlag(SphericalJoint::Flag flag) const;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+	    /**	Returns the spherical joint that this component wraps. */
+		SphericalJoint* _getInternal() const { return static_cast<SphericalJoint*>(mInternal.get()); }
+
+		/** @} */
+
+		/************************************************************************/
+		/* 						COMPONENT OVERRIDES                      		*/
+		/************************************************************************/
+	protected:
+		friend class SceneObject;
+
+		/** @copydoc CJoint::createInternal */
+		SPtr<Joint> createInternal() override;
+
+		SphericalJoint::Flag mFlag = (SphericalJoint::Flag)0;
+		LimitConeRange mLimit;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CSphericalJointRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		CSphericalJoint() {} // Serialization only
+     };
+
+	 /** @} */
 }

+ 311 - 309
Source/BansheeCore/Include/BsCharacterController.h

@@ -1,310 +1,312 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPhysicsCommon.h"
-#include "BsVector3.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** 
-	 * Controls climbing behaviour for a capsule character controller. Normally the character controller will not
-	 * automatically climb when heights are greater than the assigned step offset. However due to the shape of the capsule
-	 * it might automatically climb over slightly larger heights than assigned step offsets.
-	 */
-	enum class CharacterClimbingMode
-	{
-		Normal, /**< Normal behaviour. Capsule character controller will be able to auto-step even above the step offset. */
-		Constrained /**< The system will attempt to limit auto-step to the provided step offset and no higher. */
-	};
-
-	/** Controls behaviour when a character controller reaches a slope thats larger than its slope offset. */
-	enum class CharacterNonWalkableMode
-	{
-		Prevent, /**< Character will be prevented from going further, but will be allowed to move laterally. */
-		PreventAndSlide /**< Character will be prevented from going further, but also slide down the slope. */
-	};
-
-	/** Reports in which directions is the character colliding with other objects. */
-	enum class CharacterCollisionFlag
-	{
-		Sides = 0x1, /**< Character is colliding with its sides. */
-		Up = 0x2, /**< Character is colliding with the ceiling. */
-		Down = 0x4 /**< Character is colliding with the ground. */
-	};
-
-	/** @copydoc CharacterCollisionFlag */
-	typedef Flags<CharacterCollisionFlag> CharacterCollisionFlags;
-	BS_FLAGS_OPERATORS(CharacterCollisionFlag)
-
-	struct CHAR_CONTROLLER_DESC;
-	struct ControllerColliderCollision;
-	struct ControllerControllerCollision;
-
-	/** 
-	 * Special physics controller meant to be used for game characters. Uses the "slide-and-collide" physics instead of
-	 * of the standard physics model to handle various issues with manually moving kinematic objects. Uses a capsule to
-	 * represent the character's bounds. 
-	 */
-	class BS_CORE_EXPORT CharacterController
-	{
-	public:
-		CharacterController(const CHAR_CONTROLLER_DESC& desc) { }
-		virtual ~CharacterController() { }
-
-		/**
-		 * Moves the controller in the specified direction by the specified amount, while interacting with surrounding
-		 * geometry. Returns flags signaling where collision occurred after the movement.
-		 *
-		 * Does not account for gravity, you must apply it manually.
-		 */
-		virtual CharacterCollisionFlags move(const Vector3& displacement) = 0;
-
-		/** Returns position of the center of the controller. */
-		virtual Vector3 getPosition() const = 0;
-
-		/** 
-		 * Sets position of the center of the controller. This will teleport the character to the location. Use move()
-		 * for movement that includes physics.
-		 */
-		virtual void setPosition(const Vector3& position) = 0;
-
-		/** Returns position of the bottom of the controller. Position takes contact offset into account. */
-		virtual Vector3 getFootPosition() const = 0;
-
-		/** 
-		 * Sets position of the bottom of the controller. Position takes contact offset into account. This will teleport the
-		 * character to the location. Use move() for movement that includes physics.
-		 */
-		virtual void setFootPosition(const Vector3& position) = 0;
-
-		/** Returns the radius of the controller capsule. */
-		virtual float getRadius() const = 0;
-
-		/** Sets the radius of the controller capsule. */
-		virtual void setRadius(float radius) = 0;
-
-		/** Returns the height between the centers of the two spheres of the controller capsule. */
-		virtual float getHeight() const = 0;
-
-		/** Sets the height between the centers of the two spheres of the controller capsule. */
-		virtual void setHeight(float height) = 0;
-
-		/** Returns the up direction of capsule. Determines capsule orientation. */
-		virtual Vector3 getUp() const = 0;
-
-		/** Sets the up direction of capsule. Determines capsule orientation. */
-		virtual void setUp(const Vector3& up) = 0;
-
-		/** 
-		 * Returns climbing mode.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::climbingMode
-		 */
-		virtual CharacterClimbingMode getClimbingMode() const = 0;
-
-		/** 
-		 * Sets climbing mode.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::climbingMode
-		 */
-		virtual void setClimbingMode(CharacterClimbingMode mode) = 0;
-
-		/** 
-		 * Returns non-walkable mode.
-		 *
-		 * @copydoc CHAR_CONTROLLER_DESC::nonWalkableMode
-		 */
-		virtual CharacterNonWalkableMode getNonWalkableMode() const = 0;
-
-		/** 
-		 * Sets non-walkable mode.
-		 *
-		 * @copydoc CHAR_CONTROLLER_DESC::nonWalkableMode
-		 */
-		virtual void setNonWalkableMode(CharacterNonWalkableMode mode) = 0;
-
-		/** 
-		 * Returns minimum move distance.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::minMoveDistance
-		 */
-		virtual float getMinMoveDistance() const = 0;
-
-		/** 
-		 * Sets minimum move distance.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::minMoveDistance
-		 */
-		virtual void setMinMoveDistance(float value) = 0;
-
-		/** 
-		 * Returns the contact offset.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::contactOffset
-		 */
-		virtual float getContactOffset() const = 0;
-
-		/** 
-		 * Sets the contact offset.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::contactOffset
-		 */
-		virtual void setContactOffset(float value) = 0;
-
-		/** 
-		 * Returns the step offset.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::stepOffset
-		 */
-		virtual float getStepOffset() const = 0;
-
-		/** 
-		 * Sets the step offset.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::stepOffset
-		 */
-		virtual void setStepOffset(float value) = 0;
-
-		/**
-		 * Returns the slope angle.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::slopeLimit
-		 */
-		virtual Radian getSlopeLimit() const = 0;
-
-		/**
-		 * Sets the slope angle.
-		 *
-		 * @copydoc	CHAR_CONTROLLER_DESC::slopeLimit
-		 */
-		virtual void setSlopeLimit(Radian value) = 0;
-
-		/** Sets the layer that controls what can the controller collide with. */
-		virtual void setLayer(UINT64 layer) { mLayer = layer; }
-
-		/** Gets the layer that controls what can the controller collide with. */
-		virtual UINT64 getLayer() const { return mLayer; }
-
-		/** Creates a new character controller. */
-		static SPtr<CharacterController> create(const CHAR_CONTROLLER_DESC& desc);
-
-		/** Triggered when the controller hits a collider. */
-		Event<void(const ControllerColliderCollision&)> onColliderHit;
-
-		/** Triggered when the controller hits another character controller. */
-		Event<void(const ControllerControllerCollision&)> onControllerHit;
-
-		/** @cond INTERNAL */
-
-		/** 
-		 * Sets the object that owns this physics object, if any. Used for high level systems so they can easily map their
-		 * high level physics objects from the low level ones returned by various queries and events.
-		 */
-		void _setOwner(PhysicsOwnerType type, void* owner) { mOwner.type = type; mOwner.ownerData = owner; }
-
-		/** 
-		 * Gets the object that owns this physics object, if any. Used for high level systems so they can easily map their
-		 * high level physics objects from the low level ones returned by various queries and events.
-		 */
-		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
-
-		/** @endcond */
-	private:
-		PhysicsObjectOwner mOwner;
-		UINT64 mLayer = 1;
-	};
-
-	/** Contains all the information required for initializing a character controller. */
-	struct CHAR_CONTROLLER_DESC
-	{
-		/** Center of the controller capsule */
-		Vector3 position;
-
-		/**
-		 * Contact offset specifies a skin around the object within which contacts will be generated. It should be a small
-		 * positive non-zero value.
-		 */
-		float contactOffset = 0.1f;
-
-		/**
-		 * Controls which obstacles will the character be able to automatically step over without being stopped. This is the
-		 * height of the maximum obstacle that will be stepped over (with exceptions, see climbingMode).
-		 */
-		float stepOffset = 0.5f;
-
-		/**
-		 * Controls which slopes should the character consider too steep and won't be able to move over. See
-		 * nonWalkableMode for more information.
-		 */
-		Radian slopeLimit = Degree(45.0f);
-
-		/** 
-		 * Represents minimum distance that the character will move during a call to move(). This is used to stop the
-		 * recursive motion algorithm when the remaining distance is too small.
-		 */
-		float minMoveDistance = 0.0f;
-
-		/** Height between the centers of the two spheres of the controller capsule. */
-		float height = 0.0f; 
-
-		/** Radius of the controller capsule. */
-		float radius = 1.0f;
-		
-		/** Up direction of controller capsule. Determines capsule orientation. */
-		Vector3 up = Vector3::UNIT_Y;
-
-		/** 
-		 * Controls what happens when character encounters a height higher than its step offset. 
-		 *
-		 * @see	CharacterClimbingMode
-		 */
-		CharacterClimbingMode climbingMode = CharacterClimbingMode::Normal;
-
-		/** 
-		 * Controls what happens when character encounters a slope higher than its slope offset. 
-		 *
-		 * @see	CharacterNonWalkableMode
-		 */
-		CharacterNonWalkableMode nonWalkableMode = CharacterNonWalkableMode::Prevent;
-	};
-
-	/** Contains data about a collision of a character controller and another object. */
-	struct ControllerCollision
-	{
-		Vector3 position; /**< Contact position. */
-		Vector3 normal; /**< Contact normal. */
-		Vector3 motionDir; /**< Direction of motion after the hit. */
-		float motionAmount; /**< Magnitude of motion after the hit. */
-	};
-
-	/** Contains data about a collision of a character controller and a collider. */
-	struct ControllerColliderCollision : ControllerCollision
-	{
-		/**
-		 * Component of the controller that was touched. Can be null if the controller has no component parent, in which 
-		 * case check ::colliderRaw. 
-		 */
-		HCollider collider;
-		Collider* colliderRaw; /**< Collider that was touched. */
-		UINT32 triangleIndex; /**< Touched triangle index for mesh colliders. */
-	};
-
-	/** Contains data about a collision between two character controllers. */
-	struct ControllerControllerCollision : ControllerCollision
-	{
-		/**
-		 * Component of the controller that was touched. Can be null if the controller has no component parent, in which 
-		 * case check ::controllerRaw. 
-		 */
-		HCharacterController controller; 
-		CharacterController* controllerRaw; /**< Controller that was touched. */
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPhysicsCommon.h"
+#include "BsVector3.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/** 
+	 * Controls climbing behaviour for a capsule character controller. Normally the character controller will not
+	 * automatically climb when heights are greater than the assigned step offset. However due to the shape of the capsule
+	 * it might automatically climb over slightly larger heights than assigned step offsets.
+	 */
+	enum class CharacterClimbingMode
+	{
+		Normal, /**< Normal behaviour. Capsule character controller will be able to auto-step even above the step offset. */
+		Constrained /**< The system will attempt to limit auto-step to the provided step offset and no higher. */
+	};
+
+	/** Controls behaviour when a character controller reaches a slope thats larger than its slope offset. */
+	enum class CharacterNonWalkableMode
+	{
+		Prevent, /**< Character will be prevented from going further, but will be allowed to move laterally. */
+		PreventAndSlide /**< Character will be prevented from going further, but also slide down the slope. */
+	};
+
+	/** Reports in which directions is the character colliding with other objects. */
+	enum class CharacterCollisionFlag
+	{
+		Sides = 0x1, /**< Character is colliding with its sides. */
+		Up = 0x2, /**< Character is colliding with the ceiling. */
+		Down = 0x4 /**< Character is colliding with the ground. */
+	};
+
+	/** @copydoc CharacterCollisionFlag */
+	typedef Flags<CharacterCollisionFlag> CharacterCollisionFlags;
+	BS_FLAGS_OPERATORS(CharacterCollisionFlag)
+
+	struct CHAR_CONTROLLER_DESC;
+	struct ControllerColliderCollision;
+	struct ControllerControllerCollision;
+
+	/** 
+	 * Special physics controller meant to be used for game characters. Uses the "slide-and-collide" physics instead of
+	 * of the standard physics model to handle various issues with manually moving kinematic objects. Uses a capsule to
+	 * represent the character's bounds. 
+	 */
+	class BS_CORE_EXPORT CharacterController
+	{
+	public:
+		CharacterController(const CHAR_CONTROLLER_DESC& desc) { }
+		virtual ~CharacterController() { }
+
+		/**
+		 * Moves the controller in the specified direction by the specified amount, while interacting with surrounding
+		 * geometry. Returns flags signaling where collision occurred after the movement.
+		 *
+		 * Does not account for gravity, you must apply it manually.
+		 */
+		virtual CharacterCollisionFlags move(const Vector3& displacement) = 0;
+
+		/** Returns position of the center of the controller. */
+		virtual Vector3 getPosition() const = 0;
+
+		/** 
+		 * Sets position of the center of the controller. This will teleport the character to the location. Use move()
+		 * for movement that includes physics.
+		 */
+		virtual void setPosition(const Vector3& position) = 0;
+
+		/** Returns position of the bottom of the controller. Position takes contact offset into account. */
+		virtual Vector3 getFootPosition() const = 0;
+
+		/** 
+		 * Sets position of the bottom of the controller. Position takes contact offset into account. This will teleport the
+		 * character to the location. Use move() for movement that includes physics.
+		 */
+		virtual void setFootPosition(const Vector3& position) = 0;
+
+		/** Returns the radius of the controller capsule. */
+		virtual float getRadius() const = 0;
+
+		/** Sets the radius of the controller capsule. */
+		virtual void setRadius(float radius) = 0;
+
+		/** Returns the height between the centers of the two spheres of the controller capsule. */
+		virtual float getHeight() const = 0;
+
+		/** Sets the height between the centers of the two spheres of the controller capsule. */
+		virtual void setHeight(float height) = 0;
+
+		/** Returns the up direction of capsule. Determines capsule orientation. */
+		virtual Vector3 getUp() const = 0;
+
+		/** Sets the up direction of capsule. Determines capsule orientation. */
+		virtual void setUp(const Vector3& up) = 0;
+
+		/** 
+		 * Returns climbing mode.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::climbingMode
+		 */
+		virtual CharacterClimbingMode getClimbingMode() const = 0;
+
+		/** 
+		 * Sets climbing mode.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::climbingMode
+		 */
+		virtual void setClimbingMode(CharacterClimbingMode mode) = 0;
+
+		/** 
+		 * Returns non-walkable mode.
+		 *
+		 * @copydoc CHAR_CONTROLLER_DESC::nonWalkableMode
+		 */
+		virtual CharacterNonWalkableMode getNonWalkableMode() const = 0;
+
+		/** 
+		 * Sets non-walkable mode.
+		 *
+		 * @copydoc CHAR_CONTROLLER_DESC::nonWalkableMode
+		 */
+		virtual void setNonWalkableMode(CharacterNonWalkableMode mode) = 0;
+
+		/** 
+		 * Returns minimum move distance.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::minMoveDistance
+		 */
+		virtual float getMinMoveDistance() const = 0;
+
+		/** 
+		 * Sets minimum move distance.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::minMoveDistance
+		 */
+		virtual void setMinMoveDistance(float value) = 0;
+
+		/** 
+		 * Returns the contact offset.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::contactOffset
+		 */
+		virtual float getContactOffset() const = 0;
+
+		/** 
+		 * Sets the contact offset.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::contactOffset
+		 */
+		virtual void setContactOffset(float value) = 0;
+
+		/** 
+		 * Returns the step offset.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::stepOffset
+		 */
+		virtual float getStepOffset() const = 0;
+
+		/** 
+		 * Sets the step offset.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::stepOffset
+		 */
+		virtual void setStepOffset(float value) = 0;
+
+		/**
+		 * Returns the slope angle.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::slopeLimit
+		 */
+		virtual Radian getSlopeLimit() const = 0;
+
+		/**
+		 * Sets the slope angle.
+		 *
+		 * @copydoc	CHAR_CONTROLLER_DESC::slopeLimit
+		 */
+		virtual void setSlopeLimit(Radian value) = 0;
+
+		/** Sets the layer that controls what can the controller collide with. */
+		virtual void setLayer(UINT64 layer) { mLayer = layer; }
+
+		/** Gets the layer that controls what can the controller collide with. */
+		virtual UINT64 getLayer() const { return mLayer; }
+
+		/** Creates a new character controller. */
+		static SPtr<CharacterController> create(const CHAR_CONTROLLER_DESC& desc);
+
+		/** Triggered when the controller hits a collider. */
+		Event<void(const ControllerColliderCollision&)> onColliderHit;
+
+		/** Triggered when the controller hits another character controller. */
+		Event<void(const ControllerControllerCollision&)> onControllerHit;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** 
+		 * Sets the object that owns this physics object, if any. Used for high level systems so they can easily map their
+		 * high level physics objects from the low level ones returned by various queries and events.
+		 */
+		void _setOwner(PhysicsOwnerType type, void* owner) { mOwner.type = type; mOwner.ownerData = owner; }
+
+		/** 
+		 * Gets the object that owns this physics object, if any. Used for high level systems so they can easily map their
+		 * high level physics objects from the low level ones returned by various queries and events.
+		 */
+		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
+
+		/** @} */
+	private:
+		PhysicsObjectOwner mOwner;
+		UINT64 mLayer = 1;
+	};
+
+	/** Contains all the information required for initializing a character controller. */
+	struct CHAR_CONTROLLER_DESC
+	{
+		/** Center of the controller capsule */
+		Vector3 position;
+
+		/**
+		 * Contact offset specifies a skin around the object within which contacts will be generated. It should be a small
+		 * positive non-zero value.
+		 */
+		float contactOffset = 0.1f;
+
+		/**
+		 * Controls which obstacles will the character be able to automatically step over without being stopped. This is the
+		 * height of the maximum obstacle that will be stepped over (with exceptions, see climbingMode).
+		 */
+		float stepOffset = 0.5f;
+
+		/**
+		 * Controls which slopes should the character consider too steep and won't be able to move over. See
+		 * nonWalkableMode for more information.
+		 */
+		Radian slopeLimit = Degree(45.0f);
+
+		/** 
+		 * Represents minimum distance that the character will move during a call to move(). This is used to stop the
+		 * recursive motion algorithm when the remaining distance is too small.
+		 */
+		float minMoveDistance = 0.0f;
+
+		/** Height between the centers of the two spheres of the controller capsule. */
+		float height = 0.0f; 
+
+		/** Radius of the controller capsule. */
+		float radius = 1.0f;
+		
+		/** Up direction of controller capsule. Determines capsule orientation. */
+		Vector3 up = Vector3::UNIT_Y;
+
+		/** 
+		 * Controls what happens when character encounters a height higher than its step offset. 
+		 *
+		 * @see	CharacterClimbingMode
+		 */
+		CharacterClimbingMode climbingMode = CharacterClimbingMode::Normal;
+
+		/** 
+		 * Controls what happens when character encounters a slope higher than its slope offset. 
+		 *
+		 * @see	CharacterNonWalkableMode
+		 */
+		CharacterNonWalkableMode nonWalkableMode = CharacterNonWalkableMode::Prevent;
+	};
+
+	/** Contains data about a collision of a character controller and another object. */
+	struct ControllerCollision
+	{
+		Vector3 position; /**< Contact position. */
+		Vector3 normal; /**< Contact normal. */
+		Vector3 motionDir; /**< Direction of motion after the hit. */
+		float motionAmount; /**< Magnitude of motion after the hit. */
+	};
+
+	/** Contains data about a collision of a character controller and a collider. */
+	struct ControllerColliderCollision : ControllerCollision
+	{
+		/**
+		 * Component of the controller that was touched. Can be null if the controller has no component parent, in which 
+		 * case check ::colliderRaw. 
+		 */
+		HCollider collider;
+		Collider* colliderRaw; /**< Collider that was touched. */
+		UINT32 triangleIndex; /**< Touched triangle index for mesh colliders. */
+	};
+
+	/** Contains data about a collision between two character controllers. */
+	struct ControllerControllerCollision : ControllerCollision
+	{
+		/**
+		 * Component of the controller that was touched. Can be null if the controller has no component parent, in which 
+		 * case check ::controllerRaw. 
+		 */
+		HCharacterController controller; 
+		CharacterController* controllerRaw; /**< Controller that was touched. */
+	};
+
+	/** @} */
 }

+ 4 - 2
Source/BansheeCore/Include/BsCollider.h

@@ -126,7 +126,9 @@ namespace BansheeEngine
 		 */
 		Event<void(const CollisionData&)> onCollisionEnd;
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/** Returns the object containing common collider code. */
 		FCollider* _getInternal() const { return mInternal; }
@@ -143,7 +145,7 @@ namespace BansheeEngine
 		 */
 		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
 
-		/** @endcond */
+		/** @} */
 	protected:
 		FCollider* mInternal = nullptr;
 		PhysicsObjectOwner mOwner;

+ 429 - 429
Source/BansheeCore/Include/BsCommonTypes.h

@@ -1,430 +1,430 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Utility-Core
-	 *  @{
-	 */
-
-	/**	Factors used when blending new pixels with existing pixels. */
-    enum BlendFactor
-    {
-		BF_ONE, /**< Use a value of one for all pixel components. */
-		BF_ZERO, /**< Use a value of zero for all pixel components. */
-		BF_DEST_COLOR, /**< Use the existing pixel value. */
-		BF_SOURCE_COLOR, /**< Use the newly generated pixel value. */
-		BF_INV_DEST_COLOR, /**< Use the inverse of the existing value. */
-		BF_INV_SOURCE_COLOR, /**< Use the inverse of the newly generated pixel value. */
-		BF_DEST_ALPHA, /**< Use the existing alpha value. */
-		BF_SOURCE_ALPHA, /**< Use the newly generated alpha value. */
-		BF_INV_DEST_ALPHA, /**< Use the inverse of the existing alpha value. */
-		BF_INV_SOURCE_ALPHA /**< Use the inverse of the newly generated alpha value. */
-    };
-
-	/**	Operations that determines how are blending factors combined. */
-	enum BlendOperation
-	{
-		BO_ADD, /**< Blend factors are added together. */
-		BO_SUBTRACT, /**< Blend factors are subtracted in "srcFactor - dstFactor" order. */
-		BO_REVERSE_SUBTRACT, /**< Blend factors are subtracted in "dstFactor - srcFactor" order. */
-		BO_MIN, /**< Minimum of the two factors is chosen. */
-		BO_MAX /**< Maximum of the two factors is chosen. */
-	};
-
-	/**	Comparison functions used for the depth/stencil buffer. */
-    enum CompareFunction
-    {
-		CMPF_ALWAYS_FAIL, /**< Operation will always fail. */
-		CMPF_ALWAYS_PASS, /**< Operation will always pass. */
-		CMPF_LESS, /**< Operation will pass if the new value is less than existing value. */
-        CMPF_LESS_EQUAL, /**< Operation will pass if the new value is less or equal than existing value. */
-        CMPF_EQUAL, /**< Operation will pass if the new value is equal to the existing value. */
-        CMPF_NOT_EQUAL, /**< Operation will pass if the new value is not equal to the existing value. */
-        CMPF_GREATER_EQUAL, /**< Operation will pass if the new value greater or equal than the existing value. */
-        CMPF_GREATER /**< Operation will pass if the new value greater than the existing value. */
-    };
-
-	/**
-	 * Types of texture addressing modes that determine what happens when texture coordinates are outside of the valid range.
-	 */
-    enum TextureAddressingMode
-    {
-		TAM_WRAP, /**< Coordinates wrap back to the valid range. */
-		TAM_MIRROR, /**< Coordinates flip every time the size of the valid range is passed. */
-		TAM_CLAMP, /**< Coordinates are clamped within the valid range. */
-		TAM_BORDER /**< Coordinates outside of the valid range will return a separately set border color. */
-    };
-
-	/**	Types of available filtering situations. */
-    enum FilterType
-    {
-		FT_MIN, /**< The filter used when shrinking a texture. */
-        FT_MAG, /**< The filter used when magnifying a texture. */
-        FT_MIP /**< The filter used when filtering between mipmaps. */
-    };
-
-	/**	Filtering options for textures. */
-    enum FilterOptions
-    {
-		FO_NONE = 0, /**< Use no filtering. Only relevant for mipmap filtering. */
-		FO_POINT = 1, /**< Filter using the nearest found pixel. Most basic filtering. */
-		FO_LINEAR = 2, /**< Average a 2x2 pixel area, signifies bilinear filtering for texture, trilinear for mipmaps. */
-		FO_ANISOTROPIC = 3, /**< More advanced filtering that improves quality when viewing textures at a steep angle */
-		FO_USE_COMPARISON = 4 /**< Specifies that the sampled values will be compared against existing sampled data. Should be OR-ed with other filtering options. */
-    };
-
-	/**	Types of frame buffers. */
-	enum FrameBufferType
-	{
-		FBT_COLOR = 0x1,
-		FBT_DEPTH = 0x2,
-		FBT_STENCIL = 0x4
-	};
-
-	/**
-	 * Types of culling that determine how (and if) hardware discards faces with certain winding order. Winding order can
-	 * be used for determining front or back facing polygons by checking the order of its vertices from the render 
-	 * perspective.
-	 */
-    enum CullingMode
-    {
-		CULL_NONE = 0, /**< Hardware performs no culling and renders both sides. */
-		CULL_CLOCKWISE = 1, /**< Hardware culls faces that have a clockwise vertex ordering. */
-        CULL_COUNTERCLOCKWISE = 2 /**< Hardware culls faces that have a counter-clockwise vertex ordering. */
-    };
-
-	/**	Polygon mode to use when rasterizing. */
-    enum PolygonMode
-    {
-		PM_WIREFRAME = 1, /**< Render as wireframe showing only polygon outlines. */
-        PM_SOLID = 2 /**< Render as solid showing whole polygons. */
-    };
-
-	/**	Types of action that can happen on the stencil buffer. */
-	enum StencilOperation
-	{
-		SOP_KEEP, /**< Leave the stencil buffer unchanged. */
-		SOP_ZERO, /**< Set the stencil value to zero. */
-		SOP_REPLACE, /**< Replace the stencil value with the reference value. */
-		SOP_INCREMENT, /**< Increase the stencil value by 1, clamping at the maximum value. */
-		SOP_DECREMENT, /**< Decrease the stencil value by 1, clamping at 0. */
-		SOP_INCREMENT_WRAP, /**< Increase the stencil value by 1, wrapping back to 0 when incrementing past the maximum value. */
-		SOP_DECREMENT_WRAP, /**< Decrease the stencil value by 1, wrapping when decrementing 0. */
-		SOP_INVERT /**< Invert the bits of the stencil buffer. */
-	};
-
-	/** These values represent a hint to the driver when locking a hardware buffer. */
-	enum GpuLockOptions
-	{
-		/**
-		 * Allows you to write to the buffer. Can cause a CPU-GPU sync point so avoid using it often (i.e. every frame) as 
-		 * that might limit your performance significantly.
-		 */
-        GBL_READ_WRITE,
-		/**
-		 * Allows you to write to the buffer. Tells the driver to completely discard the contents of the buffer you are 
-		 * writing to. The driver will (most likely) internally allocate another buffer with same specifications (which is
-		 * fairly fast) and you will avoid CPU-GPU stalls.
-		 */
-		GBL_WRITE_ONLY_DISCARD,
-		/**  Allows you to read from a buffer. Be aware that reading is usually a very slow operation. */
-		GBL_READ_ONLY,
-		/**
-		 * Allows you to write to the buffer. Guarantees the driver that you will not be updating any part of the buffer 
-		 * that is currently used. This will also avoid CPU-GPU stalls, without requiring you to discard the entire buffer.
-		 * However it is hard to guarantee when GPU has finished using a buffer.
-		 */
-        GBL_WRITE_ONLY_NO_OVERWRITE,
-		/** Allows you to both read and write to a buffer. */
-		GBL_WRITE_ONLY	
-	};
-
-	/**
-	 * Values that represent hardware buffer usage. These usually determine in what type of memory is buffer placed in,
-	 * however that depends on rendering API.
-	 */
-	enum GpuBufferUsage 
-	{
-		/** 
-		 * Signifies that you don't plan on modifying the buffer often (or at all)	after creation. Modifying such buffer 
-		 * will involve a larger performance hit.
-		 */
-        GBU_STATIC = 1,
-		/** Signifies that you will modify this buffer fairly often. */
-		GBU_DYNAMIC = 2
-	};
-
-	/** Types of generic GPU buffers that may be attached to GPU programs. */
-	enum GpuBufferType
-	{
-		/** 
-		 * Buffer containing an array of structures. Structure parameters can usually be easily accessed from within the
-		 * GPU program.
-		 */
-		GBT_STRUCTURED,
-		/** Buffer containing raw bytes. It is up to the user to interpret the data. */
-		GBT_RAW,
-		/**
-		 * Special type of buffer allowing you to specify arguments for draw operations inside the buffer instead of 
-		 * providing them directly. Useful when you want to control drawing directly from GPU.
-		 */
-		GBT_INDIRECTARGUMENT,
-		/** A stack-like buffer that allows you to add or remove elements to/from the buffer from within the GPU program. */
-		GBT_APPENDCONSUME
-	};
-
-	/** Different types of GPU views that control how GPU sees a hardware buffer. */
-	enum GpuViewUsage
-	{
-		/** Buffer is seen as a default shader resource, used primarily for reading. (e.g. a texture for sampling) */
-		GVU_DEFAULT = 0x01,
-		/** Buffer is seen as a render target that color pixels will be written to after pixel shader stage. */
-		GVU_RENDERTARGET = 0x02,
-		/** Buffer is seen as a depth stencil target that depth and stencil information is written to. */
-		GVU_DEPTHSTENCIL = 0x04,
-		/** Buffer that allows you to write to any part of it from within a GPU program. */
-		GVU_RANDOMWRITE = 0x08
-	};
-
-	/** Type of parameter block usages. Signifies how often will parameter blocks be changed. */
-	enum GpuParamBlockUsage
-	{
-		GPBU_STATIC, /**< Buffer will be rarely, if ever, updated. */
-		GPBU_DYNAMIC /**< Buffer will be updated often (e.g. every frame). */
-	};
-
-	/** Type of a parameter in a GPU program. */
-	enum GpuParamType
-	{
-		GPT_DATA, /**< Raw data type like float, Vector3, Color, etc. */
-		GPT_TEXTURE, /**< Texture type (2D, 3D, cube, etc.) */
-		GPT_BUFFER, /**< Data buffer (raw, structured, etc.) */
-		GPT_SAMPLER /**< Sampler type (2D, 3D, cube, etc.) */
-	};
-
-	/**	Type of GPU data parameters that can be used as inputs to a GPU program. */
-	enum GpuParamDataType
-	{
-		GPDT_FLOAT1 = 1,
-		GPDT_FLOAT2 = 2,
-		GPDT_FLOAT3 = 3,
-		GPDT_FLOAT4 = 4,
-		GPDT_MATRIX_2X2 = 11,
-		GPDT_MATRIX_2X3 = 12,
-		GPDT_MATRIX_2X4 = 13,
-		GPDT_MATRIX_3X2 = 14,
-		GPDT_MATRIX_3X3 = 15,
-		GPDT_MATRIX_3X4 = 16,
-		GPDT_MATRIX_4X2 = 17,
-		GPDT_MATRIX_4X3 = 18,
-		GPDT_MATRIX_4X4 = 19,
-		GPDT_INT1 = 20,
-		GPDT_INT2 = 21,
-		GPDT_INT3 = 22,
-		GPDT_INT4 = 23,
-		GPDT_BOOL = 24,
-		GPDT_STRUCT = 25,
-		GPDT_COLOR = 26, // Same as GPDT_FLOAT4, but can be used to better deduce usage
-		GPDT_COUNT = 27, // Keep at end before GPDT_UNKNOWN
-		GPDT_UNKNOWN = 0xffff
-	};
-
-	/**	Contains data about a type used for GPU data parameters. */
-	struct GpuParamDataTypeInfo
-	{
-		UINT32 baseTypeSize;
-		UINT32 size;
-		UINT32 alignment;
-		UINT32 numRows;
-		UINT32 numColumns;
-	};
-
-	/**	Contains a lookup table for various information of all types used for data GPU parameters. Sizes are in bytes. */
-	struct GpuDataParamInfos
-	{
-		GpuDataParamInfos()
-		{
-			memset(lookup, 0, sizeof(lookup));
-
-			lookup[(UINT32)GPDT_FLOAT1] = { 4, 4, 4, 1, 1 };
-			lookup[(UINT32)GPDT_FLOAT2] = { 4, 8, 8, 1, 2 };
-			lookup[(UINT32)GPDT_FLOAT3] = { 4, 16, 16, 1, 3 };
-			lookup[(UINT32)GPDT_FLOAT4] = { 4, 16, 16, 1, 4 };
-			lookup[(UINT32)GPDT_MATRIX_2X2] = { 4, 16, 8, 2, 2 };
-			lookup[(UINT32)GPDT_MATRIX_2X3] = { 4, 32, 16, 2, 3 };
-			lookup[(UINT32)GPDT_MATRIX_2X4] = { 4, 32, 16, 2, 4 };
-			lookup[(UINT32)GPDT_MATRIX_3X2] = { 4, 24, 8, 3, 2 };
-			lookup[(UINT32)GPDT_MATRIX_3X3] = { 4, 48, 16, 3, 3 };
-			lookup[(UINT32)GPDT_MATRIX_3X4] = { 4, 48, 16, 3, 4 };
-			lookup[(UINT32)GPDT_MATRIX_4X2] = { 4, 32, 8, 4, 2 };
-			lookup[(UINT32)GPDT_MATRIX_4X3] = { 4, 64, 16, 4, 3 };
-			lookup[(UINT32)GPDT_MATRIX_4X4] = { 4, 64, 16, 4, 4 };
-			lookup[(UINT32)GPDT_INT1] = { 4, 4, 4, 1, 1 };
-			lookup[(UINT32)GPDT_INT2] = { 4, 8, 8, 1, 2 };
-			lookup[(UINT32)GPDT_INT3] = { 4, 12, 16, 1, 3 };
-			lookup[(UINT32)GPDT_INT4] = { 4, 16, 16, 1, 4 };
-			lookup[(UINT32)GPDT_BOOL] = { 4, 4, 4, 1, 1 };
-		}
-
-		GpuParamDataTypeInfo lookup[GPDT_COUNT];
-	};
-
-	/**	Type of GPU object parameters that can be used as inputs to a GPU program. */
-	enum GpuParamObjectType
-	{
-		GPOT_SAMPLER1D = 1,
-		GPOT_SAMPLER2D = 2,
-		GPOT_SAMPLER3D = 3,
-		GPOT_SAMPLERCUBE = 4,
-		GPOT_SAMPLER2DMS = 5,
-		GPOT_TEXTURE1D = 11,
-		GPOT_TEXTURE2D = 12,
-		GPOT_TEXTURE3D = 13,
-		GPOT_TEXTURECUBE = 14,
-		GPOT_TEXTURE2DMS = 15,
-		GPOT_BYTE_BUFFER = 32,
-		GPOT_STRUCTURED_BUFFER = 33,
-		GPOT_RWTYPED_BUFFER = 41,
-		GPOT_RWBYTE_BUFFER = 42,
-		GPOT_RWSTRUCTURED_BUFFER = 43,
-		GPOT_RWSTRUCTURED_BUFFER_WITH_COUNTER = 44,
-		GPOT_RWAPPEND_BUFFER = 45,
-		GPOT_RWCONSUME_BUFFER = 46,
-		GPOT_UNKNOWN = 0xffff
-	};
-
-	/** These values represent a hint to the driver when writing to a GPU buffer. */
-	enum class BufferWriteType
-	{
-		/**
-		 * Default flag with least restrictions. Can cause a CPU-GPU sync point so avoid using it often (i.e. every frame)
-		 * as that might limit your performance significantly.
-		 */
-		Normal,
-		/**
-		 * Tells the driver to completely discard the contents of the buffer you are writing to. The driver will (most
-		 * likely) internally allocate another buffer with same specifications (which is fairly fast) and you will avoid 
-		 * CPU-GPU stalls. 
-		 */
-		Discard,
-		/**
-		 * Guarantees the driver that you will not be updating any part of the buffer that is currently used. This will 
-		 * also avoid CPU-GPU stalls, without requiring you to discard the entire buffer. However it is hard to guarantee 
-		 * when GPU has finished using a buffer.
-		 */
-		NoOverwrite
-	};
-
-	/**
-	 * Suggested queue priority numbers used for sorting objects in the render queue. Objects with higher priority will
-	 * be renderer sooner.
-	 */
-	enum class QueuePriority
-	{
-		Opaque = 100000,
-		Transparent = 90000,
-		Skybox = 80000,
-		Overlay = 70000
-	};
-
-	/** Type of sorting to perform on an object when added to a render queue. */
-	enum class QueueSortType
-	{
-		FrontToBack, /**< All objects with the same priority will be rendered front to back based on their center. */
-		BackToFront, /**< All objects with the same priority will be rendered back to front based on their center. */
-		None /**< Objects will not be sorted and will be processed in the order they were added to the queue. */
-	};
-
-	/**	Flags that may be assigned to a shader that let the renderer know how to interpret the shader. */
-	enum class ShaderFlags
-	{
-		Transparent = 0x1 /**< Signifies that the shader is rendering a transparent object. */
-	};
-
-	/** Valid types of a mesh used for physics. */
-	enum class PhysicsMeshType
-	{
-		/** 
-		 * A regular triangle mesh. Mesh can be of arbitrary size but cannot be used for triggers and non-kinematic 
-         * objects. Occurs a significantly larger performance impact than convex meshes.
-		 */
-		Triangle,
-		/** 
-		 * Mesh representing a convex shape. Mesh will not have more than 256 vertices. Occurs a significantly lower
-		 * performance impact than triangle meshes.
-		 */
-		Convex
-	};
-
-	/**	Texture addressing mode, per component. */
-	struct UVWAddressingMode
-	{
-		UVWAddressingMode()
-			:u(TAM_WRAP), v(TAM_WRAP), w(TAM_WRAP)
-		{ }
-
-		bool operator==(const UVWAddressingMode& rhs) const
-		{
-			return u == rhs.u && v == rhs.v && w == rhs.w;
-		}
-
-		TextureAddressingMode u, v, w;
-	};
-    
-	/**	References a subset of surfaces within a texture. */
-	struct TextureSurface
-	{
-		TextureSurface(UINT32 mipLevel = 0, UINT32 numMipLevels = 1, 
-			UINT32 arraySlice = 0, UINT32 numArraySlices = 1)
-			:mipLevel(mipLevel), numMipLevels(numMipLevels), 
-			arraySlice(arraySlice), numArraySlices(numArraySlices)
-		{ }
-
-		UINT32 mipLevel;
-		UINT32 numMipLevels;
-		UINT32 arraySlice;
-		UINT32 numArraySlices;
-	};
-
-	/** Helper class for syncing dirty data from sim CoreObject to core CoreObject and other way around. */
-	class CoreSyncData
-	{
-	public:
-		CoreSyncData()
-			:data(nullptr), size(0)
-		{ }
-
-		CoreSyncData(UINT8* data, UINT32 size)
-			:data(data), size(size)
-		{ }
-
-		/** Gets the internal data and checks the data is of valid size. */
-		template<class T>
-		const T& getData() const
-		{
-			assert(sizeof(T) == size);
-
-			return *(T*)data;
-		}
-
-		/**	Returns a pointer to internal data buffer. */
-		UINT8* getBuffer() const { return data; }
-
-		/**	Returns the size of the internal data buffer. */
-		UINT32 getBufferSize() const { return size; }
-
-	private:
-		UINT8* data;
-		UINT32 size;
-	};
-
-	typedef Map<String, String> NameValuePairList;
-
-	/** @cond SPECIALIZATIONS */
-	BS_ALLOW_MEMCPY_SERIALIZATION(TextureSurface);
-	/** @endcond */
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Utility-Core
+	 *  @{
+	 */
+
+	/**	Factors used when blending new pixels with existing pixels. */
+    enum BlendFactor
+    {
+		BF_ONE, /**< Use a value of one for all pixel components. */
+		BF_ZERO, /**< Use a value of zero for all pixel components. */
+		BF_DEST_COLOR, /**< Use the existing pixel value. */
+		BF_SOURCE_COLOR, /**< Use the newly generated pixel value. */
+		BF_INV_DEST_COLOR, /**< Use the inverse of the existing value. */
+		BF_INV_SOURCE_COLOR, /**< Use the inverse of the newly generated pixel value. */
+		BF_DEST_ALPHA, /**< Use the existing alpha value. */
+		BF_SOURCE_ALPHA, /**< Use the newly generated alpha value. */
+		BF_INV_DEST_ALPHA, /**< Use the inverse of the existing alpha value. */
+		BF_INV_SOURCE_ALPHA /**< Use the inverse of the newly generated alpha value. */
+    };
+
+	/**	Operations that determines how are blending factors combined. */
+	enum BlendOperation
+	{
+		BO_ADD, /**< Blend factors are added together. */
+		BO_SUBTRACT, /**< Blend factors are subtracted in "srcFactor - dstFactor" order. */
+		BO_REVERSE_SUBTRACT, /**< Blend factors are subtracted in "dstFactor - srcFactor" order. */
+		BO_MIN, /**< Minimum of the two factors is chosen. */
+		BO_MAX /**< Maximum of the two factors is chosen. */
+	};
+
+	/**	Comparison functions used for the depth/stencil buffer. */
+    enum CompareFunction
+    {
+		CMPF_ALWAYS_FAIL, /**< Operation will always fail. */
+		CMPF_ALWAYS_PASS, /**< Operation will always pass. */
+		CMPF_LESS, /**< Operation will pass if the new value is less than existing value. */
+        CMPF_LESS_EQUAL, /**< Operation will pass if the new value is less or equal than existing value. */
+        CMPF_EQUAL, /**< Operation will pass if the new value is equal to the existing value. */
+        CMPF_NOT_EQUAL, /**< Operation will pass if the new value is not equal to the existing value. */
+        CMPF_GREATER_EQUAL, /**< Operation will pass if the new value greater or equal than the existing value. */
+        CMPF_GREATER /**< Operation will pass if the new value greater than the existing value. */
+    };
+
+	/**
+	 * Types of texture addressing modes that determine what happens when texture coordinates are outside of the valid range.
+	 */
+    enum TextureAddressingMode
+    {
+		TAM_WRAP, /**< Coordinates wrap back to the valid range. */
+		TAM_MIRROR, /**< Coordinates flip every time the size of the valid range is passed. */
+		TAM_CLAMP, /**< Coordinates are clamped within the valid range. */
+		TAM_BORDER /**< Coordinates outside of the valid range will return a separately set border color. */
+    };
+
+	/**	Types of available filtering situations. */
+    enum FilterType
+    {
+		FT_MIN, /**< The filter used when shrinking a texture. */
+        FT_MAG, /**< The filter used when magnifying a texture. */
+        FT_MIP /**< The filter used when filtering between mipmaps. */
+    };
+
+	/**	Filtering options for textures. */
+    enum FilterOptions
+    {
+		FO_NONE = 0, /**< Use no filtering. Only relevant for mipmap filtering. */
+		FO_POINT = 1, /**< Filter using the nearest found pixel. Most basic filtering. */
+		FO_LINEAR = 2, /**< Average a 2x2 pixel area, signifies bilinear filtering for texture, trilinear for mipmaps. */
+		FO_ANISOTROPIC = 3, /**< More advanced filtering that improves quality when viewing textures at a steep angle */
+		FO_USE_COMPARISON = 4 /**< Specifies that the sampled values will be compared against existing sampled data. Should be OR-ed with other filtering options. */
+    };
+
+	/**	Types of frame buffers. */
+	enum FrameBufferType
+	{
+		FBT_COLOR = 0x1,
+		FBT_DEPTH = 0x2,
+		FBT_STENCIL = 0x4
+	};
+
+	/**
+	 * Types of culling that determine how (and if) hardware discards faces with certain winding order. Winding order can
+	 * be used for determining front or back facing polygons by checking the order of its vertices from the render 
+	 * perspective.
+	 */
+    enum CullingMode
+    {
+		CULL_NONE = 0, /**< Hardware performs no culling and renders both sides. */
+		CULL_CLOCKWISE = 1, /**< Hardware culls faces that have a clockwise vertex ordering. */
+        CULL_COUNTERCLOCKWISE = 2 /**< Hardware culls faces that have a counter-clockwise vertex ordering. */
+    };
+
+	/**	Polygon mode to use when rasterizing. */
+    enum PolygonMode
+    {
+		PM_WIREFRAME = 1, /**< Render as wireframe showing only polygon outlines. */
+        PM_SOLID = 2 /**< Render as solid showing whole polygons. */
+    };
+
+	/**	Types of action that can happen on the stencil buffer. */
+	enum StencilOperation
+	{
+		SOP_KEEP, /**< Leave the stencil buffer unchanged. */
+		SOP_ZERO, /**< Set the stencil value to zero. */
+		SOP_REPLACE, /**< Replace the stencil value with the reference value. */
+		SOP_INCREMENT, /**< Increase the stencil value by 1, clamping at the maximum value. */
+		SOP_DECREMENT, /**< Decrease the stencil value by 1, clamping at 0. */
+		SOP_INCREMENT_WRAP, /**< Increase the stencil value by 1, wrapping back to 0 when incrementing past the maximum value. */
+		SOP_DECREMENT_WRAP, /**< Decrease the stencil value by 1, wrapping when decrementing 0. */
+		SOP_INVERT /**< Invert the bits of the stencil buffer. */
+	};
+
+	/** These values represent a hint to the driver when locking a hardware buffer. */
+	enum GpuLockOptions
+	{
+		/**
+		 * Allows you to write to the buffer. Can cause a CPU-GPU sync point so avoid using it often (every frame) as 
+		 * that might limit your performance significantly.
+		 */
+        GBL_READ_WRITE,
+		/**
+		 * Allows you to write to the buffer. Tells the driver to completely discard the contents of the buffer you are 
+		 * writing to. The driver will (most likely) internally allocate another buffer with same specifications (which is
+		 * fairly fast) and you will avoid CPU-GPU stalls.
+		 */
+		GBL_WRITE_ONLY_DISCARD,
+		/**  Allows you to read from a buffer. Be aware that reading is usually a very slow operation. */
+		GBL_READ_ONLY,
+		/**
+		 * Allows you to write to the buffer. Guarantees the driver that you will not be updating any part of the buffer 
+		 * that is currently used. This will also avoid CPU-GPU stalls, without requiring you to discard the entire buffer.
+		 * However it is hard to guarantee when GPU has finished using a buffer.
+		 */
+        GBL_WRITE_ONLY_NO_OVERWRITE,
+		/** Allows you to both read and write to a buffer. */
+		GBL_WRITE_ONLY	
+	};
+
+	/**
+	 * Values that represent hardware buffer usage. These usually determine in what type of memory is buffer placed in,
+	 * however that depends on rendering API.
+	 */
+	enum GpuBufferUsage 
+	{
+		/** 
+		 * Signifies that you don't plan on modifying the buffer often (or at all)	after creation. Modifying such buffer 
+		 * will involve a larger performance hit.
+		 */
+        GBU_STATIC = 1,
+		/** Signifies that you will modify this buffer fairly often. */
+		GBU_DYNAMIC = 2
+	};
+
+	/** Types of generic GPU buffers that may be attached to GPU programs. */
+	enum GpuBufferType
+	{
+		/** 
+		 * Buffer containing an array of structures. Structure parameters can usually be easily accessed from within the
+		 * GPU program.
+		 */
+		GBT_STRUCTURED,
+		/** Buffer containing raw bytes. It is up to the user to interpret the data. */
+		GBT_RAW,
+		/**
+		 * Special type of buffer allowing you to specify arguments for draw operations inside the buffer instead of 
+		 * providing them directly. Useful when you want to control drawing directly from GPU.
+		 */
+		GBT_INDIRECTARGUMENT,
+		/** A stack-like buffer that allows you to add or remove elements to/from the buffer from within the GPU program. */
+		GBT_APPENDCONSUME
+	};
+
+	/** Different types of GPU views that control how GPU sees a hardware buffer. */
+	enum GpuViewUsage
+	{
+		/** Buffer is seen as a default shader resource, used primarily for reading. (for example a texture for sampling) */
+		GVU_DEFAULT = 0x01,
+		/** Buffer is seen as a render target that color pixels will be written to after pixel shader stage. */
+		GVU_RENDERTARGET = 0x02,
+		/** Buffer is seen as a depth stencil target that depth and stencil information is written to. */
+		GVU_DEPTHSTENCIL = 0x04,
+		/** Buffer that allows you to write to any part of it from within a GPU program. */
+		GVU_RANDOMWRITE = 0x08
+	};
+
+	/** Type of parameter block usages. Signifies how often will parameter blocks be changed. */
+	enum GpuParamBlockUsage
+	{
+		GPBU_STATIC, /**< Buffer will be rarely, if ever, updated. */
+		GPBU_DYNAMIC /**< Buffer will be updated often (for example every frame). */
+	};
+
+	/** Type of a parameter in a GPU program. */
+	enum GpuParamType
+	{
+		GPT_DATA, /**< Raw data type like float, Vector3, Color, etc. */
+		GPT_TEXTURE, /**< Texture type (2D, 3D, cube, etc.) */
+		GPT_BUFFER, /**< Data buffer (raw, structured, etc.) */
+		GPT_SAMPLER /**< Sampler type (2D, 3D, cube, etc.) */
+	};
+
+	/**	Type of GPU data parameters that can be used as inputs to a GPU program. */
+	enum GpuParamDataType
+	{
+		GPDT_FLOAT1 = 1,
+		GPDT_FLOAT2 = 2,
+		GPDT_FLOAT3 = 3,
+		GPDT_FLOAT4 = 4,
+		GPDT_MATRIX_2X2 = 11,
+		GPDT_MATRIX_2X3 = 12,
+		GPDT_MATRIX_2X4 = 13,
+		GPDT_MATRIX_3X2 = 14,
+		GPDT_MATRIX_3X3 = 15,
+		GPDT_MATRIX_3X4 = 16,
+		GPDT_MATRIX_4X2 = 17,
+		GPDT_MATRIX_4X3 = 18,
+		GPDT_MATRIX_4X4 = 19,
+		GPDT_INT1 = 20,
+		GPDT_INT2 = 21,
+		GPDT_INT3 = 22,
+		GPDT_INT4 = 23,
+		GPDT_BOOL = 24,
+		GPDT_STRUCT = 25,
+		GPDT_COLOR = 26, // Same as GPDT_FLOAT4, but can be used to better deduce usage
+		GPDT_COUNT = 27, // Keep at end before GPDT_UNKNOWN
+		GPDT_UNKNOWN = 0xffff
+	};
+
+	/**	Contains data about a type used for GPU data parameters. */
+	struct GpuParamDataTypeInfo
+	{
+		UINT32 baseTypeSize;
+		UINT32 size;
+		UINT32 alignment;
+		UINT32 numRows;
+		UINT32 numColumns;
+	};
+
+	/**	Contains a lookup table for various information of all types used for data GPU parameters. Sizes are in bytes. */
+	struct GpuDataParamInfos
+	{
+		GpuDataParamInfos()
+		{
+			memset(lookup, 0, sizeof(lookup));
+
+			lookup[(UINT32)GPDT_FLOAT1] = { 4, 4, 4, 1, 1 };
+			lookup[(UINT32)GPDT_FLOAT2] = { 4, 8, 8, 1, 2 };
+			lookup[(UINT32)GPDT_FLOAT3] = { 4, 16, 16, 1, 3 };
+			lookup[(UINT32)GPDT_FLOAT4] = { 4, 16, 16, 1, 4 };
+			lookup[(UINT32)GPDT_MATRIX_2X2] = { 4, 16, 8, 2, 2 };
+			lookup[(UINT32)GPDT_MATRIX_2X3] = { 4, 32, 16, 2, 3 };
+			lookup[(UINT32)GPDT_MATRIX_2X4] = { 4, 32, 16, 2, 4 };
+			lookup[(UINT32)GPDT_MATRIX_3X2] = { 4, 24, 8, 3, 2 };
+			lookup[(UINT32)GPDT_MATRIX_3X3] = { 4, 48, 16, 3, 3 };
+			lookup[(UINT32)GPDT_MATRIX_3X4] = { 4, 48, 16, 3, 4 };
+			lookup[(UINT32)GPDT_MATRIX_4X2] = { 4, 32, 8, 4, 2 };
+			lookup[(UINT32)GPDT_MATRIX_4X3] = { 4, 64, 16, 4, 3 };
+			lookup[(UINT32)GPDT_MATRIX_4X4] = { 4, 64, 16, 4, 4 };
+			lookup[(UINT32)GPDT_INT1] = { 4, 4, 4, 1, 1 };
+			lookup[(UINT32)GPDT_INT2] = { 4, 8, 8, 1, 2 };
+			lookup[(UINT32)GPDT_INT3] = { 4, 12, 16, 1, 3 };
+			lookup[(UINT32)GPDT_INT4] = { 4, 16, 16, 1, 4 };
+			lookup[(UINT32)GPDT_BOOL] = { 4, 4, 4, 1, 1 };
+		}
+
+		GpuParamDataTypeInfo lookup[GPDT_COUNT];
+	};
+
+	/**	Type of GPU object parameters that can be used as inputs to a GPU program. */
+	enum GpuParamObjectType
+	{
+		GPOT_SAMPLER1D = 1,
+		GPOT_SAMPLER2D = 2,
+		GPOT_SAMPLER3D = 3,
+		GPOT_SAMPLERCUBE = 4,
+		GPOT_SAMPLER2DMS = 5,
+		GPOT_TEXTURE1D = 11,
+		GPOT_TEXTURE2D = 12,
+		GPOT_TEXTURE3D = 13,
+		GPOT_TEXTURECUBE = 14,
+		GPOT_TEXTURE2DMS = 15,
+		GPOT_BYTE_BUFFER = 32,
+		GPOT_STRUCTURED_BUFFER = 33,
+		GPOT_RWTYPED_BUFFER = 41,
+		GPOT_RWBYTE_BUFFER = 42,
+		GPOT_RWSTRUCTURED_BUFFER = 43,
+		GPOT_RWSTRUCTURED_BUFFER_WITH_COUNTER = 44,
+		GPOT_RWAPPEND_BUFFER = 45,
+		GPOT_RWCONSUME_BUFFER = 46,
+		GPOT_UNKNOWN = 0xffff
+	};
+
+	/** These values represent a hint to the driver when writing to a GPU buffer. */
+	enum class BufferWriteType
+	{
+		/**
+		 * Default flag with least restrictions. Can cause a CPU-GPU sync point so avoid using it often (every frame)
+		 * as that might limit your performance significantly.
+		 */
+		Normal,
+		/**
+		 * Tells the driver to completely discard the contents of the buffer you are writing to. The driver will (most
+		 * likely) internally allocate another buffer with same specifications (which is fairly fast) and you will avoid 
+		 * CPU-GPU stalls. 
+		 */
+		Discard,
+		/**
+		 * Guarantees the driver that you will not be updating any part of the buffer that is currently used. This will 
+		 * also avoid CPU-GPU stalls, without requiring you to discard the entire buffer. However it is hard to guarantee 
+		 * when GPU has finished using a buffer.
+		 */
+		NoOverwrite
+	};
+
+	/**
+	 * Suggested queue priority numbers used for sorting objects in the render queue. Objects with higher priority will
+	 * be renderer sooner.
+	 */
+	enum class QueuePriority
+	{
+		Opaque = 100000,
+		Transparent = 90000,
+		Skybox = 80000,
+		Overlay = 70000
+	};
+
+	/** Type of sorting to perform on an object when added to a render queue. */
+	enum class QueueSortType
+	{
+		FrontToBack, /**< All objects with the same priority will be rendered front to back based on their center. */
+		BackToFront, /**< All objects with the same priority will be rendered back to front based on their center. */
+		None /**< Objects will not be sorted and will be processed in the order they were added to the queue. */
+	};
+
+	/**	Flags that may be assigned to a shader that let the renderer know how to interpret the shader. */
+	enum class ShaderFlags
+	{
+		Transparent = 0x1 /**< Signifies that the shader is rendering a transparent object. */
+	};
+
+	/** Valid types of a mesh used for physics. */
+	enum class PhysicsMeshType
+	{
+		/** 
+		 * A regular triangle mesh. Mesh can be of arbitrary size but cannot be used for triggers and non-kinematic 
+         * objects. Occurs a significantly larger performance impact than convex meshes.
+		 */
+		Triangle,
+		/** 
+		 * Mesh representing a convex shape. Mesh will not have more than 256 vertices. Occurs a significantly lower
+		 * performance impact than triangle meshes.
+		 */
+		Convex
+	};
+
+	/**	Texture addressing mode, per component. */
+	struct UVWAddressingMode
+	{
+		UVWAddressingMode()
+			:u(TAM_WRAP), v(TAM_WRAP), w(TAM_WRAP)
+		{ }
+
+		bool operator==(const UVWAddressingMode& rhs) const
+		{
+			return u == rhs.u && v == rhs.v && w == rhs.w;
+		}
+
+		TextureAddressingMode u, v, w;
+	};
+    
+	/**	References a subset of surfaces within a texture. */
+	struct TextureSurface
+	{
+		TextureSurface(UINT32 mipLevel = 0, UINT32 numMipLevels = 1, 
+			UINT32 arraySlice = 0, UINT32 numArraySlices = 1)
+			:mipLevel(mipLevel), numMipLevels(numMipLevels), 
+			arraySlice(arraySlice), numArraySlices(numArraySlices)
+		{ }
+
+		UINT32 mipLevel;
+		UINT32 numMipLevels;
+		UINT32 arraySlice;
+		UINT32 numArraySlices;
+	};
+
+	/** Helper class for syncing dirty data from sim CoreObject to core CoreObject and other way around. */
+	class CoreSyncData
+	{
+	public:
+		CoreSyncData()
+			:data(nullptr), size(0)
+		{ }
+
+		CoreSyncData(UINT8* data, UINT32 size)
+			:data(data), size(size)
+		{ }
+
+		/** Gets the internal data and checks the data is of valid size. */
+		template<class T>
+		const T& getData() const
+		{
+			assert(sizeof(T) == size);
+
+			return *(T*)data;
+		}
+
+		/**	Returns a pointer to internal data buffer. */
+		UINT8* getBuffer() const { return data; }
+
+		/**	Returns the size of the internal data buffer. */
+		UINT32 getBufferSize() const { return size; }
+
+	private:
+		UINT8* data;
+		UINT32 size;
+	};
+
+	typedef Map<String, String> NameValuePairList;
+
+	/** @cond SPECIALIZATIONS */
+	BS_ALLOW_MEMCPY_SERIALIZATION(TextureSurface);
+	/** @endcond */
+
+	/** @} */
 }

+ 124 - 124
Source/BansheeCore/Include/BsComponent.h

@@ -1,125 +1,125 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsGameObject.h"
-#include "BsBounds.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Scene
-	 *  @{
-	 */
-
-	/** Components represent primary logic elements in the scene. They are attached to scene objects. */
-	class BS_CORE_EXPORT Component : public GameObject
-	{
-	public:
-		/**	Returns the SceneObject this Component is assigned to. */
-		HSceneObject sceneObject() const { return mParent; }
-
-		/** @copydoc sceneObject */
-		HSceneObject SO() const { return sceneObject(); }
-
-		/**	Returns a handle to this object. */
-		HComponent getHandle() const { return mThisHandle; }
-
-		/**
-		 * Called once per frame on all components.
-		 * 			
-		 * @note	Internal method.
-		 */
-		virtual void update() { }
-
-		/**
-		 * Calculates bounds of the visible contents represented by this component (e.g. a mesh for Renderable).
-		 * 
-		 * @param[in]	bounds	Bounds of the contents in world space coordinates.	
-		 * @return				True if the component has bounds with non-zero volume, otherwise false.
-		 */
-		virtual bool calculateBounds(Bounds& bounds);
-
-		/**
-		 * Checks if this and the provided component represent the same type.
-		 * 			
-		 * @note	
-		 * RTTI type cannot be checked directly since components can be further specialized internally for scripting 
-		 * purposes.
-		 */
-		virtual bool typeEquals(const Component& other);
-
-		/**
-		 * Removes the component from parent SceneObject and deletes it. All the references to this component will be 
-		 * marked as destroyed and you will get an exception if you try to use them.
-		 *
-		 * @param[in]	immediate	If true the destruction will be performed immediately, otherwise it will be delayed 
-		 *							until the end of the current frame (preferred option).
-		 */
-		void destroy(bool immediate = false);
-
-	protected:
-		friend class SceneObject;
-		friend class SceneObjectRTTI;
-
-		Component(const HSceneObject& parent);
-		virtual ~Component();
-
-		/**
-		 * Construct any resources the component needs before use. Called when the parent scene object is instantiated. 
-		 * A non-instantiated component shouldn't be used for any other purpose than serialization.
-		 */
-		virtual void instantiate() {}
-
-		/**	Called when the component is ready to be initialized. */
-		virtual void onInitialized() {}
-
-		/**	Called just before the component is destroyed. */
-		virtual void onDestroyed() {}
-
-		/**	Called just before the component is deactivated or destroyed. */
-		virtual void onDisabled() {}
-
-		/**	Called when the component is activated or created. */
-		virtual void onEnabled() {}
-
-		/** Called when the component's parent scene object has changed. */
-		virtual void onTransformChanged(TransformChangedFlags flags) { }
-
-		/** Checks whether the component wants to received the specified transform changed message. */
-		bool supportsNotify(TransformChangedFlags flags) const { return (mNotifyFlags & flags) != 0; }
-
-		/**
-		 * Destroys this component.
-		 *
-		 * @param[in]	handle		Game object handle this this object.
-		 * @param[in]	immediate	If true, the object will be deallocated and become unusable right away. Otherwise the 
-		 *							deallocation will be delayed to the end of frame (preferred method).
-		 *
-		 * @note	Unlike destroy(), does not remove the component from its parent.
-		 */
-		void destroyInternal(GameObjectHandleBase& handle, bool immediate = false) override;
-	private:
-		Component(const Component& other) { }
-
-	protected:
-		HComponent mThisHandle;
-		TransformChangedFlags mNotifyFlags;
-
-	private:
-		HSceneObject mParent;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class ComponentRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-
-	protected:
-		Component() {} // Serialization only
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsGameObject.h"
+#include "BsBounds.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Scene
+	 *  @{
+	 */
+
+	/** Components represent primary logic elements in the scene. They are attached to scene objects. */
+	class BS_CORE_EXPORT Component : public GameObject
+	{
+	public:
+		/**	Returns the SceneObject this Component is assigned to. */
+		HSceneObject sceneObject() const { return mParent; }
+
+		/** @copydoc sceneObject */
+		HSceneObject SO() const { return sceneObject(); }
+
+		/**	Returns a handle to this object. */
+		HComponent getHandle() const { return mThisHandle; }
+
+		/**
+		 * Called once per frame on all components.
+		 * 			
+		 * @note	Internal method.
+		 */
+		virtual void update() { }
+
+		/**
+		 * Calculates bounds of the visible contents represented by this component (for example a mesh for Renderable).
+		 * 
+		 * @param[in]	bounds	Bounds of the contents in world space coordinates.	
+		 * @return				True if the component has bounds with non-zero volume, otherwise false.
+		 */
+		virtual bool calculateBounds(Bounds& bounds);
+
+		/**
+		 * Checks if this and the provided component represent the same type.
+		 * 			
+		 * @note	
+		 * RTTI type cannot be checked directly since components can be further specialized internally for scripting 
+		 * purposes.
+		 */
+		virtual bool typeEquals(const Component& other);
+
+		/**
+		 * Removes the component from parent SceneObject and deletes it. All the references to this component will be 
+		 * marked as destroyed and you will get an exception if you try to use them.
+		 *
+		 * @param[in]	immediate	If true the destruction will be performed immediately, otherwise it will be delayed 
+		 *							until the end of the current frame (preferred option).
+		 */
+		void destroy(bool immediate = false);
+
+	protected:
+		friend class SceneObject;
+		friend class SceneObjectRTTI;
+
+		Component(const HSceneObject& parent);
+		virtual ~Component();
+
+		/**
+		 * Construct any resources the component needs before use. Called when the parent scene object is instantiated. 
+		 * A non-instantiated component shouldn't be used for any other purpose than serialization.
+		 */
+		virtual void instantiate() {}
+
+		/**	Called when the component is ready to be initialized. */
+		virtual void onInitialized() {}
+
+		/**	Called just before the component is destroyed. */
+		virtual void onDestroyed() {}
+
+		/**	Called just before the component is deactivated or destroyed. */
+		virtual void onDisabled() {}
+
+		/**	Called when the component is activated or created. */
+		virtual void onEnabled() {}
+
+		/** Called when the component's parent scene object has changed. */
+		virtual void onTransformChanged(TransformChangedFlags flags) { }
+
+		/** Checks whether the component wants to received the specified transform changed message. */
+		bool supportsNotify(TransformChangedFlags flags) const { return (mNotifyFlags & flags) != 0; }
+
+		/**
+		 * Destroys this component.
+		 *
+		 * @param[in]	handle		Game object handle this this object.
+		 * @param[in]	immediate	If true, the object will be deallocated and become unusable right away. Otherwise the 
+		 *							deallocation will be delayed to the end of frame (preferred method).
+		 *
+		 * @note	Unlike destroy(), does not remove the component from its parent.
+		 */
+		void destroyInternal(GameObjectHandleBase& handle, bool immediate = false) override;
+	private:
+		Component(const Component& other) { }
+
+	protected:
+		HComponent mThisHandle;
+		TransformChangedFlags mNotifyFlags;
+
+	private:
+		HSceneObject mParent;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class ComponentRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+
+	protected:
+		Component() {} // Serialization only
+	};
+
+	/** @} */
 }

+ 299 - 297
Source/BansheeCore/Include/BsCoreObject.h

@@ -1,297 +1,299 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsCoreObjectCore.h"
-#include "BsAsyncOp.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup CoreThread
-	 *  @{
-	 */
-
-	/**
-	 * Core objects provides functionality for dealing with objects that need to exist on both simulation and core thread.
-	 * It handles cross-thread initialization, destruction as well as syncing data between the two threads.
-	 * 			
-	 * It also provides a standardized way to initialize/destroy objects, and a way to specify dependant CoreObject%s. For
-	 * those purposes it might also be used for objects that only exist on the core thread.
-	 *
-	 * @note	CoreObjectCore is a counterpart to CoreObject that is used exclusively on the core thread. CoreObject on the
-	 *			other hand should be used exclusively on the simulation thread. Types that exist on both threads need to
-	 *			implement both of these.
-	 */
-	class BS_CORE_EXPORT CoreObject
-	{
-	protected:
-		/** Values that represent current state of the core object */
-		enum Flags
-		{
-			CGO_DESTROYED = 0x01, /**< Object has been destroyed and shouldn't be used. */
-			CGO_INIT_ON_CORE_THREAD = 0x02 /**< Object requires initialization on core thread. */
-		};
-
-	public:
-		/**
-		 * Frees all the data held by this object.
-		 * 			
-		 * @note	
-		 * If this object require initialization on core thread destruction is not done immediately, and is 
-		 * instead just scheduled on the core thread. Otherwise the object is destroyed immediately.
-		 */
-		virtual void destroy();
-
-		/**
-		 * Initializes all the internal resources of this object. Must be called right after construction. Generally you
-		 * should call this from a factory method to avoid the issue where user forgets to call it.
-		 * 					
-		 * @note	
-		 * If this object require initialization on core thread initialization is not done immediately, and is instead just 
-		 * scheduled on the core thread. Otherwise the object is initialized immediately.
-		 */
-		virtual void initialize();
-
-		/** Returns true if the object has been destroyed. Destroyed object should not be used. */
-		bool isDestroyed() const { return (mFlags & CGO_DESTROYED) != 0; }
-
-		/**
-		 * Blocks the current thread until the resource is fully initialized.
-		 * 			
-		 * @note	
-		 * If you call this without calling initialize first a deadlock will occur. You should not call this from core thread.
-		 */
-		void blockUntilCoreInitialized() const;
-
-		/** Returns an unique identifier for this object. */
-		UINT64 getInternalID() const { return mInternalID; }
-
-		/** Returns a shared_ptr version of "this" pointer. */
-		SPtr<CoreObject> getThisPtr() const { return mThis.lock(); }
-
-		/**
-		 * Returns an object that contains a core thread specific implementation of this CoreObject. Null is a valid return
-		 * value in case object requires no core thread implementation.
-		 *
-		 * @note	Thread safe to retrieve, but its data is only valid on the core thread.
-		 */
-		SPtr<CoreObjectCore> getCore() const { return mCoreSpecific; }
-
-		/**
-		 * Ensures all dirty syncable data is send to the core thread counterpart of this object (if any).
-		 *
-		 * @note	Call this if you have modified the object and need to make sure core thread has an up to date version. 
-		 *			Normally this is done automatically at the end of a frame.
-		 */
-		void syncToCore(CoreAccessor& accessor);
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Sets a shared this pointer to this object. This must be called immediately after construction, but before
-		 * initialize().
-		 *
-		 * @note	Internal method.
-		 * @note	This should be called by the factory creation methods so user doesn't have to call it manually.
-		 */
-		void _setThisPtr(std::shared_ptr<CoreObject> ptrThis);
-
-		/**
-		 * Schedules the object to be destroyed, and then deleted.
-		 *
-		 * @note	Internal method.
-		 */
-		template<class T, class MemAlloc>
-		static void _delete(CoreObject* obj)
-		{
-			if (!obj->isDestroyed())
-				obj->destroy();
-
-			bs_delete<T, MemAlloc>((T*)obj);
-		}
-
-		/** @endcond */
-	protected:
-		/**
-		 * Constructs a new core object.
-		 *
-		 * @param[in]	requiresCoreInit	(optional) Determines if the CoreObjectCore counterpart of this object 
-		 *									(if it has any, see createCore()) requires initialization and destruction on the
-		 *									core thread.
-		 */
-		CoreObject(bool requiresCoreInit = true);
-		virtual ~CoreObject();
-
-		/**
-		 * Queues a command to be executed on the core thread, without a return value.
-		 * 			
-		 * @note	
-		 * Requires a shared pointer to the object this function will be executed on, in order to make sure the object is 
-		 * not deleted before the command executes. Can be null if the function is static or global.
-		 */
-		static void queueGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void()> func);
-
-		/**
-		 * Queues a command to be executed on the core thread, with a return value in the form of AsyncOp.
-		 * 			
-		 * @see		AsyncOp
-		 * 			
-		 * @note	
-		 * Requires a shared pointer to the object this function will be executed on, in order to make sure the object is 
-		 * not deleted before the command executes. Can be null if the function is static or global.
-		 */
-		static AsyncOp queueReturnGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void(AsyncOp&)> func);
-
-		bool requiresInitOnCoreThread() const { return (mFlags & CGO_INIT_ON_CORE_THREAD) != 0; }
-		void setIsDestroyed(bool destroyed) { mFlags = destroyed ? mFlags | CGO_DESTROYED : mFlags & ~CGO_DESTROYED; }
-	private:
-		friend class CoreObjectManager;
-
-		volatile UINT8 mFlags;
-		UINT32 mCoreDirtyFlags;
-		UINT64 mInternalID; // ID == 0 is not a valid ID
-		std::weak_ptr<CoreObject> mThis;
-
-		/**
-		 * Queues object initialization command on the core thread. The command is added to the primary core thread queue 
-		 * and will be executed as soon as the core thread is ready.
-		 */
-		static void queueInitializeGpuCommand(const SPtr<CoreObjectCore>& obj);
-
-		/**
-		 * Queues object destruction command on the core thread. The command is added to the core thread accessor of this 
-		 * thread and will be executed after accessor commands are submitted and any previously queued commands are executed.
-		 *
-		 * @note	It is up to the caller to ensure no other accessors attempt to use this object.
-		 */
-		static void queueDestroyGpuCommand(const SPtr<CoreObjectCore>& obj);
-
-		/** Helper wrapper method used for queuing commands with no return value on the core thread. */
-		static void executeGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void()> func);
-
-		/**	Helper wrapper method used for queuing commands with a return value on the core thread. */
-		static void executeReturnGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void(AsyncOp&)> func, AsyncOp& op);
-
-	protected:
-		/************************************************************************/
-		/* 							CORE OBJECT SYNC                      		*/
-		/************************************************************************/
-
-		/**
-		 * Creates an object that contains core thread specific data and methods for this CoreObject. Can be null if such 
-		 * object is not required.
-		 */
-		virtual SPtr<CoreObjectCore> createCore() const { return nullptr; }
-
-		/**
-		 * Marks the core data as dirty. This causes the syncToCore() method to trigger the next time objects are synced 
-		 * between core and sim threads.
-		 *
-		 * @param[in]	flags	(optional)	Flags in case you want to signal that only part of the internal data is dirty. 
-		 *									syncToCore() will be called regardless and it's up to the implementation to read
-		 *									the flags value if needed.
-		 */
-		void markCoreDirty(UINT32 flags = 0xFFFFFFFF);
-
-		/** Marks the core data as clean. Normally called right after syncToCore() has been called. */
-		void markCoreClean() { mCoreDirtyFlags = 0; }
-
-		/**
-		 * Notifies the core object manager that this object is dependant on some other CoreObject(s), and the dependencies
-		 * changed since the last call to this method. This will trigger a call to  getCoreDependencies() to collect the 
-		 * new dependencies.
-		 */
-		void markDependenciesDirty();
-
-		/**
-		 * Checks is the core dirty flag set. This is used by external systems to know when internal data has changed and 
-		 * core thread potentially needs to be notified.
-		 */
-		bool isCoreDirty() const { return mCoreDirtyFlags != 0; }
-
-		/**
-		 * Returns the exact value of the internal flag that signals whether an object needs to be synced with the core thread.
-		 */
-		UINT32 getCoreDirtyFlags() const { return mCoreDirtyFlags; }
-
-		/**
-		 * Copy internal dirty data to a memory buffer that will be used for updating core thread version of that data.
-		 *
-		 * @note	
-		 * This generally happens at the end of every sim thread frame. Synced data becomes available to the core thread 
-		 * the start of the next core thread frame.
-		 */
-		virtual CoreSyncData syncToCore(FrameAlloc* allocator) { return CoreSyncData(); }
-
-		/**
-		 * Populates the provided array with all core objects that this core object depends upon. Dependencies are required
-		 * for syncing to the core thread, so the system can be aware to update the dependant objects if a dependency is
-		 * marked as dirty. (e.g. updating a camera's viewport should also trigger an update on camera so it has
-		 * a chance to potentially update its data).
-		 */
-		virtual void getCoreDependencies(Vector<CoreObject*>& dependencies) { }
-
-	protected:
-		SPtr<CoreObjectCore> mCoreSpecific;
-	};
-
-	/**
-	 * Creates a new core object using the specified allocators and returns a shared pointer to it.
-	 *
-	 * @note	
-	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
-	 * them manually.
-	 */
-	template<class Type, class MainAlloc, class PtrDataAlloc, class... Args>
-	std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
-	{
-		return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
-			&CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());
-	}
-
-	/**
-	 * Creates a new core object using the specified allocator and returns a shared pointer to it.
-	 *
-	 * @note	
-	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
-	 * them manually.
-	 */
-	template<class Type, class MainAlloc, class... Args>
-	std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
-	{
-		return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
-			&CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, GenAlloc>());
-	}
-
-	/**
-	 * Creates a new core object and returns a shared pointer to it.
-	 *
-	 * @note	
-	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
-	 * them manually.
-	 */
-	template<class Type, class... Args>
-	std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
-	{
-		return std::shared_ptr<Type>(bs_new<Type, GenAlloc>(std::forward<Args>(args)...),
-			&CoreObject::_delete<Type, GenAlloc>, StdAlloc<Type, GenAlloc>());
-	}
-
-	/**
-	 * Creates a core object shared pointer using a previously constructed object.
-	 *
-	 * @note	
-	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
-	 * them manually.
-	 */
-	template<class Type, class MainAlloc = GenAlloc, class PtrDataAlloc = GenAlloc>
-	std::shared_ptr<Type> bs_core_ptr(Type* data)
-	{
-		return std::shared_ptr<Type>(data, &CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());  
-	}
-
-	/** @} */
-}
-
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsCoreObjectCore.h"
+#include "BsAsyncOp.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup CoreThread
+	 *  @{
+	 */
+
+	/**
+	 * Core objects provides functionality for dealing with objects that need to exist on both simulation and core thread.
+	 * It handles cross-thread initialization, destruction as well as syncing data between the two threads.
+	 * 			
+	 * It also provides a standardized way to initialize/destroy objects, and a way to specify dependant CoreObject%s. For
+	 * those purposes it might also be used for objects that only exist on the core thread.
+	 *
+	 * @note	CoreObjectCore is a counterpart to CoreObject that is used exclusively on the core thread. CoreObject on the
+	 *			other hand should be used exclusively on the simulation thread. Types that exist on both threads need to
+	 *			implement both of these.
+	 */
+	class BS_CORE_EXPORT CoreObject
+	{
+	protected:
+		/** Values that represent current state of the core object */
+		enum Flags
+		{
+			CGO_DESTROYED = 0x01, /**< Object has been destroyed and shouldn't be used. */
+			CGO_INIT_ON_CORE_THREAD = 0x02 /**< Object requires initialization on core thread. */
+		};
+
+	public:
+		/**
+		 * Frees all the data held by this object.
+		 * 			
+		 * @note	
+		 * If this object require initialization on core thread destruction is not done immediately, and is 
+		 * instead just scheduled on the core thread. Otherwise the object is destroyed immediately.
+		 */
+		virtual void destroy();
+
+		/**
+		 * Initializes all the internal resources of this object. Must be called right after construction. Generally you
+		 * should call this from a factory method to avoid the issue where user forgets to call it.
+		 * 					
+		 * @note	
+		 * If this object require initialization on core thread initialization is not done immediately, and is instead just 
+		 * scheduled on the core thread. Otherwise the object is initialized immediately.
+		 */
+		virtual void initialize();
+
+		/** Returns true if the object has been destroyed. Destroyed object should not be used. */
+		bool isDestroyed() const { return (mFlags & CGO_DESTROYED) != 0; }
+
+		/**
+		 * Blocks the current thread until the resource is fully initialized.
+		 * 			
+		 * @note	
+		 * If you call this without calling initialize first a deadlock will occur. You should not call this from core thread.
+		 */
+		void blockUntilCoreInitialized() const;
+
+		/** Returns an unique identifier for this object. */
+		UINT64 getInternalID() const { return mInternalID; }
+
+		/** Returns a shared_ptr version of "this" pointer. */
+		SPtr<CoreObject> getThisPtr() const { return mThis.lock(); }
+
+		/**
+		 * Returns an object that contains a core thread specific implementation of this CoreObject. Null is a valid return
+		 * value in case object requires no core thread implementation.
+		 *
+		 * @note	Thread safe to retrieve, but its data is only valid on the core thread.
+		 */
+		SPtr<CoreObjectCore> getCore() const { return mCoreSpecific; }
+
+		/**
+		 * Ensures all dirty syncable data is send to the core thread counterpart of this object (if any).
+		 *
+		 * @note	Call this if you have modified the object and need to make sure core thread has an up to date version. 
+		 *			Normally this is done automatically at the end of a frame.
+		 */
+		void syncToCore(CoreAccessor& accessor);
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Sets a shared this pointer to this object. This must be called immediately after construction, but before
+		 * initialize().
+		 *
+		 * @note	Internal method.
+		 * @note	This should be called by the factory creation methods so user doesn't have to call it manually.
+		 */
+		void _setThisPtr(std::shared_ptr<CoreObject> ptrThis);
+
+		/**
+		 * Schedules the object to be destroyed, and then deleted.
+		 *
+		 * @note	Internal method.
+		 */
+		template<class T, class MemAlloc>
+		static void _delete(CoreObject* obj)
+		{
+			if (!obj->isDestroyed())
+				obj->destroy();
+
+			bs_delete<T, MemAlloc>((T*)obj);
+		}
+
+		/** @} */
+	protected:
+		/**
+		 * Constructs a new core object.
+		 *
+		 * @param[in]	requiresCoreInit	(optional) Determines if the CoreObjectCore counterpart of this object 
+		 *									(if it has any, see createCore()) requires initialization and destruction on the
+		 *									core thread.
+		 */
+		CoreObject(bool requiresCoreInit = true);
+		virtual ~CoreObject();
+
+		/**
+		 * Queues a command to be executed on the core thread, without a return value.
+		 * 			
+		 * @note	
+		 * Requires a shared pointer to the object this function will be executed on, in order to make sure the object is 
+		 * not deleted before the command executes. Can be null if the function is static or global.
+		 */
+		static void queueGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void()> func);
+
+		/**
+		 * Queues a command to be executed on the core thread, with a return value in the form of AsyncOp.
+		 * 			
+		 * @see		AsyncOp
+		 * 			
+		 * @note	
+		 * Requires a shared pointer to the object this function will be executed on, in order to make sure the object is 
+		 * not deleted before the command executes. Can be null if the function is static or global.
+		 */
+		static AsyncOp queueReturnGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void(AsyncOp&)> func);
+
+		bool requiresInitOnCoreThread() const { return (mFlags & CGO_INIT_ON_CORE_THREAD) != 0; }
+		void setIsDestroyed(bool destroyed) { mFlags = destroyed ? mFlags | CGO_DESTROYED : mFlags & ~CGO_DESTROYED; }
+	private:
+		friend class CoreObjectManager;
+
+		volatile UINT8 mFlags;
+		UINT32 mCoreDirtyFlags;
+		UINT64 mInternalID; // ID == 0 is not a valid ID
+		std::weak_ptr<CoreObject> mThis;
+
+		/**
+		 * Queues object initialization command on the core thread. The command is added to the primary core thread queue 
+		 * and will be executed as soon as the core thread is ready.
+		 */
+		static void queueInitializeGpuCommand(const SPtr<CoreObjectCore>& obj);
+
+		/**
+		 * Queues object destruction command on the core thread. The command is added to the core thread accessor of this 
+		 * thread and will be executed after accessor commands are submitted and any previously queued commands are executed.
+		 *
+		 * @note	It is up to the caller to ensure no other accessors attempt to use this object.
+		 */
+		static void queueDestroyGpuCommand(const SPtr<CoreObjectCore>& obj);
+
+		/** Helper wrapper method used for queuing commands with no return value on the core thread. */
+		static void executeGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void()> func);
+
+		/**	Helper wrapper method used for queuing commands with a return value on the core thread. */
+		static void executeReturnGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void(AsyncOp&)> func, AsyncOp& op);
+
+	protected:
+		/************************************************************************/
+		/* 							CORE OBJECT SYNC                      		*/
+		/************************************************************************/
+
+		/**
+		 * Creates an object that contains core thread specific data and methods for this CoreObject. Can be null if such 
+		 * object is not required.
+		 */
+		virtual SPtr<CoreObjectCore> createCore() const { return nullptr; }
+
+		/**
+		 * Marks the core data as dirty. This causes the syncToCore() method to trigger the next time objects are synced 
+		 * between core and sim threads.
+		 *
+		 * @param[in]	flags	(optional)	Flags in case you want to signal that only part of the internal data is dirty. 
+		 *									syncToCore() will be called regardless and it's up to the implementation to read
+		 *									the flags value if needed.
+		 */
+		void markCoreDirty(UINT32 flags = 0xFFFFFFFF);
+
+		/** Marks the core data as clean. Normally called right after syncToCore() has been called. */
+		void markCoreClean() { mCoreDirtyFlags = 0; }
+
+		/**
+		 * Notifies the core object manager that this object is dependant on some other CoreObject(s), and the dependencies
+		 * changed since the last call to this method. This will trigger a call to  getCoreDependencies() to collect the 
+		 * new dependencies.
+		 */
+		void markDependenciesDirty();
+
+		/**
+		 * Checks is the core dirty flag set. This is used by external systems to know when internal data has changed and 
+		 * core thread potentially needs to be notified.
+		 */
+		bool isCoreDirty() const { return mCoreDirtyFlags != 0; }
+
+		/**
+		 * Returns the exact value of the internal flag that signals whether an object needs to be synced with the core thread.
+		 */
+		UINT32 getCoreDirtyFlags() const { return mCoreDirtyFlags; }
+
+		/**
+		 * Copy internal dirty data to a memory buffer that will be used for updating core thread version of that data.
+		 *
+		 * @note	
+		 * This generally happens at the end of every sim thread frame. Synced data becomes available to the core thread 
+		 * the start of the next core thread frame.
+		 */
+		virtual CoreSyncData syncToCore(FrameAlloc* allocator) { return CoreSyncData(); }
+
+		/**
+		 * Populates the provided array with all core objects that this core object depends upon. Dependencies are required
+		 * for syncing to the core thread, so the system can be aware to update the dependant objects if a dependency is
+		 * marked as dirty (for example updating a camera's viewport should also trigger an update on camera so it has
+		 * a chance to potentially update its data).
+		 */
+		virtual void getCoreDependencies(Vector<CoreObject*>& dependencies) { }
+
+	protected:
+		SPtr<CoreObjectCore> mCoreSpecific;
+	};
+
+	/**
+	 * Creates a new core object using the specified allocators and returns a shared pointer to it.
+	 *
+	 * @note	
+	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
+	 * them manually.
+	 */
+	template<class Type, class MainAlloc, class PtrDataAlloc, class... Args>
+	std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
+	{
+		return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
+			&CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());
+	}
+
+	/**
+	 * Creates a new core object using the specified allocator and returns a shared pointer to it.
+	 *
+	 * @note	
+	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
+	 * them manually.
+	 */
+	template<class Type, class MainAlloc, class... Args>
+	std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
+	{
+		return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
+			&CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, GenAlloc>());
+	}
+
+	/**
+	 * Creates a new core object and returns a shared pointer to it.
+	 *
+	 * @note	
+	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
+	 * them manually.
+	 */
+	template<class Type, class... Args>
+	std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
+	{
+		return std::shared_ptr<Type>(bs_new<Type, GenAlloc>(std::forward<Args>(args)...),
+			&CoreObject::_delete<Type, GenAlloc>, StdAlloc<Type, GenAlloc>());
+	}
+
+	/**
+	 * Creates a core object shared pointer using a previously constructed object.
+	 *
+	 * @note	
+	 * All core thread object shared pointers must be created using this method or its overloads and you should not create 
+	 * them manually.
+	 */
+	template<class Type, class MainAlloc = GenAlloc, class PtrDataAlloc = GenAlloc>
+	std::shared_ptr<Type> bs_core_ptr(Type* data)
+	{
+		return std::shared_ptr<Type>(data, &CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());  
+	}
+
+	/** @} */
+}
+

+ 95 - 93
Source/BansheeCore/Include/BsCoreObjectCore.h

@@ -1,93 +1,95 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsAsyncOp.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup CoreThread
-	 *  @{
-	 */
-
-	/**
-	 * Represents counterpart of a CoreObject that is meant to be used specifically on the core thread. 
-	 *
-	 * @note	Core thread only.
-	 * @note	Different CoreObject implementations should implement this class for their own needs.
-	 */
-	class BS_CORE_EXPORT CoreObjectCore
-	{
-	protected:
-		/** Values that represent current state of the object */
-		enum Flags
-		{
-			CGCO_INITIALIZED = 0x01, /**< Object has been initialized and can be used. */
-			CGCO_SCHEDULED_FOR_INIT = 0x02 /**< Object has been scheduled for initialization but core thread has not completed it yet. */
-		};
-
-	public:
-		CoreObjectCore();
-		virtual ~CoreObjectCore();
-
-		/**	Called on the core thread when the object is first created. */
-		virtual void initialize();
-
-		/** Returns a shared_ptr version of "this" pointer. */
-		SPtr<CoreObjectCore> getThisPtr() const { return mThis.lock(); }
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Sets a shared this pointer to this object. This MUST be called immediately after construction.
-		 *
-		 * @note	Internal method.
-		 * @note	Called automatically by the factory creation methods so user should not call this manually.
-		 */
-		void _setThisPtr(std::shared_ptr<CoreObjectCore> ptrThis);
-
-		/** @endcond */
-
-	protected:
-		friend class CoreObjectManager;
-		friend class CoreObject;
-
-		/**
-		 * Update internal data from provided memory buffer that was populated with data from the sim thread.
-		 *
-		 * @note	
-		 * This generally happens at the start of a core thread frame. Data used was recorded on the previous sim thread 
-		 * frame.
-		 */
-		virtual void syncToCore(const CoreSyncData& data) { }
-
-		/**
-		 * Blocks the current thread until the resource is fully initialized.
-		 * 			
-		 * @note	
-		 * If you call this without calling initialize first a deadlock will occur. You should not call this from core thread.
-		 */
-		void synchronize();
-
-		/**
-		 * Returns true if the object has been properly initialized. Methods are not allowed to be called on the object
-		 * until it is initialized.
-		 */
-		bool isInitialized() const { return (mFlags & CGCO_INITIALIZED) != 0; }
-		bool isScheduledToBeInitialized() const { return (mFlags & CGCO_SCHEDULED_FOR_INIT) != 0; }
-
-		void setIsInitialized(bool initialized) { mFlags = initialized ? mFlags | CGCO_INITIALIZED : mFlags & ~CGCO_INITIALIZED; }
-		void setScheduledToBeInitialized(bool scheduled) { mFlags = scheduled ? mFlags | CGCO_SCHEDULED_FOR_INIT : mFlags & ~CGCO_SCHEDULED_FOR_INIT; }
-
-		volatile UINT8 mFlags;
-		std::weak_ptr<CoreObjectCore> mThis;
-
-		BS_STATIC_THREAD_SYNCHRONISER(mCoreGpuObjectLoadedCondition)
-		BS_STATIC_MUTEX(mCoreGpuObjectLoadedMutex)
-	};
-
-	/** @} */
-}
-
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsAsyncOp.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup CoreThread
+	 *  @{
+	 */
+
+	/**
+	 * Represents counterpart of a CoreObject that is meant to be used specifically on the core thread. 
+	 *
+	 * @note	Core thread only.
+	 * @note	Different CoreObject implementations should implement this class for their own needs.
+	 */
+	class BS_CORE_EXPORT CoreObjectCore
+	{
+	protected:
+		/** Values that represent current state of the object */
+		enum Flags
+		{
+			CGCO_INITIALIZED = 0x01, /**< Object has been initialized and can be used. */
+			CGCO_SCHEDULED_FOR_INIT = 0x02 /**< Object has been scheduled for initialization but core thread has not completed it yet. */
+		};
+
+	public:
+		CoreObjectCore();
+		virtual ~CoreObjectCore();
+
+		/**	Called on the core thread when the object is first created. */
+		virtual void initialize();
+
+		/** Returns a shared_ptr version of "this" pointer. */
+		SPtr<CoreObjectCore> getThisPtr() const { return mThis.lock(); }
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Sets a shared this pointer to this object. This MUST be called immediately after construction.
+		 *
+		 * @note	Internal method.
+		 * @note	Called automatically by the factory creation methods so user should not call this manually.
+		 */
+		void _setThisPtr(std::shared_ptr<CoreObjectCore> ptrThis);
+
+		/** @} */
+
+	protected:
+		friend class CoreObjectManager;
+		friend class CoreObject;
+
+		/**
+		 * Update internal data from provided memory buffer that was populated with data from the sim thread.
+		 *
+		 * @note	
+		 * This generally happens at the start of a core thread frame. Data used was recorded on the previous sim thread 
+		 * frame.
+		 */
+		virtual void syncToCore(const CoreSyncData& data) { }
+
+		/**
+		 * Blocks the current thread until the resource is fully initialized.
+		 * 			
+		 * @note	
+		 * If you call this without calling initialize first a deadlock will occur. You should not call this from core thread.
+		 */
+		void synchronize();
+
+		/**
+		 * Returns true if the object has been properly initialized. Methods are not allowed to be called on the object
+		 * until it is initialized.
+		 */
+		bool isInitialized() const { return (mFlags & CGCO_INITIALIZED) != 0; }
+		bool isScheduledToBeInitialized() const { return (mFlags & CGCO_SCHEDULED_FOR_INIT) != 0; }
+
+		void setIsInitialized(bool initialized) { mFlags = initialized ? mFlags | CGCO_INITIALIZED : mFlags & ~CGCO_INITIALIZED; }
+		void setScheduledToBeInitialized(bool scheduled) { mFlags = scheduled ? mFlags | CGCO_SCHEDULED_FOR_INIT : mFlags & ~CGCO_SCHEDULED_FOR_INIT; }
+
+		volatile UINT8 mFlags;
+		std::weak_ptr<CoreObjectCore> mThis;
+
+		BS_STATIC_THREAD_SYNCHRONISER(mCoreGpuObjectLoadedCondition)
+		BS_STATIC_MUTEX(mCoreGpuObjectLoadedMutex)
+	};
+
+	/** @} */
+}
+

+ 7 - 2
Source/BansheeCore/Include/BsCorePrerequisites.h

@@ -4,6 +4,10 @@
 
 #include "BsPrerequisitesUtil.h"
 
+/** @addtogroup Layers
+ *  @{
+ */
+
 /** @defgroup Core Core
  *	Second lowest layer that provides some very game-specific modules tied into a coherent whole, but it tries to be very 
  *  generic and offer something that every engine might need instead of focusing on very specialized techniques.
@@ -31,7 +35,7 @@
  */
 
 /** @defgroup Platform Platform
- *	Functionality specific for some platform (e.g. Windows, Mac).
+ *	Functionality specific for some platform (for example Windows, Mac).
  */
 
  /** @defgroup Profiling Profiling
@@ -39,7 +43,7 @@
   */
 
 /** @defgroup RenderAPI RenderAPI
-  *	Functionality for interacting with underlying render API (e.g. DirectX, OpenGL).
+  *	Functionality for interacting with underlying render API (for example DirectX, OpenGL).
   */
 
 /** @defgroup Renderer Renderer
@@ -79,6 +83,7 @@
  */
 
 /** @} */
+/** @} */
 
 #define BS_MAX_MULTIPLE_RENDER_TARGETS 8
 #define BS_FORCE_SINGLETHREADED_RENDERING 0

+ 1 - 1
Source/BansheeCore/Include/BsCoreSceneManager.h

@@ -53,7 +53,7 @@ namespace BansheeEngine
 		 *
 		 * @note	
 		 * After you add a node in the scene manager, it takes ownership of its memory and is responsible for releasing it.
-		 * Do NOT add nodes that have already been added (i.e. if you just want to change their parent). Normally this 
+		 * Do NOT add nodes that have already been added (if you just want to change their parent). Normally this 
 		 * method will only be called by SceneObject.
 		 */
 		void registerNewSO(const HSceneObject& node);

+ 185 - 185
Source/BansheeCore/Include/BsD6Joint.h

@@ -1,186 +1,186 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsJoint.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** 
-	 * Represents the most customizable type of joint. This joint type can be used to create all other built-in joint 
-	 * types, and to design your own custom ones, but is less intuitive to use. Allows a specification of a linear 
-	 * constraint (e.g. for slider), twist constraint (rotating around X) and swing constraint (rotating around Y and Z).
-	 * It also allows you to constrain limits to only specific axes or completely lock specific axes.
-	 */
-	class BS_CORE_EXPORT D6Joint : public Joint
-	{
-	public:
-		/** Specifies axes that the D6 joint can constrain motion on. */
-		enum class Axis
-		{
-			X, /**< Movement on the X axis. */
-			Y, /**< Movement on the Y axis. */
-			Z, /**< Movement on the Z axis. */
-			Twist, /**< Rotation around the X axis. */
-			SwingY, /**< Rotation around the Y axis. */
-			SwingZ, /**< Rotation around the Z axis. */
-			Count
-		};
-
-		/** Specifies type of constraint placed on a specific axis. */
-		enum class Motion
-		{
-			Locked, /**< Axis is immovable. */
-			Limited, /**< Axis will be constrained by the specified limits. */
-			Free, /**< Axis will not be constrained. */
-			Count
-		};
-
-		/** Type of drives that can be used for moving or rotating bodies attached to the joint. */
-		enum class DriveType
-		{
-			X, /**< Linear movement on the X axis using the linear drive model. */
-			Y, /**< Linear movement on the Y axis using the linear drive model. */
-			Z, /**< Linear movement on the Z axis using the linear drive model. */
-			/**
-			 * Rotation around the Y axis using the twist/swing angular drive model. Should not be used together with 
-			 * SLERP mode. 
-			 */
-			Swing, 
-			/** 
-			 * Rotation around the Z axis using the twist/swing angular drive model. Should not be used together with 
-			 * SLERP mode. 
-			 */
-			Twist,
-			/** 
-			 * Rotation using spherical linear interpolation. Uses the SLERP angular drive mode which performs rotation
-			 * by interpolating the quaternion values directly over the shortest path (applies to all three axes, which
-			 * they all must be unlocked).
-			 */
-			SLERP, 
-			Count
-		};
-
-		/** 
-		 * Specifies parameters for a drive that will attempt to move the joint bodies to the specified drive position and
-		 * velocity.
-		 */
-		struct Drive
-		{
-			bool operator==(const Drive& other) const
-			{
-				return stiffness == other.stiffness && damping == other.damping && forceLimit == other.forceLimit &&
-					acceleration == other.acceleration;
-			}
-
-			/** Spring strength. Force proportional to the position error. */
-			float stiffness = 0.0f;
-
-			/** Damping strength. Force propertional to the velocity error. */
-			float damping = 0.0f;
-
-			/** Maximum force the drive can apply. */
-			float forceLimit = FLT_MAX;
-
-			/** 
-			 * If true the drive will generate acceleration instead of forces. Acceleration drives are easier to tune as
-			 * they account for the masses of the actors to which the joint is attached.
-			 */
-			bool acceleration = false;
-		};
-
-	public:
-		virtual ~D6Joint() { }
-
-		/** 
-		 * Returns motion constraint for the specified axis. 
-		 *
-		 * @see	setMotion
-		 */
-		virtual Motion getMotion(Axis axis) const = 0;
-
-		/** 
-		 * Allows you to constrain motion of the specified axis. Be aware that when setting drives for a specific axis
-		 * you must also take care not to constrain its motion in a conflicting way (e.g. you cannot add a drive that
-		 * moves the joint on X axis, and then lock the X axis).
-		 *
-		 * Unlocking translations degrees of freedom allows the bodies to move along the subset of the unlocked axes.
-		 * (e.g. unlocking just one translational axis is the equivalent of a slider joint.)
-		 *
-		 * Angular degrees of freedom are partitioned as twist (around X axis) and swing (around Y and Z axes). Different
-		 * effects can be achieves by unlocking their various combinations: 
-		 *  - If a single degree of angular freedom is unlocked it should be the twist degree as it has extra options for
-		 *    that case (e.g. for a hinge joint).
-		 *  - If both swing degrees are unlocked but twist is locked the result is a zero-twist joint. 
-		 *  - If one swing and one twist degree of freedom are unlocked the result is a zero-swing joint (e.g. an arm
-		 *    attached at the elbow)
-		 *  - If all angular degrees of freedom are unlocked the result is the same as the spherical joint.
-		 */
-		virtual void setMotion(Axis axis, Motion motion) = 0;
-
-		/** Returns the current rotation of the joint around the X axis. */
-		virtual Radian getTwist() const = 0;
-
-		/** Returns the current rotation of the joint around the Y axis. */
-		virtual Radian getSwingY() const = 0;
-
-		/** Returns the current rotation of the joint around the Z axis. */
-		virtual Radian getSwingZ() const = 0;
-
-		/** Returns the linear limit used for constraining translation degrees of freedom. */
-		virtual LimitLinear getLimitLinear() const = 0;
-
-		/** Sets the linear limit used for constraining translation degrees of freedom. */
-		virtual void setLimitLinear(const LimitLinear& limit) = 0;
-		
-		/** Returns the angular limit used for constraining the twist (rotation around X) degree of freedom. */
-		virtual LimitAngularRange getLimitTwist() const = 0;
-
-		/** Sets the angular limit used for constraining the twist (rotation around X) degree of freedom. */
-		virtual void setLimitTwist(const LimitAngularRange& limit) = 0;
-
-		/** Returns the cone limit used for constraining the swing (rotation around Y and Z) degree of freedom. */
-		virtual LimitConeRange getLimitSwing() const = 0;
-
-		/** Sets the cone limit used for constraining the swing (rotation around Y and Z) degree of freedom. */
-		virtual void setLimitSwing(const LimitConeRange& limit) = 0;
-	
-		/**
-		 * Returns a drive that will attempt to move the specified degree(s) of freedom to the wanted position and velocity. 
-		 */
-		virtual Drive getDrive(DriveType type) const = 0;
-
-		/**
-		 * Sets a drive that will attempt to move the specified degree(s) of freedom to the wanted position and velocity. 
-		 */
-		virtual void setDrive(DriveType type, const Drive& drive) = 0;
-
-		/** Returns the drive's target position relative to the joint's first body. */
-		virtual Vector3 getDrivePosition() const = 0;
-
-		/** Returns the drive's target rotation relative to the joint's first body. */
-		virtual Quaternion getDriveRotation() const = 0;
-
-		/** Sets the drive's target position and rotation relative to the joint's first body. */
-		virtual void setDriveTransform(const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** Returns the drive's target linear velocity. */
-		virtual Vector3 getDriveLinearVelocity() const = 0;
-
-		/** Returns the drive's target angular velocity. */
-		virtual Vector3 getDriveAngularVelocity() const = 0;
-
-		/** Sets the drive's target linear and angular velocities. */
-		virtual void setDriveVelocity(const Vector3& linear, const Vector3& angular) = 0;
-
-		/** Creates a new D6 joint. */
-		static SPtr<D6Joint> create();
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsJoint.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/** 
+	 * Represents the most customizable type of joint. This joint type can be used to create all other built-in joint 
+	 * types, and to design your own custom ones, but is less intuitive to use. Allows a specification of a linear 
+	 * constraint (for example for slider), twist constraint (rotating around X) and swing constraint (rotating around Y and
+	 * Z). It also allows you to constrain limits to only specific axes or completely lock specific axes.
+	 */
+	class BS_CORE_EXPORT D6Joint : public Joint
+	{
+	public:
+		/** Specifies axes that the D6 joint can constrain motion on. */
+		enum class Axis
+		{
+			X, /**< Movement on the X axis. */
+			Y, /**< Movement on the Y axis. */
+			Z, /**< Movement on the Z axis. */
+			Twist, /**< Rotation around the X axis. */
+			SwingY, /**< Rotation around the Y axis. */
+			SwingZ, /**< Rotation around the Z axis. */
+			Count
+		};
+
+		/** Specifies type of constraint placed on a specific axis. */
+		enum class Motion
+		{
+			Locked, /**< Axis is immovable. */
+			Limited, /**< Axis will be constrained by the specified limits. */
+			Free, /**< Axis will not be constrained. */
+			Count
+		};
+
+		/** Type of drives that can be used for moving or rotating bodies attached to the joint. */
+		enum class DriveType
+		{
+			X, /**< Linear movement on the X axis using the linear drive model. */
+			Y, /**< Linear movement on the Y axis using the linear drive model. */
+			Z, /**< Linear movement on the Z axis using the linear drive model. */
+			/**
+			 * Rotation around the Y axis using the twist/swing angular drive model. Should not be used together with 
+			 * SLERP mode. 
+			 */
+			Swing, 
+			/** 
+			 * Rotation around the Z axis using the twist/swing angular drive model. Should not be used together with 
+			 * SLERP mode. 
+			 */
+			Twist,
+			/** 
+			 * Rotation using spherical linear interpolation. Uses the SLERP angular drive mode which performs rotation
+			 * by interpolating the quaternion values directly over the shortest path (applies to all three axes, which
+			 * they all must be unlocked).
+			 */
+			SLERP, 
+			Count
+		};
+
+		/** 
+		 * Specifies parameters for a drive that will attempt to move the joint bodies to the specified drive position and
+		 * velocity.
+		 */
+		struct Drive
+		{
+			bool operator==(const Drive& other) const
+			{
+				return stiffness == other.stiffness && damping == other.damping && forceLimit == other.forceLimit &&
+					acceleration == other.acceleration;
+			}
+
+			/** Spring strength. Force proportional to the position error. */
+			float stiffness = 0.0f;
+
+			/** Damping strength. Force propertional to the velocity error. */
+			float damping = 0.0f;
+
+			/** Maximum force the drive can apply. */
+			float forceLimit = FLT_MAX;
+
+			/** 
+			 * If true the drive will generate acceleration instead of forces. Acceleration drives are easier to tune as
+			 * they account for the masses of the actors to which the joint is attached.
+			 */
+			bool acceleration = false;
+		};
+
+	public:
+		virtual ~D6Joint() { }
+
+		/** 
+		 * Returns motion constraint for the specified axis. 
+		 *
+		 * @see	setMotion
+		 */
+		virtual Motion getMotion(Axis axis) const = 0;
+
+		/** 
+		 * Allows you to constrain motion of the specified axis. Be aware that when setting drives for a specific axis
+		 * you must also take care not to constrain its motion in a conflicting way (for example you cannot add a drive that
+		 * moves the joint on X axis, and then lock the X axis).
+		 *
+		 * Unlocking translations degrees of freedom allows the bodies to move along the subset of the unlocked axes.
+		 * (for example unlocking just one translational axis is the equivalent of a slider joint.)
+		 *
+		 * Angular degrees of freedom are partitioned as twist (around X axis) and swing (around Y and Z axes). Different
+		 * effects can be achieves by unlocking their various combinations: 
+		 *  - If a single degree of angular freedom is unlocked it should be the twist degree as it has extra options for
+		 *    that case (for example for a hinge joint).
+		 *  - If both swing degrees are unlocked but twist is locked the result is a zero-twist joint. 
+		 *  - If one swing and one twist degree of freedom are unlocked the result is a zero-swing joint (for example an arm
+		 *    attached at the elbow)
+		 *  - If all angular degrees of freedom are unlocked the result is the same as the spherical joint.
+		 */
+		virtual void setMotion(Axis axis, Motion motion) = 0;
+
+		/** Returns the current rotation of the joint around the X axis. */
+		virtual Radian getTwist() const = 0;
+
+		/** Returns the current rotation of the joint around the Y axis. */
+		virtual Radian getSwingY() const = 0;
+
+		/** Returns the current rotation of the joint around the Z axis. */
+		virtual Radian getSwingZ() const = 0;
+
+		/** Returns the linear limit used for constraining translation degrees of freedom. */
+		virtual LimitLinear getLimitLinear() const = 0;
+
+		/** Sets the linear limit used for constraining translation degrees of freedom. */
+		virtual void setLimitLinear(const LimitLinear& limit) = 0;
+		
+		/** Returns the angular limit used for constraining the twist (rotation around X) degree of freedom. */
+		virtual LimitAngularRange getLimitTwist() const = 0;
+
+		/** Sets the angular limit used for constraining the twist (rotation around X) degree of freedom. */
+		virtual void setLimitTwist(const LimitAngularRange& limit) = 0;
+
+		/** Returns the cone limit used for constraining the swing (rotation around Y and Z) degree of freedom. */
+		virtual LimitConeRange getLimitSwing() const = 0;
+
+		/** Sets the cone limit used for constraining the swing (rotation around Y and Z) degree of freedom. */
+		virtual void setLimitSwing(const LimitConeRange& limit) = 0;
+	
+		/**
+		 * Returns a drive that will attempt to move the specified degree(s) of freedom to the wanted position and velocity. 
+		 */
+		virtual Drive getDrive(DriveType type) const = 0;
+
+		/**
+		 * Sets a drive that will attempt to move the specified degree(s) of freedom to the wanted position and velocity. 
+		 */
+		virtual void setDrive(DriveType type, const Drive& drive) = 0;
+
+		/** Returns the drive's target position relative to the joint's first body. */
+		virtual Vector3 getDrivePosition() const = 0;
+
+		/** Returns the drive's target rotation relative to the joint's first body. */
+		virtual Quaternion getDriveRotation() const = 0;
+
+		/** Sets the drive's target position and rotation relative to the joint's first body. */
+		virtual void setDriveTransform(const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** Returns the drive's target linear velocity. */
+		virtual Vector3 getDriveLinearVelocity() const = 0;
+
+		/** Returns the drive's target angular velocity. */
+		virtual Vector3 getDriveAngularVelocity() const = 0;
+
+		/** Sets the drive's target linear and angular velocities. */
+		virtual void setDriveVelocity(const Vector3& linear, const Vector3& angular) = 0;
+
+		/** Creates a new D6 joint. */
+		static SPtr<D6Joint> create();
+	};
+
+	/** @} */
 }

+ 1 - 1
Source/BansheeCore/Include/BsFCollider.h

@@ -30,7 +30,7 @@ namespace BansheeEngine
 		virtual void setTransform(const Vector3& pos, const Quaternion& rotation) = 0;
 
 		/** 
-		 * Enables/disables a collider as a trigger. A trigger will not be used for collisions (i.e. objects will pass 
+		 * Enables/disables a collider as a trigger. A trigger will not be used for collisions (objects will pass 
 		 * through it), but collision events will still be reported. 
 		 */
 		virtual void setIsTrigger(bool value) = 0;

+ 76 - 76
Source/BansheeCore/Include/BsFJoint.h

@@ -1,77 +1,77 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsVector3.h"
-#include "BsQuaternion.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** Specifies first or second body referenced by a Joint. */
-	enum class JointBody
-	{
-		A, B
-	};
-
-	/** @cond INTERNAL */
-
-	/** Provides common functionality used by all Joint types. */
-	class BS_CORE_EXPORT FJoint
-	{
-	public:
-		virtual ~FJoint() { }
-
-		/** Returns one of the bodies managed by the joint. */
-		virtual Rigidbody* getBody(JointBody body) const = 0;
-
-		/** Sets a body managed by the joint. One of the bodies must be movable (i.e. non-kinematic). */
-		virtual void setBody(JointBody body, Rigidbody* value) = 0;
-
-		/** Returns the position relative to the body, at which the body is anchored to the joint. */
-		virtual Vector3 getPosition(JointBody body) const = 0;
-
-		/** Returns the rotation relative to the body, at which the body is anchored to the joint. */
-		virtual Quaternion getRotation(JointBody body) const = 0;
-
-		/** Sets the position and rotation relative to the body, at which the body is anchored to the joint.  */
-		virtual void setTransform(JointBody body, const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** 
-		 * Returns the maximum force the joint can apply before breaking. Broken joints no longer participate in physics 
-		 * simulation. 
-		 */
-		virtual float getBreakForce() const = 0;
-
-		/** 
-		 * Sets the maximum force the joint can apply before breaking. Broken joints no longer participate in physics 
-		 * simulation. 
-		 */
-		virtual void setBreakForce(float force) = 0;
-
-		/** 
-		 * Returns the maximum torque the joint can apply before breaking. Broken joints no longer participate in physics 
-		 * simulation. 
-		 */
-		virtual float getBreakTorque() const = 0;
-
-		/** 
-		 * Sets the maximum torque the joint can apply before breaking. Broken joints no longer participate in physics 
-		 * simulation. 
-		 */
-		virtual void setBreakTorque(float torque) = 0;
-
-		/** Checks whether collisions between the two bodies managed by the joint are enabled. */
-		virtual bool getEnableCollision() const = 0;
-
-		/** Sets whether collision between the two bodies managed by the joint are enabled. */
-		virtual void setEnableCollision(bool value) = 0;
-	};
-
-	/** @endcond */
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsVector3.h"
+#include "BsQuaternion.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/** Specifies first or second body referenced by a Joint. */
+	enum class JointBody
+	{
+		A, B
+	};
+
+	/** @cond INTERNAL */
+
+	/** Provides common functionality used by all Joint types. */
+	class BS_CORE_EXPORT FJoint
+	{
+	public:
+		virtual ~FJoint() { }
+
+		/** Returns one of the bodies managed by the joint. */
+		virtual Rigidbody* getBody(JointBody body) const = 0;
+
+		/** Sets a body managed by the joint. One of the bodies must be movable (non-kinematic). */
+		virtual void setBody(JointBody body, Rigidbody* value) = 0;
+
+		/** Returns the position relative to the body, at which the body is anchored to the joint. */
+		virtual Vector3 getPosition(JointBody body) const = 0;
+
+		/** Returns the rotation relative to the body, at which the body is anchored to the joint. */
+		virtual Quaternion getRotation(JointBody body) const = 0;
+
+		/** Sets the position and rotation relative to the body, at which the body is anchored to the joint.  */
+		virtual void setTransform(JointBody body, const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** 
+		 * Returns the maximum force the joint can apply before breaking. Broken joints no longer participate in physics 
+		 * simulation. 
+		 */
+		virtual float getBreakForce() const = 0;
+
+		/** 
+		 * Sets the maximum force the joint can apply before breaking. Broken joints no longer participate in physics 
+		 * simulation. 
+		 */
+		virtual void setBreakForce(float force) = 0;
+
+		/** 
+		 * Returns the maximum torque the joint can apply before breaking. Broken joints no longer participate in physics 
+		 * simulation. 
+		 */
+		virtual float getBreakTorque() const = 0;
+
+		/** 
+		 * Sets the maximum torque the joint can apply before breaking. Broken joints no longer participate in physics 
+		 * simulation. 
+		 */
+		virtual void setBreakTorque(float torque) = 0;
+
+		/** Checks whether collisions between the two bodies managed by the joint are enabled. */
+		virtual bool getEnableCollision() const = 0;
+
+		/** Sets whether collision between the two bodies managed by the joint are enabled. */
+		virtual void setEnableCollision(bool value) = 0;
+	};
+
+	/** @endcond */
+	/** @} */
 }

+ 99 - 97
Source/BansheeCore/Include/BsFont.h

@@ -1,98 +1,100 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsResource.h"
-#include "BsFontDesc.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Text
-	 *  @{
-	 */
-
-	/**	Contains textures and data about every character for a bitmap font of a specific size. */
-	struct BS_CORE_EXPORT FontBitmap : public IReflectable
-	{
-		/**	Returns a character description for the character with the specified Unicode key. */
-		const CHAR_DESC& getCharDesc(UINT32 charId) const;
-
-		UINT32 size; /**< Font size for which the data is contained. */
-		FONT_DESC fontDesc; /**< Font description containing per-character and general font data. */
-		Vector<HTexture> texturePages; /**< Textures in which the character's pixels are stored. */
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class FontBitmapRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	// TODO - When saved on disk font currently stores a copy of the texture pages. This should be acceptable
-	// if you import a new TrueType or OpenType font since the texture will be generated on the spot
-	// but if you use a bitmap texture to initialize the font manually, then you will potentially have duplicate textures.
-	// Also, changing the source texture will not automatically update the font because there is no direct link between them.
-	// -- This is probably not a large problem, but it is something to keep an eye out.
-
-	/**	Font resource containing data about textual characters and how to render text. */
-	class BS_CORE_EXPORT Font : public Resource
-	{
-	public:
-		virtual ~Font();
-
-		/**
-		 * Returns font bitmap for a specific size if it exists, null otherwise.
-		 *
-		 * @param[in]	size	Size of the bitmap in points.
-		 */
-		SPtr<const FontBitmap> getBitmap(UINT32 size) const;
-
-		/**	Finds the available font bitmap size closest to the provided size. */
-		INT32 getClosestSize(UINT32 size) const;
-
-		/**	Creates a new font from the provided per-size font data. */
-		static HFont create(const Vector<SPtr<FontBitmap>>& fontInitData);
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Initializes the font with specified per-size font data.
-		 *
-		 * @note	Internal method. Factory methods will call this automatically for you.
-		 */
-		void initialize(const Vector<SPtr<FontBitmap>>& fontData);
-
-		/** Creates a new font as a pointer instead of a resource handle. */
-		static FontPtr _createPtr(const Vector<SPtr<FontBitmap>>& fontInitData);
-
-		/** @endcond */
-
-	protected:
-		friend class FontManager;
-
-		Font();
-
-		/** @copydoc Resource::getResourceDependencies */
-		void getResourceDependencies(FrameVector<HResource>& dependencies) const override;
-
-		/** @copydoc CoreObject::getCoreDependencies */
-		void getCoreDependencies(Vector<CoreObject*>& dependencies) override;
-
-	private:
-		Map<UINT32, SPtr<FontBitmap>> mFontDataPerSize;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class FontRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsResource.h"
+#include "BsFontDesc.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Text
+	 *  @{
+	 */
+
+	/**	Contains textures and data about every character for a bitmap font of a specific size. */
+	struct BS_CORE_EXPORT FontBitmap : public IReflectable
+	{
+		/**	Returns a character description for the character with the specified Unicode key. */
+		const CHAR_DESC& getCharDesc(UINT32 charId) const;
+
+		UINT32 size; /**< Font size for which the data is contained. */
+		FONT_DESC fontDesc; /**< Font description containing per-character and general font data. */
+		Vector<HTexture> texturePages; /**< Textures in which the character's pixels are stored. */
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class FontBitmapRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	// TODO - When saved on disk font currently stores a copy of the texture pages. This should be acceptable
+	// if you import a new TrueType or OpenType font since the texture will be generated on the spot
+	// but if you use a bitmap texture to initialize the font manually, then you will potentially have duplicate textures.
+	// Also, changing the source texture will not automatically update the font because there is no direct link between them.
+	// -- This is probably not a large problem, but it is something to keep an eye out.
+
+	/**	Font resource containing data about textual characters and how to render text. */
+	class BS_CORE_EXPORT Font : public Resource
+	{
+	public:
+		virtual ~Font();
+
+		/**
+		 * Returns font bitmap for a specific size if it exists, null otherwise.
+		 *
+		 * @param[in]	size	Size of the bitmap in points.
+		 */
+		SPtr<const FontBitmap> getBitmap(UINT32 size) const;
+
+		/**	Finds the available font bitmap size closest to the provided size. */
+		INT32 getClosestSize(UINT32 size) const;
+
+		/**	Creates a new font from the provided per-size font data. */
+		static HFont create(const Vector<SPtr<FontBitmap>>& fontInitData);
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Initializes the font with specified per-size font data.
+		 *
+		 * @note	Internal method. Factory methods will call this automatically for you.
+		 */
+		void initialize(const Vector<SPtr<FontBitmap>>& fontData);
+
+		/** Creates a new font as a pointer instead of a resource handle. */
+		static FontPtr _createPtr(const Vector<SPtr<FontBitmap>>& fontInitData);
+
+		/** @} */
+
+	protected:
+		friend class FontManager;
+
+		Font();
+
+		/** @copydoc Resource::getResourceDependencies */
+		void getResourceDependencies(FrameVector<HResource>& dependencies) const override;
+
+		/** @copydoc CoreObject::getCoreDependencies */
+		void getCoreDependencies(Vector<CoreObject*>& dependencies) override;
+
+	private:
+		Map<UINT32, SPtr<FontBitmap>> mFontDataPerSize;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class FontRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 171 - 167
Source/BansheeCore/Include/BsFontDesc.h

@@ -1,168 +1,172 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Text
-	 *  @{
-	 */
-
-	/**	Kerning pair representing larger or smaller offset between a specific pair of characters. */
-	struct KerningPair
-	{
-		UINT32 otherCharId;
-		INT32 amount;
-	};
-
-	/**	Describes a single character in a font of a specific size. */
-	struct CHAR_DESC
-	{
-		UINT32 charId; /**< Character ID, corresponding to a Unicode key. */
-		UINT32 page; /**< Index of the texture the character is located on. */
-		float uvX, uvY; /**< Texture coordinates of the character in the page texture. */
-		float uvWidth, uvHeight; /**< Width/height of the character in texture coordinates. */
-		UINT32 width, height; /**< Width/height of the character in pixels. */
-		INT32 xOffset, yOffset; /**< Offset for the visible portion of the character in pixels. */
-		INT32 xAdvance, yAdvance; /**< Determines how much to advance the pen after writing this character, in pixels. */
-
-		Vector<KerningPair> kerningPairs; /**< Pairs that determine if certain character pairs should be closer or father together. e.g. "AV" combination. */
-	};
-
-	/**	Describes a font. */
-	struct FONT_DESC
-	{
-		Map<UINT32, CHAR_DESC> characters; /**< All characters in the font referenced by character ID. */
-		INT32 baselineOffset; /**< Y offset to the baseline on which the characters are placed, in pixels. */
-		UINT32 lineHeight; /**< Height of a single line of the font, in pixels. */
-		CHAR_DESC missingGlyph; /**< Character to use when data for a character is missing. */
-		UINT32 spaceWidth; /**< Width of a space in pixels. */
-	};
-
-	/** @cond SPECIALIZATIONS */
-
-	// Make CHAR_DESC serializable
-	template<> struct RTTIPlainType<CHAR_DESC>
-	{	
-		enum { id = TID_CHAR_DESC }; enum { hasDynamicSize = 1 };
-
-		static void toMemory(const CHAR_DESC& data, char* memory)
-		{ 
-			UINT32 size = getDynamicSize(data);
-
-			memcpy(memory, &size, sizeof(UINT32));
-			memory += sizeof(UINT32);
-
-			memory = rttiWriteElem(data.charId, memory);
-			memory = rttiWriteElem(data.page, memory);
-			memory = rttiWriteElem(data.uvX, memory);
-			memory = rttiWriteElem(data.uvY, memory);
-			memory = rttiWriteElem(data.uvWidth, memory);
-			memory = rttiWriteElem(data.uvHeight, memory);
-			memory = rttiWriteElem(data.width, memory);
-			memory = rttiWriteElem(data.height, memory);
-			memory = rttiWriteElem(data.xOffset, memory);
-			memory = rttiWriteElem(data.yOffset, memory);
-			memory = rttiWriteElem(data.xAdvance, memory);
-			memory = rttiWriteElem(data.yAdvance, memory);
-			memory = rttiWriteElem(data.kerningPairs, memory);
-		}
-
-		static UINT32 fromMemory(CHAR_DESC& data, char* memory)
-		{ 
-			UINT32 size;
-			memcpy(&size, memory, sizeof(UINT32)); 
-			memory += sizeof(UINT32);
-
-			memory = rttiReadElem(data.charId, memory);
-			memory = rttiReadElem(data.page, memory);
-			memory = rttiReadElem(data.uvX, memory);
-			memory = rttiReadElem(data.uvY, memory);
-			memory = rttiReadElem(data.uvWidth, memory);
-			memory = rttiReadElem(data.uvHeight, memory);
-			memory = rttiReadElem(data.width, memory);
-			memory = rttiReadElem(data.height, memory);
-			memory = rttiReadElem(data.xOffset, memory);
-			memory = rttiReadElem(data.yOffset, memory);
-			memory = rttiReadElem(data.xAdvance, memory);
-			memory = rttiReadElem(data.yAdvance, memory);
-			memory = rttiReadElem(data.kerningPairs, memory);
-
-			return size;
-		}
-
-		static UINT32 getDynamicSize(const CHAR_DESC& data)	
-		{ 
-			UINT64 dataSize = sizeof(data.charId)
-				+ sizeof(data.page)
-				+ sizeof(data.uvX)
-				+ sizeof(data.uvY)
-				+ sizeof(data.uvWidth)
-				+ sizeof(data.uvHeight)
-				+ sizeof(data.width)
-				+ sizeof(data.height)
-				+ sizeof(data.xOffset)
-				+ sizeof(data.yOffset)
-				+ sizeof(data.xAdvance)
-				+ sizeof(data.yAdvance)
-				+ RTTIPlainType<Vector<KerningPair>>::getDynamicSize(data.kerningPairs);
-
-			dataSize += sizeof(UINT32);
-
-			return (UINT32)dataSize;
-		}	
-	}; 
-
-	// Make FONT_DESC serializable
-	template<> struct RTTIPlainType<FONT_DESC>
-	{	
-		enum { id = TID_FONT_DESC }; enum { hasDynamicSize = 1 };
-
-		static void toMemory(const FONT_DESC& data, char* memory)
-		{ 
-			UINT32 size = sizeof(UINT32);
-			char* memoryStart = memory;
-			memory += sizeof(UINT32);
-			
-			memory = rttiWriteElem(data.characters, memory, size);
-			memory = rttiWriteElem(data.baselineOffset, memory, size);
-			memory = rttiWriteElem(data.lineHeight, memory, size);
-			memory = rttiWriteElem(data.missingGlyph, memory, size);
-			memory = rttiWriteElem(data.spaceWidth, memory, size);
-
-			memcpy(memoryStart, &size, sizeof(UINT32));
-		}
-
-		static UINT32 fromMemory(FONT_DESC& data, char* memory)
-		{ 
-			UINT32 size;
-			memcpy(&size, memory, sizeof(UINT32)); 
-			memory += sizeof(UINT32);
-
-			memory = rttiReadElem(data.characters, memory);
-			memory = rttiReadElem(data.baselineOffset, memory);
-			memory = rttiReadElem(data.lineHeight, memory);
-			memory = rttiReadElem(data.missingGlyph, memory);
-			memory = rttiReadElem(data.spaceWidth, memory);
-
-			return size;
-		}
-
-		static UINT32 getDynamicSize(const FONT_DESC& data)	
-		{ 
-			UINT64 dataSize = sizeof(UINT32);
-			dataSize += rttiGetElemSize(data.characters);
-			dataSize += rttiGetElemSize(data.baselineOffset);
-			dataSize += rttiGetElemSize(data.lineHeight);
-			dataSize += rttiGetElemSize(data.missingGlyph);
-			dataSize += rttiGetElemSize(data.spaceWidth);
-
-			return (UINT32)dataSize;
-		}	
-	}; 
-
-	/** @endcond */
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Text
+	 *  @{
+	 */
+
+	/**	Kerning pair representing larger or smaller offset between a specific pair of characters. */
+	struct KerningPair
+	{
+		UINT32 otherCharId;
+		INT32 amount;
+	};
+
+	/**	Describes a single character in a font of a specific size. */
+	struct CHAR_DESC
+	{
+		UINT32 charId; /**< Character ID, corresponding to a Unicode key. */
+		UINT32 page; /**< Index of the texture the character is located on. */
+		float uvX, uvY; /**< Texture coordinates of the character in the page texture. */
+		float uvWidth, uvHeight; /**< Width/height of the character in texture coordinates. */
+		UINT32 width, height; /**< Width/height of the character in pixels. */
+		INT32 xOffset, yOffset; /**< Offset for the visible portion of the character in pixels. */
+		INT32 xAdvance, yAdvance; /**< Determines how much to advance the pen after writing this character, in pixels. */
+
+		/**
+		 * Pairs that determine if certain character pairs should be closer or father together. for example "AV"
+		 * combination.
+		 */
+		Vector<KerningPair> kerningPairs;
+	};
+
+	/**	Describes a font. */
+	struct FONT_DESC
+	{
+		Map<UINT32, CHAR_DESC> characters; /**< All characters in the font referenced by character ID. */
+		INT32 baselineOffset; /**< Y offset to the baseline on which the characters are placed, in pixels. */
+		UINT32 lineHeight; /**< Height of a single line of the font, in pixels. */
+		CHAR_DESC missingGlyph; /**< Character to use when data for a character is missing. */
+		UINT32 spaceWidth; /**< Width of a space in pixels. */
+	};
+
+	/** @cond SPECIALIZATIONS */
+
+	// Make CHAR_DESC serializable
+	template<> struct RTTIPlainType<CHAR_DESC>
+	{	
+		enum { id = TID_CHAR_DESC }; enum { hasDynamicSize = 1 };
+
+		static void toMemory(const CHAR_DESC& data, char* memory)
+		{ 
+			UINT32 size = getDynamicSize(data);
+
+			memcpy(memory, &size, sizeof(UINT32));
+			memory += sizeof(UINT32);
+
+			memory = rttiWriteElem(data.charId, memory);
+			memory = rttiWriteElem(data.page, memory);
+			memory = rttiWriteElem(data.uvX, memory);
+			memory = rttiWriteElem(data.uvY, memory);
+			memory = rttiWriteElem(data.uvWidth, memory);
+			memory = rttiWriteElem(data.uvHeight, memory);
+			memory = rttiWriteElem(data.width, memory);
+			memory = rttiWriteElem(data.height, memory);
+			memory = rttiWriteElem(data.xOffset, memory);
+			memory = rttiWriteElem(data.yOffset, memory);
+			memory = rttiWriteElem(data.xAdvance, memory);
+			memory = rttiWriteElem(data.yAdvance, memory);
+			memory = rttiWriteElem(data.kerningPairs, memory);
+		}
+
+		static UINT32 fromMemory(CHAR_DESC& data, char* memory)
+		{ 
+			UINT32 size;
+			memcpy(&size, memory, sizeof(UINT32)); 
+			memory += sizeof(UINT32);
+
+			memory = rttiReadElem(data.charId, memory);
+			memory = rttiReadElem(data.page, memory);
+			memory = rttiReadElem(data.uvX, memory);
+			memory = rttiReadElem(data.uvY, memory);
+			memory = rttiReadElem(data.uvWidth, memory);
+			memory = rttiReadElem(data.uvHeight, memory);
+			memory = rttiReadElem(data.width, memory);
+			memory = rttiReadElem(data.height, memory);
+			memory = rttiReadElem(data.xOffset, memory);
+			memory = rttiReadElem(data.yOffset, memory);
+			memory = rttiReadElem(data.xAdvance, memory);
+			memory = rttiReadElem(data.yAdvance, memory);
+			memory = rttiReadElem(data.kerningPairs, memory);
+
+			return size;
+		}
+
+		static UINT32 getDynamicSize(const CHAR_DESC& data)	
+		{ 
+			UINT64 dataSize = sizeof(data.charId)
+				+ sizeof(data.page)
+				+ sizeof(data.uvX)
+				+ sizeof(data.uvY)
+				+ sizeof(data.uvWidth)
+				+ sizeof(data.uvHeight)
+				+ sizeof(data.width)
+				+ sizeof(data.height)
+				+ sizeof(data.xOffset)
+				+ sizeof(data.yOffset)
+				+ sizeof(data.xAdvance)
+				+ sizeof(data.yAdvance)
+				+ RTTIPlainType<Vector<KerningPair>>::getDynamicSize(data.kerningPairs);
+
+			dataSize += sizeof(UINT32);
+
+			return (UINT32)dataSize;
+		}	
+	}; 
+
+	// Make FONT_DESC serializable
+	template<> struct RTTIPlainType<FONT_DESC>
+	{	
+		enum { id = TID_FONT_DESC }; enum { hasDynamicSize = 1 };
+
+		static void toMemory(const FONT_DESC& data, char* memory)
+		{ 
+			UINT32 size = sizeof(UINT32);
+			char* memoryStart = memory;
+			memory += sizeof(UINT32);
+			
+			memory = rttiWriteElem(data.characters, memory, size);
+			memory = rttiWriteElem(data.baselineOffset, memory, size);
+			memory = rttiWriteElem(data.lineHeight, memory, size);
+			memory = rttiWriteElem(data.missingGlyph, memory, size);
+			memory = rttiWriteElem(data.spaceWidth, memory, size);
+
+			memcpy(memoryStart, &size, sizeof(UINT32));
+		}
+
+		static UINT32 fromMemory(FONT_DESC& data, char* memory)
+		{ 
+			UINT32 size;
+			memcpy(&size, memory, sizeof(UINT32)); 
+			memory += sizeof(UINT32);
+
+			memory = rttiReadElem(data.characters, memory);
+			memory = rttiReadElem(data.baselineOffset, memory);
+			memory = rttiReadElem(data.lineHeight, memory);
+			memory = rttiReadElem(data.missingGlyph, memory);
+			memory = rttiReadElem(data.spaceWidth, memory);
+
+			return size;
+		}
+
+		static UINT32 getDynamicSize(const FONT_DESC& data)	
+		{ 
+			UINT64 dataSize = sizeof(UINT32);
+			dataSize += rttiGetElemSize(data.characters);
+			dataSize += rttiGetElemSize(data.baselineOffset);
+			dataSize += rttiGetElemSize(data.lineHeight);
+			dataSize += rttiGetElemSize(data.missingGlyph);
+			dataSize += rttiGetElemSize(data.spaceWidth);
+
+			return (UINT32)dataSize;
+		}	
+	}; 
+
+	/** @endcond */
+	/** @} */
 }

+ 120 - 118
Source/BansheeCore/Include/BsGameObject.h

@@ -1,119 +1,121 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsIReflectable.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Scene
-	 *  @{
-	 */
-
-	/** @cond INTERNAL */
-
-	/** Flags used for notifying child scene object and components when a transform has been changed. */
-	enum TransformChangedFlags
-	{
-		TCF_None = 0x00, /**< Component will not be notified about any events relating to the transform. */
-		TCF_Transform = 0x01, /**< Component will be notified when the its position, rotation or scale has changed. */
-		TCF_Parent = 0x02 /**< Component will be notified when its parent changes. */
-	};
-
-	/** @endcond */
-
-	/**
-	 * Type of object that can be referenced by a GameObject handle. Each object has an unique ID and is registered with 
-	 * the GameObjectManager.
-	 */
-	class BS_CORE_EXPORT GameObject : public IReflectable
-	{
-	public:
-		GameObject();
-		virtual ~GameObject();
-
-		/**	Returns the unique instance ID of the GameObject. */
-		UINT64 getInstanceId() const { return mInstanceData->mInstanceId; }
-
-		/**
-		 * Returns an ID that identifies a link between this object and its equivalent in the linked prefab. This will be
-		 * -1 if the object has no prefab link, or if the object is specific to the instance and has no prefab equivalent.
-		 */
-		UINT32 getLinkId() const { return mLinkId; }
-
-		/**	Gets the name of the object. */
-		const String& getName() const { return mName; }
-
-		/**	Sets the name of the object. */
-		void setName(const String& name) { mName = name; }
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Marks the object as destroyed. Generally this means the object has been queued for destruction but it hasn't 
-		 * occurred yet.
-		 */
-		void _setIsDestroyed() { mIsDestroyed = true; }
-
-		/**	Checks if the object has been destroyed. */
-		bool _getIsDestroyed() const { return mIsDestroyed; }
-
-		/** Changes the prefab link ID for this object. See getLinkId(). */
-		void _setLinkId(UINT32 id) { mLinkId = id; }
-
-		/**
-		 * Replaces the instance data with another objects instance data. This object will basically become the original 
-		 * owner of the provided instance data as far as all game object handles referencing it are concerned.
-		 *
-		 * @note
-		 * No alive objects should ever be sharing the same instance data. This can be used for restoring dead handles.
-		 */
-		virtual void _setInstanceData(GameObjectInstanceDataPtr& other);
-
-		/** Returns instance data that identifies this GameObject and is used for referencing by game object handles. */
-		virtual GameObjectInstanceDataPtr _getInstanceData() const { return mInstanceData; }
-
-		/** @endcond */
-
-	protected:
-		friend class GameObjectHandleBase;
-		friend class GameObjectManager;
-		friend class PrefabDiff;
-		friend class PrefabUtility;
-
-		/**	Initializes the GameObject after construction. */
-		void initialize(const std::shared_ptr<GameObject>& object, UINT64 instanceId);
-
-		/**
-		 * Destroys this object.
-		 *
-		 * @param[in]	handle		Game object handle to this object.
-		 * @param[in]	immediate	If true, the object will be deallocated and become unusable right away. Otherwise the 
-		 *							deallocation will be delayed to the end of frame (preferred method).
-		 */
-		virtual void destroyInternal(GameObjectHandleBase& handle, bool immediate = false) = 0;
-
-	protected:
-		String mName;
-		UINT32 mLinkId;
-
-	private:
-		friend class Prefab;
-
-		GameObjectInstanceDataPtr mInstanceData;
-		bool mIsDestroyed;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-
-	public:
-		friend class GameObjectRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsIReflectable.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Scene
+	 *  @{
+	 */
+
+	/** @cond INTERNAL */
+
+	/** Flags used for notifying child scene object and components when a transform has been changed. */
+	enum TransformChangedFlags
+	{
+		TCF_None = 0x00, /**< Component will not be notified about any events relating to the transform. */
+		TCF_Transform = 0x01, /**< Component will be notified when the its position, rotation or scale has changed. */
+		TCF_Parent = 0x02 /**< Component will be notified when its parent changes. */
+	};
+
+	/** @endcond */
+
+	/**
+	 * Type of object that can be referenced by a GameObject handle. Each object has an unique ID and is registered with 
+	 * the GameObjectManager.
+	 */
+	class BS_CORE_EXPORT GameObject : public IReflectable
+	{
+	public:
+		GameObject();
+		virtual ~GameObject();
+
+		/**	Returns the unique instance ID of the GameObject. */
+		UINT64 getInstanceId() const { return mInstanceData->mInstanceId; }
+
+		/**
+		 * Returns an ID that identifies a link between this object and its equivalent in the linked prefab. This will be
+		 * -1 if the object has no prefab link, or if the object is specific to the instance and has no prefab equivalent.
+		 */
+		UINT32 getLinkId() const { return mLinkId; }
+
+		/**	Gets the name of the object. */
+		const String& getName() const { return mName; }
+
+		/**	Sets the name of the object. */
+		void setName(const String& name) { mName = name; }
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Marks the object as destroyed. Generally this means the object has been queued for destruction but it hasn't 
+		 * occurred yet.
+		 */
+		void _setIsDestroyed() { mIsDestroyed = true; }
+
+		/**	Checks if the object has been destroyed. */
+		bool _getIsDestroyed() const { return mIsDestroyed; }
+
+		/** Changes the prefab link ID for this object. See getLinkId(). */
+		void _setLinkId(UINT32 id) { mLinkId = id; }
+
+		/**
+		 * Replaces the instance data with another objects instance data. This object will basically become the original 
+		 * owner of the provided instance data as far as all game object handles referencing it are concerned.
+		 *
+		 * @note
+		 * No alive objects should ever be sharing the same instance data. This can be used for restoring dead handles.
+		 */
+		virtual void _setInstanceData(GameObjectInstanceDataPtr& other);
+
+		/** Returns instance data that identifies this GameObject and is used for referencing by game object handles. */
+		virtual GameObjectInstanceDataPtr _getInstanceData() const { return mInstanceData; }
+
+		/** @} */
+
+	protected:
+		friend class GameObjectHandleBase;
+		friend class GameObjectManager;
+		friend class PrefabDiff;
+		friend class PrefabUtility;
+
+		/**	Initializes the GameObject after construction. */
+		void initialize(const std::shared_ptr<GameObject>& object, UINT64 instanceId);
+
+		/**
+		 * Destroys this object.
+		 *
+		 * @param[in]	handle		Game object handle to this object.
+		 * @param[in]	immediate	If true, the object will be deallocated and become unusable right away. Otherwise the 
+		 *							deallocation will be delayed to the end of frame (preferred method).
+		 */
+		virtual void destroyInternal(GameObjectHandleBase& handle, bool immediate = false) = 0;
+
+	protected:
+		String mName;
+		UINT32 mLinkId;
+
+	private:
+		friend class Prefab;
+
+		GameObjectInstanceDataPtr mInstanceData;
+		bool mIsDestroyed;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+
+	public:
+		friend class GameObjectRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 305 - 301
Source/BansheeCore/Include/BsGameObjectHandle.h

@@ -1,302 +1,306 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	class GameObjectManager;
-
-	template <typename T>
-	class GameObjectHandle;
-
-	/** @cond INTERNAL */
-
-	/**	Contains instance data that is held by all GameObject handles. */
-	struct GameObjectInstanceData
-	{
-		GameObjectInstanceData()
-			:mInstanceId(0), object(nullptr)
-		{ }
-
-		std::shared_ptr<GameObject> object;
-		UINT64 mInstanceId;
-	};
-
-	typedef std::shared_ptr<GameObjectInstanceData> GameObjectInstanceDataPtr;
-
-	/**	Internal data shared between GameObject handles. */
-	struct BS_CORE_EXPORT GameObjectHandleData
-	{
-		GameObjectHandleData()
-			:mPtr(nullptr)
-		{ }
-
-		GameObjectHandleData(const std::shared_ptr<GameObjectInstanceData>& ptr)
-		{
-			mPtr = ptr;
-		}
-
-		std::shared_ptr<GameObjectInstanceData> mPtr;
-	};
-
-	/** @endcond */
-
-	/**
-	 * A handle that can point to various types of game objects. It primarily keeps track if the object is still alive, 
-	 * so anything still referencing it doesn't accidentally use it.
-	 * 			
-	 * @note	
-	 * This class exists because references between game objects should be quite loose. For example one game object should
-	 * be able to reference another one without the other one knowing. But if that is the case I also need to handle the
-	 * case when the other object we're referencing has been deleted, and that is the main purpose of this class.	
-	 */
-	class BS_CORE_EXPORT GameObjectHandleBase : public IReflectable
-	{
-	public:
-		GameObjectHandleBase();
-
-		/**
-		 * Returns true if the object the handle is pointing to has been destroyed.
-		 *
-		 * @param[in] checkQueued	Game objects can be queued for destruction but not actually destroyed yet, and still
-		 *							accessible. If this is false this method will return true only if the object is 
-		 *							completely inaccessible (fully destroyed). If this is true this method will return true
-		 *							if object is completely inaccessible or if it is just queued for destruction.
-		 */
-		bool isDestroyed(bool checkQueued = false) const;
-
-		/**	Returns the instance ID of the object the handle is referencing. */
-		UINT64 getInstanceId() const { return mData->mPtr != nullptr ? mData->mPtr->mInstanceId : 0; }
-
-		/**
-		 * Returns pointer to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		GameObject* get() const 
-		{ 
-			throwIfDestroyed();
-
-			return mData->mPtr->object.get(); 
-		}
-
-		/**
-		 * Returns a smart pointer to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		std::shared_ptr<GameObject> getInternalPtr() const
-		{
-			throwIfDestroyed();
-
-			return mData->mPtr->object;
-		}
-
-		/**
-		 * Returns pointer to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		GameObject* operator->() const { return get(); }
-
-		/**
-		 * Returns reference to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		GameObject& operator*() const { return *get(); }
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** Returns internal handle data. */
-		std::shared_ptr<GameObjectHandleData> _getHandleData() const { return mData; }
-
-		/** Resolves a handle to a proper GameObject in case it was created uninitialized. */
-		void _resolve(const GameObjectHandleBase& object);
-
-		/**	Changes the GameObject instance the handle is pointing to. */
-		void _setHandleData(const GameObjectPtr& object);
-
-		/** @endcond */
-
-	protected:
-		friend class GameObjectManager;
-
-		template<class _Ty1, class _Ty2>
-		friend bool operator==(const GameObjectHandle<_Ty1>& _Left, const GameObjectHandle<_Ty2>& _Right);
-
-		GameObjectHandleBase(const std::shared_ptr<GameObject> ptr);
-		GameObjectHandleBase(const std::shared_ptr<GameObjectHandleData>& data);
-		GameObjectHandleBase(std::nullptr_t ptr);
-
-		/**	Throws an exception if the referenced GameObject has been destroyed. */
-		inline void throwIfDestroyed() const;
-		
-		/**	Invalidates the handle signifying the referenced object was destroyed. */
-		void destroy()
-		{
-			// It's important not to clear mData->mPtr as some code might rely
-			// on it. (e.g. for restoring lost handles)
-
-			if (mData->mPtr != nullptr)
-				mData->mPtr->object = nullptr;
-		}
-
-		std::shared_ptr<GameObjectHandleData> mData;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class GameObjectHandleRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
-
-	/** @addtogroup Scene
-	 *  @{
-	 */
-
-	/**
-	 * @copydoc	GameObjectHandleBase
-	 *
-	 * @note	It is important this class contains no data since we often value cast it to its base.
-	 */
-	template <typename T>
-	class GameObjectHandle : public GameObjectHandleBase
-	{
-	public:
-		/**	Constructs a new empty handle. */
-		GameObjectHandle()
-			:GameObjectHandleBase()
-		{	
-			mData = bs_shared_ptr_new<GameObjectHandleData>();
-		}
-
-		/**	Copy constructor from another handle of the same type. */
-		template <typename T1>
-		GameObjectHandle(const GameObjectHandle<T1>& ptr)
-			:GameObjectHandleBase()
-		{ 	
-			mData = ptr._getHandleData();
-		}
-
-		/**	Copy constructor from another handle of the base type. */
-		GameObjectHandle(const GameObjectHandleBase& ptr)
-			:GameObjectHandleBase()
-		{ 	
-			mData = ptr._getHandleData();
-		}
-
-		/**	Invalidates the handle. */
-		GameObjectHandle<T>& operator=(std::nullptr_t ptr)
-		{ 	
-			mData = bs_shared_ptr_new<GameObjectHandleData>();
-
-			return *this;
-		}
-
-		/**	Casts a specific handle to the base handle. */
-		operator GameObjectHandleBase()
-		{
-			GameObjectHandleBase base(mData);
-
-			return base;
-		}
-
-		/**
-		 * Returns a pointer to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		T* get() const 
-		{ 
-			throwIfDestroyed();
-
-			return reinterpret_cast<T*>(mData->mPtr->object.get()); 
-		}
-
-		/**
-		 * Returns a smart pointer to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		std::shared_ptr<T> getInternalPtr() const
-		{
-			throwIfDestroyed();
-
-			return std::static_pointer_cast<T>(mData->mPtr->object);
-		}
-
-		/**
-		 * Returns pointer to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		T* operator->() const { return get(); }
-
-		/**
-		 * Returns reference to the referenced GameObject.
-		 *
-		 * @note	Throws exception if the GameObject was destroyed.
-		 */
-		T& operator*() const { return *get(); }
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		template<class _Ty>
-		struct Bool_struct
-		{
-			int _Member;
-		};
-
-		/**
-		 * Allows direct conversion of handle to bool.
-		 *
-		 * @note	
-		 * This is needed because we can't directly convert to bool since then we can assign pointer to bool and that's 
-		 * weird.
-		 */
-		operator int Bool_struct<T>::*() const
-		{
-			return (((mData->mPtr != nullptr) && (mData->mPtr->object != nullptr)) ? &Bool_struct<T>::_Member : 0);
-		}
-
-		/** @endcond */
-	};
-
-	/**	Casts one GameObject handle type to another. */
-	template<class _Ty1, class _Ty2>
-		GameObjectHandle<_Ty1> static_object_cast(const GameObjectHandle<_Ty2>& other)
-	{	
-		return GameObjectHandle<_Ty1>(other);
-	}
-
-	/** @cond INTERNAL */
-
-	/**	Compares if two handles point to the same GameObject. */
-	template<class _Ty1, class _Ty2>
-	bool operator==(const GameObjectHandle<_Ty1>& _Left, const GameObjectHandle<_Ty2>& _Right)
-	{	
-		return (_Left.mData == nullptr && _Right.mData == nullptr) || 
-			(_Left.mData != nullptr && _Right.mData != nullptr && _Left.getInstanceId() == _Right.getInstanceId());
-	}
-
-	/**	Compares if two handles point to different GameObject%s. */
-	template<class _Ty1, class _Ty2>
-	bool operator!=(const GameObjectHandle<_Ty1>& _Left, const GameObjectHandle<_Ty2>& _Right)
-	{	
-		return (!(_Left == _Right));
-	}
-
-	/** @endcond */
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	class GameObjectManager;
+
+	template <typename T>
+	class GameObjectHandle;
+
+	/** @cond INTERNAL */
+
+	/**	Contains instance data that is held by all GameObject handles. */
+	struct GameObjectInstanceData
+	{
+		GameObjectInstanceData()
+			:mInstanceId(0), object(nullptr)
+		{ }
+
+		std::shared_ptr<GameObject> object;
+		UINT64 mInstanceId;
+	};
+
+	typedef std::shared_ptr<GameObjectInstanceData> GameObjectInstanceDataPtr;
+
+	/**	Internal data shared between GameObject handles. */
+	struct BS_CORE_EXPORT GameObjectHandleData
+	{
+		GameObjectHandleData()
+			:mPtr(nullptr)
+		{ }
+
+		GameObjectHandleData(const std::shared_ptr<GameObjectInstanceData>& ptr)
+		{
+			mPtr = ptr;
+		}
+
+		std::shared_ptr<GameObjectInstanceData> mPtr;
+	};
+
+	/** @endcond */
+
+	/**
+	 * A handle that can point to various types of game objects. It primarily keeps track if the object is still alive, 
+	 * so anything still referencing it doesn't accidentally use it.
+	 * 			
+	 * @note	
+	 * This class exists because references between game objects should be quite loose. For example one game object should
+	 * be able to reference another one without the other one knowing. But if that is the case I also need to handle the
+	 * case when the other object we're referencing has been deleted, and that is the main purpose of this class.	
+	 */
+	class BS_CORE_EXPORT GameObjectHandleBase : public IReflectable
+	{
+	public:
+		GameObjectHandleBase();
+
+		/**
+		 * Returns true if the object the handle is pointing to has been destroyed.
+		 *
+		 * @param[in] checkQueued	Game objects can be queued for destruction but not actually destroyed yet, and still
+		 *							accessible. If this is false this method will return true only if the object is 
+		 *							completely inaccessible (fully destroyed). If this is true this method will return true
+		 *							if object is completely inaccessible or if it is just queued for destruction.
+		 */
+		bool isDestroyed(bool checkQueued = false) const;
+
+		/**	Returns the instance ID of the object the handle is referencing. */
+		UINT64 getInstanceId() const { return mData->mPtr != nullptr ? mData->mPtr->mInstanceId : 0; }
+
+		/**
+		 * Returns pointer to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		GameObject* get() const 
+		{ 
+			throwIfDestroyed();
+
+			return mData->mPtr->object.get(); 
+		}
+
+		/**
+		 * Returns a smart pointer to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		std::shared_ptr<GameObject> getInternalPtr() const
+		{
+			throwIfDestroyed();
+
+			return mData->mPtr->object;
+		}
+
+		/**
+		 * Returns pointer to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		GameObject* operator->() const { return get(); }
+
+		/**
+		 * Returns reference to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		GameObject& operator*() const { return *get(); }
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** Returns internal handle data. */
+		std::shared_ptr<GameObjectHandleData> _getHandleData() const { return mData; }
+
+		/** Resolves a handle to a proper GameObject in case it was created uninitialized. */
+		void _resolve(const GameObjectHandleBase& object);
+
+		/**	Changes the GameObject instance the handle is pointing to. */
+		void _setHandleData(const GameObjectPtr& object);
+
+		/** @} */
+
+	protected:
+		friend class GameObjectManager;
+
+		template<class _Ty1, class _Ty2>
+		friend bool operator==(const GameObjectHandle<_Ty1>& _Left, const GameObjectHandle<_Ty2>& _Right);
+
+		GameObjectHandleBase(const std::shared_ptr<GameObject> ptr);
+		GameObjectHandleBase(const std::shared_ptr<GameObjectHandleData>& data);
+		GameObjectHandleBase(std::nullptr_t ptr);
+
+		/**	Throws an exception if the referenced GameObject has been destroyed. */
+		inline void throwIfDestroyed() const;
+		
+		/**	Invalidates the handle signifying the referenced object was destroyed. */
+		void destroy()
+		{
+			// It's important not to clear mData->mPtr as some code might rely
+			// on it. (for example for restoring lost handles)
+
+			if (mData->mPtr != nullptr)
+				mData->mPtr->object = nullptr;
+		}
+
+		std::shared_ptr<GameObjectHandleData> mData;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class GameObjectHandleRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
+
+	/** @addtogroup Scene
+	 *  @{
+	 */
+
+	/**
+	 * @copydoc	GameObjectHandleBase
+	 *
+	 * @note	It is important this class contains no data since we often value cast it to its base.
+	 */
+	template <typename T>
+	class GameObjectHandle : public GameObjectHandleBase
+	{
+	public:
+		/**	Constructs a new empty handle. */
+		GameObjectHandle()
+			:GameObjectHandleBase()
+		{	
+			mData = bs_shared_ptr_new<GameObjectHandleData>();
+		}
+
+		/**	Copy constructor from another handle of the same type. */
+		template <typename T1>
+		GameObjectHandle(const GameObjectHandle<T1>& ptr)
+			:GameObjectHandleBase()
+		{ 	
+			mData = ptr._getHandleData();
+		}
+
+		/**	Copy constructor from another handle of the base type. */
+		GameObjectHandle(const GameObjectHandleBase& ptr)
+			:GameObjectHandleBase()
+		{ 	
+			mData = ptr._getHandleData();
+		}
+
+		/**	Invalidates the handle. */
+		GameObjectHandle<T>& operator=(std::nullptr_t ptr)
+		{ 	
+			mData = bs_shared_ptr_new<GameObjectHandleData>();
+
+			return *this;
+		}
+
+		/**	Casts a specific handle to the base handle. */
+		operator GameObjectHandleBase()
+		{
+			GameObjectHandleBase base(mData);
+
+			return base;
+		}
+
+		/**
+		 * Returns a pointer to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		T* get() const 
+		{ 
+			throwIfDestroyed();
+
+			return reinterpret_cast<T*>(mData->mPtr->object.get()); 
+		}
+
+		/**
+		 * Returns a smart pointer to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		std::shared_ptr<T> getInternalPtr() const
+		{
+			throwIfDestroyed();
+
+			return std::static_pointer_cast<T>(mData->mPtr->object);
+		}
+
+		/**
+		 * Returns pointer to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		T* operator->() const { return get(); }
+
+		/**
+		 * Returns reference to the referenced GameObject.
+		 *
+		 * @note	Throws exception if the GameObject was destroyed.
+		 */
+		T& operator*() const { return *get(); }
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		template<class _Ty>
+		struct Bool_struct
+		{
+			int _Member;
+		};
+
+		/**
+		 * Allows direct conversion of handle to bool.
+		 *
+		 * @note	
+		 * This is needed because we can't directly convert to bool since then we can assign pointer to bool and that's 
+		 * weird.
+		 */
+		operator int Bool_struct<T>::*() const
+		{
+			return (((mData->mPtr != nullptr) && (mData->mPtr->object != nullptr)) ? &Bool_struct<T>::_Member : 0);
+		}
+
+		/** @} */
+	};
+
+	/**	Casts one GameObject handle type to another. */
+	template<class _Ty1, class _Ty2>
+		GameObjectHandle<_Ty1> static_object_cast(const GameObjectHandle<_Ty2>& other)
+	{	
+		return GameObjectHandle<_Ty1>(other);
+	}
+
+	/** @cond INTERNAL */
+
+	/**	Compares if two handles point to the same GameObject. */
+	template<class _Ty1, class _Ty2>
+	bool operator==(const GameObjectHandle<_Ty1>& _Left, const GameObjectHandle<_Ty2>& _Right)
+	{	
+		return (_Left.mData == nullptr && _Right.mData == nullptr) || 
+			(_Left.mData != nullptr && _Right.mData != nullptr && _Left.getInstanceId() == _Right.getInstanceId());
+	}
+
+	/**	Compares if two handles point to different GameObject%s. */
+	template<class _Ty1, class _Ty2>
+	bool operator!=(const GameObjectHandle<_Ty1>& _Left, const GameObjectHandle<_Ty2>& _Right)
+	{	
+		return (!(_Left == _Right));
+	}
+
+	/** @endcond */
+	/** @} */
 }

+ 56 - 56
Source/BansheeCore/Include/BsGpuParamDesc.h

@@ -1,57 +1,57 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Describes a single GPU program data (e.g. int, float, Vector2) parameter. */
-	struct GpuParamDataDesc
-	{
-		String name;
-		UINT32 elementSize; /**< In multiples of 4 bytes. */
-		UINT32 arraySize;
-		UINT32 arrayElementStride; /**< In multiples of 4 bytes. */
-		GpuParamDataType type;
-
-		UINT32 paramBlockSlot;
-		UINT32 gpuMemOffset; /**< In multiples of 4 bytes, or index for parameters not in a buffer. */
-		UINT32 cpuMemOffset; /**< In multiples of 4 bytes. */
-	};
-
-	/**	Describes a single GPU program object (e.g. texture, sampler state) parameter. */
-	struct GpuParamObjectDesc
-	{
-		String name;
-		GpuParamObjectType type;
-
-		UINT32 slot;
-	};
-
-	/**	Describes a GPU program parameter block (collection of GPU program data parameters). */
-	struct GpuParamBlockDesc
-	{
-		String name;
-		UINT32 slot;
-		UINT32 blockSize; /**< In multiples of 4 bytes. */
-		bool isShareable;
-	};
-
-	/** Contains all parameter information for a GPU program, including data and object parameters, plus parameter blocks. */
-	struct GpuParamDesc
-	{
-		Map<String, GpuParamBlockDesc> paramBlocks;
-		Map<String, GpuParamDataDesc> params;
-
-		Map<String, GpuParamObjectDesc> samplers;
-		Map<String, GpuParamObjectDesc> textures;
-		Map<String, GpuParamObjectDesc> buffers;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Describes a single GPU program data (for example int, float, Vector2) parameter. */
+	struct GpuParamDataDesc
+	{
+		String name;
+		UINT32 elementSize; /**< In multiples of 4 bytes. */
+		UINT32 arraySize;
+		UINT32 arrayElementStride; /**< In multiples of 4 bytes. */
+		GpuParamDataType type;
+
+		UINT32 paramBlockSlot;
+		UINT32 gpuMemOffset; /**< In multiples of 4 bytes, or index for parameters not in a buffer. */
+		UINT32 cpuMemOffset; /**< In multiples of 4 bytes. */
+	};
+
+	/**	Describes a single GPU program object (for example texture, sampler state) parameter. */
+	struct GpuParamObjectDesc
+	{
+		String name;
+		GpuParamObjectType type;
+
+		UINT32 slot;
+	};
+
+	/**	Describes a GPU program parameter block (collection of GPU program data parameters). */
+	struct GpuParamBlockDesc
+	{
+		String name;
+		UINT32 slot;
+		UINT32 blockSize; /**< In multiples of 4 bytes. */
+		bool isShareable;
+	};
+
+	/** Contains all parameter information for a GPU program, including data and object parameters, plus parameter blocks. */
+	struct GpuParamDesc
+	{
+		Map<String, GpuParamBlockDesc> paramBlocks;
+		Map<String, GpuParamDataDesc> params;
+
+		Map<String, GpuParamObjectDesc> samplers;
+		Map<String, GpuParamObjectDesc> textures;
+		Map<String, GpuParamObjectDesc> buffers;
+	};
+
+	/** @} */
 }

+ 245 - 245
Source/BansheeCore/Include/BsGpuProgram.h

@@ -1,246 +1,246 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsCoreObject.h"
-#include "BsIReflectable.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Types of programs that may run on GPU. */
-	enum GpuProgramType
-	{
-		GPT_VERTEX_PROGRAM,
-		GPT_FRAGMENT_PROGRAM,
-		GPT_GEOMETRY_PROGRAM,
-		GPT_DOMAIN_PROGRAM,
-		GPT_HULL_PROGRAM,
-		GPT_COMPUTE_PROGRAM
-	};
-
-	/**	GPU program profiles representing supported feature sets. */
-	enum GpuProgramProfile
-	{
-		GPP_NONE,
-		GPP_FS_1_1,
-		GPP_FS_1_2,
-		GPP_FS_1_3,
-		GPP_FS_1_4,
-		GPP_FS_2_0,
-		GPP_FS_2_x,
-		GPP_FS_2_a,
-		GPP_FS_2_b,
-		GPP_FS_3_0,
-		GPP_FS_3_x,
-		GPP_FS_4_0,
-		GPP_FS_4_1,
-		GPP_FS_5_0,
-		GPP_VS_1_1,
-		GPP_VS_2_0,
-		GPP_VS_2_x,
-		GPP_VS_2_a,
-		GPP_VS_3_0,
-		GPP_VS_4_0,
-		GPP_VS_4_1,
-		GPP_VS_5_0,
-		GPP_GS_4_0,
-		GPP_GS_4_1,
-		GPP_GS_5_0,
-		GPP_HS_5_0,
-		GPP_DS_5_0,
-		GPP_CS_5_0
-	};
-
-	/** Data describing a GpuProgram. */
-	class BS_CORE_EXPORT GpuProgramProperties
-	{
-	public:
-		GpuProgramProperties(const String& source, const String& entryPoint,
-			GpuProgramType gptype, GpuProgramProfile profile);
-
-		virtual ~GpuProgramProperties() { }
-
-        /** Source used for creating this program. */
-        const String& getSource() const { return mSource; }
-        
-		/**	Type of GPU program (e.g. fragment, vertex). */
-        GpuProgramType getType() const { return mType; }
-
-		/**	Profile of the GPU program (e.g. VS_4_0, VS_5_0). */
-		GpuProgramProfile getProfile() const { return mProfile; }
-
-		/**	Name of the program entry method (e.g. "main"). */
-		const String& getEntryPoint() const { return mEntryPoint; }
-
-	protected:
-		friend class GpuProgramRTTI;
-
-		GpuProgramType mType;
-		String mEntryPoint;
-		GpuProgramProfile mProfile;
-		String mSource;
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Core thread version of a GpuProgram.
-	 *
-	 * @note	Core thread only.
-	 */
-	class BS_CORE_EXPORT GpuProgramCore : public CoreObjectCore
-	{
-	public:
-		virtual ~GpuProgramCore() { }
-
-		/** Returns whether this program can be supported on the current renderer and hardware. */
-        virtual bool isSupported() const;
-
-		/** Returns true if shader was successfully compiled. */
-		virtual bool isCompiled() const { return mIsCompiled; }
-
-		/**	Returns an error message returned by the compiler, if the compilation failed. */
-		virtual String getCompileErrorMessage() const { return mCompileError; }
-
-		/**
-		 * Sets whether this geometry program requires adjacency information from the input primitives.
-		 *
-		 * @note	Only relevant for geometry programs.
-		 */
-		virtual void setAdjacencyInfoRequired(bool required) { mNeedsAdjacencyInfo = required; }
-
-		/**
-		 * Returns whether this geometry program requires adjacency information from the input primitives.
-		 *
-		 * @note	Only relevant for geometry programs.
-		 */
-		virtual bool isAdjacencyInfoRequired() const { return mNeedsAdjacencyInfo; }
-
-		/** @copydoc GpuProgram::createParameters */
-		virtual SPtr<GpuParamsCore> createParameters();
-
-		/** @copydoc GpuProgram::getParamDesc */
-		GpuParamDescPtr getParamDesc() const { return mParametersDesc; }
-
-		/**	Returns GPU program input declaration. Only relevant for vertex programs. */
-		SPtr<VertexDeclarationCore> getInputDeclaration() const { return mInputDeclaration; }
-
-		/**	Returns properties that contain information about the GPU program. */
-		const GpuProgramProperties& getProperties() const { return mProperties; }
-
-		/** @copydoc GpuProgram::create */
-		static SPtr<GpuProgramCore> create(const String& source, const String& entryPoint, const String& language, GpuProgramType gptype,
-			GpuProgramProfile profile, bool requiresAdjacency = false);
-
-	protected:
-		GpuProgramCore(const String& source, const String& entryPoint,
-			GpuProgramType gptype, GpuProgramProfile profile, bool isAdjacencyInfoRequired = false);
-
-		/** Returns whether required capabilities for this program is supported. */
-		bool isRequiredCapabilitiesSupported() const;
-
-		bool mNeedsAdjacencyInfo;
-
-		bool mIsCompiled;
-		String mCompileError;
-
-		GpuParamDescPtr mParametersDesc;
-		SPtr<VertexDeclarationCore> mInputDeclaration;
-		GpuProgramProperties mProperties;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Contains a GPU program such as vertex or fragment program which gets compiled from the provided source code.
-	 *
-	 * @note	Sim thread only.
-	 */
-	class BS_CORE_EXPORT GpuProgram : public IReflectable, public CoreObject
-	{
-	public:
-		virtual ~GpuProgram() { }
-
-		/**
-		 * Returns true if shader was successfully compiled. 
-		 *
-		 * @note	Only valid after core thread has initialized the program.
-		 */
-		bool isCompiled() const;
-
-		/**
-		 * Returns an error message returned by the compiler, if the compilation failed.
-		 *
-		 * @note	Only valid after core thread has initialized the program.
-		 */
-		String getCompileErrorMessage() const;
-
-		/**
-		 * Creates a new parameters object compatible with this program definition. You may populate the returned object 
-		 * with actual parameter values and bind it to the pipeline to render an object using those values and this program.
-		 *
-		 * @note	Only valid after core thread has initialized the program.
-		 */
-		GpuParamsPtr createParameters();
-
-		/**
-		 * Returns description of all parameters in this GPU program.
-		 *
-		 * @note	Only valid after core thread has initialized the program.
-		 */
-		GpuParamDescPtr getParamDesc() const;
-
-		/** Retrieves a core implementation of a gpu program usable only from the core thread. */
-		SPtr<GpuProgramCore> getCore() const;
-
-		/** Returns properties that contain information about the GPU program. */
-		const GpuProgramProperties& getProperties() const { return mProperties; }
-
-		/**
-		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
-		 * isCompiled() with return false, and you will be able to retrieve the error message via getCompileErrorMessage().
-		 *
-		 * @param[in]	source				Source code to compile the shader from.
-		 * @param[in]	entryPoint			Name of the entry point function, e.g. "main".
-		 * @param[in]	language			Language the source is written in, e.g. "hlsl" or "glsl".
-		 * @param[in]	gptype				Type of the program, e.g. vertex or fragment.
-		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
-		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
-		 *									program.
-		 */
-		static GpuProgramPtr create(const String& source, const String& entryPoint, const String& language, GpuProgramType gptype,
-			GpuProgramProfile profile, bool requiresAdjacency = false);
-
-	protected:
-		friend class GpuProgramManager;
-
-		GpuProgram(const String& source, const String& entryPoint, const String& language,
-			GpuProgramType gptype, GpuProgramProfile profile, bool isAdjacencyInfoRequired = false);
-
-		/** @copydoc CoreObject::createCore */
-		SPtr<CoreObjectCore> createCore() const;
-
-		/** @copydoc Resource::calculateSize */
-		size_t calculateSize() const { return 0; } // TODO 
-
-	protected:
-		bool mNeedsAdjacencyInfo;
-		String mLanguage;
-		GpuProgramProperties mProperties;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class GpuProgramRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsCoreObject.h"
+#include "BsIReflectable.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Types of programs that may run on GPU. */
+	enum GpuProgramType
+	{
+		GPT_VERTEX_PROGRAM,
+		GPT_FRAGMENT_PROGRAM,
+		GPT_GEOMETRY_PROGRAM,
+		GPT_DOMAIN_PROGRAM,
+		GPT_HULL_PROGRAM,
+		GPT_COMPUTE_PROGRAM
+	};
+
+	/**	GPU program profiles representing supported feature sets. */
+	enum GpuProgramProfile
+	{
+		GPP_NONE,
+		GPP_FS_1_1,
+		GPP_FS_1_2,
+		GPP_FS_1_3,
+		GPP_FS_1_4,
+		GPP_FS_2_0,
+		GPP_FS_2_x,
+		GPP_FS_2_a,
+		GPP_FS_2_b,
+		GPP_FS_3_0,
+		GPP_FS_3_x,
+		GPP_FS_4_0,
+		GPP_FS_4_1,
+		GPP_FS_5_0,
+		GPP_VS_1_1,
+		GPP_VS_2_0,
+		GPP_VS_2_x,
+		GPP_VS_2_a,
+		GPP_VS_3_0,
+		GPP_VS_4_0,
+		GPP_VS_4_1,
+		GPP_VS_5_0,
+		GPP_GS_4_0,
+		GPP_GS_4_1,
+		GPP_GS_5_0,
+		GPP_HS_5_0,
+		GPP_DS_5_0,
+		GPP_CS_5_0
+	};
+
+	/** Data describing a GpuProgram. */
+	class BS_CORE_EXPORT GpuProgramProperties
+	{
+	public:
+		GpuProgramProperties(const String& source, const String& entryPoint,
+			GpuProgramType gptype, GpuProgramProfile profile);
+
+		virtual ~GpuProgramProperties() { }
+
+        /** Source used for creating this program. */
+        const String& getSource() const { return mSource; }
+        
+		/**	Type of GPU program (for example fragment, vertex). */
+        GpuProgramType getType() const { return mType; }
+
+		/**	Profile of the GPU program (for example VS_4_0, VS_5_0). */
+		GpuProgramProfile getProfile() const { return mProfile; }
+
+		/**	Name of the program entry method (for example "main"). */
+		const String& getEntryPoint() const { return mEntryPoint; }
+
+	protected:
+		friend class GpuProgramRTTI;
+
+		GpuProgramType mType;
+		String mEntryPoint;
+		GpuProgramProfile mProfile;
+		String mSource;
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Core thread version of a GpuProgram.
+	 *
+	 * @note	Core thread only.
+	 */
+	class BS_CORE_EXPORT GpuProgramCore : public CoreObjectCore
+	{
+	public:
+		virtual ~GpuProgramCore() { }
+
+		/** Returns whether this program can be supported on the current renderer and hardware. */
+        virtual bool isSupported() const;
+
+		/** Returns true if shader was successfully compiled. */
+		virtual bool isCompiled() const { return mIsCompiled; }
+
+		/**	Returns an error message returned by the compiler, if the compilation failed. */
+		virtual String getCompileErrorMessage() const { return mCompileError; }
+
+		/**
+		 * Sets whether this geometry program requires adjacency information from the input primitives.
+		 *
+		 * @note	Only relevant for geometry programs.
+		 */
+		virtual void setAdjacencyInfoRequired(bool required) { mNeedsAdjacencyInfo = required; }
+
+		/**
+		 * Returns whether this geometry program requires adjacency information from the input primitives.
+		 *
+		 * @note	Only relevant for geometry programs.
+		 */
+		virtual bool isAdjacencyInfoRequired() const { return mNeedsAdjacencyInfo; }
+
+		/** @copydoc GpuProgram::createParameters */
+		virtual SPtr<GpuParamsCore> createParameters();
+
+		/** @copydoc GpuProgram::getParamDesc */
+		GpuParamDescPtr getParamDesc() const { return mParametersDesc; }
+
+		/**	Returns GPU program input declaration. Only relevant for vertex programs. */
+		SPtr<VertexDeclarationCore> getInputDeclaration() const { return mInputDeclaration; }
+
+		/**	Returns properties that contain information about the GPU program. */
+		const GpuProgramProperties& getProperties() const { return mProperties; }
+
+		/** @copydoc GpuProgram::create */
+		static SPtr<GpuProgramCore> create(const String& source, const String& entryPoint, const String& language, GpuProgramType gptype,
+			GpuProgramProfile profile, bool requiresAdjacency = false);
+
+	protected:
+		GpuProgramCore(const String& source, const String& entryPoint,
+			GpuProgramType gptype, GpuProgramProfile profile, bool isAdjacencyInfoRequired = false);
+
+		/** Returns whether required capabilities for this program is supported. */
+		bool isRequiredCapabilitiesSupported() const;
+
+		bool mNeedsAdjacencyInfo;
+
+		bool mIsCompiled;
+		String mCompileError;
+
+		GpuParamDescPtr mParametersDesc;
+		SPtr<VertexDeclarationCore> mInputDeclaration;
+		GpuProgramProperties mProperties;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Contains a GPU program such as vertex or fragment program which gets compiled from the provided source code.
+	 *
+	 * @note	Sim thread only.
+	 */
+	class BS_CORE_EXPORT GpuProgram : public IReflectable, public CoreObject
+	{
+	public:
+		virtual ~GpuProgram() { }
+
+		/**
+		 * Returns true if shader was successfully compiled. 
+		 *
+		 * @note	Only valid after core thread has initialized the program.
+		 */
+		bool isCompiled() const;
+
+		/**
+		 * Returns an error message returned by the compiler, if the compilation failed.
+		 *
+		 * @note	Only valid after core thread has initialized the program.
+		 */
+		String getCompileErrorMessage() const;
+
+		/**
+		 * Creates a new parameters object compatible with this program definition. You may populate the returned object 
+		 * with actual parameter values and bind it to the pipeline to render an object using those values and this program.
+		 *
+		 * @note	Only valid after core thread has initialized the program.
+		 */
+		GpuParamsPtr createParameters();
+
+		/**
+		 * Returns description of all parameters in this GPU program.
+		 *
+		 * @note	Only valid after core thread has initialized the program.
+		 */
+		GpuParamDescPtr getParamDesc() const;
+
+		/** Retrieves a core implementation of a gpu program usable only from the core thread. */
+		SPtr<GpuProgramCore> getCore() const;
+
+		/** Returns properties that contain information about the GPU program. */
+		const GpuProgramProperties& getProperties() const { return mProperties; }
+
+		/**
+		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
+		 * isCompiled() with return false, and you will be able to retrieve the error message via getCompileErrorMessage().
+		 *
+		 * @param[in]	source				Source code to compile the shader from.
+		 * @param[in]	entryPoint			Name of the entry point function, for example "main".
+		 * @param[in]	language			Language the source is written in, for example "hlsl" or "glsl".
+		 * @param[in]	gptype				Type of the program, for example vertex or fragment.
+		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
+		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
+		 *									program.
+		 */
+		static GpuProgramPtr create(const String& source, const String& entryPoint, const String& language, GpuProgramType gptype,
+			GpuProgramProfile profile, bool requiresAdjacency = false);
+
+	protected:
+		friend class GpuProgramManager;
+
+		GpuProgram(const String& source, const String& entryPoint, const String& language,
+			GpuProgramType gptype, GpuProgramProfile profile, bool isAdjacencyInfoRequired = false);
+
+		/** @copydoc CoreObject::createCore */
+		SPtr<CoreObjectCore> createCore() const;
+
+		/** @copydoc Resource::calculateSize */
+		size_t calculateSize() const { return 0; } // TODO 
+
+	protected:
+		bool mNeedsAdjacencyInfo;
+		String mLanguage;
+		GpuProgramProperties mProperties;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class GpuProgramRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 143 - 143
Source/BansheeCore/Include/BsGpuProgramManager.h

@@ -1,144 +1,144 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsModule.h"
-#include "BsException.h"
-#include "BsGpuProgram.h"
-
-namespace BansheeEngine 
-{
-	/** @cond INTERNAL */
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Factory responsible for creating GPU programs of a certain type. */
-	class BS_CORE_EXPORT GpuProgramFactory
-	{
-	public:
-        GpuProgramFactory() {}
-		virtual ~GpuProgramFactory() { }
-
-		/**	Returns GPU program language this factory is capable creating GPU programs from. */
-		virtual const String& getLanguage() const = 0;
-
-		/**
-		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
-		 * GpuProgram::isCompiled() method on the returned program will return false, and you will be able to retrieve 
-		 * the error message via GpuProgram::getCompileErrorMessage().
-		 *
-		 * @param[in]	source				Source code to compile the shader from.
-		 * @param[in]	entryPoint			Name of the entry point function, e.g. "main".
-		 * @param[in]	gptype				Type of the program, e.g. vertex or fragment.
-		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
-		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
-		 *									program.
-		 */
-		virtual SPtr<GpuProgramCore> create(const String& source, const String& entryPoint, GpuProgramType gptype, 
-			GpuProgramProfile profile, bool requiresAdjacencyInformation) = 0;
-
-		/** @copydoc GpuProgramManager::createEmpty */
-		virtual SPtr<GpuProgramCore> create(GpuProgramType type) = 0;
-	};
-
-	/**
-	 * Manager responsible for creating GPU programs. It will automatically try to find the appropriate handler for a 
-	 * specific GPU program language and create the program if possible.
-	 *
-	 * @note	Sim thread only.
-	 */
-	class BS_CORE_EXPORT GpuProgramManager : public Module<GpuProgramManager>
-	{
-	public:
-		/**
-		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
-		 * GpuProgram::isCompiled() method on the returned program will return false, and you will be able to retrieve the 
-		 * error message via GpuProgram::getCompileErrorMessage().
-		 *
-		 * @param[in]	source				Source code to compile the shader from.
-		 * @param[in]	entryPoint			Name of the entry point function, e.g. "main".
-		 * @param[in]	language			Language the source is written in, e.g. "hlsl" or "glsl".
-		 * @param[in]	gptype				Type of the program, e.g. vertex or fragment.
-		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
-		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
-		 *									program.
-		 */
-		GpuProgramPtr create(const String& source, const String& entryPoint, const String& language, 
-			GpuProgramType gptype, GpuProgramProfile profile, bool requiresAdjacency = false);
-
-		/**
-		 * Creates a completely empty and uninitialized GpuProgram. Should only be used for specific purposes, like 
-		 * deserialization, as it requires additional manual initialization that is not required normally.
-		 */
-		GpuProgramPtr createEmpty(const String& language, GpuProgramType type);
-	};
-
-	/**
-	 * Manager responsible for creating GPU programs. It will automatically	try to find the appropriate handler for a 
-	 * specific GPU program language and create the program if possible.
-	 *
-	 * @note	Core thread only.
-	 */
-	class BS_CORE_EXPORT GpuProgramCoreManager : public Module<GpuProgramCoreManager>
-	{
-	public:
-		GpuProgramCoreManager();
-		virtual ~GpuProgramCoreManager();
-
-		/**
-		 * Registers a new factory that is able to create GPU programs for a certain language. If any other factory for the
-		 * same language exists, it will overwrite it.
-		 */
-		void addFactory(GpuProgramFactory* factory);
-
-		/**
-		 * Unregisters a GPU program factory, essentially making it not possible to create GPU programs using the language 
-		 * the factory supported.
-		 */
-		void removeFactory(GpuProgramFactory* factory);
-
-		/** Query if a GPU program language is supported. (.e.g. "hlsl", "glsl"). */
-		bool isLanguageSupported(const String& lang);
-
-		/**
-		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
-		 * GpuProgramCore::isCompiled() method on the returned program will return false, and you will be able to retrieve 
-		 * the error message via GpuProgramCore::getCompileErrorMessage().
-		 *
-		 * @param[in]	source				Source code to compile the shader from.
-		 * @param[in]	entryPoint			Name of the entry point function, e.g. "main".
-		 * @param[in]	language			Language the source is written in, e.g. "hlsl" or "glsl".
-		 * @param[in]	gptype				Type of the program, e.g. vertex or fragment.
-		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
-		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
-		 *									program.
-		 */
-		SPtr<GpuProgramCore> create(const String& source, const String& entryPoint, const String& language, 
-			GpuProgramType gptype, GpuProgramProfile profile, bool requiresAdjacency = false);
-
-	protected:
-		friend class GpuProgram;
-
-		/**
-		 * Creates a GPU program without initializing it.
-		 *
-		 * @see		create
-		 */
-		SPtr<GpuProgramCore> createInternal(const String& source, const String& entryPoint, const String& language,
-			GpuProgramType gptype, GpuProgramProfile profile, bool requiresAdjacency = false);
-
-		/** Attempts to find a factory for the specified language. Returns null if it cannot find one. */
-		GpuProgramFactory* getFactory(const String& language);
-
-	protected:
-		typedef Map<String, GpuProgramFactory*> FactoryMap;
-
-		FactoryMap mFactories;
-		GpuProgramFactory* mNullFactory; /**< Factory for dealing with GPU programs that can't be created. */
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsModule.h"
+#include "BsException.h"
+#include "BsGpuProgram.h"
+
+namespace BansheeEngine 
+{
+	/** @cond INTERNAL */
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Factory responsible for creating GPU programs of a certain type. */
+	class BS_CORE_EXPORT GpuProgramFactory
+	{
+	public:
+        GpuProgramFactory() {}
+		virtual ~GpuProgramFactory() { }
+
+		/**	Returns GPU program language this factory is capable creating GPU programs from. */
+		virtual const String& getLanguage() const = 0;
+
+		/**
+		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
+		 * GpuProgram::isCompiled() method on the returned program will return false, and you will be able to retrieve 
+		 * the error message via GpuProgram::getCompileErrorMessage().
+		 *
+		 * @param[in]	source				Source code to compile the shader from.
+		 * @param[in]	entryPoint			Name of the entry point function, for example "main".
+		 * @param[in]	gptype				Type of the program, for example vertex or fragment.
+		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
+		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
+		 *									program.
+		 */
+		virtual SPtr<GpuProgramCore> create(const String& source, const String& entryPoint, GpuProgramType gptype, 
+			GpuProgramProfile profile, bool requiresAdjacencyInformation) = 0;
+
+		/** @copydoc GpuProgramManager::createEmpty */
+		virtual SPtr<GpuProgramCore> create(GpuProgramType type) = 0;
+	};
+
+	/**
+	 * Manager responsible for creating GPU programs. It will automatically try to find the appropriate handler for a 
+	 * specific GPU program language and create the program if possible.
+	 *
+	 * @note	Sim thread only.
+	 */
+	class BS_CORE_EXPORT GpuProgramManager : public Module<GpuProgramManager>
+	{
+	public:
+		/**
+		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
+		 * GpuProgram::isCompiled() method on the returned program will return false, and you will be able to retrieve the 
+		 * error message via GpuProgram::getCompileErrorMessage().
+		 *
+		 * @param[in]	source				Source code to compile the shader from.
+		 * @param[in]	entryPoint			Name of the entry point function, for example "main".
+		 * @param[in]	language			Language the source is written in, for example "hlsl" or "glsl".
+		 * @param[in]	gptype				Type of the program, for example vertex or fragment.
+		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
+		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
+		 *									program.
+		 */
+		GpuProgramPtr create(const String& source, const String& entryPoint, const String& language, 
+			GpuProgramType gptype, GpuProgramProfile profile, bool requiresAdjacency = false);
+
+		/**
+		 * Creates a completely empty and uninitialized GpuProgram. Should only be used for specific purposes, like 
+		 * deserialization, as it requires additional manual initialization that is not required normally.
+		 */
+		GpuProgramPtr createEmpty(const String& language, GpuProgramType type);
+	};
+
+	/**
+	 * Manager responsible for creating GPU programs. It will automatically	try to find the appropriate handler for a 
+	 * specific GPU program language and create the program if possible.
+	 *
+	 * @note	Core thread only.
+	 */
+	class BS_CORE_EXPORT GpuProgramCoreManager : public Module<GpuProgramCoreManager>
+	{
+	public:
+		GpuProgramCoreManager();
+		virtual ~GpuProgramCoreManager();
+
+		/**
+		 * Registers a new factory that is able to create GPU programs for a certain language. If any other factory for the
+		 * same language exists, it will overwrite it.
+		 */
+		void addFactory(GpuProgramFactory* factory);
+
+		/**
+		 * Unregisters a GPU program factory, essentially making it not possible to create GPU programs using the language 
+		 * the factory supported.
+		 */
+		void removeFactory(GpuProgramFactory* factory);
+
+		/** Query if a GPU program language is supported (for example "hlsl", "glsl"). */
+		bool isLanguageSupported(const String& lang);
+
+		/**
+		 * Creates a new GPU program using the provided source code. If compilation fails or program is not supported
+		 * GpuProgramCore::isCompiled() method on the returned program will return false, and you will be able to retrieve 
+		 * the error message via GpuProgramCore::getCompileErrorMessage().
+		 *
+		 * @param[in]	source				Source code to compile the shader from.
+		 * @param[in]	entryPoint			Name of the entry point function, for example "main".
+		 * @param[in]	language			Language the source is written in, for example "hlsl" or "glsl".
+		 * @param[in]	gptype				Type of the program, for example vertex or fragment.
+		 * @param[in]	profile				Program profile specifying supported feature-set. Must match the type.
+		 * @param[in]	requiresAdjacency	If true then adjacency information will be provided when rendering using this 
+		 *									program.
+		 */
+		SPtr<GpuProgramCore> create(const String& source, const String& entryPoint, const String& language, 
+			GpuProgramType gptype, GpuProgramProfile profile, bool requiresAdjacency = false);
+
+	protected:
+		friend class GpuProgram;
+
+		/**
+		 * Creates a GPU program without initializing it.
+		 *
+		 * @see		create
+		 */
+		SPtr<GpuProgramCore> createInternal(const String& source, const String& entryPoint, const String& language,
+			GpuProgramType gptype, GpuProgramProfile profile, bool requiresAdjacency = false);
+
+		/** Attempts to find a factory for the specified language. Returns null if it cannot find one. */
+		GpuProgramFactory* getFactory(const String& language);
+
+	protected:
+		typedef Map<String, GpuProgramFactory*> FactoryMap;
+
+		FactoryMap mFactories;
+		GpuProgramFactory* mNullFactory; /**< Factory for dealing with GPU programs that can't be created. */
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 75 - 75
Source/BansheeCore/Include/BsHString.h

@@ -1,76 +1,76 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-namespace BansheeEngine
-{
-	/** @addtogroup Localization
-	 *  @{
-	 */
-
-	/**
-	 * String handle. Provides a wrapper around an Unicode string, primarily for localization purposes.
-	 * 			
-	 * Actual value for this string is looked up in a global string table based on the provided identifier string and 
-	 * currently active language. If such value doesn't exist then the identifier is used as is.
-	 *			
-	 * Use {0}, {1}, etc. in the string value for values that might change dynamically.
-	 */
-	class BS_CORE_EXPORT HString
-	{
-	public:
-		/**
-		 * Creates a new localized string with the specified identifier. If the identifier doesn't previously exist in the 
-		 * string table, identifier value will also be used for initializing the default language version of the string.
-		 *
-		 * @param[in]	identifier		String you can use for later referencing the localized string.
-		 * @param[in]	stringTableId	Unique identifier of the string table to retrieve the string from.
-		 */
-		explicit HString(const WString& identifier, UINT32 stringTableId = 0);
-
-		/**
-		 * Creates a new localized string with the specified identifier and sets the default language version of the 
-		 * string. If a string with that identifier already exists default language string will be updated.
-		 *
-		 * @param[in]	identifier		String you can use for later referencing the localized string.
-		 * @param[in]	default			Default string to assign to the specified identifier. Language to which it will be 
-		 *								assigned depends on the StringTable::DEFAULT_LANGUAGE value.
-		 * @param[in]	stringTableId	Unique identifier of the string table to retrieve the string from.
-		 */
-		explicit HString(const WString& identifier, const WString& default, UINT32 stringTableId = 0);
-
-		/**
-		 * Creates a new empty localized string.
-		 *
-		 * @param[in]	stringTableId	Unique identifier of the string table to retrieve the string from.
-		 */
-		HString(UINT32 stringTableId = 0);
-		HString(const HString& copy);
-		~HString();
-
-		HString& operator=(const HString& rhs);
-
-		operator const WString& () const;
-		const WString& getValue() const;
-
-		/**
-		 * Sets a value of a string parameter. Parameters are specified as bracketed values within the string itself 
-		 * (e.g. {0}, {1}) etc. Use ^ as an escape character.
-		 *
-		 * @note	This is useful for strings that have dynamically changing values, like numbers, embedded in them.
-		 */
-		void setParameter(UINT32 idx, const WString& value);
-		
-		/** Returns an empty string. */
-		static const HString& dummy();
-	private:
-		SPtr<LocalizedStringData> mStringData;
-		WString* mParameters;
-
-		mutable bool mIsDirty;
-		mutable WString mCachedString;
-		mutable WString* mStringPtr;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+namespace BansheeEngine
+{
+	/** @addtogroup Localization
+	 *  @{
+	 */
+
+	/**
+	 * String handle. Provides a wrapper around an Unicode string, primarily for localization purposes.
+	 * 			
+	 * Actual value for this string is looked up in a global string table based on the provided identifier string and 
+	 * currently active language. If such value doesn't exist then the identifier is used as is.
+	 *			
+	 * Use {0}, {1}, etc. in the string value for values that might change dynamically.
+	 */
+	class BS_CORE_EXPORT HString
+	{
+	public:
+		/**
+		 * Creates a new localized string with the specified identifier. If the identifier doesn't previously exist in the 
+		 * string table, identifier value will also be used for initializing the default language version of the string.
+		 *
+		 * @param[in]	identifier		String you can use for later referencing the localized string.
+		 * @param[in]	stringTableId	Unique identifier of the string table to retrieve the string from.
+		 */
+		explicit HString(const WString& identifier, UINT32 stringTableId = 0);
+
+		/**
+		 * Creates a new localized string with the specified identifier and sets the default language version of the 
+		 * string. If a string with that identifier already exists default language string will be updated.
+		 *
+		 * @param[in]	identifier		String you can use for later referencing the localized string.
+		 * @param[in]	default			Default string to assign to the specified identifier. Language to which it will be 
+		 *								assigned depends on the StringTable::DEFAULT_LANGUAGE value.
+		 * @param[in]	stringTableId	Unique identifier of the string table to retrieve the string from.
+		 */
+		explicit HString(const WString& identifier, const WString& default, UINT32 stringTableId = 0);
+
+		/**
+		 * Creates a new empty localized string.
+		 *
+		 * @param[in]	stringTableId	Unique identifier of the string table to retrieve the string from.
+		 */
+		HString(UINT32 stringTableId = 0);
+		HString(const HString& copy);
+		~HString();
+
+		HString& operator=(const HString& rhs);
+
+		operator const WString& () const;
+		const WString& getValue() const;
+
+		/**
+		 * Sets a value of a string parameter. Parameters are specified as bracketed values within the string itself 
+		 * (for example {0}, {1}) etc. Use ^ as an escape character.
+		 *
+		 * @note	This is useful for strings that have dynamically changing values, like numbers, embedded in them.
+		 */
+		void setParameter(UINT32 idx, const WString& value);
+		
+		/** Returns an empty string. */
+		static const HString& dummy();
+	private:
+		SPtr<LocalizedStringData> mStringData;
+		WString* mParameters;
+
+		mutable bool mIsDirty;
+		mutable WString mCachedString;
+		mutable WString* mStringPtr;
+	};
+
+	/** @} */
 }

+ 161 - 161
Source/BansheeCore/Include/BsHardwareBuffer.h

@@ -1,162 +1,162 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine 
-{
-	/** @cond INTERNAL */
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/**
-	 * Abstract class defining common features of hardware buffers. Hardware buffers usually represent areas of memory the 
-	 * GPU or the driver can access directly.
-	 *
-	 * @note	Core thread only.
-	 * @note	Be aware that reading from non-system memory hardware buffers is usually slow and should be avoided.
-	 */
-	class BS_CORE_EXPORT HardwareBuffer
-    {
-    public:
-        virtual ~HardwareBuffer() {}
-
-		/**
-		 * Locks a portion of the buffer and returns pointer to the locked area. You must call unlock() when done.
-		 *
-		 * @param[in]	offset	Offset in bytes from which to lock the buffer.
-		 * @param[in]	length	Length of the area you want to lock, in bytes.
-		 * @param[in]	options	Signifies what you want to do with the returned pointer. Caller must ensure not to do 
-		 *						anything he hasn't requested (e.g. don't try to read from the buffer unless you requested 
-		 *						it here).
-		 */
-		virtual void* lock(UINT32 offset, UINT32 length, GpuLockOptions options)
-        {
-            assert(!isLocked() && "Cannot lock this buffer, it is already locked!");
-            void* ret = lockImpl(offset, length, options);
-            mIsLocked = true;
-
-			mLockStart = offset;
-			mLockSize = length;
-            return ret;
-        }
-
-		/**
-		 * Locks the entire buffer and returns pointer to the locked area. You must call unlock() when done.
-		 *
-		 * @param[in]	options	Signifies what you want to do with the returned pointer. Caller must ensure not to do 
-		 *						anything he hasn't requested (e.g. don't try to read from the buffer unless you requested
-		 *						it here).
-		 */
-        void* lock(GpuLockOptions options)
-        {
-            return this->lock(0, mSizeInBytes, options);
-        }
-
-		/**	Releases the lock on this buffer.  */
-		virtual void unlock()
-        {
-            assert(isLocked() && "Cannot unlock this buffer, it is not locked!");
-
-            unlockImpl();
-            mIsLocked = false;
-        }
-
-		/**
-		 * Reads data from a portion of the buffer and copies it to the destination buffer. Caller must ensure destination 
-		 * buffer is large enough.
-		 *
-		 * @param[in]	offset	Offset in bytes from which to copy the data.
-		 * @param[in]	length	Length of the area you want to copy, in bytes.
-		 * @param[in]	dest	Destination buffer large enough to store the read data.
-		 */
-        virtual void readData(UINT32 offset, UINT32 length, void* dest) = 0;
-
-		/**
-		 * Writes data into a portion of the buffer from the source memory. 
-		 *
-		 * @param[in]	offset		Offset in bytes from which to copy the data.
-		 * @param[in]	length		Length of the area you want to copy, in bytes.
-		 * @param[in]	source		Source buffer containing the data to write.
-		 * @param[in]	writeFlags	Optional write flags that may affect performance.
-		 */
-        virtual void writeData(UINT32 offset, UINT32 length, const void* source,
-				BufferWriteType writeFlags = BufferWriteType::Normal) = 0;
-
-		/**
-		 * Copies data from a specific portion of the source buffer into a specific portion of this buffer.
-		 *
-		 * @param[in]	srcBuffer			Buffer to copy from.
-		 * @param[in]	srcOffset			Offset into the source buffer to start copying from, in bytes.
-		 * @param[in]	dstOffset			Offset into this buffer to start copying to, in bytes.
-		 * @param[in]	length				Size of the data to copy, in bytes.
-		 * @param[in]	discardWholeBuffer	Specify true if the data in the current buffer can be entirely discarded. This
-		 *									may improve performance.
-		 */
-		virtual void copyData(HardwareBuffer& srcBuffer, UINT32 srcOffset, 
-			UINT32 dstOffset, UINT32 length, bool discardWholeBuffer = false)
-		{
-			const void *srcData = srcBuffer.lock(
-				srcOffset, length, GBL_READ_ONLY);
-			this->writeData(dstOffset, length, srcData, discardWholeBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
-			srcBuffer.unlock();
-		}
-
-		/**
-		 * Copy data from the provided buffer into this buffer. If buffers are not the same size, smaller size will be used.
-		 */
-		virtual void copyData(HardwareBuffer& srcBuffer)
-		{
-			UINT32 sz = std::min(getSizeInBytes(), srcBuffer.getSizeInBytes()); 
-			copyData(srcBuffer, 0, 0, sz, true);
-		}
-			
-		/** Returns the size of this buffer in bytes. */
-        UINT32 getSizeInBytes(void) const { return mSizeInBytes; }
-
-		/**	Returns the Usage flags with which this buffer was created. */
-        GpuBufferUsage getUsage() const { return mUsage; }
-
-		/**	Returns whether this buffer is held in system memory. */
-		bool isSystemMemory() const { return mSystemMemory; }
-
-		/**	Returns whether or not this buffer is currently locked. */
-        bool isLocked() const { return mIsLocked; }	
-
-	protected:
-		friend class HardwareBufferManager;
-
-		/**
-		 * Constructs a new buffer.
-		 *
-		 * @param[in]	usage			Determines most common usage of the buffer. Usually has effect on what type of 
-		 *								memory will be buffer allocated in but that depends on render API. Specify dynamic 
-		 *								if you plan on modifying it often, static otherwise.
-		 * @param[in]	systemMemory	If enabled the the buffer will be kept in the system memory. System memory buffers 
-		 *								are often used as a source or destination for copies from/to other buffers. Some 
-		 *								APIs don't allow reading from non-system memory buffers.
-		 */
-		HardwareBuffer(GpuBufferUsage usage, bool systemMemory)
-			: mUsage(usage), mIsLocked(false), mSystemMemory(systemMemory)
-		{  }
-
-		/** @copydoc lock */
-		virtual void* lockImpl(UINT32 offset, UINT32 length, GpuLockOptions options) = 0;
-
-		/** @copydoc unlock */
-		virtual void unlockImpl() = 0;
-
-	protected:
-		UINT32 mSizeInBytes;
-		GpuBufferUsage mUsage;
-		bool mIsLocked;
-		UINT32 mLockStart;
-		UINT32 mLockSize;
-		bool mSystemMemory;
-    };
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine 
+{
+	/** @cond INTERNAL */
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/**
+	 * Abstract class defining common features of hardware buffers. Hardware buffers usually represent areas of memory the 
+	 * GPU or the driver can access directly.
+	 *
+	 * @note	Core thread only.
+	 * @note	Be aware that reading from non-system memory hardware buffers is usually slow and should be avoided.
+	 */
+	class BS_CORE_EXPORT HardwareBuffer
+    {
+    public:
+        virtual ~HardwareBuffer() {}
+
+		/**
+		 * Locks a portion of the buffer and returns pointer to the locked area. You must call unlock() when done.
+		 *
+		 * @param[in]	offset	Offset in bytes from which to lock the buffer.
+		 * @param[in]	length	Length of the area you want to lock, in bytes.
+		 * @param[in]	options	Signifies what you want to do with the returned pointer. Caller must ensure not to do 
+		 *						anything he hasn't requested (for example don't try to read from the buffer unless you
+		 *						requested it here).
+		 */
+		virtual void* lock(UINT32 offset, UINT32 length, GpuLockOptions options)
+        {
+            assert(!isLocked() && "Cannot lock this buffer, it is already locked!");
+            void* ret = lockImpl(offset, length, options);
+            mIsLocked = true;
+
+			mLockStart = offset;
+			mLockSize = length;
+            return ret;
+        }
+
+		/**
+		 * Locks the entire buffer and returns pointer to the locked area. You must call unlock() when done.
+		 *
+		 * @param[in]	options	Signifies what you want to do with the returned pointer. Caller must ensure not to do 
+		 *						anything he hasn't requested (for example don't try to read from the buffer unless you
+		 *						requested it here).
+		 */
+        void* lock(GpuLockOptions options)
+        {
+            return this->lock(0, mSizeInBytes, options);
+        }
+
+		/**	Releases the lock on this buffer.  */
+		virtual void unlock()
+        {
+            assert(isLocked() && "Cannot unlock this buffer, it is not locked!");
+
+            unlockImpl();
+            mIsLocked = false;
+        }
+
+		/**
+		 * Reads data from a portion of the buffer and copies it to the destination buffer. Caller must ensure destination 
+		 * buffer is large enough.
+		 *
+		 * @param[in]	offset	Offset in bytes from which to copy the data.
+		 * @param[in]	length	Length of the area you want to copy, in bytes.
+		 * @param[in]	dest	Destination buffer large enough to store the read data.
+		 */
+        virtual void readData(UINT32 offset, UINT32 length, void* dest) = 0;
+
+		/**
+		 * Writes data into a portion of the buffer from the source memory. 
+		 *
+		 * @param[in]	offset		Offset in bytes from which to copy the data.
+		 * @param[in]	length		Length of the area you want to copy, in bytes.
+		 * @param[in]	source		Source buffer containing the data to write.
+		 * @param[in]	writeFlags	Optional write flags that may affect performance.
+		 */
+        virtual void writeData(UINT32 offset, UINT32 length, const void* source,
+				BufferWriteType writeFlags = BufferWriteType::Normal) = 0;
+
+		/**
+		 * Copies data from a specific portion of the source buffer into a specific portion of this buffer.
+		 *
+		 * @param[in]	srcBuffer			Buffer to copy from.
+		 * @param[in]	srcOffset			Offset into the source buffer to start copying from, in bytes.
+		 * @param[in]	dstOffset			Offset into this buffer to start copying to, in bytes.
+		 * @param[in]	length				Size of the data to copy, in bytes.
+		 * @param[in]	discardWholeBuffer	Specify true if the data in the current buffer can be entirely discarded. This
+		 *									may improve performance.
+		 */
+		virtual void copyData(HardwareBuffer& srcBuffer, UINT32 srcOffset, 
+			UINT32 dstOffset, UINT32 length, bool discardWholeBuffer = false)
+		{
+			const void *srcData = srcBuffer.lock(
+				srcOffset, length, GBL_READ_ONLY);
+			this->writeData(dstOffset, length, srcData, discardWholeBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
+			srcBuffer.unlock();
+		}
+
+		/**
+		 * Copy data from the provided buffer into this buffer. If buffers are not the same size, smaller size will be used.
+		 */
+		virtual void copyData(HardwareBuffer& srcBuffer)
+		{
+			UINT32 sz = std::min(getSizeInBytes(), srcBuffer.getSizeInBytes()); 
+			copyData(srcBuffer, 0, 0, sz, true);
+		}
+			
+		/** Returns the size of this buffer in bytes. */
+        UINT32 getSizeInBytes(void) const { return mSizeInBytes; }
+
+		/**	Returns the Usage flags with which this buffer was created. */
+        GpuBufferUsage getUsage() const { return mUsage; }
+
+		/**	Returns whether this buffer is held in system memory. */
+		bool isSystemMemory() const { return mSystemMemory; }
+
+		/**	Returns whether or not this buffer is currently locked. */
+        bool isLocked() const { return mIsLocked; }	
+
+	protected:
+		friend class HardwareBufferManager;
+
+		/**
+		 * Constructs a new buffer.
+		 *
+		 * @param[in]	usage			Determines most common usage of the buffer. Usually has effect on what type of 
+		 *								memory will be buffer allocated in but that depends on render API. Specify dynamic 
+		 *								if you plan on modifying it often, static otherwise.
+		 * @param[in]	systemMemory	If enabled the the buffer will be kept in the system memory. System memory buffers 
+		 *								are often used as a source or destination for copies from/to other buffers. Some 
+		 *								APIs don't allow reading from non-system memory buffers.
+		 */
+		HardwareBuffer(GpuBufferUsage usage, bool systemMemory)
+			: mUsage(usage), mIsLocked(false), mSystemMemory(systemMemory)
+		{  }
+
+		/** @copydoc lock */
+		virtual void* lockImpl(UINT32 offset, UINT32 length, GpuLockOptions options) = 0;
+
+		/** @copydoc unlock */
+		virtual void unlockImpl() = 0;
+
+	protected:
+		UINT32 mSizeInBytes;
+		GpuBufferUsage mUsage;
+		bool mIsLocked;
+		UINT32 mLockStart;
+		UINT32 mLockSize;
+		bool mSystemMemory;
+    };
+
+	/** @} */
+	/** @endcond */
 }

+ 104 - 101
Source/BansheeCore/Include/BsHingeJoint.h

@@ -1,102 +1,105 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsJoint.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** Hinge joint removes all but a single rotation degree of freedom from its two attached bodies (e.g. a door hinge). */
-	class BS_CORE_EXPORT HingeJoint : public Joint
-	{
-	public:
-		/** Flags that control hinge joint options. */
-		enum class Flag
-		{
-			Limit = 0x1, /** Joint limit is enabled. */
-			Drive = 0x2 /** Joint drive is enabled. */
-		};
-
-		/** Properties of a drive that drives the joint's angular velocity towards a paricular value. */
-		struct Drive
-		{
-			/** Target speed of the joint. */
-			float speed = 0.0f;
-
-			/** Maximum torque the drive is allowed to apply .*/
-			float forceLimit = FLT_MAX;
-
-			/** Scales the velocity of the first body, and its response to drive torque is scaled down. */
-			float gearRatio = 1.0f;
-
-			/** 
-			 * If the joint is moving faster than the drive's target speed, the drive will try to break. If you don't want
-			 * the breaking to happen set this to true.
-			 */
-			bool freeSpin = false;
-
-			bool operator==(const Drive& other) const
-			{
-				return speed == other.speed && forceLimit == other.forceLimit && gearRatio == other.gearRatio && 
-					freeSpin && other.freeSpin;
-			}
-		};
-
-	public:
-		virtual ~HingeJoint() { }
-
-		/** Returns the current angle between the two attached bodes. */
-		virtual Radian getAngle() const = 0;
-
-		/** Returns the current angular speed of the joint. */
-		virtual float getSpeed() const = 0;
-
-		/** 
-		 * Returns the limit of the joint. Limit constrains the motion to the specified angle range. You must enable the
-		 * limit flag on the joint in order for this to be recognized. 
-		 *
-		 * @see LimitAngularRange
-		 */
-		virtual LimitAngularRange getLimit() const = 0;
-
-		/**
-		 * Sets the limit of the joint. Limit constrains the motion to the specified angle range. You must enable the limit
-		 * flag on the joint in order for this to be recognized. 
-		 *
-		 * @see LimitAngularRange
-		 */
-		virtual void setLimit(const LimitAngularRange& limit) = 0;
-
-		/** 
-		 * Returns the drive properties of the joint. It drives the joint's angular velocity towards a particular value. You
-		 * must enable the drive flag on the joint in order for the drive to be active.
-		 *
-		 * @see HingeJoint::Drive
-		 */
-		virtual Drive getDrive() const = 0;
-
-		/** 
-		 * Sets the drive properties of the joint. It drives the joint's angular velocity towards a particular value. You 
-		 * must enable the drive flag on the joint in order for the drive to be active.
-		 *
-		 * @see HingeJoint::Drive
-		 */
-		virtual void setDrive(const Drive& drive) = 0;
-
-		/** Enables or disables a flag that controls joint behaviour. */
-		virtual void setFlag(Flag flag, bool enabled) = 0;
-
-		/** Checks is the specified option enabled. */
-		virtual bool hasFlag(Flag flag) const = 0;
-
-		/** Creates a new hinge joint. */
-		static SPtr<HingeJoint> create();
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsJoint.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/**
+	 * Hinge joint removes all but a single rotation degree of freedom from its two attached bodies (for example a door 
+	 * hinge). 
+	 */
+	class BS_CORE_EXPORT HingeJoint : public Joint
+	{
+	public:
+		/** Flags that control hinge joint options. */
+		enum class Flag
+		{
+			Limit = 0x1, /** Joint limit is enabled. */
+			Drive = 0x2 /** Joint drive is enabled. */
+		};
+
+		/** Properties of a drive that drives the joint's angular velocity towards a paricular value. */
+		struct Drive
+		{
+			/** Target speed of the joint. */
+			float speed = 0.0f;
+
+			/** Maximum torque the drive is allowed to apply .*/
+			float forceLimit = FLT_MAX;
+
+			/** Scales the velocity of the first body, and its response to drive torque is scaled down. */
+			float gearRatio = 1.0f;
+
+			/** 
+			 * If the joint is moving faster than the drive's target speed, the drive will try to break. If you don't want
+			 * the breaking to happen set this to true.
+			 */
+			bool freeSpin = false;
+
+			bool operator==(const Drive& other) const
+			{
+				return speed == other.speed && forceLimit == other.forceLimit && gearRatio == other.gearRatio && 
+					freeSpin && other.freeSpin;
+			}
+		};
+
+	public:
+		virtual ~HingeJoint() { }
+
+		/** Returns the current angle between the two attached bodes. */
+		virtual Radian getAngle() const = 0;
+
+		/** Returns the current angular speed of the joint. */
+		virtual float getSpeed() const = 0;
+
+		/** 
+		 * Returns the limit of the joint. Limit constrains the motion to the specified angle range. You must enable the
+		 * limit flag on the joint in order for this to be recognized. 
+		 *
+		 * @see LimitAngularRange
+		 */
+		virtual LimitAngularRange getLimit() const = 0;
+
+		/**
+		 * Sets the limit of the joint. Limit constrains the motion to the specified angle range. You must enable the limit
+		 * flag on the joint in order for this to be recognized. 
+		 *
+		 * @see LimitAngularRange
+		 */
+		virtual void setLimit(const LimitAngularRange& limit) = 0;
+
+		/** 
+		 * Returns the drive properties of the joint. It drives the joint's angular velocity towards a particular value. You
+		 * must enable the drive flag on the joint in order for the drive to be active.
+		 *
+		 * @see HingeJoint::Drive
+		 */
+		virtual Drive getDrive() const = 0;
+
+		/** 
+		 * Sets the drive properties of the joint. It drives the joint's angular velocity towards a particular value. You 
+		 * must enable the drive flag on the joint in order for the drive to be active.
+		 *
+		 * @see HingeJoint::Drive
+		 */
+		virtual void setDrive(const Drive& drive) = 0;
+
+		/** Enables or disables a flag that controls joint behaviour. */
+		virtual void setFlag(Flag flag, bool enabled) = 0;
+
+		/** Checks is the specified option enabled. */
+		virtual bool hasFlag(Flag flag) const = 0;
+
+		/** Creates a new hinge joint. */
+		static SPtr<HingeJoint> create();
+	};
+
+	/** @} */
 }

+ 11 - 8
Source/BansheeCore/Include/BsImporter.h

@@ -13,8 +13,8 @@ namespace BansheeEngine
 	 */
 
 	/** 
-	 * Contains a resource that was imported from a file that contains multiple resources (e.g. an animation from an FBX 
-	 * file). 
+	 * Contains a resource that was imported from a file that contains multiple resources (for example an animation from an
+	 * FBX file). 
 	 */
 	struct SubResource
 	{
@@ -31,7 +31,8 @@ namespace BansheeEngine
 
 		/**
 		 * Imports a resource at the specified location, and returns the loaded data. If file contains more than one
-		 * resource only the primary resource is imported (e.g. for an FBX a mesh would be imported, but animations ignored).
+		 * resource only the primary resource is imported (for example an FBX a mesh would be imported, but animations
+		 * ignored).
 		 *
 		 * @param[in]	inputFilePath	Pathname of the input file.
 		 * @param[in]	importOptions	(optional) Options for controlling the import. Caller must ensure import options 
@@ -51,8 +52,8 @@ namespace BansheeEngine
 
 		/**
 		 * Imports a resource at the specified location, and returns the loaded data. This method returns all imported
-		 * resources, which is relevant for files that can contain multiple resources (e.g. an FBX which may contain both
-		 * a mesh and animations). 
+		 * resources, which is relevant for files that can contain multiple resources (for example an FBX which may contain
+		 * both a mesh and animations). 
 		 *
 		 * @param[in]	inputFilePath	Pathname of the input file.
 		 * @param[in]	importOptions	(optional) Options for controlling the import. Caller must ensure import options 
@@ -113,7 +114,9 @@ namespace BansheeEngine
 		 */
 		bool supportsFileType(const UINT8* magicNumber, UINT32 magicNumSize) const;
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**
 		 * Adds a new asset importer for the specified file extension. If an asset importer for that extension already 
@@ -131,7 +134,7 @@ namespace BansheeEngine
 
 		/**
 		 * Imports a resource at the specified location but doesn't create resource handles. This method returns all 
-		 * imported resources, which is relevant for files that can contain multiple resources (e.g. an FBX which may
+		 * imported resources, which is relevant for files that can contain multiple resources (for example an FBX which may
 		 * contain both a mesh and animations). 
 		 *
 		 * @param[in]	inputFilePath	Pathname of the input file.
@@ -145,7 +148,7 @@ namespace BansheeEngine
 		 */
 		Vector<SubResourceRaw> _importAllRaw(const Path& inputFilePath, ConstImportOptionsPtr importOptions = nullptr);
 
-		/** @endcond */
+		/** @} */
 	private:
 		/** 
 		 * Searches available importers and attempts to find one that can import the file of the provided type. Returns null

+ 249 - 247
Source/BansheeCore/Include/BsInput.h

@@ -1,248 +1,250 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsModule.h"
-#include "BsOSInputHandler.h"
-#include "BsRawInputHandler.h"
-#include "BsInputFwd.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Input
-	 *  @{
-	 */
-
-	/**
-	 * Primary module used for dealing with input. Allows you to receieve and query raw or OS input for 
-	 * mouse/keyboard/gamepad.
-	 *
-	 * All inputs are received through an input handler, which can be overriden to provide custom input functionality.
-	 */
-	class BS_CORE_EXPORT Input : public Module<Input>
-	{
-		/** Possible button states. */
-		enum class ButtonState
-		{
-			Off, /**< Button is not being pressed. */
-			On, /**< Button is being pressed. */
-			ToggledOn, /**< Button has been pressed this frame. */
-			ToggledOff, /**< Button has been released this frame. */
-			ToggledOnOff, /**< Button has been pressed and released this frame. */
-		};
-
-		/** Contains axis and device data per device. */
-		struct DeviceData
-		{
-			DeviceData();
-
-			Vector<RawAxisState> axes;
-			ButtonState keyStates[BC_Count];
-		};
-
-		/**	Different types of possible input event callbacks. */
-		enum class EventType
-		{
-			ButtonUp, ButtonDown, PointerMoved, PointerUp, PointerDown, PointerDoubleClick, TextInput, Command
-		};
-
-		/**	Stores information about a queued input event that is to be triggered later. */
-		struct QueuedEvent
-		{
-			QueuedEvent(EventType type, UINT32 idx)
-				:type(type), idx(idx)
-			{ }
-
-			EventType type;
-			UINT32 idx;
-		};
-
-	public:
-		Input();
-		~Input();
-
-		/**
-		 * Returns value of the specified input axis. Normally in range [-1.0, 1.0] but can be outside the range for 
-		 * devices with unbound axes (e.g. mouse).
-		 *
-		 * @param[in]	type		Type of axis to query. Usually a type from InputAxis but can be a custom value.
-		 * @param[in]	deviceIdx	Index of the device in case more than one is hooked up (0 - primary).
-		 */
-		float getAxisValue(UINT32 type, UINT32 deviceIdx = 0) const;
-
-		/**
-		 * Query if the provided button is currently being held (this frame or previous frames).
-		 *
-		 * @param[in]	keyCode		Code of the button to query.
-		 * @param[in]	deviceIdx	Device to query the button on (0 - primary).
-		 */
-		bool isButtonHeld(ButtonCode keyCode, UINT32 deviceIdx = 0) const;
-
-		/**
-		 * Query if the provided button is currently being released (only true for one frame).
-		 *
-		 * @param[in]	keyCode		Code of the button to query.
-		 * @param[in]	deviceIdx	Device to query the button on (0 - primary).
-		 */
-		bool isButtonUp(ButtonCode keyCode, UINT32 deviceIdx = 0) const;
-
-		/**
-		 * Query if the provided button is currently being pressed (only true for one frame).
-		 *
-		 * @param[in]	keyCode		Code of the button to query.
-		 * @param[in]	deviceIdx	Device to query the button on (0 - primary).
-		 */
-		bool isButtonDown(ButtonCode keyCode, UINT32 deviceIdx = 0) const;
-
-		/** Returns position of the pointer (e.g. mouse cursor) relative to the screen. */
-		Vector2I getPointerPosition() const;
-
-		/** Returns difference between last and current pointer position. */
-		Vector2I getPointerDelta() const { return mPointerDelta; }
-
-		/**
-		 * Query if the provided pointer button is currently being held (this frame or previous frames).
-		 *
-		 * @param[in]	pointerButton		Code of the button to query.
-		 */
-		bool isPointerButtonHeld(PointerEventButton pointerButton) const;
-
-		/**
-		 * Query if the provided pointer button is currently being released (only true for one frame).
-		 *
-		 * @param[in]	pointerButton		Code of the button to query.
-		 */
-		bool isPointerButtonUp(PointerEventButton pointerButton) const;
-
-		/**
-		 * Query if the provided pointer button is currently being pressed (only true for one frame).
-		 *
-		 * @param[in]	pointerButton		Code of the button to query.
-		 */
-		bool isPointerButtonDown(PointerEventButton pointerButton) const;
-
-		/** Query has the left pointer button has been double-clicked this frame. */
-		bool isPointerDoubleClicked() const;
-
-		/** Enables or disables mouse smoothing. Smoothing makes the changes to mouse axes more gradual. */
-		void setMouseSmoothing(bool enabled);
-
-		/** Triggered whenever a button is first pressed. */
-		Event<void(const ButtonEvent&)> onButtonDown;
-
-		/**	Triggered whenever a button is first released. */
-		Event<void(const ButtonEvent&)> onButtonUp;
-
-		/**	Triggered whenever user inputs a text character. */
-		Event<void(const TextInputEvent&)> onCharInput;
-
-		/**	Triggers when some pointing device (mouse cursor, touch) moves. */
-		Event<void(const PointerEvent&)> onPointerMoved;
-
-		/**	Triggers when some pointing device (mouse cursor, touch) button is pressed. */
-		Event<void(const PointerEvent&)> onPointerPressed;
-
-		/**	Triggers when some pointing device (mouse cursor, touch) button is released. */
-		Event<void(const PointerEvent&)> onPointerReleased;
-
-		/**	Triggers when some pointing device (mouse cursor, touch) button is double clicked. */
-		Event<void(const PointerEvent&)> onPointerDoubleClick;
-
-		// TODO Low priority: Remove this, I can emulate it using virtual input
-		/**	Triggers on special input commands. */
-		Event<void(InputCommandType)> onInputCommand;
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Registers a new input handler. Replaces any previous input handler.
-		 *
-		 * @note	Internal method.
-		 */
-		void _registerRawInputHandler(std::shared_ptr<RawInputHandler> inputHandler);
-
-		/**
-		 * Called every frame. Detects button state changes and prepares callback events to trigger via a call to 
-		 * _triggerCallbacks().
-		 *
-		 * @note	Internal method.
-		 */
-		void _update();
-
-		/**
-		 * Triggers any queued input event callbacks.
-		 * 
-		 * @note	Internal method.
-		 */
-		void _triggerCallbacks();
-
-		/** @endcond */
-
-	private:
-		/**	Triggered by input handler when a button is pressed. */
-		void buttonDown(UINT32 deviceIdx, ButtonCode code, UINT64 timestamp);
-
-		/**	Triggered by input handler when a button is released. */
-		void buttonUp(UINT32 deviceIdx, ButtonCode code, UINT64 timestamp);
-
-		/**	Triggered by input handler when a single character is input. */
-		void charInput(UINT32 chr);
-
-		/**	Triggered by input handler when a mouse/joystick axis is moved. */
-		void axisMoved(UINT32 deviceIdx, const RawAxisState& state, UINT32 axis);
-
-		/**	Cursor movement as OS reports it. Used for screen cursor position. */
-		void cursorMoved(const PointerEvent& event);
-
-		/**	Cursor button presses as OS reports it. */
-		void cursorPressed(const PointerEvent& event);
-
-		/**	Cursor button releases as OS reports it. */
-		void cursorReleased(const PointerEvent& event);
-		
-		/**	Cursor button releases as OS reports it. */
-		void cursorDoubleClick(const PointerEvent& event);
-
-		/** Input commands as OS reports them. */
-		void inputCommandEntered(InputCommandType commandType);
-
-		/** Called when window in focus changes, as reported by the OS. */
-		void inputWindowChanged(RenderWindow& win);
-
-	private:
-		std::shared_ptr<RawInputHandler> mRawInputHandler;
-		std::shared_ptr<OSInputHandler> mOSInputHandler;
-
-		Vector<DeviceData> mDevices;
-		Vector2I mPointerPosition;
-		Vector2I mPointerDelta;
-		ButtonState mPointerButtonStates[3];
-		bool mPointerDoubleClicked;
-		bool mLastPositionSet;
-
-		Vector<QueuedEvent> mQueuedEvents;
-
-		Vector<TextInputEvent> mTextInputEvents;
-		Vector<InputCommandType> mCommandEvents;
-		Vector<PointerEvent> mPointerDoubleClickEvents;
-		Vector<PointerEvent> mPointerReleasedEvents;
-		Vector<PointerEvent> mPointerPressedEvents;
-		Vector<PointerEvent> mPointerMovedEvents;
-
-		Vector<ButtonEvent> mButtonDownEvents;
-		Vector<ButtonEvent> mButtonUpEvents;
-
-		/************************************************************************/
-		/* 								STATICS		                      		*/
-		/************************************************************************/
-		static const int HISTORY_BUFFER_SIZE; // Size of buffer used for input smoothing
-		static const float WEIGHT_MODIFIER;
-	};
-
-	/** Provides easier access to Input. */
-	BS_CORE_EXPORT Input& gInput();
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsModule.h"
+#include "BsOSInputHandler.h"
+#include "BsRawInputHandler.h"
+#include "BsInputFwd.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Input
+	 *  @{
+	 */
+
+	/**
+	 * Primary module used for dealing with input. Allows you to receieve and query raw or OS input for 
+	 * mouse/keyboard/gamepad.
+	 *
+	 * All inputs are received through an input handler, which can be overriden to provide custom input functionality.
+	 */
+	class BS_CORE_EXPORT Input : public Module<Input>
+	{
+		/** Possible button states. */
+		enum class ButtonState
+		{
+			Off, /**< Button is not being pressed. */
+			On, /**< Button is being pressed. */
+			ToggledOn, /**< Button has been pressed this frame. */
+			ToggledOff, /**< Button has been released this frame. */
+			ToggledOnOff, /**< Button has been pressed and released this frame. */
+		};
+
+		/** Contains axis and device data per device. */
+		struct DeviceData
+		{
+			DeviceData();
+
+			Vector<RawAxisState> axes;
+			ButtonState keyStates[BC_Count];
+		};
+
+		/**	Different types of possible input event callbacks. */
+		enum class EventType
+		{
+			ButtonUp, ButtonDown, PointerMoved, PointerUp, PointerDown, PointerDoubleClick, TextInput, Command
+		};
+
+		/**	Stores information about a queued input event that is to be triggered later. */
+		struct QueuedEvent
+		{
+			QueuedEvent(EventType type, UINT32 idx)
+				:type(type), idx(idx)
+			{ }
+
+			EventType type;
+			UINT32 idx;
+		};
+
+	public:
+		Input();
+		~Input();
+
+		/**
+		 * Returns value of the specified input axis. Normally in range [-1.0, 1.0] but can be outside the range for 
+		 * devices with unbound axes (for example mouse).
+		 *
+		 * @param[in]	type		Type of axis to query. Usually a type from InputAxis but can be a custom value.
+		 * @param[in]	deviceIdx	Index of the device in case more than one is hooked up (0 - primary).
+		 */
+		float getAxisValue(UINT32 type, UINT32 deviceIdx = 0) const;
+
+		/**
+		 * Query if the provided button is currently being held (this frame or previous frames).
+		 *
+		 * @param[in]	keyCode		Code of the button to query.
+		 * @param[in]	deviceIdx	Device to query the button on (0 - primary).
+		 */
+		bool isButtonHeld(ButtonCode keyCode, UINT32 deviceIdx = 0) const;
+
+		/**
+		 * Query if the provided button is currently being released (only true for one frame).
+		 *
+		 * @param[in]	keyCode		Code of the button to query.
+		 * @param[in]	deviceIdx	Device to query the button on (0 - primary).
+		 */
+		bool isButtonUp(ButtonCode keyCode, UINT32 deviceIdx = 0) const;
+
+		/**
+		 * Query if the provided button is currently being pressed (only true for one frame).
+		 *
+		 * @param[in]	keyCode		Code of the button to query.
+		 * @param[in]	deviceIdx	Device to query the button on (0 - primary).
+		 */
+		bool isButtonDown(ButtonCode keyCode, UINT32 deviceIdx = 0) const;
+
+		/** Returns position of the pointer (for example mouse cursor) relative to the screen. */
+		Vector2I getPointerPosition() const;
+
+		/** Returns difference between last and current pointer position. */
+		Vector2I getPointerDelta() const { return mPointerDelta; }
+
+		/**
+		 * Query if the provided pointer button is currently being held (this frame or previous frames).
+		 *
+		 * @param[in]	pointerButton		Code of the button to query.
+		 */
+		bool isPointerButtonHeld(PointerEventButton pointerButton) const;
+
+		/**
+		 * Query if the provided pointer button is currently being released (only true for one frame).
+		 *
+		 * @param[in]	pointerButton		Code of the button to query.
+		 */
+		bool isPointerButtonUp(PointerEventButton pointerButton) const;
+
+		/**
+		 * Query if the provided pointer button is currently being pressed (only true for one frame).
+		 *
+		 * @param[in]	pointerButton		Code of the button to query.
+		 */
+		bool isPointerButtonDown(PointerEventButton pointerButton) const;
+
+		/** Query has the left pointer button has been double-clicked this frame. */
+		bool isPointerDoubleClicked() const;
+
+		/** Enables or disables mouse smoothing. Smoothing makes the changes to mouse axes more gradual. */
+		void setMouseSmoothing(bool enabled);
+
+		/** Triggered whenever a button is first pressed. */
+		Event<void(const ButtonEvent&)> onButtonDown;
+
+		/**	Triggered whenever a button is first released. */
+		Event<void(const ButtonEvent&)> onButtonUp;
+
+		/**	Triggered whenever user inputs a text character. */
+		Event<void(const TextInputEvent&)> onCharInput;
+
+		/**	Triggers when some pointing device (mouse cursor, touch) moves. */
+		Event<void(const PointerEvent&)> onPointerMoved;
+
+		/**	Triggers when some pointing device (mouse cursor, touch) button is pressed. */
+		Event<void(const PointerEvent&)> onPointerPressed;
+
+		/**	Triggers when some pointing device (mouse cursor, touch) button is released. */
+		Event<void(const PointerEvent&)> onPointerReleased;
+
+		/**	Triggers when some pointing device (mouse cursor, touch) button is double clicked. */
+		Event<void(const PointerEvent&)> onPointerDoubleClick;
+
+		// TODO Low priority: Remove this, I can emulate it using virtual input
+		/**	Triggers on special input commands. */
+		Event<void(InputCommandType)> onInputCommand;
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Registers a new input handler. Replaces any previous input handler.
+		 *
+		 * @note	Internal method.
+		 */
+		void _registerRawInputHandler(std::shared_ptr<RawInputHandler> inputHandler);
+
+		/**
+		 * Called every frame. Detects button state changes and prepares callback events to trigger via a call to 
+		 * _triggerCallbacks().
+		 *
+		 * @note	Internal method.
+		 */
+		void _update();
+
+		/**
+		 * Triggers any queued input event callbacks.
+		 * 
+		 * @note	Internal method.
+		 */
+		void _triggerCallbacks();
+
+		/** @} */
+
+	private:
+		/**	Triggered by input handler when a button is pressed. */
+		void buttonDown(UINT32 deviceIdx, ButtonCode code, UINT64 timestamp);
+
+		/**	Triggered by input handler when a button is released. */
+		void buttonUp(UINT32 deviceIdx, ButtonCode code, UINT64 timestamp);
+
+		/**	Triggered by input handler when a single character is input. */
+		void charInput(UINT32 chr);
+
+		/**	Triggered by input handler when a mouse/joystick axis is moved. */
+		void axisMoved(UINT32 deviceIdx, const RawAxisState& state, UINT32 axis);
+
+		/**	Cursor movement as OS reports it. Used for screen cursor position. */
+		void cursorMoved(const PointerEvent& event);
+
+		/**	Cursor button presses as OS reports it. */
+		void cursorPressed(const PointerEvent& event);
+
+		/**	Cursor button releases as OS reports it. */
+		void cursorReleased(const PointerEvent& event);
+		
+		/**	Cursor button releases as OS reports it. */
+		void cursorDoubleClick(const PointerEvent& event);
+
+		/** Input commands as OS reports them. */
+		void inputCommandEntered(InputCommandType commandType);
+
+		/** Called when window in focus changes, as reported by the OS. */
+		void inputWindowChanged(RenderWindow& win);
+
+	private:
+		std::shared_ptr<RawInputHandler> mRawInputHandler;
+		std::shared_ptr<OSInputHandler> mOSInputHandler;
+
+		Vector<DeviceData> mDevices;
+		Vector2I mPointerPosition;
+		Vector2I mPointerDelta;
+		ButtonState mPointerButtonStates[3];
+		bool mPointerDoubleClicked;
+		bool mLastPositionSet;
+
+		Vector<QueuedEvent> mQueuedEvents;
+
+		Vector<TextInputEvent> mTextInputEvents;
+		Vector<InputCommandType> mCommandEvents;
+		Vector<PointerEvent> mPointerDoubleClickEvents;
+		Vector<PointerEvent> mPointerReleasedEvents;
+		Vector<PointerEvent> mPointerPressedEvents;
+		Vector<PointerEvent> mPointerMovedEvents;
+
+		Vector<ButtonEvent> mButtonDownEvents;
+		Vector<ButtonEvent> mButtonUpEvents;
+
+		/************************************************************************/
+		/* 								STATICS		                      		*/
+		/************************************************************************/
+		static const int HISTORY_BUFFER_SIZE; // Size of buffer used for input smoothing
+		static const float WEIGHT_MODIFIER;
+	};
+
+	/** Provides easier access to Input. */
+	BS_CORE_EXPORT Input& gInput();
+
+	/** @} */
 }

+ 9 - 4
Source/BansheeCore/Include/BsInputFwd.h

@@ -310,16 +310,21 @@ namespace BansheeEngine
 
 		Vector2I screenPos; /**< Screen position where the input event occurred. */
 		Vector2I delta; /**< Change in movement since last sent event. */
-		bool buttonStates[(UINT32)PointerEventButton::Count]; /**< States of the pointer buttons (e.g. mouse buttons). */
-		PointerEventButton button; /**< Button that triggered the pointer event. Might be irrelevant 
-										depending on event type. (e.g. move events don't correspond to a button. */
+		/** States of the pointer buttons (for example mouse buttons). */
+		bool buttonStates[(UINT32)PointerEventButton::Count]; 
+		/**
+		 * Button that triggered the pointer event. Might be irrelevant depending on event type. (for example move events
+		 * don't correspond to a button.
+		 */
+		PointerEventButton button;
 		PointerEventType type; /**< Type of the pointer event. */
 
 		bool shift; /**< Is shift button on the keyboard being held down. */
 		bool control; /**< Is control button on the keyboard being held down. */
 		bool alt; /**< Is alt button on the keyboard being held down. */
 
-		float mouseWheelScrollAmount; /**< If mouse wheel is being scrolled, what is the amount. Only relevant for move events. */
+		/** If mouse wheel is being scrolled, what is the amount. Only relevant for move events. */
+		float mouseWheelScrollAmount; 
 
 		/**
 		 * Check if the event has been marked as used. Internally this means nothing but caller might choose to ignore an 

+ 325 - 323
Source/BansheeCore/Include/BsJoint.h

@@ -1,324 +1,326 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPhysicsCommon.h"
-#include "BsFJoint.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** 
-	 * Base class for all Joint types. Joints constrain how two rigidbodies move relative to one another (e.g. a door 
-	 * hinge). One of the bodies in the joint must always be movable (i.e. non-kinematic).
-	 */
-	class BS_CORE_EXPORT Joint
-	{
-	public:
-		virtual ~Joint() { }
-
-		/** @copydoc FJoint::getBody */
-		inline Rigidbody* getBody(JointBody body) const;
-
-		/** @copydoc FJoint::setBody */
-		inline void setBody(JointBody body, Rigidbody* value);
-
-		/** @copydoc FJoint::getPosition */
-		inline Vector3 getPosition(JointBody body) const;
-
-		/** @copydoc FJoint::getRotation */
-		inline Quaternion getRotation(JointBody body) const;
-
-		/** @copydoc FJoint::setTransform */
-		inline void setTransform(JointBody body, const Vector3& position, const Quaternion& rotation);
-
-		/** @copydoc FJoint::getBreakForce */
-		inline float getBreakForce() const;
-
-		/** @copydoc FJoint::setBreakForce */
-		inline void setBreakForce(float force);
-
-		/** @copydoc FJoint::getBreakTorque */
-		inline float getBreakTorque() const;
-
-		/** @copydoc FJoint::setBreakTorque */
-		inline void setBreakTorque(float torque);
-
-		/** @copydoc FJoint::getEnableCollision */
-		inline bool getEnableCollision() const;
-
-		/** @copydoc FJoint::setEnableCollision */
-		inline void setEnableCollision(bool value);
-
-		/** Triggered when the joint's break force or torque is exceeded. */
-		Event<void()> onJointBreak;
-
-		/** @cond INTERNAL */
-
-		/** 
-		 * Sets the object that owns this physics object, if any. Used for high level systems so they can easily map their
-		 * high level physics objects from the low level ones returned by various queries and events.
-		 */
-		void _setOwner(PhysicsOwnerType type, void* owner) { mOwner.type = type; mOwner.ownerData = owner; }
-
-		/** 
-		 * Gets the object that owns this physics object, if any. Used for high level systems so they can easily map their
-		 * high level physics objects from the low level ones returned by various queries and events.
-		 */
-		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
-
-		/** @endcond */
-
-	protected:
-		PhysicsObjectOwner mOwner;
-		FJoint* mInternal = nullptr;
-	};
-
-	/** 
-	 * Controls spring parameters for a physics joint limits. If a limit is soft (body bounces back due to restition when 
-	 * the limit is reached) the spring will pull the body back towards the limit using the specified parameters.
-	 */
-	struct Spring
-	{
-		/** Constructs a spring with no force. */
-		Spring() { }
-
-		/** 
-		 * Constructs a spring. 
-		 *
-		 * @param	stiffness	Spring strength. Force proportional to the position error.
-		 * @param	damping		Damping strength. Force propertional to the velocity error.
-		 */
-		Spring(float stiffness, float damping)
-			:stiffness(stiffness), damping(damping)
-		{ }
-
-		bool operator==(const Spring& other) const
-		{
-			return stiffness == other.stiffness && damping == other.damping;
-		}
-
-		/** Spring strength. Force proportional to the position error. */
-		float stiffness = 0.0f;
-
-		/** Damping strength. Force propertional to the velocity error. */
-		float damping = 0.0f;
-	};
-
-	/** Contains common values used by all Joint limit types. */
-	struct LimitCommon
-	{
-		LimitCommon(float contactDist = -1.0f)
-			:contactDist(contactDist)
-		{ }
-
-		LimitCommon(const Spring& spring, float restitution = 0.0f)
-			:spring(spring), restitution(restitution)
-		{ }
-
-		/** 
-		 * Distance from the limit at which it becomes active. Allows the solver to activate earlier than the limit is
-		 * reached to avoid breaking the limit.
-		 */
-		float contactDist = -1.0f;
-
-		/**
-		 * Controls how do objects react when the limit is reached, values closer to zero specify non-ellastic collision,
-		 * while those closer to one specify more ellastic (i.e bouncy) collision. Must be in [0, 1] range.
-		 */
-		float restitution = 0.0f;
-
-		/** Spring that controls how are the bodies pulled back towards the limit when they breach it. */
-		Spring spring;
-	};
-
-	/** Represents a joint limit between two distance values. Lower value must be less than the upper value. */
-	struct LimitLinearRange : LimitCommon
-	{
-		/** Constructs an empty limit. */
-		LimitLinearRange()
-		{ }
-
-		/**
-		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
-		 * 
-		 * @param	lower		Lower distance of the limit. Must be less than @p upper.
-		 * @param	upper		Upper distance of the limit. Must be more than @p lower.
-		 * @param	contactDist	Distance from the limit at which it becomes active. Allows the solver to activate earlier
-		 *						than the limit is reached to avoid breaking the limit. Specify -1 for the default.
-		 */
-		LimitLinearRange(float lower, float upper, float contactDist = -1.0f)
-			:LimitCommon(contactDist), lower(lower), upper(upper)
-		{ }
-
-		/**
-		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
-		 * parameter and will be pulled back towards the limit by the provided spring.
-		 * 
-		 * @param	lower		Lower distance of the limit. Must be less than @p upper.
-		 * @param	upper		Upper distance of the limit. Must be more than @p lower.
-		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
-		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
-		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
-		 *						collision. Must be in [0, 1] range.
-		 */
-		LimitLinearRange(float lower, float upper, const Spring& spring, float restitution = 0.0f)
-			:LimitCommon(spring, restitution), lower(lower), upper(upper)
-		{ }
-
-		bool operator==(const LimitLinearRange& other) const
-		{
-			return lower == other.lower && upper == other.upper && contactDist == other.contactDist && 
-				restitution == other.restitution && spring == other.spring;
-		}
-
-		/** Lower distance of the limit. Must be less than #upper. */
-		float lower = 0.0f; 
-
-		/** Upper distance of the limit. Must be more than #lower. */
-		float upper = 0.0f;
-	};
-
-	/** Represents a joint limit between zero a single distance value. */
-	struct LimitLinear : LimitCommon
-	{
-		/** Constructs an empty limit. */
-		LimitLinear()
-		{ }
-
-		/**
-		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
-		 * 
-		 * @param	extent		Distance at which the limit becomes active. 
-		 * @param	contactDist	Distance from the limit at which it becomes active. Allows the solver to activate earlier
-		 *						than the limit is reached to avoid breaking the limit. Specify -1 for the default.
-		 */
-		LimitLinear(float extent, float contactDist = -1.0f)
-			:LimitCommon(contactDist), extent(extent)
-		{ }
-
-		/**
-		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
-		 * parameter and will be pulled back towards the limit by the provided spring.
-		 * 
-		 * @param	extent		Distance at which the limit becomes active. 
-		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
-		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
-		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
-		 *						collision. Must be in [0, 1] range.
-		 */
-		LimitLinear(float extent, const Spring& spring, float restitution = 0.0f)
-			:LimitCommon(spring, restitution), extent(extent)
-		{ }
-
-		bool operator==(const LimitLinear& other) const
-		{
-			return extent == other.extent && contactDist == other.contactDist && restitution == other.restitution &&
-				spring == other.spring;
-		}
-
-		/** Distance at which the limit becomes active. */
-		float extent = 0.0f;
-	};
-
-	/** Represents a joint limit between two angles. */
-	struct LimitAngularRange : LimitCommon
-	{
-		/** Constructs an empty limit. */
-		LimitAngularRange()
-		{ }
-
-		/**
-		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
-		 * 
-		 * @param	lower		Lower angle of the limit. Must be less than @p upper.
-		 * @param	upper		Upper angle of the limit. Must be more than @p lower.
-		 * @param	contactDist	Distance from the limit at which it becomes active. Allows the solver to activate earlier
-		 *						than the limit is reached to avoid breaking the limit. Specify -1 for the default.
-		 */
-		LimitAngularRange(Radian lower, Radian upper, float contactDist = -1.0f)
-			:LimitCommon(contactDist), lower(lower), upper(upper)
-		{ }
-
-		/**
-		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
-		 * parameter and will be pulled back towards the limit by the provided spring.
-		 * 
-		 * @param	lower		Lower angle of the limit. Must be less than @p upper.
-		 * @param	upper		Upper angle of the limit. Must be more than @p lower.
-		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
-		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
-		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
-		 *						collision. Must be in [0, 1] range.
-		 */
-		LimitAngularRange(Radian lower, Radian upper, const Spring& spring, float restitution = 0.0f)
-			:LimitCommon(spring, restitution), lower(lower), upper(upper)
-		{ }
-
-		bool operator==(const LimitAngularRange& other) const
-		{
-			return lower == other.lower && upper == other.upper && contactDist == other.contactDist && 
-				restitution == other.restitution && spring == other.spring;
-		}
-
-		/** Lower angle of the limit. Must be less than #upper. */
-		Radian lower = Radian(0.0f);
-
-		/** Upper angle of the limit. Must be less than #lower. */
-		Radian upper = Radian(0.0f);
-	};
-
-	/** Represents a joint limit that contraints movement to within an elliptical cone. */
-	struct LimitConeRange : LimitCommon
-	{
-		/** Constructs a limit with a 45 degree cone. */
-		LimitConeRange()
-		{ }
-
-		/**
-		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
-		 * 
-		 * @param	yLimitAngle		Y angle of the cone. Movement is constrainted between 0 and this angle on the Y axis.
-		 * @param	zLimitAngle		Z angle of the cone. Movement is constrainted between 0 and this angle on the Z axis.
-		 * @param	contactDist		Distance from the limit at which it becomes active. Allows the solver to activate 
-		 *							earlier than the limit is reached to avoid breaking the limit. Specify -1 for the 
-		 *							default.
-		 */
-		LimitConeRange(Radian yLimitAngle, Radian zLimitAngle, float contactDist = -1.0f)
-			:LimitCommon(contactDist), yLimitAngle(yLimitAngle), zLimitAngle(zLimitAngle)
-		{ }
-
-		/**
-		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
-		 * parameter and will be pulled back towards the limit by the provided spring.
-		 * 
-		 * @param	yLimitAngle	Y angle of the cone. Movement is constrainted between 0 and this angle on the Y axis.
-		 * @param	zLimitAngle	Z angle of the cone. Movement is constrainted between 0 and this angle on the Z axis.
-		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
-		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
-		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
-		 *						collision. Must be in [0, 1] range.
-		 */
-		LimitConeRange(Radian yLimitAngle, Radian zLimitAngle, const Spring& spring, float restitution = 0.0f)
-			:LimitCommon(spring, restitution), yLimitAngle(yLimitAngle), zLimitAngle(zLimitAngle)
-		{ }
-
-		bool operator==(const LimitConeRange& other) const
-		{
-			return yLimitAngle == other.yLimitAngle && zLimitAngle == other.zLimitAngle && 
-				contactDist == other.contactDist && restitution == other.restitution && spring == other.spring;
-		}
-
-		/** Y angle of the cone. Movement is constrainted between 0 and this angle on the Y axis. */
-		Radian yLimitAngle = Radian(Math::PI * 0.5f);
-
-		/** Z angle of the cone. Movement is constrainted between 0 and this angle on the Z axis. */
-		Radian zLimitAngle = Radian(Math::PI * 0.5f);
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPhysicsCommon.h"
+#include "BsFJoint.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/** 
+	 * Base class for all Joint types. Joints constrain how two rigidbodies move relative to one another (for example a door 
+	 * hinge). One of the bodies in the joint must always be movable (non-kinematic).
+	 */
+	class BS_CORE_EXPORT Joint
+	{
+	public:
+		virtual ~Joint() { }
+
+		/** @copydoc FJoint::getBody */
+		inline Rigidbody* getBody(JointBody body) const;
+
+		/** @copydoc FJoint::setBody */
+		inline void setBody(JointBody body, Rigidbody* value);
+
+		/** @copydoc FJoint::getPosition */
+		inline Vector3 getPosition(JointBody body) const;
+
+		/** @copydoc FJoint::getRotation */
+		inline Quaternion getRotation(JointBody body) const;
+
+		/** @copydoc FJoint::setTransform */
+		inline void setTransform(JointBody body, const Vector3& position, const Quaternion& rotation);
+
+		/** @copydoc FJoint::getBreakForce */
+		inline float getBreakForce() const;
+
+		/** @copydoc FJoint::setBreakForce */
+		inline void setBreakForce(float force);
+
+		/** @copydoc FJoint::getBreakTorque */
+		inline float getBreakTorque() const;
+
+		/** @copydoc FJoint::setBreakTorque */
+		inline void setBreakTorque(float torque);
+
+		/** @copydoc FJoint::getEnableCollision */
+		inline bool getEnableCollision() const;
+
+		/** @copydoc FJoint::setEnableCollision */
+		inline void setEnableCollision(bool value);
+
+		/** Triggered when the joint's break force or torque is exceeded. */
+		Event<void()> onJointBreak;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** 
+		 * Sets the object that owns this physics object, if any. Used for high level systems so they can easily map their
+		 * high level physics objects from the low level ones returned by various queries and events.
+		 */
+		void _setOwner(PhysicsOwnerType type, void* owner) { mOwner.type = type; mOwner.ownerData = owner; }
+
+		/** 
+		 * Gets the object that owns this physics object, if any. Used for high level systems so they can easily map their
+		 * high level physics objects from the low level ones returned by various queries and events.
+		 */
+		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
+
+		/** @} */
+
+	protected:
+		PhysicsObjectOwner mOwner;
+		FJoint* mInternal = nullptr;
+	};
+
+	/** 
+	 * Controls spring parameters for a physics joint limits. If a limit is soft (body bounces back due to restition when 
+	 * the limit is reached) the spring will pull the body back towards the limit using the specified parameters.
+	 */
+	struct Spring
+	{
+		/** Constructs a spring with no force. */
+		Spring() { }
+
+		/** 
+		 * Constructs a spring. 
+		 *
+		 * @param	stiffness	Spring strength. Force proportional to the position error.
+		 * @param	damping		Damping strength. Force propertional to the velocity error.
+		 */
+		Spring(float stiffness, float damping)
+			:stiffness(stiffness), damping(damping)
+		{ }
+
+		bool operator==(const Spring& other) const
+		{
+			return stiffness == other.stiffness && damping == other.damping;
+		}
+
+		/** Spring strength. Force proportional to the position error. */
+		float stiffness = 0.0f;
+
+		/** Damping strength. Force propertional to the velocity error. */
+		float damping = 0.0f;
+	};
+
+	/** Contains common values used by all Joint limit types. */
+	struct LimitCommon
+	{
+		LimitCommon(float contactDist = -1.0f)
+			:contactDist(contactDist)
+		{ }
+
+		LimitCommon(const Spring& spring, float restitution = 0.0f)
+			:spring(spring), restitution(restitution)
+		{ }
+
+		/** 
+		 * Distance from the limit at which it becomes active. Allows the solver to activate earlier than the limit is
+		 * reached to avoid breaking the limit.
+		 */
+		float contactDist = -1.0f;
+
+		/**
+		 * Controls how do objects react when the limit is reached, values closer to zero specify non-ellastic collision,
+		 * while those closer to one specify more ellastic (i.e bouncy) collision. Must be in [0, 1] range.
+		 */
+		float restitution = 0.0f;
+
+		/** Spring that controls how are the bodies pulled back towards the limit when they breach it. */
+		Spring spring;
+	};
+
+	/** Represents a joint limit between two distance values. Lower value must be less than the upper value. */
+	struct LimitLinearRange : LimitCommon
+	{
+		/** Constructs an empty limit. */
+		LimitLinearRange()
+		{ }
+
+		/**
+		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
+		 * 
+		 * @param	lower		Lower distance of the limit. Must be less than @p upper.
+		 * @param	upper		Upper distance of the limit. Must be more than @p lower.
+		 * @param	contactDist	Distance from the limit at which it becomes active. Allows the solver to activate earlier
+		 *						than the limit is reached to avoid breaking the limit. Specify -1 for the default.
+		 */
+		LimitLinearRange(float lower, float upper, float contactDist = -1.0f)
+			:LimitCommon(contactDist), lower(lower), upper(upper)
+		{ }
+
+		/**
+		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
+		 * parameter and will be pulled back towards the limit by the provided spring.
+		 * 
+		 * @param	lower		Lower distance of the limit. Must be less than @p upper.
+		 * @param	upper		Upper distance of the limit. Must be more than @p lower.
+		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
+		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
+		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
+		 *						collision. Must be in [0, 1] range.
+		 */
+		LimitLinearRange(float lower, float upper, const Spring& spring, float restitution = 0.0f)
+			:LimitCommon(spring, restitution), lower(lower), upper(upper)
+		{ }
+
+		bool operator==(const LimitLinearRange& other) const
+		{
+			return lower == other.lower && upper == other.upper && contactDist == other.contactDist && 
+				restitution == other.restitution && spring == other.spring;
+		}
+
+		/** Lower distance of the limit. Must be less than #upper. */
+		float lower = 0.0f; 
+
+		/** Upper distance of the limit. Must be more than #lower. */
+		float upper = 0.0f;
+	};
+
+	/** Represents a joint limit between zero a single distance value. */
+	struct LimitLinear : LimitCommon
+	{
+		/** Constructs an empty limit. */
+		LimitLinear()
+		{ }
+
+		/**
+		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
+		 * 
+		 * @param	extent		Distance at which the limit becomes active. 
+		 * @param	contactDist	Distance from the limit at which it becomes active. Allows the solver to activate earlier
+		 *						than the limit is reached to avoid breaking the limit. Specify -1 for the default.
+		 */
+		LimitLinear(float extent, float contactDist = -1.0f)
+			:LimitCommon(contactDist), extent(extent)
+		{ }
+
+		/**
+		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
+		 * parameter and will be pulled back towards the limit by the provided spring.
+		 * 
+		 * @param	extent		Distance at which the limit becomes active. 
+		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
+		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
+		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
+		 *						collision. Must be in [0, 1] range.
+		 */
+		LimitLinear(float extent, const Spring& spring, float restitution = 0.0f)
+			:LimitCommon(spring, restitution), extent(extent)
+		{ }
+
+		bool operator==(const LimitLinear& other) const
+		{
+			return extent == other.extent && contactDist == other.contactDist && restitution == other.restitution &&
+				spring == other.spring;
+		}
+
+		/** Distance at which the limit becomes active. */
+		float extent = 0.0f;
+	};
+
+	/** Represents a joint limit between two angles. */
+	struct LimitAngularRange : LimitCommon
+	{
+		/** Constructs an empty limit. */
+		LimitAngularRange()
+		{ }
+
+		/**
+		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
+		 * 
+		 * @param	lower		Lower angle of the limit. Must be less than @p upper.
+		 * @param	upper		Upper angle of the limit. Must be more than @p lower.
+		 * @param	contactDist	Distance from the limit at which it becomes active. Allows the solver to activate earlier
+		 *						than the limit is reached to avoid breaking the limit. Specify -1 for the default.
+		 */
+		LimitAngularRange(Radian lower, Radian upper, float contactDist = -1.0f)
+			:LimitCommon(contactDist), lower(lower), upper(upper)
+		{ }
+
+		/**
+		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
+		 * parameter and will be pulled back towards the limit by the provided spring.
+		 * 
+		 * @param	lower		Lower angle of the limit. Must be less than @p upper.
+		 * @param	upper		Upper angle of the limit. Must be more than @p lower.
+		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
+		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
+		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
+		 *						collision. Must be in [0, 1] range.
+		 */
+		LimitAngularRange(Radian lower, Radian upper, const Spring& spring, float restitution = 0.0f)
+			:LimitCommon(spring, restitution), lower(lower), upper(upper)
+		{ }
+
+		bool operator==(const LimitAngularRange& other) const
+		{
+			return lower == other.lower && upper == other.upper && contactDist == other.contactDist && 
+				restitution == other.restitution && spring == other.spring;
+		}
+
+		/** Lower angle of the limit. Must be less than #upper. */
+		Radian lower = Radian(0.0f);
+
+		/** Upper angle of the limit. Must be less than #lower. */
+		Radian upper = Radian(0.0f);
+	};
+
+	/** Represents a joint limit that contraints movement to within an elliptical cone. */
+	struct LimitConeRange : LimitCommon
+	{
+		/** Constructs a limit with a 45 degree cone. */
+		LimitConeRange()
+		{ }
+
+		/**
+		 * Constructs a hard limit. Once the limit is reached the movement of the attached bodies will come to a stop.
+		 * 
+		 * @param	yLimitAngle		Y angle of the cone. Movement is constrainted between 0 and this angle on the Y axis.
+		 * @param	zLimitAngle		Z angle of the cone. Movement is constrainted between 0 and this angle on the Z axis.
+		 * @param	contactDist		Distance from the limit at which it becomes active. Allows the solver to activate 
+		 *							earlier than the limit is reached to avoid breaking the limit. Specify -1 for the 
+		 *							default.
+		 */
+		LimitConeRange(Radian yLimitAngle, Radian zLimitAngle, float contactDist = -1.0f)
+			:LimitCommon(contactDist), yLimitAngle(yLimitAngle), zLimitAngle(zLimitAngle)
+		{ }
+
+		/**
+		 * Constructs a soft limit. Once the limit is reached the bodies will bounce back according to the resitution
+		 * parameter and will be pulled back towards the limit by the provided spring.
+		 * 
+		 * @param	yLimitAngle	Y angle of the cone. Movement is constrainted between 0 and this angle on the Y axis.
+		 * @param	zLimitAngle	Z angle of the cone. Movement is constrainted between 0 and this angle on the Z axis.
+		 * @param	spring		Spring that controls how are the bodies pulled back towards the limit when they breach it.
+		 * @param	resitution	Controls how do objects react when the limit is reached, values closer to zero specify
+		 *						non-ellastic collision, while those closer to one specify more ellastic (i.e bouncy)
+		 *						collision. Must be in [0, 1] range.
+		 */
+		LimitConeRange(Radian yLimitAngle, Radian zLimitAngle, const Spring& spring, float restitution = 0.0f)
+			:LimitCommon(spring, restitution), yLimitAngle(yLimitAngle), zLimitAngle(zLimitAngle)
+		{ }
+
+		bool operator==(const LimitConeRange& other) const
+		{
+			return yLimitAngle == other.yLimitAngle && zLimitAngle == other.zLimitAngle && 
+				contactDist == other.contactDist && restitution == other.restitution && spring == other.spring;
+		}
+
+		/** Y angle of the cone. Movement is constrainted between 0 and this angle on the Y axis. */
+		Radian yLimitAngle = Radian(Math::PI * 0.5f);
+
+		/** Z angle of the cone. Movement is constrainted between 0 and this angle on the Z axis. */
+		Radian zLimitAngle = Radian(Math::PI * 0.5f);
+	};
+
+	/** @} */
 }

+ 302 - 302
Source/BansheeCore/Include/BsMaterialParam.h

@@ -1,303 +1,303 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsGpuParam.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	class MaterialParams;
-
-	/**
-	 * A handle that allows you to set a Material parameter. Internally keeps a reference to the material parameters so that
-	 * possibly expensive lookup of parameter name can be avoided each time the parameter is accessed, and instead the 
-	 * handle can be cached.
-	 * 			
-	 * @note	
-	 * This is pretty much identical to GPU parameter version (e.g. TGpuDataParam), except that this will get/set parameter 
-	 * values on all GPU programs attached to the material, while TGpuDataParam works only for single GPU program's 
-	 * parameters. Also, additional parameters that might be optimized out in the GPU program will still exist here as long 
-	 * as they're  defined in the shader used by the material, which is not the case with TGpuDataParam.
-	 * @note
-	 * For core-thread version of this class no shader-based caching is done, and instead this represents just a wrapper
-	 * for multiple GPU parameters.
-	 * 
-	 * @see		Material
-	 */
-	template<class T, bool Core>
-	class BS_CORE_EXPORT TMaterialDataParam
-	{ };
-
-	/** @copydoc TMaterialDataParam */
-	template<class T>
-	class BS_CORE_EXPORT TMaterialDataParam<T, false>
-	{
-	public:
-		TMaterialDataParam(const String& name, const SPtr<MaterialParams>& params, 
-			const SPtr<Vector<TGpuDataParam<T, false>>>& gpuParams);
-		TMaterialDataParam() { }
-
-		/** @copydoc TGpuDataParam::set */
-		void set(const T& value, UINT32 arrayIdx = 0);
-
-		/** @copydoc TGpuDataParam::get */
-		T get(UINT32 arrayIdx = 0);
-
-	protected:
-		UINT32 mParamIndex;
-		UINT32 mArraySize;
-		SPtr<MaterialParams> mMaterialParams;
-		SPtr<Vector<TGpuDataParam<T, false>>> mGPUParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<class T>
-	class BS_CORE_EXPORT TMaterialDataParam<T, true>
-	{
-	public:
-		TMaterialDataParam(const SPtr<Vector<TGpuDataParam<T, true>>>& params);
-		TMaterialDataParam() { }
-
-		/** @copydoc TGpuDataParam::set */
-		void set(const T& value, UINT32 arrayIdx = 0);
-
-		/** @copydoc TGpuDataParam::get */
-		T get(UINT32 arrayIdx = 0);
-
-	protected:
-		SPtr<Vector<TGpuDataParam<T, true>>> mParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<bool Core>
-	class BS_CORE_EXPORT TMaterialParamStruct
-	{ };
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamStruct<false>
-	{
-	public:
-		TMaterialParamStruct(const String& name, const SPtr<MaterialParams>& params,
-			const SPtr<Vector<TGpuParamStruct<false>>>& gpuParams);
-		TMaterialParamStruct() { }
-
-		/** @copydoc TGpuParamStruct::set */
-		void set(const void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
-
-		/** @copydoc TGpuParamStruct::get */
-		void get(void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
-
-		/** @copydoc TGpuParamStruct::getElementSize */
-		UINT32 getElementSize() const;
-
-	protected:
-		UINT32 mParamIndex;
-		UINT32 mArraySize;
-		SPtr<MaterialParams> mMaterialParams;
-		SPtr<Vector<TGpuParamStruct<false>>> mGPUParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamStruct<true>
-	{
-	public:
-		TMaterialParamStruct(const SPtr<Vector<TGpuParamStruct<true>>>& params);
-		TMaterialParamStruct() { }
-
-		/** @copydoc TGpuParamStruct::set */
-		void set(const void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
-
-		/** @copydoc TGpuParamStruct::get */
-		void get(void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
-
-		/** @copydoc TGpuParamStruct::getElementSize */
-		UINT32 getElementSize() const;
-
-	protected:
-		SPtr<Vector<TGpuParamStruct<true>>> mParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<bool Core>
-	class BS_CORE_EXPORT TMaterialParamTexture
-	{ };
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamTexture<false>
-	{
-	public:
-		TMaterialParamTexture(const String& name, const SPtr<MaterialParams>& params, 
-			const SPtr<Vector<TGpuParamTexture<false>>>& gpuParams);
-		TMaterialParamTexture() { }
-
-		/** @copydoc GpuParamTexture::set */
-		void set(const HTexture& texture);
-
-		/** @copydoc GpuParamTexture::get */
-		HTexture get();
-
-	protected:
-		UINT32 mParamIndex;
-		SPtr<MaterialParams> mMaterialParams;
-		SPtr<Vector<TGpuParamTexture<false>>> mGPUParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamTexture<true>
-	{
-	public:
-		TMaterialParamTexture(const SPtr<Vector<TGpuParamTexture<true>>>& params);
-		TMaterialParamTexture() { }
-
-		/** @copydoc GpuParamTexture::set */
-		void set(const SPtr<TextureCore>& texture);
-
-		/** @copydoc GpuParamTexture::get */
-		SPtr<TextureCore> get();
-
-	protected:
-		SPtr<Vector<TGpuParamTexture<true>>> mParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<bool Core>
-	class BS_CORE_EXPORT TMaterialParamLoadStoreTexture
-	{ };
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamLoadStoreTexture<false>
-	{
-	public:
-		TMaterialParamLoadStoreTexture(const String& name, const SPtr<MaterialParams>& params,
-			const SPtr<Vector<TGpuParamLoadStoreTexture<false>>>& gpuParams);
-		TMaterialParamLoadStoreTexture() { }
-
-		/** @copydoc GpuParamLoadStoreTexture::set */
-		void set(const HTexture& texture, const TextureSurface& surface);
-
-		/** @copydoc GpuParamLoadStoreTexture::get */
-		HTexture get();
-
-	protected:
-		UINT32 mParamIndex;
-		SPtr<MaterialParams> mMaterialParams;
-		SPtr<Vector<TGpuParamLoadStoreTexture<false>>> mGPUParams;
-	};
-
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamLoadStoreTexture<true>
-	{
-	public:
-		TMaterialParamLoadStoreTexture(const SPtr<Vector<TGpuParamLoadStoreTexture<true>>>& params);
-		TMaterialParamLoadStoreTexture() { }
-
-		/** @copydoc GpuParamLoadStoreTexture::set */
-		void set(const SPtr<TextureCore>& texture, const TextureSurface& surface);
-
-		/** @copydoc GpuParamLoadStoreTexture::get */
-		SPtr<TextureCore> get();
-
-	protected:
-		SPtr<Vector<TGpuParamLoadStoreTexture<true>>> mParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<bool Core>
-	class BS_CORE_EXPORT TMaterialParamSampState
-	{ };
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamSampState<false>
-	{
-	public:
-		TMaterialParamSampState(const String& name, const SPtr<MaterialParams>& params, 
-			const SPtr<Vector<TGpuParamSampState<false>>>& gpuParams);
-		TMaterialParamSampState() { }
-
-		/** @copydoc GpuParamSampState::set */
-		void set(const SPtr<SamplerState>& sampState);
-
-		/** @copydoc GpuParamSampState::get */
-		SPtr<SamplerState> get();
-
-	protected:
-		UINT32 mParamIndex;
-		SPtr<MaterialParams> mMaterialParams;
-		SPtr<Vector<TGpuParamSampState<false>>> mGPUParams;
-	};
-
-	/** @copydoc TMaterialDataParam */
-	template<>
-	class BS_CORE_EXPORT TMaterialParamSampState<true>
-	{
-	public:
-		TMaterialParamSampState(const SPtr<Vector<TGpuParamSampState<true>>>& params);
-		TMaterialParamSampState() { }
-
-		/** @copydoc GpuParamSampState::set */
-		void set(const SPtr<SamplerStateCore>& sampState);
-
-		/** @copydoc GpuParamSampState::get */
-		SPtr<SamplerStateCore> get();
-
-	protected:
-		SPtr<Vector<TGpuParamSampState<true>>> mParams;
-	};
-
-	/** @} */
-
-	/** @addtogroup Material
-	 *  @{
-	 */
-
-	typedef TMaterialDataParam<float, false> MaterialParamFloat;
-	typedef TMaterialDataParam<Vector2, false> MaterialParamVec2;
-	typedef TMaterialDataParam<Vector3, false> MaterialParamVec3;
-	typedef TMaterialDataParam<Vector4, false> MaterialParamVec4;
-	typedef TMaterialDataParam<int, false> MaterialParamInt;
-	typedef TMaterialDataParam<Vector2I, false> MaterialParamVec2I;
-	typedef TMaterialDataParam<Vector3I, false> MaterialParamVec3I;
-	typedef TMaterialDataParam<Vector4I, false> MaterialParamVec4I;
-	typedef TMaterialDataParam<Matrix3, false> MaterialParamMat3;
-	typedef TMaterialDataParam<Matrix4, false> MaterialParamMat4;
-	typedef TMaterialDataParam<Color, false> MaterialParamColor;
-
-	typedef TMaterialDataParam<float, true> MaterialParamFloatCore;
-	typedef TMaterialDataParam<Vector2, true> MaterialParamVec2Core;
-	typedef TMaterialDataParam<Vector3, true> MaterialParamVec3Core;
-	typedef TMaterialDataParam<Vector4, true> MaterialParamVec4Core;
-	typedef TMaterialDataParam<int, true> MaterialParamIntCore;
-	typedef TMaterialDataParam<Vector2I, true> MaterialParamVec2ICore;
-	typedef TMaterialDataParam<Vector3I, true> MaterialParamVec3ICore;
-	typedef TMaterialDataParam<Vector4I, true> MaterialParamVec4ICore;
-	typedef TMaterialDataParam<Matrix3, true> MaterialParamMat3Core;
-	typedef TMaterialDataParam<Matrix4, true> MaterialParamMat4Core;
-	typedef TMaterialDataParam<Color, true> MaterialParamColorCore;
-
-	typedef TMaterialParamStruct<false> MaterialParamStruct;
-	typedef TMaterialParamStruct<true> MaterialParamStructCore;
-
-	typedef TMaterialParamTexture<false> MaterialParamTexture;
-	typedef TMaterialParamTexture<true> MaterialParamTextureCore;
-
-	typedef TMaterialParamLoadStoreTexture<false> MaterialParamLoadStoreTexture;
-	typedef TMaterialParamLoadStoreTexture<true> MaterialParamLoadStoreTextureCore;
-
-	typedef TMaterialParamSampState<false> MaterialParamSampState;
-	typedef TMaterialParamSampState<true> MaterialParamSampStateCore;
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsGpuParam.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	class MaterialParams;
+
+	/**
+	 * A handle that allows you to set a Material parameter. Internally keeps a reference to the material parameters so that
+	 * possibly expensive lookup of parameter name can be avoided each time the parameter is accessed, and instead the 
+	 * handle can be cached.
+	 * 			
+	 * @note	
+	 * This is pretty much identical to GPU parameter version (for example TGpuDataParam), except that this will get/set
+	 * parameter values on all GPU programs attached to the material, while TGpuDataParam works only for single GPU
+	 * program's parameters. Also, additional parameters that might be optimized out in the GPU program will still exist
+	 * here as long as they're  defined in the shader used by the material, which is not the case with TGpuDataParam.
+	 * @note
+	 * For core-thread version of this class no shader-based caching is done, and instead this represents just a wrapper
+	 * for multiple GPU parameters.
+	 * 
+	 * @see		Material
+	 */
+	template<class T, bool Core>
+	class BS_CORE_EXPORT TMaterialDataParam
+	{ };
+
+	/** @copydoc TMaterialDataParam */
+	template<class T>
+	class BS_CORE_EXPORT TMaterialDataParam<T, false>
+	{
+	public:
+		TMaterialDataParam(const String& name, const SPtr<MaterialParams>& params, 
+			const SPtr<Vector<TGpuDataParam<T, false>>>& gpuParams);
+		TMaterialDataParam() { }
+
+		/** @copydoc TGpuDataParam::set */
+		void set(const T& value, UINT32 arrayIdx = 0);
+
+		/** @copydoc TGpuDataParam::get */
+		T get(UINT32 arrayIdx = 0);
+
+	protected:
+		UINT32 mParamIndex;
+		UINT32 mArraySize;
+		SPtr<MaterialParams> mMaterialParams;
+		SPtr<Vector<TGpuDataParam<T, false>>> mGPUParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<class T>
+	class BS_CORE_EXPORT TMaterialDataParam<T, true>
+	{
+	public:
+		TMaterialDataParam(const SPtr<Vector<TGpuDataParam<T, true>>>& params);
+		TMaterialDataParam() { }
+
+		/** @copydoc TGpuDataParam::set */
+		void set(const T& value, UINT32 arrayIdx = 0);
+
+		/** @copydoc TGpuDataParam::get */
+		T get(UINT32 arrayIdx = 0);
+
+	protected:
+		SPtr<Vector<TGpuDataParam<T, true>>> mParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<bool Core>
+	class BS_CORE_EXPORT TMaterialParamStruct
+	{ };
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamStruct<false>
+	{
+	public:
+		TMaterialParamStruct(const String& name, const SPtr<MaterialParams>& params,
+			const SPtr<Vector<TGpuParamStruct<false>>>& gpuParams);
+		TMaterialParamStruct() { }
+
+		/** @copydoc TGpuParamStruct::set */
+		void set(const void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
+
+		/** @copydoc TGpuParamStruct::get */
+		void get(void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
+
+		/** @copydoc TGpuParamStruct::getElementSize */
+		UINT32 getElementSize() const;
+
+	protected:
+		UINT32 mParamIndex;
+		UINT32 mArraySize;
+		SPtr<MaterialParams> mMaterialParams;
+		SPtr<Vector<TGpuParamStruct<false>>> mGPUParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamStruct<true>
+	{
+	public:
+		TMaterialParamStruct(const SPtr<Vector<TGpuParamStruct<true>>>& params);
+		TMaterialParamStruct() { }
+
+		/** @copydoc TGpuParamStruct::set */
+		void set(const void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
+
+		/** @copydoc TGpuParamStruct::get */
+		void get(void* value, UINT32 sizeBytes, UINT32 arrayIdx = 0);
+
+		/** @copydoc TGpuParamStruct::getElementSize */
+		UINT32 getElementSize() const;
+
+	protected:
+		SPtr<Vector<TGpuParamStruct<true>>> mParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<bool Core>
+	class BS_CORE_EXPORT TMaterialParamTexture
+	{ };
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamTexture<false>
+	{
+	public:
+		TMaterialParamTexture(const String& name, const SPtr<MaterialParams>& params, 
+			const SPtr<Vector<TGpuParamTexture<false>>>& gpuParams);
+		TMaterialParamTexture() { }
+
+		/** @copydoc GpuParamTexture::set */
+		void set(const HTexture& texture);
+
+		/** @copydoc GpuParamTexture::get */
+		HTexture get();
+
+	protected:
+		UINT32 mParamIndex;
+		SPtr<MaterialParams> mMaterialParams;
+		SPtr<Vector<TGpuParamTexture<false>>> mGPUParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamTexture<true>
+	{
+	public:
+		TMaterialParamTexture(const SPtr<Vector<TGpuParamTexture<true>>>& params);
+		TMaterialParamTexture() { }
+
+		/** @copydoc GpuParamTexture::set */
+		void set(const SPtr<TextureCore>& texture);
+
+		/** @copydoc GpuParamTexture::get */
+		SPtr<TextureCore> get();
+
+	protected:
+		SPtr<Vector<TGpuParamTexture<true>>> mParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<bool Core>
+	class BS_CORE_EXPORT TMaterialParamLoadStoreTexture
+	{ };
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamLoadStoreTexture<false>
+	{
+	public:
+		TMaterialParamLoadStoreTexture(const String& name, const SPtr<MaterialParams>& params,
+			const SPtr<Vector<TGpuParamLoadStoreTexture<false>>>& gpuParams);
+		TMaterialParamLoadStoreTexture() { }
+
+		/** @copydoc GpuParamLoadStoreTexture::set */
+		void set(const HTexture& texture, const TextureSurface& surface);
+
+		/** @copydoc GpuParamLoadStoreTexture::get */
+		HTexture get();
+
+	protected:
+		UINT32 mParamIndex;
+		SPtr<MaterialParams> mMaterialParams;
+		SPtr<Vector<TGpuParamLoadStoreTexture<false>>> mGPUParams;
+	};
+
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamLoadStoreTexture<true>
+	{
+	public:
+		TMaterialParamLoadStoreTexture(const SPtr<Vector<TGpuParamLoadStoreTexture<true>>>& params);
+		TMaterialParamLoadStoreTexture() { }
+
+		/** @copydoc GpuParamLoadStoreTexture::set */
+		void set(const SPtr<TextureCore>& texture, const TextureSurface& surface);
+
+		/** @copydoc GpuParamLoadStoreTexture::get */
+		SPtr<TextureCore> get();
+
+	protected:
+		SPtr<Vector<TGpuParamLoadStoreTexture<true>>> mParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<bool Core>
+	class BS_CORE_EXPORT TMaterialParamSampState
+	{ };
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamSampState<false>
+	{
+	public:
+		TMaterialParamSampState(const String& name, const SPtr<MaterialParams>& params, 
+			const SPtr<Vector<TGpuParamSampState<false>>>& gpuParams);
+		TMaterialParamSampState() { }
+
+		/** @copydoc GpuParamSampState::set */
+		void set(const SPtr<SamplerState>& sampState);
+
+		/** @copydoc GpuParamSampState::get */
+		SPtr<SamplerState> get();
+
+	protected:
+		UINT32 mParamIndex;
+		SPtr<MaterialParams> mMaterialParams;
+		SPtr<Vector<TGpuParamSampState<false>>> mGPUParams;
+	};
+
+	/** @copydoc TMaterialDataParam */
+	template<>
+	class BS_CORE_EXPORT TMaterialParamSampState<true>
+	{
+	public:
+		TMaterialParamSampState(const SPtr<Vector<TGpuParamSampState<true>>>& params);
+		TMaterialParamSampState() { }
+
+		/** @copydoc GpuParamSampState::set */
+		void set(const SPtr<SamplerStateCore>& sampState);
+
+		/** @copydoc GpuParamSampState::get */
+		SPtr<SamplerStateCore> get();
+
+	protected:
+		SPtr<Vector<TGpuParamSampState<true>>> mParams;
+	};
+
+	/** @} */
+
+	/** @addtogroup Material
+	 *  @{
+	 */
+
+	typedef TMaterialDataParam<float, false> MaterialParamFloat;
+	typedef TMaterialDataParam<Vector2, false> MaterialParamVec2;
+	typedef TMaterialDataParam<Vector3, false> MaterialParamVec3;
+	typedef TMaterialDataParam<Vector4, false> MaterialParamVec4;
+	typedef TMaterialDataParam<int, false> MaterialParamInt;
+	typedef TMaterialDataParam<Vector2I, false> MaterialParamVec2I;
+	typedef TMaterialDataParam<Vector3I, false> MaterialParamVec3I;
+	typedef TMaterialDataParam<Vector4I, false> MaterialParamVec4I;
+	typedef TMaterialDataParam<Matrix3, false> MaterialParamMat3;
+	typedef TMaterialDataParam<Matrix4, false> MaterialParamMat4;
+	typedef TMaterialDataParam<Color, false> MaterialParamColor;
+
+	typedef TMaterialDataParam<float, true> MaterialParamFloatCore;
+	typedef TMaterialDataParam<Vector2, true> MaterialParamVec2Core;
+	typedef TMaterialDataParam<Vector3, true> MaterialParamVec3Core;
+	typedef TMaterialDataParam<Vector4, true> MaterialParamVec4Core;
+	typedef TMaterialDataParam<int, true> MaterialParamIntCore;
+	typedef TMaterialDataParam<Vector2I, true> MaterialParamVec2ICore;
+	typedef TMaterialDataParam<Vector3I, true> MaterialParamVec3ICore;
+	typedef TMaterialDataParam<Vector4I, true> MaterialParamVec4ICore;
+	typedef TMaterialDataParam<Matrix3, true> MaterialParamMat3Core;
+	typedef TMaterialDataParam<Matrix4, true> MaterialParamMat4Core;
+	typedef TMaterialDataParam<Color, true> MaterialParamColorCore;
+
+	typedef TMaterialParamStruct<false> MaterialParamStruct;
+	typedef TMaterialParamStruct<true> MaterialParamStructCore;
+
+	typedef TMaterialParamTexture<false> MaterialParamTexture;
+	typedef TMaterialParamTexture<true> MaterialParamTextureCore;
+
+	typedef TMaterialParamLoadStoreTexture<false> MaterialParamLoadStoreTexture;
+	typedef TMaterialParamLoadStoreTexture<true> MaterialParamLoadStoreTextureCore;
+
+	typedef TMaterialParamSampState<false> MaterialParamSampState;
+	typedef TMaterialParamSampState<true> MaterialParamSampStateCore;
+
+	/** @} */
 }

+ 396 - 396
Source/BansheeCore/Include/BsMaterialParams.h

@@ -1,396 +1,396 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsIReflectable.h"
-#include "BsStaticAlloc.h"
-#include "BsVector2.h"
-#include "BsVector3.h"
-#include "BsVector4.h"
-#include "BsVector2I.h"
-#include "BsVectorNI.h"
-#include "BsColor.h"
-#include "BsMatrix3.h"
-#include "BsMatrix4.h"
-#include "BsMatrixNxM.h"
-#include "BsGpuParams.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Material
-	 *  @{
-	 */
-
-	/** 
-	 * Contains all parameter values set in a Material. This is similar to GpuParams which also stores parameter values,
-	 * however GpuParams are built for use on the GPU-side and don't store parameters that don't exist in a compiled GPU
-	 * program. This object on the other hand stores all parameters defined in a shader, regardless or not if they actually
-	 * exist in the GPU program. Additionally GpuParams are defined per-program (e.g. vertex, fragment) while this object
-	 * exists for the entire material.
-	 *
-	 * @note
-	 * This introduces redundancy as parameters stored by GpuParams and this object are duplicated. If this is an issue the
-	 * implementation can be modified to only store parameters not included in GpuParams.
-	 * @note
-	 * The reason why parameters in this class and GpuParams differ is most often compiler optimizations. If a compiler
-	 * optimizes out a variable in a GPU program we should still be able to store it, either for later when the variable
-	 * will be introduced, or for other techniques that might have that variable implemented.
-	 */
-	class BS_CORE_EXPORT MaterialParams : public IReflectable
-	{
-	public:
-		/** Type of material parameter. */
-		enum class ParamType
-		{
-			Data, Texture, Sampler
-		};
-
-		/** Result codes for getParam method. */
-		enum class GetParamResult
-		{
-			Success,
-			NotFound,
-			InvalidType,
-			IndexOutOfBounds
-		};
-
-		/** Meta-data about a parameter. */
-		struct ParamData
-		{
-			ParamType type;
-			GpuParamDataType dataType;
-			UINT32 index;
-			UINT32 arraySize;
-		};
-
-		/** Raw data for a single structure parameter. */
-		class BS_CORE_EXPORT StructParamData : public IReflectable
-		{
-		public:
-			UINT8* data;
-			UINT32 dataSize;
-
-			friend class StructParamDataRTTI;
-			static RTTITypeBase* getRTTIStatic();
-			virtual RTTITypeBase* getRTTI() const override;
-		};
-
-		/** Data for a single texture parameter. */
-		class BS_CORE_EXPORT TextureParamData : public IReflectable
-		{
-		public:
-			HTexture value;
-			bool isLoadStore;
-			TextureSurface surface;
-
-			friend class TextureParamDataRTTI;
-			static RTTITypeBase* getRTTIStatic();
-			virtual RTTITypeBase* getRTTI() const override;
-		};
-
-		/** Creates a new material params object and initializes enough room for parameters from the provided shader. */
-		MaterialParams(const HShader& shader);
-		~MaterialParams();
-
-		/** 
-		 * Returns the value of a shader data parameter with the specified name at the specified array index. If the
-		 * parameter name, index or type is not valid a warning will be logged and output value will not be retrieved.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
-		 * @param[out]	output		If successful, value of the parameter.
-		 *
-		 * @tparam		T			Native type of the parameter.
-		 */
-		template <typename T>
-		void getDataParam(const String& name, UINT32 arrayIdx, T& output) const
-		{
-			GpuParamDataType dataType = TGpuDataParamInfo<T>::TypeId;
-
-			const ParamData* param = nullptr;
-			auto result = getParamData(name, ParamType::Data, dataType, arrayIdx, &param);
-			if (result != GetParamResult::Success)
-				return;
-
-			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES[dataType];
-			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
-			output = *(T*)(mDataParamsBuffer[param->index + arrayIdx * paramTypeSize]);
-
-			memcpy(output, &mDataParamsBuffer[param->index + arrayIdx * paramTypeSize], sizeof(paramTypeSize));
-		}
-
-		/** 
-		 * Sets the value of a shader data parameter with the specified name at the specified array index. If the
-		 * parameter name, index or type is not valid a warning will be logged and output value will not be set.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
-		 * @param[in]	input		New value of the parameter.
-		 *
-		 * @tparam		T			Native type of the parameter.
-		 */
-		template <typename T>
-		void setDataParam(const String& name, UINT32 arrayIdx, const T& input) const
-		{
-			GpuParamDataType dataType = TGpuDataParamInfo<T>::TypeId;
-
-			const ParamData* param = nullptr;
-			auto result = getParamData(name, ParamType::Data, dataType, arrayIdx, &param);
-			if (result != GetParamResult::Success)
-				return;
-
-			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES[dataType];
-			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
-
-			memcpy(&mDataParamsBuffer[param->index + arrayIdx * paramTypeSize], input, sizeof(paramTypeSize));
-		}
-
-		/** 
-		 * Returns the value of a shader structure parameter with the specified name at the specified array index. If the
-		 * parameter name, index or type is not valid a warning will be logged and output value will not be retrieved.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[out]	value		Pre-allocated buffer of @p size bytes where the value will be retrieved.
-		 * @param[in]	size		Size of the buffer into which to write the value. Must match parameter struct's size.
-		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
-		 */
-		void getStructData(const String& name, void* value, UINT32 size, UINT32 arrayIdx) const;
-
-		/** 
-		 * Sets the value of a shader structure parameter with the specified name at the specified array index. If the
-		 * parameter name, index or type is not valid a warning will be logged and output value will not be retrieved.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	value		Buffer of @p size bytes containing the new value of the structure.
-		 * @param[in]	size		Size of the buffer from which to retrieve the value. Must match parameter struct's size.
-		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
-		 */
-		void setStructData(const String& name, const void* value, UINT32 size, UINT32 arrayIdx);
-
-		/** 
-		 * Returns the value of a shader texture parameter with the specified name. If the parameter name or type is not 
-		 * valid a warning will be logged and output value will not be retrieved.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[out]	value		Output value of the parameter.
-		 */
-		void getTexture(const String& name, HTexture& value) const;
-
-		/** 
-		 * Sets the value of a shader texture parameter with the specified name. If the parameter name or type is not 
-		 * valid a warning will be logged and output value will not be set.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	value		New value of the parameter.
-		 */
-		void setTexture(const String& name, const HTexture& value);
-
-		/** 
-		 * Returns the value of a shader load/store texture parameter with the specified name. If the parameter name or 
-		 * type is not valid a warning will be logged and output value will not be retrieved.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[out]	value		Output value of the parameter.
-		 * @param[out]	surface		Surface describing which part of the texture is being accessed.
-		 */
-		void getLoadStoreTexture(const String& name, HTexture& value, TextureSurface& surface) const;
-
-		/** 
-		 * Sets the value of a shader load/store texture parameter with the specified name. If the parameter name or 
-		 * type is not valid a warning will be logged and the value will not be set.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	value		New value of the parameter.
-		 * @param[in]	surface		Surface describing which part of the texture is being accessed.
-		 */
-		void setLoadStoreTexture(const String& name, const HTexture& value, const TextureSurface& surface);
-
-		/** 
-		 * Sets the value of a shader sampler state parameter with the specified name. If the parameter name or type is not 
-		 * valid a warning will be logged and output value will not be set.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[out]	value		Output value of the parameter.
-		 */
-		void getSamplerState(const String& name, SamplerStatePtr& value) const;
-
-		/** 
-		 * Sets the value of a shader sampler state parameter with the specified name. If the parameter name or type is not 
-		 * valid a warning will be logged and output value will not be set.
-		 * 
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	value		New value of the parameter.
-		 */
-		void setSamplerState(const String& name, const SamplerStatePtr& value);
-
-		/** 
-		 * Returns data about a parameter and reports an error if there is a type or size mismatch, or if the parameter
-		 * does exist.
-		 *
-		 * @param[in]	name		Name of the shader parameter.
-		 * @param[in]	type		Type of the parameter retrieve. Error will be logged if actual type of the parameter 
-		 *							doesn't match.
-		 * @param[in]	dataType	Only relevant if the parameter is a data type. Determines exact data type of the parameter
-		 *							to retrieve. 
-		 * @param[in]	arrayIdx	Array index of the entry to retrieve. 
-		 * @param[out]	output		Object describing the parameter with an index to its data. If the parameter was not found
-		 *							this value is undefined. This value will still be valid if parameter was found but
-		 *							some other error was reported.
-		 *
-		 * @return					Success or error state of the request.
-		 */
-		GetParamResult getParamData(const String& name, ParamType type, GpuParamDataType dataType, UINT32 arrayIdx, 
-			const ParamData** output) const;
-
-		/**
-		 * Logs an error that was reported by getParamData().
-		 *
-		 * @param[in]	name		Name of the shader parameter for which the error occurred.
-		 * @param[in]	arrayIdx	Array index for which the error occurred. 
-		 */
-		void reportGetParamError(GetParamResult errorCode, const String& name, UINT32 arrayIdx) const;
-
-		/** 
-		 * Equivalent to getStructData(const String&, UINT32, T&) except it uses the internal parameter index
-		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		template <typename T>
-		void getDataParam(UINT32 index, UINT32 arrayIdx, T& output) const
-		{
-			GpuParamDataType dataType = (GpuParamDataType)TGpuDataParamInfo<T>::TypeId;
-
-			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[dataType];
-			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
-
-			assert(sizeof(output) == paramTypeSize);
-			memcpy(&output, &mDataParamsBuffer[index + arrayIdx * paramTypeSize], paramTypeSize);
-		}
-
-		/** 
-		 * Equivalent to setDataParam(const String&, UINT32, T&) except it uses the internal parameter index
-		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		template <typename T>
-		void setDataParam(UINT32 index, UINT32 arrayIdx, const T& input) const
-		{
-			GpuParamDataType dataType = (GpuParamDataType)TGpuDataParamInfo<T>::TypeId;
-
-			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[dataType];
-			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
-
-			assert(sizeof(input) == paramTypeSize);
-			memcpy(&mDataParamsBuffer[index + arrayIdx * paramTypeSize], &input, paramTypeSize);
-		}
-
-		/** 
-		 * Equivalent to getStructData(const String&, UINT32, void*, UINT32) except it uses the internal parameter index
-		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void getStructData(UINT32 index, void* value, UINT32 size) const;
-
-		/** 
-		 * Equivalent to setStructData(const String&, UINT32, void*, UINT32) except it uses the internal parameter index
-		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void setStructData(UINT32 index, const void* value, UINT32 size);
-
-		/** 
-		 * Returns a size of a struct parameter in bytes, using the internal parameter index. Caller must guarantee the 
-		 * index is valid. 
-		 */
-		UINT32 getStructSize(UINT32 index) const;
-
-		/** 
-		 * Equivalent to getTexture(const String&, HTexture&) except it uses the internal parameter index directly, 
-		 * avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void getTexture(UINT32 index, HTexture& value) const;
-
-		/** 
-		 * Equivalent to setTexture(const String&, HTexture&) except it uses the internal parameter index directly, 
-		 * avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void setTexture(UINT32 index, const HTexture& value);
-
-		/** 
-		 * Equivalent to getLoadStoreTexture(const String&, HTexture&, TextureSurface&) except it uses the internal 
-		 * parameter index directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void getLoadStoreTexture(UINT32 index, HTexture& value, TextureSurface& surface) const;
-
-		/** 
-		 * Equivalent to setLoadStoreTexture(const String&, HTexture&, TextureSurface&) except it uses the internal 
-		 * parameter index directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void setLoadStoreTexture(UINT32 index, const HTexture& value, const TextureSurface& surface);
-
-		/** 
-		 * Checks is a texture with the specified index a load/store texture or a normal one. Caller must guarantee the 
-		 * index is valid.
-		 */
-		bool getIsTextureLoadStore(UINT32 index) const;
-
-		/** 
-		 * Equivalent to getSamplerState(const String&, SamplerStatePtr&) except it uses the internal parameter index 
-		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void getSamplerState(UINT32 index, SamplerStatePtr& value) const;
-
-		/** 
-		 * Equivalent to setSamplerState(const String&, SamplerStatePtr&) except it uses the internal parameter index 
-		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
-		 */
-		void setSamplerState(UINT32 index, const SamplerStatePtr& value);
-
-		/** 
-		 * Returns the default texture (one assigned when no other is provided), if available for the specified index. 
-		 * Index is the internal parameter index and the caller must guarantee the index is valid.
-		 */
-		void getDefaultTexture(UINT32 index, HTexture& value) const;
-
-		/** 
-		 * Returns the default sampler state (one assigned when no other is provided), if available for the specified index.
-		 * Index is the internal parameter index and the caller must guarantee the index is valid.
-		 */
-		void getDefaultSamplerState(UINT32 index, SamplerStatePtr& value) const;
-
-	private:
-		const static UINT32 STATIC_BUFFER_SIZE = 256;
-
-		UnorderedMap<String, ParamData> mParams;
-
-		UINT8* mDataParamsBuffer = nullptr;
-		StructParamData* mStructParams = nullptr;
-		TextureParamData* mTextureParams = nullptr;
-		SamplerStatePtr* mSamplerStateParams = nullptr;
-		HTexture* mDefaultTextureParams = nullptr;
-		SamplerStatePtr* mDefaultSamplerStateParams = nullptr;
-
-		UINT32 mDataSize = 0;
-		UINT32 mNumStructParams = 0;
-		UINT32 mNumTextureParams = 0;
-		UINT32 mNumSamplerParams = 0;
-
-		mutable StaticAlloc<STATIC_BUFFER_SIZE, STATIC_BUFFER_SIZE> mAlloc;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-
-	public:
-		MaterialParams() { } // Only for serialization
-
-		friend class MaterialParamsRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @cond SPECIALIZATIONS */
-	BS_ALLOW_MEMCPY_SERIALIZATION(MaterialParams::ParamData);
-	/** @endcond */
-
-	/** @} */
-	/** @endcond */
-}
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsIReflectable.h"
+#include "BsStaticAlloc.h"
+#include "BsVector2.h"
+#include "BsVector3.h"
+#include "BsVector4.h"
+#include "BsVector2I.h"
+#include "BsVectorNI.h"
+#include "BsColor.h"
+#include "BsMatrix3.h"
+#include "BsMatrix4.h"
+#include "BsMatrixNxM.h"
+#include "BsGpuParams.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Material
+	 *  @{
+	 */
+
+	/** 
+	 * Contains all parameter values set in a Material. This is similar to GpuParams which also stores parameter values,
+	 * however GpuParams are built for use on the GPU-side and don't store parameters that don't exist in a compiled GPU
+	 * program. This object on the other hand stores all parameters defined in a shader, regardless or not if they actually
+	 * exist in the GPU program. Additionally GpuParams are defined per-program (for example vertex, fragment) while this
+	 * object exists for the entire material.
+	 *
+	 * @note
+	 * This introduces redundancy as parameters stored by GpuParams and this object are duplicated. If this is an issue the
+	 * implementation can be modified to only store parameters not included in GpuParams.
+	 * @note
+	 * The reason why parameters in this class and GpuParams differ is most often compiler optimizations. If a compiler
+	 * optimizes out a variable in a GPU program we should still be able to store it, either for later when the variable
+	 * will be introduced, or for other techniques that might have that variable implemented.
+	 */
+	class BS_CORE_EXPORT MaterialParams : public IReflectable
+	{
+	public:
+		/** Type of material parameter. */
+		enum class ParamType
+		{
+			Data, Texture, Sampler
+		};
+
+		/** Result codes for getParam method. */
+		enum class GetParamResult
+		{
+			Success,
+			NotFound,
+			InvalidType,
+			IndexOutOfBounds
+		};
+
+		/** Meta-data about a parameter. */
+		struct ParamData
+		{
+			ParamType type;
+			GpuParamDataType dataType;
+			UINT32 index;
+			UINT32 arraySize;
+		};
+
+		/** Raw data for a single structure parameter. */
+		class BS_CORE_EXPORT StructParamData : public IReflectable
+		{
+		public:
+			UINT8* data;
+			UINT32 dataSize;
+
+			friend class StructParamDataRTTI;
+			static RTTITypeBase* getRTTIStatic();
+			virtual RTTITypeBase* getRTTI() const override;
+		};
+
+		/** Data for a single texture parameter. */
+		class BS_CORE_EXPORT TextureParamData : public IReflectable
+		{
+		public:
+			HTexture value;
+			bool isLoadStore;
+			TextureSurface surface;
+
+			friend class TextureParamDataRTTI;
+			static RTTITypeBase* getRTTIStatic();
+			virtual RTTITypeBase* getRTTI() const override;
+		};
+
+		/** Creates a new material params object and initializes enough room for parameters from the provided shader. */
+		MaterialParams(const HShader& shader);
+		~MaterialParams();
+
+		/** 
+		 * Returns the value of a shader data parameter with the specified name at the specified array index. If the
+		 * parameter name, index or type is not valid a warning will be logged and output value will not be retrieved.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
+		 * @param[out]	output		If successful, value of the parameter.
+		 *
+		 * @tparam		T			Native type of the parameter.
+		 */
+		template <typename T>
+		void getDataParam(const String& name, UINT32 arrayIdx, T& output) const
+		{
+			GpuParamDataType dataType = TGpuDataParamInfo<T>::TypeId;
+
+			const ParamData* param = nullptr;
+			auto result = getParamData(name, ParamType::Data, dataType, arrayIdx, &param);
+			if (result != GetParamResult::Success)
+				return;
+
+			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES[dataType];
+			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
+			output = *(T*)(mDataParamsBuffer[param->index + arrayIdx * paramTypeSize]);
+
+			memcpy(output, &mDataParamsBuffer[param->index + arrayIdx * paramTypeSize], sizeof(paramTypeSize));
+		}
+
+		/** 
+		 * Sets the value of a shader data parameter with the specified name at the specified array index. If the
+		 * parameter name, index or type is not valid a warning will be logged and output value will not be set.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
+		 * @param[in]	input		New value of the parameter.
+		 *
+		 * @tparam		T			Native type of the parameter.
+		 */
+		template <typename T>
+		void setDataParam(const String& name, UINT32 arrayIdx, const T& input) const
+		{
+			GpuParamDataType dataType = TGpuDataParamInfo<T>::TypeId;
+
+			const ParamData* param = nullptr;
+			auto result = getParamData(name, ParamType::Data, dataType, arrayIdx, &param);
+			if (result != GetParamResult::Success)
+				return;
+
+			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES[dataType];
+			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
+
+			memcpy(&mDataParamsBuffer[param->index + arrayIdx * paramTypeSize], input, sizeof(paramTypeSize));
+		}
+
+		/** 
+		 * Returns the value of a shader structure parameter with the specified name at the specified array index. If the
+		 * parameter name, index or type is not valid a warning will be logged and output value will not be retrieved.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[out]	value		Pre-allocated buffer of @p size bytes where the value will be retrieved.
+		 * @param[in]	size		Size of the buffer into which to write the value. Must match parameter struct's size.
+		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
+		 */
+		void getStructData(const String& name, void* value, UINT32 size, UINT32 arrayIdx) const;
+
+		/** 
+		 * Sets the value of a shader structure parameter with the specified name at the specified array index. If the
+		 * parameter name, index or type is not valid a warning will be logged and output value will not be retrieved.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	value		Buffer of @p size bytes containing the new value of the structure.
+		 * @param[in]	size		Size of the buffer from which to retrieve the value. Must match parameter struct's size.
+		 * @param[in]	arrayIdx	If the parameter is an array, index of the entry to access.
+		 */
+		void setStructData(const String& name, const void* value, UINT32 size, UINT32 arrayIdx);
+
+		/** 
+		 * Returns the value of a shader texture parameter with the specified name. If the parameter name or type is not 
+		 * valid a warning will be logged and output value will not be retrieved.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[out]	value		Output value of the parameter.
+		 */
+		void getTexture(const String& name, HTexture& value) const;
+
+		/** 
+		 * Sets the value of a shader texture parameter with the specified name. If the parameter name or type is not 
+		 * valid a warning will be logged and output value will not be set.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	value		New value of the parameter.
+		 */
+		void setTexture(const String& name, const HTexture& value);
+
+		/** 
+		 * Returns the value of a shader load/store texture parameter with the specified name. If the parameter name or 
+		 * type is not valid a warning will be logged and output value will not be retrieved.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[out]	value		Output value of the parameter.
+		 * @param[out]	surface		Surface describing which part of the texture is being accessed.
+		 */
+		void getLoadStoreTexture(const String& name, HTexture& value, TextureSurface& surface) const;
+
+		/** 
+		 * Sets the value of a shader load/store texture parameter with the specified name. If the parameter name or 
+		 * type is not valid a warning will be logged and the value will not be set.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	value		New value of the parameter.
+		 * @param[in]	surface		Surface describing which part of the texture is being accessed.
+		 */
+		void setLoadStoreTexture(const String& name, const HTexture& value, const TextureSurface& surface);
+
+		/** 
+		 * Sets the value of a shader sampler state parameter with the specified name. If the parameter name or type is not 
+		 * valid a warning will be logged and output value will not be set.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[out]	value		Output value of the parameter.
+		 */
+		void getSamplerState(const String& name, SamplerStatePtr& value) const;
+
+		/** 
+		 * Sets the value of a shader sampler state parameter with the specified name. If the parameter name or type is not 
+		 * valid a warning will be logged and output value will not be set.
+		 * 
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	value		New value of the parameter.
+		 */
+		void setSamplerState(const String& name, const SamplerStatePtr& value);
+
+		/** 
+		 * Returns data about a parameter and reports an error if there is a type or size mismatch, or if the parameter
+		 * does exist.
+		 *
+		 * @param[in]	name		Name of the shader parameter.
+		 * @param[in]	type		Type of the parameter retrieve. Error will be logged if actual type of the parameter 
+		 *							doesn't match.
+		 * @param[in]	dataType	Only relevant if the parameter is a data type. Determines exact data type of the parameter
+		 *							to retrieve. 
+		 * @param[in]	arrayIdx	Array index of the entry to retrieve. 
+		 * @param[out]	output		Object describing the parameter with an index to its data. If the parameter was not found
+		 *							this value is undefined. This value will still be valid if parameter was found but
+		 *							some other error was reported.
+		 *
+		 * @return					Success or error state of the request.
+		 */
+		GetParamResult getParamData(const String& name, ParamType type, GpuParamDataType dataType, UINT32 arrayIdx, 
+			const ParamData** output) const;
+
+		/**
+		 * Logs an error that was reported by getParamData().
+		 *
+		 * @param[in]	name		Name of the shader parameter for which the error occurred.
+		 * @param[in]	arrayIdx	Array index for which the error occurred. 
+		 */
+		void reportGetParamError(GetParamResult errorCode, const String& name, UINT32 arrayIdx) const;
+
+		/** 
+		 * Equivalent to getStructData(const String&, UINT32, T&) except it uses the internal parameter index
+		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		template <typename T>
+		void getDataParam(UINT32 index, UINT32 arrayIdx, T& output) const
+		{
+			GpuParamDataType dataType = (GpuParamDataType)TGpuDataParamInfo<T>::TypeId;
+
+			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[dataType];
+			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
+
+			assert(sizeof(output) == paramTypeSize);
+			memcpy(&output, &mDataParamsBuffer[index + arrayIdx * paramTypeSize], paramTypeSize);
+		}
+
+		/** 
+		 * Equivalent to setDataParam(const String&, UINT32, T&) except it uses the internal parameter index
+		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		template <typename T>
+		void setDataParam(UINT32 index, UINT32 arrayIdx, const T& input) const
+		{
+			GpuParamDataType dataType = (GpuParamDataType)TGpuDataParamInfo<T>::TypeId;
+
+			const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[dataType];
+			UINT32 paramTypeSize = typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize;
+
+			assert(sizeof(input) == paramTypeSize);
+			memcpy(&mDataParamsBuffer[index + arrayIdx * paramTypeSize], &input, paramTypeSize);
+		}
+
+		/** 
+		 * Equivalent to getStructData(const String&, UINT32, void*, UINT32) except it uses the internal parameter index
+		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void getStructData(UINT32 index, void* value, UINT32 size) const;
+
+		/** 
+		 * Equivalent to setStructData(const String&, UINT32, void*, UINT32) except it uses the internal parameter index
+		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void setStructData(UINT32 index, const void* value, UINT32 size);
+
+		/** 
+		 * Returns a size of a struct parameter in bytes, using the internal parameter index. Caller must guarantee the 
+		 * index is valid. 
+		 */
+		UINT32 getStructSize(UINT32 index) const;
+
+		/** 
+		 * Equivalent to getTexture(const String&, HTexture&) except it uses the internal parameter index directly, 
+		 * avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void getTexture(UINT32 index, HTexture& value) const;
+
+		/** 
+		 * Equivalent to setTexture(const String&, HTexture&) except it uses the internal parameter index directly, 
+		 * avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void setTexture(UINT32 index, const HTexture& value);
+
+		/** 
+		 * Equivalent to getLoadStoreTexture(const String&, HTexture&, TextureSurface&) except it uses the internal 
+		 * parameter index directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void getLoadStoreTexture(UINT32 index, HTexture& value, TextureSurface& surface) const;
+
+		/** 
+		 * Equivalent to setLoadStoreTexture(const String&, HTexture&, TextureSurface&) except it uses the internal 
+		 * parameter index directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void setLoadStoreTexture(UINT32 index, const HTexture& value, const TextureSurface& surface);
+
+		/** 
+		 * Checks is a texture with the specified index a load/store texture or a normal one. Caller must guarantee the 
+		 * index is valid.
+		 */
+		bool getIsTextureLoadStore(UINT32 index) const;
+
+		/** 
+		 * Equivalent to getSamplerState(const String&, SamplerStatePtr&) except it uses the internal parameter index 
+		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void getSamplerState(UINT32 index, SamplerStatePtr& value) const;
+
+		/** 
+		 * Equivalent to setSamplerState(const String&, SamplerStatePtr&) except it uses the internal parameter index 
+		 * directly, avoiding the name lookup. Caller must guarantee the index is valid.
+		 */
+		void setSamplerState(UINT32 index, const SamplerStatePtr& value);
+
+		/** 
+		 * Returns the default texture (one assigned when no other is provided), if available for the specified index. 
+		 * Index is the internal parameter index and the caller must guarantee the index is valid.
+		 */
+		void getDefaultTexture(UINT32 index, HTexture& value) const;
+
+		/** 
+		 * Returns the default sampler state (one assigned when no other is provided), if available for the specified index.
+		 * Index is the internal parameter index and the caller must guarantee the index is valid.
+		 */
+		void getDefaultSamplerState(UINT32 index, SamplerStatePtr& value) const;
+
+	private:
+		const static UINT32 STATIC_BUFFER_SIZE = 256;
+
+		UnorderedMap<String, ParamData> mParams;
+
+		UINT8* mDataParamsBuffer = nullptr;
+		StructParamData* mStructParams = nullptr;
+		TextureParamData* mTextureParams = nullptr;
+		SamplerStatePtr* mSamplerStateParams = nullptr;
+		HTexture* mDefaultTextureParams = nullptr;
+		SamplerStatePtr* mDefaultSamplerStateParams = nullptr;
+
+		UINT32 mDataSize = 0;
+		UINT32 mNumStructParams = 0;
+		UINT32 mNumTextureParams = 0;
+		UINT32 mNumSamplerParams = 0;
+
+		mutable StaticAlloc<STATIC_BUFFER_SIZE, STATIC_BUFFER_SIZE> mAlloc;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+
+	public:
+		MaterialParams() { } // Only for serialization
+
+		friend class MaterialParamsRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @cond SPECIALIZATIONS */
+	BS_ALLOW_MEMCPY_SERIALIZATION(MaterialParams::ParamData);
+	/** @endcond */
+
+	/** @} */
+	/** @endcond */
+}

+ 231 - 231
Source/BansheeCore/Include/BsMeshHeap.h

@@ -1,232 +1,232 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsCoreObject.h"
-#include "BsDrawOps.h"
-#include "BsIndexBuffer.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Resources
-	 *  @{
-	 */
-
-	/**
-	 * Core thread version of MeshHeap.
-	 *
-	 * @note	Core thread only.
-	 */
-	class BS_CORE_EXPORT MeshHeapCore : public CoreObjectCore
-	{
-		/**	Signifies how is a data chunk used. */
-		enum class UseFlags
-		{
-			Used, /**< Data chunk is used by both CPU and GPU. */
-			CPUFree, /**< Data chunk was released by CPU but not GPU. */
-			GPUFree, /**< Data chunk was released by GPU but not CPU. */
-			Free /**< Data chunk was released by both CPU and GPU. */
-		};
-
-		/**	Represents a continuous chunk of memory. */
-		struct ChunkData
-		{
-			UINT32 start, size;
-		};
-
-		/**	Represents an allocated piece of data representing a mesh. */
-		struct AllocatedData
-		{
-			UINT32 vertChunkIdx;
-			UINT32 idxChunkIdx;
-
-			UseFlags useFlags;
-			UINT32 eventQueryIdx;
-			SPtr<TransientMeshCore> mesh;
-		};
-
-		/**	Data about a GPU query. */
-		struct QueryData
-		{
-			EventQueryPtr query;
-			UINT32 queryId;
-		};
-
-	public:
-		~MeshHeapCore();
-
-	private:
-		friend class MeshHeap;
-		friend class TransientMesh;
-		friend class TransientMeshCore;
-
-		MeshHeapCore(UINT32 numVertices, UINT32 numIndices, 
-			const VertexDataDescPtr& vertexDesc, IndexType indexType = IT_32BIT);
-
-		/** @copydoc CoreObjectCore::initialize() */
-		virtual void initialize() override;
-
-		/**
-		 * Allocates a new mesh in the heap, expanding the heap if needed. 
-		 *
-		 * @param[in]	meshId		Mesh for which we are allocating the data.
-		 * @param[in]	meshData	Data to initialize the new mesh with.
-		 */
-		void alloc(SPtr<TransientMeshCore> mesh, const MeshDataPtr& meshData);
-
-		/** Deallocates the provided mesh. Freed memory will be re-used as soon as the GPU is done with the mesh. */
-		void dealloc(SPtr<TransientMeshCore> mesh);
-
-		/** Resizes the vertex buffers so they max contain the provided number of vertices. */
-		void growVertexBuffer(UINT32 numVertices);
-
-		/** Resizes the index buffer so they max contain the provided number of indices. */
-		void growIndexBuffer(UINT32 numIndices);
-
-		/**
-		 * Creates a new event query or returns an existing one from the pool if available. Returned value is an index 
-		 * into event query array.
-		 */
-		UINT32 createEventQuery();
-
-		/** Frees the event query with the specified index and returns it to the pool so it may be reused later. */
-		void freeEventQuery(UINT32 idx);
-
-		/**	Gets internal vertex data for all the meshes. */
-		SPtr<VertexData> getVertexData() const;
-
-		/**	Gets internal index data for all the meshes. */
-		SPtr<IndexBufferCore> getIndexBuffer() const;
-
-		/** Returns a structure that describes how are the vertices stored in the mesh's vertex buffer. */
-		SPtr<VertexDataDesc> getVertexDesc() const;
-
-		/**
-		 * Returns the offset in vertices from the start of the buffer to the first vertex of the mesh with the provided ID.
-		 */
-		UINT32 getVertexOffset(UINT32 meshId) const;
-
-		/**
-		 * Returns the offset in indices from the start of the buffer to the first index of the mesh with the provided ID.
-		 */
-		UINT32 getIndexOffset(UINT32 meshId) const;
-
-		/** Called by the render system when a mesh gets queued to the GPU. */
-		void notifyUsedOnGPU(UINT32 meshId);
-
-		/**
-		 * Called by an GPU event query when GPU processes the query. Normally signals the heap that the GPU is done with 
-		 * the mesh.
-		 */
-		static void queryTriggered(SPtr<MeshHeapCore> thisPtr, UINT32 meshId, UINT32 queryId);
-
-		/**
-		 * Attempts to reorganize the vertex and index buffer chunks in order to in order to make free memory contigous.
-		 *
-		 * @note	
-		 * This will not actually copy any data from index/vertex buffers, and will only modify the chunk descriptors.
-		 */
-		void mergeWithNearbyChunks(UINT32 chunkVertIdx, UINT32 chunkIdxIdx);
-
-	private:
-		UINT32 mNumVertices;
-		UINT32 mNumIndices;
-
-		Vector<UINT8*> mCPUVertexData;
-		UINT8* mCPUIndexData;
-
-		SPtr<VertexData> mVertexData;
-		SPtr<IndexBufferCore> mIndexBuffer;
-
-		Map<UINT32, AllocatedData> mMeshAllocData;
-
-		VertexDataDescPtr mVertexDesc;
-		IndexType mIndexType;
-
-		Vector<ChunkData> mVertChunks;
-		Vector<ChunkData> mIdxChunks;
-
-		Stack<UINT32> mEmptyVertChunks;
-		Stack<UINT32> mEmptyIdxChunks;
-
-		List<UINT32> mFreeVertChunks;
-		List<UINT32> mFreeIdxChunks;
-
-		Vector<QueryData> mEventQueries; 
-		Stack<UINT32> mFreeEventQueries;
-
-		UINT32 mNextQueryId;
-
-		static const float GrowPercent;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Mesh heap allows you to quickly allocate and deallocate a large amounts of temporary meshes without the large 
-	 * overhead of normal Mesh creation. Only requirement is that meshes share the same vertex description and index type.
-	 * 			
-	 * @note	
-	 * This class should be considered as a replacement for a normal Mesh if you are constantly updating the mesh (e.g. 
-	 * every frame) and you are not able to discard entire mesh contents on each update. Not using discard flag on normal 
-	 * meshes may introduce GPU-CPU sync points which may severely limit performance. Primary purpose of this class is to 
-	 * avoid those sync points by not forcing you to discard contents.
-	 * Downside is that this class may allocate 2-3x (or more) memory than it is actually needed for your data.
-	 * @note
-	 * Sim thread only
-	 */
-	class BS_CORE_EXPORT MeshHeap : public CoreObject
-	{
-	public:
-		/**
-		 * Allocates a new mesh in the heap, expanding the heap if needed. Mesh will be initialized with the provided 
-		 * @p meshData. You may use the returned transient mesh for drawing.
-		 *
-		 * @note	
-		 * Offsets provided by MeshData are ignored. MeshHeap will determine where the data will be written internally.
-		 */
-		TransientMeshPtr alloc(const MeshDataPtr& meshData, DrawOperationType drawOp = DOT_TRIANGLE_LIST);
-
-		/**
-		 * Deallocates the provided mesh and makes that room on the heap re-usable as soon as the GPU is also done with the 
-		 * mesh.
-		 */
-		void dealloc(const TransientMeshPtr& mesh);
-
-		/** Retrieves a core implementation of a mesh heap usable only from the core thread. */
-		SPtr<MeshHeapCore> getCore() const;
-
-		/**
-		 * Creates a new mesh heap.
-		 *
-		 * @param[in]	numVertices	Initial number of vertices the heap may store. This will grow automatically if needed.
-		 * @param[in]	numIndices	Initial number of indices the heap may store. This will grow automatically if needed.
-		 * @param[in]	vertexDesc	Description of the stored vertices.
-		 * @param[in]	indexType	Type of the stored indices.
-		 */
-		static MeshHeapPtr create(UINT32 numVertices, UINT32 numIndices, 
-			const VertexDataDescPtr& vertexDesc, IndexType indexType = IT_32BIT);
-
-	private:
-		/** @copydoc create */
-		MeshHeap(UINT32 numVertices, UINT32 numIndices, 
-			const VertexDataDescPtr& vertexDesc, IndexType indexType = IT_32BIT);
-
-		/** @copydoc CoreObject::createCore */
-		SPtr<CoreObjectCore> createCore() const override;
-
-	private:
-		UINT32 mNumVertices;
-		UINT32 mNumIndices;
-
-		VertexDataDescPtr mVertexDesc;
-		IndexType mIndexType;
-
-		Map<UINT32, TransientMeshPtr> mMeshes;
-		UINT32 mNextFreeId;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsCoreObject.h"
+#include "BsDrawOps.h"
+#include "BsIndexBuffer.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Resources
+	 *  @{
+	 */
+
+	/**
+	 * Core thread version of MeshHeap.
+	 *
+	 * @note	Core thread only.
+	 */
+	class BS_CORE_EXPORT MeshHeapCore : public CoreObjectCore
+	{
+		/**	Signifies how is a data chunk used. */
+		enum class UseFlags
+		{
+			Used, /**< Data chunk is used by both CPU and GPU. */
+			CPUFree, /**< Data chunk was released by CPU but not GPU. */
+			GPUFree, /**< Data chunk was released by GPU but not CPU. */
+			Free /**< Data chunk was released by both CPU and GPU. */
+		};
+
+		/**	Represents a continuous chunk of memory. */
+		struct ChunkData
+		{
+			UINT32 start, size;
+		};
+
+		/**	Represents an allocated piece of data representing a mesh. */
+		struct AllocatedData
+		{
+			UINT32 vertChunkIdx;
+			UINT32 idxChunkIdx;
+
+			UseFlags useFlags;
+			UINT32 eventQueryIdx;
+			SPtr<TransientMeshCore> mesh;
+		};
+
+		/**	Data about a GPU query. */
+		struct QueryData
+		{
+			EventQueryPtr query;
+			UINT32 queryId;
+		};
+
+	public:
+		~MeshHeapCore();
+
+	private:
+		friend class MeshHeap;
+		friend class TransientMesh;
+		friend class TransientMeshCore;
+
+		MeshHeapCore(UINT32 numVertices, UINT32 numIndices, 
+			const VertexDataDescPtr& vertexDesc, IndexType indexType = IT_32BIT);
+
+		/** @copydoc CoreObjectCore::initialize() */
+		virtual void initialize() override;
+
+		/**
+		 * Allocates a new mesh in the heap, expanding the heap if needed. 
+		 *
+		 * @param[in]	meshId		Mesh for which we are allocating the data.
+		 * @param[in]	meshData	Data to initialize the new mesh with.
+		 */
+		void alloc(SPtr<TransientMeshCore> mesh, const MeshDataPtr& meshData);
+
+		/** Deallocates the provided mesh. Freed memory will be re-used as soon as the GPU is done with the mesh. */
+		void dealloc(SPtr<TransientMeshCore> mesh);
+
+		/** Resizes the vertex buffers so they max contain the provided number of vertices. */
+		void growVertexBuffer(UINT32 numVertices);
+
+		/** Resizes the index buffer so they max contain the provided number of indices. */
+		void growIndexBuffer(UINT32 numIndices);
+
+		/**
+		 * Creates a new event query or returns an existing one from the pool if available. Returned value is an index 
+		 * into event query array.
+		 */
+		UINT32 createEventQuery();
+
+		/** Frees the event query with the specified index and returns it to the pool so it may be reused later. */
+		void freeEventQuery(UINT32 idx);
+
+		/**	Gets internal vertex data for all the meshes. */
+		SPtr<VertexData> getVertexData() const;
+
+		/**	Gets internal index data for all the meshes. */
+		SPtr<IndexBufferCore> getIndexBuffer() const;
+
+		/** Returns a structure that describes how are the vertices stored in the mesh's vertex buffer. */
+		SPtr<VertexDataDesc> getVertexDesc() const;
+
+		/**
+		 * Returns the offset in vertices from the start of the buffer to the first vertex of the mesh with the provided ID.
+		 */
+		UINT32 getVertexOffset(UINT32 meshId) const;
+
+		/**
+		 * Returns the offset in indices from the start of the buffer to the first index of the mesh with the provided ID.
+		 */
+		UINT32 getIndexOffset(UINT32 meshId) const;
+
+		/** Called by the render system when a mesh gets queued to the GPU. */
+		void notifyUsedOnGPU(UINT32 meshId);
+
+		/**
+		 * Called by an GPU event query when GPU processes the query. Normally signals the heap that the GPU is done with 
+		 * the mesh.
+		 */
+		static void queryTriggered(SPtr<MeshHeapCore> thisPtr, UINT32 meshId, UINT32 queryId);
+
+		/**
+		 * Attempts to reorganize the vertex and index buffer chunks in order to in order to make free memory contigous.
+		 *
+		 * @note	
+		 * This will not actually copy any data from index/vertex buffers, and will only modify the chunk descriptors.
+		 */
+		void mergeWithNearbyChunks(UINT32 chunkVertIdx, UINT32 chunkIdxIdx);
+
+	private:
+		UINT32 mNumVertices;
+		UINT32 mNumIndices;
+
+		Vector<UINT8*> mCPUVertexData;
+		UINT8* mCPUIndexData;
+
+		SPtr<VertexData> mVertexData;
+		SPtr<IndexBufferCore> mIndexBuffer;
+
+		Map<UINT32, AllocatedData> mMeshAllocData;
+
+		VertexDataDescPtr mVertexDesc;
+		IndexType mIndexType;
+
+		Vector<ChunkData> mVertChunks;
+		Vector<ChunkData> mIdxChunks;
+
+		Stack<UINT32> mEmptyVertChunks;
+		Stack<UINT32> mEmptyIdxChunks;
+
+		List<UINT32> mFreeVertChunks;
+		List<UINT32> mFreeIdxChunks;
+
+		Vector<QueryData> mEventQueries; 
+		Stack<UINT32> mFreeEventQueries;
+
+		UINT32 mNextQueryId;
+
+		static const float GrowPercent;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Mesh heap allows you to quickly allocate and deallocate a large amounts of temporary meshes without the large 
+	 * overhead of normal Mesh creation. Only requirement is that meshes share the same vertex description and index type.
+	 * 			
+	 * @note	
+	 * This class should be considered as a replacement for a normal Mesh if you are constantly updating the mesh (for 
+	 * example every frame) and you are not able to discard entire mesh contents on each update. Not using discard flag on
+	 * normal meshes may introduce GPU-CPU sync points which may severely limit performance. Primary purpose of this class
+	 * is to avoid those sync points by not forcing you to discard contents.
+	 * Downside is that this class may allocate 2-3x (or more) memory than it is actually needed for your data.
+	 * @note
+	 * Sim thread only
+	 */
+	class BS_CORE_EXPORT MeshHeap : public CoreObject
+	{
+	public:
+		/**
+		 * Allocates a new mesh in the heap, expanding the heap if needed. Mesh will be initialized with the provided 
+		 * @p meshData. You may use the returned transient mesh for drawing.
+		 *
+		 * @note	
+		 * Offsets provided by MeshData are ignored. MeshHeap will determine where the data will be written internally.
+		 */
+		TransientMeshPtr alloc(const MeshDataPtr& meshData, DrawOperationType drawOp = DOT_TRIANGLE_LIST);
+
+		/**
+		 * Deallocates the provided mesh and makes that room on the heap re-usable as soon as the GPU is also done with the 
+		 * mesh.
+		 */
+		void dealloc(const TransientMeshPtr& mesh);
+
+		/** Retrieves a core implementation of a mesh heap usable only from the core thread. */
+		SPtr<MeshHeapCore> getCore() const;
+
+		/**
+		 * Creates a new mesh heap.
+		 *
+		 * @param[in]	numVertices	Initial number of vertices the heap may store. This will grow automatically if needed.
+		 * @param[in]	numIndices	Initial number of indices the heap may store. This will grow automatically if needed.
+		 * @param[in]	vertexDesc	Description of the stored vertices.
+		 * @param[in]	indexType	Type of the stored indices.
+		 */
+		static MeshHeapPtr create(UINT32 numVertices, UINT32 numIndices, 
+			const VertexDataDescPtr& vertexDesc, IndexType indexType = IT_32BIT);
+
+	private:
+		/** @copydoc create */
+		MeshHeap(UINT32 numVertices, UINT32 numIndices, 
+			const VertexDataDescPtr& vertexDesc, IndexType indexType = IT_32BIT);
+
+		/** @copydoc CoreObject::createCore */
+		SPtr<CoreObjectCore> createCore() const override;
+
+	private:
+		UINT32 mNumVertices;
+		UINT32 mNumIndices;
+
+		VertexDataDescPtr mVertexDesc;
+		IndexType mIndexType;
+
+		Map<UINT32, TransientMeshPtr> mMeshes;
+		UINT32 mNextFreeId;
+	};
+
+	/** @} */
 }

+ 87 - 84
Source/BansheeCore/Include/BsMeshUtility.h

@@ -1,85 +1,88 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Utility-Core
-	 *  @{
-	 */
-
-	/** Performs various operations on mesh geometry. */
-	class BS_CORE_EXPORT MeshUtility
-	{
-	public:
-		/**
-		 * Calculates per-vertex normals based on the provided vertices and indices.
-		 *
-		 * @param[in]	vertices	Set of vertices containing vertex positions.
-		 * @param[in]	indices		Set of indices containing indexes into vertex array for each triangle.
-		 * @param[in]	numVertices	Number of vertices in the @p vertices array.
-		 * @param[in]	numIndices	Number of indices in the @p indices array. Must be a multiple of three.
-		 * @param[out]	normals		Pre-allocated buffer that will contain the calculated normals. Must be the same size
-		 *							as the vertex array.
-		 * @param[in]	indexSize	Size of a single index in the indices array, in bytes.
-		 *
-		 * @note	
-		 * Vertices should be split before calling this method if there are any discontinuities. (e.g. a vertex on a corner
-		 * of a cube should be split into three vertices used by three triangles in order for the normals to be valid.)
-		 */
-		static void calculateNormals(Vector3* vertices, UINT8* indices, UINT32 numVertices, 
-			UINT32 numIndices, Vector3* normals, UINT32 indexSize = 4);
-
-		/**
-		 * Calculates per-vertex tangents and bitangents based on the provided vertices, uv coordinates and indices.
-		 *
-		 * @param[in]	vertices	Set of vertices containing vertex positions.
-		 * @param[in]	normals		Set of normals to use when calculating tangents. Must the the same length as the number
-		 *							of vertices.
-		 * @param[in]	uv			Set of UV coordinates to use when calculating tangents. Must the the same length as the
-		 *							number of vertices.
-		 * @param[in]	indices		Set of indices containing indexes into vertex array for each triangle.
-		 * @param[in]	numVertices	Number of vertices in the @p vertices, @p normals and @p uv arrays.
-		 * @param[in]	numIndices	Number of indices in the @p indices array. Must be a multiple of three.
-		 * @param[out]	tangents	Pre-allocated buffer that will contain the calculated tangents. Must be the same size
-		 *							as the vertex array.
-		 * @param[out]	bitangents	Pre-allocated buffer that will contain the calculated bitangents. Must be the same size
-		 *							as the vertex array.
-		 * @param[in]	indexSize	Size of a single index in the indices array, in bytes.
-		 *
-		 * @note	
-		 * Vertices should be split before calling this method if there are any discontinuities. (e.g. a vertex on a corner
-		 * of a cube should be split into three vertices used by three triangles in order for the normals to be valid.)
-		 */
-		static void calculateTangents(Vector3* vertices, Vector3* normals, Vector2* uv, UINT8* indices, UINT32 numVertices, 
-			UINT32 numIndices, Vector3* tangents, Vector3* bitangents, UINT32 indexSize = 4);
-
-		/**
-		 * Calculates per-vertex tangent space (normal, tangent, bitangent) based on the provided vertices, uv coordinates
-		 * and indices.
-		 *
-		 * @param[in]	vertices	Set of vertices containing vertex positions.
-		 * @param[in]	uv			Set of UV coordinates to use when calculating tangents.
-		 * @param[in]	indices		Set of indices containing indexes into vertex array for each triangle.
-		 * @param[in]	numVertices	Number of vertices in the "vertices" array.
-		 * @param[in]	numIndices	Number of indices in the "indices" array. Must be a multiple of three.
-		 * @param[out]	normals		Pre-allocated buffer that will contain the calculated normals. Must be the same size
-		 *							as the vertex array.
-		 * @param[out]	tangents	Pre-allocated buffer that will contain the calculated tangents. Must be the same size
-		 *							as the vertex array.
-		 * @param[out]	bitangents	Pre-allocated buffer that will contain the calculated bitangents. Must be the same size
-		 *							as the vertex array.
-		 * @param[in]	indexSize	Size of a single index in the indices array, in bytes.
-		 *
-		 * @note	
-		 * Vertices should be split before calling this method if there are any discontinuities. (e.g. a vertex on a corner
-		 * of a cube should be split into three vertices used by three triangles in order for the normals to be valid.)
-		 */
-		static void calculateTangentSpace(Vector3* vertices, Vector2* uv, UINT8* indices, UINT32 numVertices, 
-			UINT32 numIndices, Vector3* normals, Vector3* tangents, Vector3* bitangents, UINT32 indexSize = 4);
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Utility-Core
+	 *  @{
+	 */
+
+	/** Performs various operations on mesh geometry. */
+	class BS_CORE_EXPORT MeshUtility
+	{
+	public:
+		/**
+		 * Calculates per-vertex normals based on the provided vertices and indices.
+		 *
+		 * @param[in]	vertices	Set of vertices containing vertex positions.
+		 * @param[in]	indices		Set of indices containing indexes into vertex array for each triangle.
+		 * @param[in]	numVertices	Number of vertices in the @p vertices array.
+		 * @param[in]	numIndices	Number of indices in the @p indices array. Must be a multiple of three.
+		 * @param[out]	normals		Pre-allocated buffer that will contain the calculated normals. Must be the same size
+		 *							as the vertex array.
+		 * @param[in]	indexSize	Size of a single index in the indices array, in bytes.
+		 *
+		 * @note	
+		 * Vertices should be split before calling this method if there are any discontinuities. (for example a vertex on a
+		 * corner of a cube should be split into three vertices used by three triangles in order for the normals to be
+		 * valid.)
+		 */
+		static void calculateNormals(Vector3* vertices, UINT8* indices, UINT32 numVertices, 
+			UINT32 numIndices, Vector3* normals, UINT32 indexSize = 4);
+
+		/**
+		 * Calculates per-vertex tangents and bitangents based on the provided vertices, uv coordinates and indices.
+		 *
+		 * @param[in]	vertices	Set of vertices containing vertex positions.
+		 * @param[in]	normals		Set of normals to use when calculating tangents. Must the the same length as the number
+		 *							of vertices.
+		 * @param[in]	uv			Set of UV coordinates to use when calculating tangents. Must the the same length as the
+		 *							number of vertices.
+		 * @param[in]	indices		Set of indices containing indexes into vertex array for each triangle.
+		 * @param[in]	numVertices	Number of vertices in the @p vertices, @p normals and @p uv arrays.
+		 * @param[in]	numIndices	Number of indices in the @p indices array. Must be a multiple of three.
+		 * @param[out]	tangents	Pre-allocated buffer that will contain the calculated tangents. Must be the same size
+		 *							as the vertex array.
+		 * @param[out]	bitangents	Pre-allocated buffer that will contain the calculated bitangents. Must be the same size
+		 *							as the vertex array.
+		 * @param[in]	indexSize	Size of a single index in the indices array, in bytes.
+		 *
+		 * @note	
+		 * Vertices should be split before calling this method if there are any discontinuities. (for example a vertex on a
+		 * corner of a cube should be split into three vertices used by three triangles in order for the normals to be
+		 * valid.)
+		 */
+		static void calculateTangents(Vector3* vertices, Vector3* normals, Vector2* uv, UINT8* indices, UINT32 numVertices, 
+			UINT32 numIndices, Vector3* tangents, Vector3* bitangents, UINT32 indexSize = 4);
+
+		/**
+		 * Calculates per-vertex tangent space (normal, tangent, bitangent) based on the provided vertices, uv coordinates
+		 * and indices.
+		 *
+		 * @param[in]	vertices	Set of vertices containing vertex positions.
+		 * @param[in]	uv			Set of UV coordinates to use when calculating tangents.
+		 * @param[in]	indices		Set of indices containing indexes into vertex array for each triangle.
+		 * @param[in]	numVertices	Number of vertices in the "vertices" array.
+		 * @param[in]	numIndices	Number of indices in the "indices" array. Must be a multiple of three.
+		 * @param[out]	normals		Pre-allocated buffer that will contain the calculated normals. Must be the same size
+		 *							as the vertex array.
+		 * @param[out]	tangents	Pre-allocated buffer that will contain the calculated tangents. Must be the same size
+		 *							as the vertex array.
+		 * @param[out]	bitangents	Pre-allocated buffer that will contain the calculated bitangents. Must be the same size
+		 *							as the vertex array.
+		 * @param[in]	indexSize	Size of a single index in the indices array, in bytes.
+		 *
+		 * @note	
+		 * Vertices should be split before calling this method if there are any discontinuities. (for example. a vertex on
+		 * a corner of a cube should be split into three vertices used by three triangles in order for the normals to be
+		 * valid.)
+		 */
+		static void calculateTangentSpace(Vector3* vertices, Vector2* uv, UINT8* indices, UINT32 numVertices, 
+			UINT32 numIndices, Vector3* normals, Vector3* tangents, Vector3* bitangents, UINT32 indexSize = 4);
+	};
+
+	/** @} */
 }

+ 2 - 1
Source/BansheeCore/Include/BsParamBlocks.h

@@ -17,7 +17,8 @@ namespace BansheeEngine
 
 /** 
  * Starts a new custom parameter block. Custom parameter blocks allow you to create C++ structures that map directly
- * to GPU program buffers (e.g. uniform buffer in OpenGL or constant buffer in DX). Must be followed by BS_PARAM_BLOCK_END.
+ * to GPU program buffers (for example uniform buffer in OpenGL or constant buffer in DX). Must be followed by 
+ * BS_PARAM_BLOCK_END.
  */
 #define BS_PARAM_BLOCK_BEGIN(Name)																							\
 	struct Name																												\

+ 1 - 1
Source/BansheeCore/Include/BsPass.h

@@ -80,7 +80,7 @@ namespace BansheeEngine
 	};
 
 	/**
-	 * Class defining a single pass of a technique (of a material), i.e. a single rendering call.
+	 * Class defining a single pass of a technique (of a material).
 	 *
 	 * Pass may contain multiple GPU programs (vertex, fragment, geometry, etc.), and a set of pipeline states (blend, 
 	 * rasterizer, etc.).

+ 595 - 593
Source/BansheeCore/Include/BsPhysics.h

@@ -1,594 +1,596 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPhysicsCommon.h"
-#include "BsModule.h"
-#include "BsVector3.h"
-#include "BsVector2.h"
-#include "BsQuaternion.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	struct PHYSICS_INIT_DESC;
-
-	/** Flags for controlling physics behaviour globally. */
-	enum class PhysicsFlag
-	{
-		/** 
-		 * Automatically recovers character controllers that are interpenetrating geometry. This can happen if a controller
-		 * is spawned or teleported into geometry, its size/rotation is changed so it penetrates geometry, or simply
-		 * because of numerical imprecision.
-		 */
-		CCT_OverlapRecovery = 1<<0,
-		/**
-		 * Performs more accurate sweeps when moving the character controller, making it less likely to interpenetrate
-		 * geometry. When overlap recovery is turned on you can consider turning this off as it can compensate for the
-		 * less precise sweeps.
-		 */
-		CCT_PreciseSweeps = 1<<1,
-		/**
-		 * Large triangles can cause problems with character controller collision. If this option is enabled the triangles
-		 * larger than a certain size will be automatically tesselated into smaller triangles, in order to help with
-		 * precision.
-		 *
-		 * @see Physics::getMaxTesselationEdgeLength
-		 */
-		CCT_Tesselation = 1<<2,
-		/** 
-		 * Enables continous collision detection. This will prevent fast-moving objects from tunneling through each other.
-		 * You must also enable CCD for individual Rigidbodies. This option can have a significant performance impact.
-		 */
-		CCD_Enable = 1<<3
-	};
-
-	/** @copydoc CharacterCollisionFlag */
-	typedef Flags<PhysicsFlag> PhysicsFlags;
-	BS_FLAGS_OPERATORS(PhysicsFlag)
-
-	/** Provides global physics settings, factory methods for physics objects and scene queries. */
-	class BS_CORE_EXPORT Physics : public Module<Physics>
-	{
-	public:
-		Physics(const PHYSICS_INIT_DESC& init);
-		virtual ~Physics() { }
-
-		/******************************************************************************************************************/
-		/************************************************* QUERIES ********************************************************/
-		/******************************************************************************************************************/
-
-		/**
-		 * Casts a ray into the scene and returns the closest found hit, if any.
-		 * 
-		 * @param[in]	ray		Ray to cast into the scene.
-		 * @param[out]	hit		Information recorded about a hit. Only valid if method returns true.
-		 * @param[in]	layer	Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max		Maximum distance at which to perform the query. Hits past this distance will not be
-		 *						detected.
-		 * @return				True if something was hit, false otherwise.
-		 */
-		virtual bool rayCast(const Ray& ray, PhysicsQueryHit& hit, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const;
-
-		/**
-		 * Casts a ray into the scene and returns the closest found hit, if any.
-		 * 
-		 * @param[in]	origin		Origin of the ray to cast into the scene.
-		 * @param[in]	unitDir		Unit direction of the ray to cast into the scene.
-		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool rayCast(const Vector3& origin, const Vector3& unitDir, PhysicsQueryHit& hit,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a box and returns the closest found hit, if any.
-		 * 
-		 * @param[in]	box			Box to sweep through the scene.
-		 * @param[in]	rotation	Orientation of the box.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool boxCast(const AABox& box, const Quaternion& rotation, const Vector3& unitDir, PhysicsQueryHit& hit,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a sphere and returns the closest found hit, if any.
-		 * 
-		 * @param[in]	sphere		Sphere to sweep through the scene.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool sphereCast(const Sphere& sphere, const Vector3& unitDir, PhysicsQueryHit& hit,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a capsule and returns the closest found hit, if any.
-		 * 
-		 * @param[in]	capsule		Capsule to sweep through the scene.
-		 * @param[in]	rotation	Orientation of the capsule.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool capsuleCast(const Capsule& capsule, const Quaternion& rotation, const Vector3& unitDir,
-			PhysicsQueryHit& hit, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a convex mesh and returns the closest found hit, if any.
-		 * 
-		 * @param[in]	mesh		Mesh to sweep through the scene. Must be convex.
-		 * @param[in]	position	Starting position of the mesh.
-		 * @param[in]	rotation	Orientation of the mesh.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool convexCast(const HPhysicsMesh& mesh, const Vector3& position, const Quaternion& rotation,
-			const Vector3& unitDir, PhysicsQueryHit& hit, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Casts a ray into the scene and returns all found hits.
-		 * 
-		 * @param[in]	ray		Ray to cast into the scene.
-		 * @param[in]	layer	Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max		Maximum distance at which to perform the query. Hits past this distance will not be
-		 *						detected.
-		 * @return				List of all detected hits.
-		 */
-		virtual Vector<PhysicsQueryHit> rayCastAll(const Ray& ray, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const;
-
-		/**
-		 * Casts a ray into the scene and returns all found hits.
-		 * 
-		 * @param[in]	origin		Origin of the ray to cast into the scene.
-		 * @param[in]	unitDir		Unit direction of the ray to cast into the scene.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					List of all detected hits.
-		 */
-		virtual Vector<PhysicsQueryHit> rayCastAll(const Vector3& origin, const Vector3& unitDir,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a box and returns all found hits.
-		 * 
-		 * @param[in]	box			Box to sweep through the scene.
-		 * @param[in]	rotation	Orientation of the box.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					List of all detected hits.
-		 */
-		virtual Vector<PhysicsQueryHit> boxCastAll(const AABox& box, const Quaternion& rotation, 
-			const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a sphere and returns all found hits.
-		 * 
-		 * @param[in]	sphere		Sphere to sweep through the scene.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					List of all detected hits.
-		 */
-		virtual Vector<PhysicsQueryHit> sphereCastAll(const Sphere& sphere, const Vector3& unitDir,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a capsule and returns all found hits.
-		 * 
-		 * @param[in]	capsule		Capsule to sweep through the scene.
-		 * @param[in]	rotation	Orientation of the capsule.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					List of all detected hits.
-		 */
-		virtual Vector<PhysicsQueryHit> capsuleCastAll(const Capsule& capsule, const Quaternion& rotation, 
-			const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a convex mesh and returns all found hits.
-		 * 
-		 * @param[in]	mesh		Mesh to sweep through the scene. Must be convex.
-		 * @param[in]	position	Starting position of the mesh.
-		 * @param[in]	rotation	Orientation of the mesh.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					List of all detected hits.
-		 */
-		virtual Vector<PhysicsQueryHit> convexCastAll(const HPhysicsMesh& mesh, const Vector3& position, 
-			const Quaternion& rotation, const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Casts a ray into the scene and checks if it has hit anything. This can be significantly more efficient than other
-		 * types of cast* calls.
-		 * 
-		 * @param[in]	ray		Ray to cast into the scene.
-		 * @param[in]	layer	Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max		Maximum distance at which to perform the query. Hits past this distance will not be
-		 *						detected.
-		 * @return				True if something was hit, false otherwise.
-		 */
-		virtual bool rayCastAny(const Ray& ray, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const;
-
-		/**
-		 * Casts a ray into the scene and checks if it has hit anything. This can be significantly more efficient than other
-		 * types of cast* calls.
-		 * 
-		 * @param[in]	origin		Origin of the ray to cast into the scene.
-		 * @param[in]	unitDir		Unit direction of the ray to cast into the scene.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool rayCastAny(const Vector3& origin, const Vector3& unitDir,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a box and checks if it has hit anything. This can be significantly more
-		 * efficient than other types of cast* calls.
-		 * 
-		 * @param[in]	box			Box to sweep through the scene.
-		 * @param[in]	rotation	Orientation of the box.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool boxCastAny(const AABox& box, const Quaternion& rotation, const Vector3& unitDir,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a sphere and checks if it has hit anything. This can be significantly more
-		 * efficient than other types of cast* calls.
-		 * 
-		 * @param[in]	sphere		Sphere to sweep through the scene.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool sphereCastAny(const Sphere& sphere, const Vector3& unitDir,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a capsule and checks if it has hit anything. This can be significantly more
-		 * efficient than other types of cast* calls.
-		 * 
-		 * @param[in]	capsule		Capsule to sweep through the scene.
-		 * @param[in]	rotation	Orientation of the capsule.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool capsuleCastAny(const Capsule& capsule, const Quaternion& rotation, const Vector3& unitDir,
-			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Performs a sweep into the scene using a convex mesh and checks if it has hit anything. This can be significantly
-		 * more efficient than other types of cast* calls.
-		 * 
-		 * @param[in]	mesh		Mesh to sweep through the scene. Must be convex.
-		 * @param[in]	position	Starting position of the mesh.
-		 * @param[in]	rotation	Orientation of the mesh.
-		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
-		 *							detected.
-		 * @return					True if something was hit, false otherwise.
-		 */
-		virtual bool convexCastAny(const HPhysicsMesh& mesh, const Vector3& position, const Quaternion& rotation,
-			const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
-
-		/**
-		 * Returns a list of all colliders in the scene that overlap the provided box.
-		 * 
-		 * @param[in]	box			Box to check for overlap.
-		 * @param[in]	rotation	Orientation of the box.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					List of all colliders that overlap the box.
-		 */
-		virtual Vector<HCollider> boxOverlap(const AABox& box, const Quaternion& rotation, 
-			UINT64 layer = BS_ALL_LAYERS) const;
-
-		/**
-		 * Returns a list of all colliders in the scene that overlap the provided sphere.
-		 * 
-		 * @param[in]	Sphere		Sphere to check for overlap.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					List of all colliders that overlap the sphere.
-		 */
-		virtual Vector<HCollider> sphereOverlap(const Sphere& sphere, UINT64 layer = BS_ALL_LAYERS) const;
-
-		/**
-		 * Returns a list of all colliders in the scene that overlap the provided capsule.
-		 * 
-		 * @param[in]	capsule		Capsule to check for overlap.
-		 * @param[in]	rotation	Orientation of the capsule.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					List of all colliders that overlap the capsule.
-		 */
-		virtual Vector<HCollider> capsuleOverlap(const Capsule& capsule, const Quaternion& rotation,
-			UINT64 layer = BS_ALL_LAYERS) const;
-
-		/**
-		 * Returns a list of all colliders in the scene that overlap the provided convex mesh.
-		 * 
-		 * @param[in]	mesh		Mesh to check for overlap. Must be convex.
-		 * @param[in]	position	Position of the mesh.
-		 * @param[in]	rotation	Orientation of the mesh.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					List of all colliders that overlap the mesh.
-		 */
-		virtual Vector<HCollider> convexOverlap(const HPhysicsMesh& mesh, const Vector3& position, 
-			const Quaternion& rotation, UINT64 layer = BS_ALL_LAYERS) const;
-
-		/**
-		 * Checks if the provided box overlaps any other collider in the scene.
-		 * 
-		 * @param[in]	box			Box to check for overlap.
-		 * @param[in]	rotation	Orientation of the box.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					True if there is overlap with another object, false otherwise.
-		 */
-		virtual bool boxOverlapAny(const AABox& box, const Quaternion& rotation, UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/**
-		 * Checks if the provided sphere overlaps any other collider in the scene.
-		 * 
-		 * @param[in]	sphere		Sphere to check for overlap.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					True if there is overlap with another object, false otherwise.
-		 */
-		virtual bool sphereOverlapAny(const Sphere& sphere, UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/**
-		 * Checks if the provided capsule overlaps any other collider in the scene.
-		 * 
-		 * @param[in]	capsule		Capsule to check for overlap.
-		 * @param[in]	rotation	Orientation of the capsule.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					True if there is overlap with another object, false otherwise.
-		 */
-		virtual bool capsuleOverlapAny(const Capsule& capsule, const Quaternion& rotation, 
-			UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/**
-		 * Checks if the provided convex mesh overlaps any other collider in the scene.
-		 * 
-		 * @param[in]	mesh		Mesh to check for overlap. Must be convex.
-		 * @param[in]	position	Position of the mesh.
-		 * @param[in]	rotation	Orientation of the mesh.
-		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
-		 * @return					True if there is overlap with another object, false otherwise.
-		 */
-		virtual bool convexOverlapAny(const HPhysicsMesh& mesh, const Vector3& position, const Quaternion& rotation,
-			UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/******************************************************************************************************************/
-		/************************************************* OPTIONS ********************************************************/
-		/******************************************************************************************************************/
-
-		/** Checks is a specific physics option enabled. */
-		virtual bool hasFlag(PhysicsFlags flag) const { return mFlags & flag; }
-
-		/** Enables or disabled a specific physics option. */
-		virtual void setFlag(PhysicsFlags flag, bool enabled) { if (enabled) mFlags |= flag; else mFlags &= ~flag; }
-
-		/** Gets the global gravity value for all objects in the scene. */
-		virtual Vector3 getGravity() const = 0;
-
-		/** Sets the global gravity value for all objects in the scene. */
-		virtual void setGravity(const Vector3& gravity) = 0;
-
-		/** 
-		 * Adds a new physics region. Certain physics options require you to set up regions in which physics objects are
-		 * allowed to be in, and objects outside of these regions will not be handled by physics. You do not need to set
-		 * up these regions by default.
-		 */
-		virtual UINT32 addBroadPhaseRegion(const AABox& region) = 0;
-
-		/** Removes a physics region. */
-		virtual void removeBroadPhaseRegion(UINT32 handle) = 0;
-
-		/** Removes all physics regions. */
-		virtual void clearBroadPhaseRegions() = 0;
-
-		/** 
-		 * Returns a maximum edge length before a triangle is tesselated. 
-		 *
-		 * @see PhysicsFlags::CCT_Tesselation
-		 */
-		virtual float getMaxTesselationEdgeLength() const = 0;
-
-		/** 
-		 * Sets a maximum edge length before a triangle is tesselated. 
-		 *
-		 * @see PhysicsFlags::CCT_Tesselation
-		 */
-		virtual void setMaxTesselationEdgeLength(float length) = 0;
-
-		/** 
-		 * Enables or disables collision between two layers. Each physics object can be assigned a specific layer, and here
-		 * you can determine which layers can interact with each other.
-		 */
-		void toggleCollision(UINT64 groupA, UINT64 groupB, bool enabled);
-
-		/** Checks if two collision layers are allowed to interact. */
-		bool isCollisionEnabled(UINT64 groupA, UINT64 groupB) const;
-
-		/** @cond INTERNAL */
-
-		/******************************************************************************************************************/
-		/************************************************* CREATION *******************************************************/
-		/******************************************************************************************************************/
-
-		/** @copydoc PhysicsMaterial::create */
-		virtual SPtr<PhysicsMaterial> createMaterial(float staticFriction, float dynamicFriction, float restitution) = 0;
-
-		/** @copydoc PhysicsMesh::create */
-		virtual SPtr<PhysicsMesh> createMesh(const MeshDataPtr& meshData, PhysicsMeshType type) = 0;
-
-		/** @copydoc Rigidbody::create */
-		virtual SPtr<Rigidbody> createRigidbody(const HSceneObject& linkedSO) = 0;
-
-		/** @copydoc BoxCollider::create */
-		virtual SPtr<BoxCollider> createBoxCollider(const Vector3& extents, const Vector3& position,
-			const Quaternion& rotation) = 0;
-
-		/** @copydoc SphereCollider::create */
-		virtual SPtr<SphereCollider> createSphereCollider(float radius,
-			const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** @copydoc PlaneCollider::create */
-		virtual SPtr<PlaneCollider> createPlaneCollider(const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** @copydoc CapsuleCollider::create */
-		virtual SPtr<CapsuleCollider> createCapsuleCollider(float radius, float halfHeight,
-			const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** @copydoc MeshCollider::create */
-		virtual SPtr<MeshCollider> createMeshCollider(const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** @copydoc FixedJoint::create */
-		virtual SPtr<FixedJoint> createFixedJoint() = 0;
-
-		/** @copydoc DistanceJoint::create */
-		virtual SPtr<DistanceJoint> createDistanceJoint() = 0;
-
-		/** @copydoc HingeJoint::create */
-		virtual SPtr<HingeJoint> createHingeJoint() = 0;
-
-		/** @copydoc SphericalJoint::create */
-		virtual SPtr<SphericalJoint> createSphericalJoint() = 0;
-
-		/** @copydoc SliderJoint::create */
-		virtual SPtr<SliderJoint> createSliderJoint() = 0;
-
-		/** @copydoc D6Joint::create */
-		virtual SPtr<D6Joint> createD6Joint() = 0;
-
-		/** @copydoc CharacterController::create */
-		virtual SPtr<CharacterController> createCharacterController(const CHAR_CONTROLLER_DESC& desc) = 0;
-
-		/** Triggers physics simulation update as needed. Should be called once per frame. */
-		virtual void update() = 0;
-
-		/** @copydoc Physics::boxOverlap() */
-		virtual Vector<Collider*> _boxOverlap(const AABox& box, const Quaternion& rotation,
-			UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/** @copydoc Physics::sphereOverlap() */
-		virtual Vector<Collider*> _sphereOverlap(const Sphere& sphere, UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/** @copydoc Physics::capsuleOverlap() */
-		virtual Vector<Collider*> _capsuleOverlap(const Capsule& capsule, const Quaternion& rotation,
-			UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/** @copydoc Physics::convexOverlap() */
-		virtual Vector<Collider*> _convexOverlap(const HPhysicsMesh& mesh, const Vector3& position,
-			const Quaternion& rotation, UINT64 layer = BS_ALL_LAYERS) const = 0;
-
-		/** 
-		 * Checks does the ray hit the provided collider. 
-		 *
-		 * @param[in]	origin		Origin of the ray to check.
-		 * @param[in]	unitDir		Unit direction of the ray to check.
-		 * @param[in]	collider	Collider to check for hit.
-		 * @param[out]	hit			Information about the hit. Valid only if the method returns true.
-		 * @param[in]	maxDist		Maximum distance from the ray origin to search for hits.
-		 * @return					True if the ray has hit the collider.
-		 */
-		virtual bool _rayCast(const Vector3& origin, const Vector3& unitDir, const Collider& collider, PhysicsQueryHit& hit, 
-			float maxDist = FLT_MAX) const = 0;
-
-		/** Checks is the physics simulation update currently in progress. */
-		bool _isUpdateInProgress() const { return mUpdateInProgress; }
-
-		/** @endcond */
-
-		static const UINT64 CollisionMapSize = 64;
-	protected:
-		friend class Rigidbody;
-
-		/** 
-		 * Registers a new rigidbody. Should be called whenever a new rigidbody is created. 
-		 * 
-		 * @param[in]	body		Newly created rigidbody.
-		 * @param[in]	priority	Priority that determines in what order is the physics simulation update applied to
-		 *							rigidbodes. Higher priority means it is applied before lower priority.
-		 */
-		void registerRigidbody(Rigidbody* body, UINT32 priority);
-
-		/** 
-		 * Unregisters a rigidbody. Should be called before a rigidbody is destroyed.
-		 *
-		 * @param[in]	id			ID of the rigidbody to remove.
-		 * @param[in]	priority	Original priority of the rigidbody.
-		 */
-		void unregisterRigidbody(UINT32 id, UINT32 priority);
-
-		/** Changes the priority of a rigidbody. */
-		void updatePriority(UINT32 id, UINT32 oldPriority, UINT32 newPriority);
-
-		mutable Mutex mMutex;
-		bool mCollisionMap[CollisionMapSize][CollisionMapSize];
-
-		bool mUpdateInProgress = false;
-		PhysicsFlags mFlags;
-		Vector<Vector<Rigidbody*>> mRigidbodies; // TODO: Unused for now, but keeping it here just in case I change the design. Remove later.
-
-		const static UINT32 MAX_PRIORITY = 128;
-	};
-
-	/** Provides easier access to Physics. */
-	BS_CORE_EXPORT Physics& gPhysics();
-
-	/** Contains parameters used for initializing the physics system. */
-	struct PHYSICS_INIT_DESC
-	{
-		float typicalLength = 1.0f; /**< Typical length of an object in the scene. */
-		float typicalSpeed = 9.81f; /**< Typical speed of an object in the scene. */
-		Vector3 gravity = Vector3(0.0f, -9.81f, 0.0f); /**< Initial gravity. */
-		bool initCooking = true; /**< Determines should the cooking library be initialized. */
-		float timeStep = 1.0f / 60.0f; /**< Determines using what interval should the physics update happen. */
-		/** Flags that control global physics option. */
-		PhysicsFlags flags = PhysicsFlag::CCT_OverlapRecovery | PhysicsFlag::CCT_PreciseSweeps | PhysicsFlag::CCD_Enable;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPhysicsCommon.h"
+#include "BsModule.h"
+#include "BsVector3.h"
+#include "BsVector2.h"
+#include "BsQuaternion.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	struct PHYSICS_INIT_DESC;
+
+	/** Flags for controlling physics behaviour globally. */
+	enum class PhysicsFlag
+	{
+		/** 
+		 * Automatically recovers character controllers that are interpenetrating geometry. This can happen if a controller
+		 * is spawned or teleported into geometry, its size/rotation is changed so it penetrates geometry, or simply
+		 * because of numerical imprecision.
+		 */
+		CCT_OverlapRecovery = 1<<0,
+		/**
+		 * Performs more accurate sweeps when moving the character controller, making it less likely to interpenetrate
+		 * geometry. When overlap recovery is turned on you can consider turning this off as it can compensate for the
+		 * less precise sweeps.
+		 */
+		CCT_PreciseSweeps = 1<<1,
+		/**
+		 * Large triangles can cause problems with character controller collision. If this option is enabled the triangles
+		 * larger than a certain size will be automatically tesselated into smaller triangles, in order to help with
+		 * precision.
+		 *
+		 * @see Physics::getMaxTesselationEdgeLength
+		 */
+		CCT_Tesselation = 1<<2,
+		/** 
+		 * Enables continous collision detection. This will prevent fast-moving objects from tunneling through each other.
+		 * You must also enable CCD for individual Rigidbodies. This option can have a significant performance impact.
+		 */
+		CCD_Enable = 1<<3
+	};
+
+	/** @copydoc CharacterCollisionFlag */
+	typedef Flags<PhysicsFlag> PhysicsFlags;
+	BS_FLAGS_OPERATORS(PhysicsFlag)
+
+	/** Provides global physics settings, factory methods for physics objects and scene queries. */
+	class BS_CORE_EXPORT Physics : public Module<Physics>
+	{
+	public:
+		Physics(const PHYSICS_INIT_DESC& init);
+		virtual ~Physics() { }
+
+		/******************************************************************************************************************/
+		/************************************************* QUERIES ********************************************************/
+		/******************************************************************************************************************/
+
+		/**
+		 * Casts a ray into the scene and returns the closest found hit, if any.
+		 * 
+		 * @param[in]	ray		Ray to cast into the scene.
+		 * @param[out]	hit		Information recorded about a hit. Only valid if method returns true.
+		 * @param[in]	layer	Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max		Maximum distance at which to perform the query. Hits past this distance will not be
+		 *						detected.
+		 * @return				True if something was hit, false otherwise.
+		 */
+		virtual bool rayCast(const Ray& ray, PhysicsQueryHit& hit, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const;
+
+		/**
+		 * Casts a ray into the scene and returns the closest found hit, if any.
+		 * 
+		 * @param[in]	origin		Origin of the ray to cast into the scene.
+		 * @param[in]	unitDir		Unit direction of the ray to cast into the scene.
+		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool rayCast(const Vector3& origin, const Vector3& unitDir, PhysicsQueryHit& hit,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a box and returns the closest found hit, if any.
+		 * 
+		 * @param[in]	box			Box to sweep through the scene.
+		 * @param[in]	rotation	Orientation of the box.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool boxCast(const AABox& box, const Quaternion& rotation, const Vector3& unitDir, PhysicsQueryHit& hit,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a sphere and returns the closest found hit, if any.
+		 * 
+		 * @param[in]	sphere		Sphere to sweep through the scene.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool sphereCast(const Sphere& sphere, const Vector3& unitDir, PhysicsQueryHit& hit,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a capsule and returns the closest found hit, if any.
+		 * 
+		 * @param[in]	capsule		Capsule to sweep through the scene.
+		 * @param[in]	rotation	Orientation of the capsule.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool capsuleCast(const Capsule& capsule, const Quaternion& rotation, const Vector3& unitDir,
+			PhysicsQueryHit& hit, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a convex mesh and returns the closest found hit, if any.
+		 * 
+		 * @param[in]	mesh		Mesh to sweep through the scene. Must be convex.
+		 * @param[in]	position	Starting position of the mesh.
+		 * @param[in]	rotation	Orientation of the mesh.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[out]	hit			Information recorded about a hit. Only valid if method returns true.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool convexCast(const HPhysicsMesh& mesh, const Vector3& position, const Quaternion& rotation,
+			const Vector3& unitDir, PhysicsQueryHit& hit, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Casts a ray into the scene and returns all found hits.
+		 * 
+		 * @param[in]	ray		Ray to cast into the scene.
+		 * @param[in]	layer	Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max		Maximum distance at which to perform the query. Hits past this distance will not be
+		 *						detected.
+		 * @return				List of all detected hits.
+		 */
+		virtual Vector<PhysicsQueryHit> rayCastAll(const Ray& ray, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const;
+
+		/**
+		 * Casts a ray into the scene and returns all found hits.
+		 * 
+		 * @param[in]	origin		Origin of the ray to cast into the scene.
+		 * @param[in]	unitDir		Unit direction of the ray to cast into the scene.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					List of all detected hits.
+		 */
+		virtual Vector<PhysicsQueryHit> rayCastAll(const Vector3& origin, const Vector3& unitDir,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a box and returns all found hits.
+		 * 
+		 * @param[in]	box			Box to sweep through the scene.
+		 * @param[in]	rotation	Orientation of the box.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					List of all detected hits.
+		 */
+		virtual Vector<PhysicsQueryHit> boxCastAll(const AABox& box, const Quaternion& rotation, 
+			const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a sphere and returns all found hits.
+		 * 
+		 * @param[in]	sphere		Sphere to sweep through the scene.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					List of all detected hits.
+		 */
+		virtual Vector<PhysicsQueryHit> sphereCastAll(const Sphere& sphere, const Vector3& unitDir,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a capsule and returns all found hits.
+		 * 
+		 * @param[in]	capsule		Capsule to sweep through the scene.
+		 * @param[in]	rotation	Orientation of the capsule.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					List of all detected hits.
+		 */
+		virtual Vector<PhysicsQueryHit> capsuleCastAll(const Capsule& capsule, const Quaternion& rotation, 
+			const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a convex mesh and returns all found hits.
+		 * 
+		 * @param[in]	mesh		Mesh to sweep through the scene. Must be convex.
+		 * @param[in]	position	Starting position of the mesh.
+		 * @param[in]	rotation	Orientation of the mesh.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					List of all detected hits.
+		 */
+		virtual Vector<PhysicsQueryHit> convexCastAll(const HPhysicsMesh& mesh, const Vector3& position, 
+			const Quaternion& rotation, const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Casts a ray into the scene and checks if it has hit anything. This can be significantly more efficient than other
+		 * types of cast* calls.
+		 * 
+		 * @param[in]	ray		Ray to cast into the scene.
+		 * @param[in]	layer	Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max		Maximum distance at which to perform the query. Hits past this distance will not be
+		 *						detected.
+		 * @return				True if something was hit, false otherwise.
+		 */
+		virtual bool rayCastAny(const Ray& ray, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const;
+
+		/**
+		 * Casts a ray into the scene and checks if it has hit anything. This can be significantly more efficient than other
+		 * types of cast* calls.
+		 * 
+		 * @param[in]	origin		Origin of the ray to cast into the scene.
+		 * @param[in]	unitDir		Unit direction of the ray to cast into the scene.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool rayCastAny(const Vector3& origin, const Vector3& unitDir,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a box and checks if it has hit anything. This can be significantly more
+		 * efficient than other types of cast* calls.
+		 * 
+		 * @param[in]	box			Box to sweep through the scene.
+		 * @param[in]	rotation	Orientation of the box.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool boxCastAny(const AABox& box, const Quaternion& rotation, const Vector3& unitDir,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a sphere and checks if it has hit anything. This can be significantly more
+		 * efficient than other types of cast* calls.
+		 * 
+		 * @param[in]	sphere		Sphere to sweep through the scene.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool sphereCastAny(const Sphere& sphere, const Vector3& unitDir,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a capsule and checks if it has hit anything. This can be significantly more
+		 * efficient than other types of cast* calls.
+		 * 
+		 * @param[in]	capsule		Capsule to sweep through the scene.
+		 * @param[in]	rotation	Orientation of the capsule.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool capsuleCastAny(const Capsule& capsule, const Quaternion& rotation, const Vector3& unitDir,
+			UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Performs a sweep into the scene using a convex mesh and checks if it has hit anything. This can be significantly
+		 * more efficient than other types of cast* calls.
+		 * 
+		 * @param[in]	mesh		Mesh to sweep through the scene. Must be convex.
+		 * @param[in]	position	Starting position of the mesh.
+		 * @param[in]	rotation	Orientation of the mesh.
+		 * @param[in]	unitDir		Unit direction towards which to perform the sweep.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @param[in]	max			Maximum distance at which to perform the query. Hits past this distance will not be
+		 *							detected.
+		 * @return					True if something was hit, false otherwise.
+		 */
+		virtual bool convexCastAny(const HPhysicsMesh& mesh, const Vector3& position, const Quaternion& rotation,
+			const Vector3& unitDir, UINT64 layer = BS_ALL_LAYERS, float max = FLT_MAX) const = 0;
+
+		/**
+		 * Returns a list of all colliders in the scene that overlap the provided box.
+		 * 
+		 * @param[in]	box			Box to check for overlap.
+		 * @param[in]	rotation	Orientation of the box.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					List of all colliders that overlap the box.
+		 */
+		virtual Vector<HCollider> boxOverlap(const AABox& box, const Quaternion& rotation, 
+			UINT64 layer = BS_ALL_LAYERS) const;
+
+		/**
+		 * Returns a list of all colliders in the scene that overlap the provided sphere.
+		 * 
+		 * @param[in]	Sphere		Sphere to check for overlap.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					List of all colliders that overlap the sphere.
+		 */
+		virtual Vector<HCollider> sphereOverlap(const Sphere& sphere, UINT64 layer = BS_ALL_LAYERS) const;
+
+		/**
+		 * Returns a list of all colliders in the scene that overlap the provided capsule.
+		 * 
+		 * @param[in]	capsule		Capsule to check for overlap.
+		 * @param[in]	rotation	Orientation of the capsule.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					List of all colliders that overlap the capsule.
+		 */
+		virtual Vector<HCollider> capsuleOverlap(const Capsule& capsule, const Quaternion& rotation,
+			UINT64 layer = BS_ALL_LAYERS) const;
+
+		/**
+		 * Returns a list of all colliders in the scene that overlap the provided convex mesh.
+		 * 
+		 * @param[in]	mesh		Mesh to check for overlap. Must be convex.
+		 * @param[in]	position	Position of the mesh.
+		 * @param[in]	rotation	Orientation of the mesh.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					List of all colliders that overlap the mesh.
+		 */
+		virtual Vector<HCollider> convexOverlap(const HPhysicsMesh& mesh, const Vector3& position, 
+			const Quaternion& rotation, UINT64 layer = BS_ALL_LAYERS) const;
+
+		/**
+		 * Checks if the provided box overlaps any other collider in the scene.
+		 * 
+		 * @param[in]	box			Box to check for overlap.
+		 * @param[in]	rotation	Orientation of the box.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					True if there is overlap with another object, false otherwise.
+		 */
+		virtual bool boxOverlapAny(const AABox& box, const Quaternion& rotation, UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/**
+		 * Checks if the provided sphere overlaps any other collider in the scene.
+		 * 
+		 * @param[in]	sphere		Sphere to check for overlap.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					True if there is overlap with another object, false otherwise.
+		 */
+		virtual bool sphereOverlapAny(const Sphere& sphere, UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/**
+		 * Checks if the provided capsule overlaps any other collider in the scene.
+		 * 
+		 * @param[in]	capsule		Capsule to check for overlap.
+		 * @param[in]	rotation	Orientation of the capsule.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					True if there is overlap with another object, false otherwise.
+		 */
+		virtual bool capsuleOverlapAny(const Capsule& capsule, const Quaternion& rotation, 
+			UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/**
+		 * Checks if the provided convex mesh overlaps any other collider in the scene.
+		 * 
+		 * @param[in]	mesh		Mesh to check for overlap. Must be convex.
+		 * @param[in]	position	Position of the mesh.
+		 * @param[in]	rotation	Orientation of the mesh.
+		 * @param[in]	layer		Layers to consider for the query. This allows you to ignore certain groups of objects.
+		 * @return					True if there is overlap with another object, false otherwise.
+		 */
+		virtual bool convexOverlapAny(const HPhysicsMesh& mesh, const Vector3& position, const Quaternion& rotation,
+			UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/******************************************************************************************************************/
+		/************************************************* OPTIONS ********************************************************/
+		/******************************************************************************************************************/
+
+		/** Checks is a specific physics option enabled. */
+		virtual bool hasFlag(PhysicsFlags flag) const { return mFlags & flag; }
+
+		/** Enables or disabled a specific physics option. */
+		virtual void setFlag(PhysicsFlags flag, bool enabled) { if (enabled) mFlags |= flag; else mFlags &= ~flag; }
+
+		/** Gets the global gravity value for all objects in the scene. */
+		virtual Vector3 getGravity() const = 0;
+
+		/** Sets the global gravity value for all objects in the scene. */
+		virtual void setGravity(const Vector3& gravity) = 0;
+
+		/** 
+		 * Adds a new physics region. Certain physics options require you to set up regions in which physics objects are
+		 * allowed to be in, and objects outside of these regions will not be handled by physics. You do not need to set
+		 * up these regions by default.
+		 */
+		virtual UINT32 addBroadPhaseRegion(const AABox& region) = 0;
+
+		/** Removes a physics region. */
+		virtual void removeBroadPhaseRegion(UINT32 handle) = 0;
+
+		/** Removes all physics regions. */
+		virtual void clearBroadPhaseRegions() = 0;
+
+		/** 
+		 * Returns a maximum edge length before a triangle is tesselated. 
+		 *
+		 * @see PhysicsFlags::CCT_Tesselation
+		 */
+		virtual float getMaxTesselationEdgeLength() const = 0;
+
+		/** 
+		 * Sets a maximum edge length before a triangle is tesselated. 
+		 *
+		 * @see PhysicsFlags::CCT_Tesselation
+		 */
+		virtual void setMaxTesselationEdgeLength(float length) = 0;
+
+		/** 
+		 * Enables or disables collision between two layers. Each physics object can be assigned a specific layer, and here
+		 * you can determine which layers can interact with each other.
+		 */
+		void toggleCollision(UINT64 groupA, UINT64 groupB, bool enabled);
+
+		/** Checks if two collision layers are allowed to interact. */
+		bool isCollisionEnabled(UINT64 groupA, UINT64 groupB) const;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/******************************************************************************************************************/
+		/************************************************* CREATION *******************************************************/
+		/******************************************************************************************************************/
+
+		/** @copydoc PhysicsMaterial::create */
+		virtual SPtr<PhysicsMaterial> createMaterial(float staticFriction, float dynamicFriction, float restitution) = 0;
+
+		/** @copydoc PhysicsMesh::create */
+		virtual SPtr<PhysicsMesh> createMesh(const MeshDataPtr& meshData, PhysicsMeshType type) = 0;
+
+		/** @copydoc Rigidbody::create */
+		virtual SPtr<Rigidbody> createRigidbody(const HSceneObject& linkedSO) = 0;
+
+		/** @copydoc BoxCollider::create */
+		virtual SPtr<BoxCollider> createBoxCollider(const Vector3& extents, const Vector3& position,
+			const Quaternion& rotation) = 0;
+
+		/** @copydoc SphereCollider::create */
+		virtual SPtr<SphereCollider> createSphereCollider(float radius,
+			const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** @copydoc PlaneCollider::create */
+		virtual SPtr<PlaneCollider> createPlaneCollider(const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** @copydoc CapsuleCollider::create */
+		virtual SPtr<CapsuleCollider> createCapsuleCollider(float radius, float halfHeight,
+			const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** @copydoc MeshCollider::create */
+		virtual SPtr<MeshCollider> createMeshCollider(const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** @copydoc FixedJoint::create */
+		virtual SPtr<FixedJoint> createFixedJoint() = 0;
+
+		/** @copydoc DistanceJoint::create */
+		virtual SPtr<DistanceJoint> createDistanceJoint() = 0;
+
+		/** @copydoc HingeJoint::create */
+		virtual SPtr<HingeJoint> createHingeJoint() = 0;
+
+		/** @copydoc SphericalJoint::create */
+		virtual SPtr<SphericalJoint> createSphericalJoint() = 0;
+
+		/** @copydoc SliderJoint::create */
+		virtual SPtr<SliderJoint> createSliderJoint() = 0;
+
+		/** @copydoc D6Joint::create */
+		virtual SPtr<D6Joint> createD6Joint() = 0;
+
+		/** @copydoc CharacterController::create */
+		virtual SPtr<CharacterController> createCharacterController(const CHAR_CONTROLLER_DESC& desc) = 0;
+
+		/** Triggers physics simulation update as needed. Should be called once per frame. */
+		virtual void update() = 0;
+
+		/** @copydoc Physics::boxOverlap() */
+		virtual Vector<Collider*> _boxOverlap(const AABox& box, const Quaternion& rotation,
+			UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/** @copydoc Physics::sphereOverlap() */
+		virtual Vector<Collider*> _sphereOverlap(const Sphere& sphere, UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/** @copydoc Physics::capsuleOverlap() */
+		virtual Vector<Collider*> _capsuleOverlap(const Capsule& capsule, const Quaternion& rotation,
+			UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/** @copydoc Physics::convexOverlap() */
+		virtual Vector<Collider*> _convexOverlap(const HPhysicsMesh& mesh, const Vector3& position,
+			const Quaternion& rotation, UINT64 layer = BS_ALL_LAYERS) const = 0;
+
+		/** 
+		 * Checks does the ray hit the provided collider. 
+		 *
+		 * @param[in]	origin		Origin of the ray to check.
+		 * @param[in]	unitDir		Unit direction of the ray to check.
+		 * @param[in]	collider	Collider to check for hit.
+		 * @param[out]	hit			Information about the hit. Valid only if the method returns true.
+		 * @param[in]	maxDist		Maximum distance from the ray origin to search for hits.
+		 * @return					True if the ray has hit the collider.
+		 */
+		virtual bool _rayCast(const Vector3& origin, const Vector3& unitDir, const Collider& collider, PhysicsQueryHit& hit, 
+			float maxDist = FLT_MAX) const = 0;
+
+		/** Checks is the physics simulation update currently in progress. */
+		bool _isUpdateInProgress() const { return mUpdateInProgress; }
+
+		/** @} */
+
+		static const UINT64 CollisionMapSize = 64;
+	protected:
+		friend class Rigidbody;
+
+		/** 
+		 * Registers a new rigidbody. Should be called whenever a new rigidbody is created. 
+		 * 
+		 * @param[in]	body		Newly created rigidbody.
+		 * @param[in]	priority	Priority that determines in what order is the physics simulation update applied to
+		 *							rigidbodes. Higher priority means it is applied before lower priority.
+		 */
+		void registerRigidbody(Rigidbody* body, UINT32 priority);
+
+		/** 
+		 * Unregisters a rigidbody. Should be called before a rigidbody is destroyed.
+		 *
+		 * @param[in]	id			ID of the rigidbody to remove.
+		 * @param[in]	priority	Original priority of the rigidbody.
+		 */
+		void unregisterRigidbody(UINT32 id, UINT32 priority);
+
+		/** Changes the priority of a rigidbody. */
+		void updatePriority(UINT32 id, UINT32 oldPriority, UINT32 newPriority);
+
+		mutable Mutex mMutex;
+		bool mCollisionMap[CollisionMapSize][CollisionMapSize];
+
+		bool mUpdateInProgress = false;
+		PhysicsFlags mFlags;
+		Vector<Vector<Rigidbody*>> mRigidbodies; // TODO: Unused for now, but keeping it here just in case I change the design. Remove later.
+
+		const static UINT32 MAX_PRIORITY = 128;
+	};
+
+	/** Provides easier access to Physics. */
+	BS_CORE_EXPORT Physics& gPhysics();
+
+	/** Contains parameters used for initializing the physics system. */
+	struct PHYSICS_INIT_DESC
+	{
+		float typicalLength = 1.0f; /**< Typical length of an object in the scene. */
+		float typicalSpeed = 9.81f; /**< Typical speed of an object in the scene. */
+		Vector3 gravity = Vector3(0.0f, -9.81f, 0.0f); /**< Initial gravity. */
+		bool initCooking = true; /**< Determines should the cooking library be initialized. */
+		float timeStep = 1.0f / 60.0f; /**< Determines using what interval should the physics update happen. */
+		/** Flags that control global physics option. */
+		PhysicsFlags flags = PhysicsFlag::CCT_OverlapRecovery | PhysicsFlag::CCT_PreciseSweeps | PhysicsFlag::CCD_Enable;
+	};
+
+	/** @} */
 }

+ 86 - 84
Source/BansheeCore/Include/BsPhysicsMaterial.h

@@ -1,85 +1,87 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsResource.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** Physics material that controls how objects react when they collide. */
-	class BS_CORE_EXPORT PhysicsMaterial : public Resource
-	{
-	public:
-		virtual ~PhysicsMaterial() { }
-
-		/** 
-		  * Sets static friction of the material. Controls friction when two in-contact objects are not moving lateral to
-		  * each other (e.g. how difficult is to get an object moving from a static state while it is in contact other
-		  * object(s)).
-		  */
-		virtual void setStaticFriction(float value) = 0;
-
-		/** Gets static friction of the material. */
-		virtual float getStaticFriction() const = 0;
-
-		/**
-		 * Sets dynamic friction of the material. Controls friction when two in-contact objects are moving lateral to each
-		 * other (e.g. how quickly does an object slow down when sliding along another object).
-		 */
-		virtual void setDynamicFriction(float value) = 0;
-
-		/** Gets dynamic friction of the material .*/
-		virtual float getDynamicFriction() const = 0;
-
-		/** 
-		 * Sets restitution coefficient of the material. Controls "bounciness" of an object during a collision. Value of 1
-		 * means the collision is elastic, and value of 0 means the value is inelastic. Must be in [0, 1] range.
-		 */
-		virtual void setRestitutionCoefficient(float value) = 0;
-
-		/** Gets restitution coefficient of the material. */
-		virtual float getRestitutionCoefficient() const = 0;
-
-		/** 
-		 * Creates a new physics material. 
-		 *
-		 * @param[in]	staticFriction	Controls friction when two in-contact objects are not moving lateral to each other
-		 *								(e.g. how difficult is to get an object moving from a static state while it is in
-		 *								contact other object(s)).
-		 * @param[in]	dynamicFriction	Sets dynamic friction of the material. Controls friction when two in-contact objects
-		 *								are moving lateral to each other (e.g. how quickly does an object slow down when
-		 *								sliding along another object).
-		 * @param[in]	restitution		Controls "bounciness" of an object during a collision. Value of 1 means the
-		 *								collision is elastic, and value of 0 means the value is inelastic. Must be in
-		 *								[0, 1] range.
-		 */
-		static HPhysicsMaterial create(float staticFriction = 0.0f, float dynamicFriction = 0.0f, float restitution = 0.0f);
-
-		/** @cond INTERNAL */
-
-		/** 
-		 * @copydoc create()
-		 *
-		 * For internal use. Requires manual initialization after creation.
-		 */
-		static PhysicsMaterialPtr _createPtr(float staticFriction = 0.0f, float dynamicFriction = 0.0f, 
-			float restitution = 0.0f);
-
-		/** @endcond */
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class PhysicsMaterialRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsResource.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/** Physics material that controls how objects react when they collide. */
+	class BS_CORE_EXPORT PhysicsMaterial : public Resource
+	{
+	public:
+		virtual ~PhysicsMaterial() { }
+
+		/** 
+		  * Sets static friction of the material. Controls friction when two in-contact objects are not moving lateral to
+		  * each other (for example how difficult is to get an object moving from a static state while it is in contact 
+		  * other object(s)).
+		  */
+		virtual void setStaticFriction(float value) = 0;
+
+		/** Gets static friction of the material. */
+		virtual float getStaticFriction() const = 0;
+
+		/**
+		 * Sets dynamic friction of the material. Controls friction when two in-contact objects are moving lateral to each
+		 * other (for example how quickly does an object slow down when sliding along another object).
+		 */
+		virtual void setDynamicFriction(float value) = 0;
+
+		/** Gets dynamic friction of the material .*/
+		virtual float getDynamicFriction() const = 0;
+
+		/** 
+		 * Sets restitution coefficient of the material. Controls "bounciness" of an object during a collision. Value of 1
+		 * means the collision is elastic, and value of 0 means the value is inelastic. Must be in [0, 1] range.
+		 */
+		virtual void setRestitutionCoefficient(float value) = 0;
+
+		/** Gets restitution coefficient of the material. */
+		virtual float getRestitutionCoefficient() const = 0;
+
+		/** 
+		 * Creates a new physics material. 
+		 *
+		 * @param[in]	staticFriction	Controls friction when two in-contact objects are not moving lateral to each other
+		 *								(for example how difficult is to get an object moving from a static state while it
+		 *								is in contact other object(s)).
+		 * @param[in]	dynamicFriction	Sets dynamic friction of the material. Controls friction when two in-contact objects
+		 *								are moving lateral to each other (for example how quickly does an object slow down
+		 *								when sliding along another object).
+		 * @param[in]	restitution		Controls "bounciness" of an object during a collision. Value of 1 means the
+		 *								collision is elastic, and value of 0 means the value is inelastic. Must be in
+		 *								[0, 1] range.
+		 */
+		static HPhysicsMaterial create(float staticFriction = 0.0f, float dynamicFriction = 0.0f, float restitution = 0.0f);
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** 
+		 * @copydoc create()
+		 *
+		 * For internal use. Requires manual initialization after creation.
+		 */
+		static PhysicsMaterialPtr _createPtr(float staticFriction = 0.0f, float dynamicFriction = 0.0f, 
+			float restitution = 0.0f);
+
+		/** @} */
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class PhysicsMaterialRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 4 - 2
Source/BansheeCore/Include/BsPhysicsMesh.h

@@ -38,7 +38,9 @@ namespace BansheeEngine
 		 */
 		static HPhysicsMesh create(const MeshDataPtr& meshData, PhysicsMeshType type = PhysicsMeshType::Convex);
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/** Returns the internal implementation of the physics mesh. */
 		virtual FPhysicsMesh* _getInternal() { return mInternal.get(); }
@@ -50,7 +52,7 @@ namespace BansheeEngine
 		 */
 		static PhysicsMeshPtr _createPtr(const MeshDataPtr& meshData, PhysicsMeshType type);
 
-		/** @endcond */
+		/** @} */
 
 	protected:
 		/** @copydoc Resource::initialize() */

+ 382 - 380
Source/BansheeCore/Include/BsPixelData.h

@@ -1,381 +1,383 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPixelVolume.h"
-#include "BsGpuResourceData.h"
-#include "BsIReflectable.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Resources
-	 *  @{
-	 */
-
-	/** Pixel formats usable by images, textures and render surfaces. */
-    enum PixelFormat
-    {
-        /** Unknown pixel format. */
-        PF_UNKNOWN = 0,
-        /** 8-bit pixel format, all bits red. */
-        PF_R8 = 1,
-		/** 2 byte pixel format, 1 byte red, 1 byte green. */
-		PF_R8G8 = 2,
-        /** 24-bit pixel format, 8 bits for red, green and blue. */
-        PF_R8G8B8 = 3,
-        /** 24-bit pixel format, 8 bits for blue, green and red. */
-        PF_B8G8R8 = 4,
-        /** 32-bit pixel format, 8 bits for alpha, red, green and blue. */
-        PF_A8R8G8B8 = 5,
-        /** 32-bit pixel format, 8 bits for blue, green, red and alpha. */
-        PF_A8B8G8R8 = 6,
-        /** 32-bit pixel format, 8 bits for blue, green, red and alpha. */
-        PF_B8G8R8A8 = 7,
-		/** 32-bit pixel format, 8 bits for red, green, blue and alpha. */
-		PF_R8G8B8A8 = 8,
-        /** 
-		 * 32-bit pixel format, 8 bits for red, 8 bits for green, 8 bits for blue. Like PF_A8R8G8B8, but alpha will get 
-		 * discarded.
-		 */
-        PF_X8R8G8B8 = 9,
-        /** 
-		 * 32-bit pixel format, 8 bits for blue, 8 bits for green, 8 bits for red. Like PF_A8B8G8R8, but alpha will get 
-		 * discarded.
-		 */
-        PF_X8B8G8R8 = 10,
-		/** 
-		 * 32-bit pixel format, 8 bits for red, 8 bits for green, 8 bits for blue. Like PF_R8G8B8A8, but alpha will get 
-		 * discarded. 
-		 */
-		PF_R8G8B8X8 = 11,
-		/** 32-bit pixel format, 8 bits for blue, 8 bits for green, 8 bits for red. */
-		/** Like PF_B8G8R8A8, but alpha will get discarded. */
-		PF_B8G8R8X8 = 12,
-		/** 24-bit pixel format, 8 bits for red, green and blue. */
-		PF_BYTE_RGB = PF_R8G8B8,
-		/** 24-bit pixel format, 8 bits for blue, green and red. */
-		PF_BYTE_BGR = PF_B8G8R8,
-		/** 32-bit pixel format, 8 bits for blue, green, red and alpha. */
-		PF_BYTE_BGRA = PF_B8G8R8A8,
-		/** 32-bit pixel format, 8 bits for red, green, blue and alpha. */
-		PF_BYTE_RGBA = PF_R8G8B8A8,      
-        /** DXT1/BC1 format containing opaque RGB or 1-bit alpha RGB. 4 bits per pixel. */
-        PF_BC1 = 13,
-		/** DXT3/BC2 format containing RGB with premultiplied alpha. 4 bits per pixel. */
-		PF_BC1a = 14,
-        /** DXT3/BC2 format containing RGB with explicit alpha. 8 bits per pixel. */
-        PF_BC2 = 15,
-        /** DXT5/BC2 format containing RGB with explicit alpha. 8 bits per pixel. Better alpha gradients than BC2. */
-        PF_BC3 = 16,
-		/** One channel compressed format. 4 bits per pixel. */
-		PF_BC4 = 17,
-		/** Two channel compressed format. 8 bits per pixel. */
-		PF_BC5 = 18,
-		/** Format storing RGB in half (16-bit) floating point format usable for HDR. 8 bits per pixel. */
-		PF_BC6H = 19,
-		/** 
-		 * Format storing RGB with optional alpha channel. Similar to BC1/BC2/BC3 formats but with higher quality and 
-		 * higher decompress overhead. 8 bits per pixel. 
-		 */
-		PF_BC7 = 20,
-		/** 16-bit pixel format, 16 bits (float) for red. */
-        PF_FLOAT16_R = 21,
-		/** 32-bit, 2-channel s10e5 floating point pixel format, 16-bit red, 16-bit green. */
-		PF_FLOAT16_RG = 22,
-        /** 48-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue. */
-        PF_FLOAT16_RGB = 23,
-        /** 
-		 * 64-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue, 16 bits 
-		 * (float) for alpha. 
-		 */
-        PF_FLOAT16_RGBA = 24,
-		/** 32-bit pixel format, 32 bits (float) for red. */
-        PF_FLOAT32_R = 25,
-		/** 64-bit, 2-channel floating point pixel format, 32-bit red, 32-bit green. */
-		PF_FLOAT32_RG = 26,
-        /** 96-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue. */
-        PF_FLOAT32_RGB = 27,
-        /** 
-		 * 128-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue, 32 bits 
-		 * (float) for alpha. 
-		 */
-        PF_FLOAT32_RGBA = 28,
-		/** Depth stencil format, 32bit depth, 8bit stencil + 24 unused. */
-		PF_D32_S8X24 = 29,
-		/** Depth stencil fomrat, 24bit depth + 8bit stencil. */
-		PF_D24S8 = 30,
-		/** Depth format, 32bits. */
-		PF_D32 = 31,
-		/** Depth format, 16bits. */
-		PF_D16 = 32,
-		/** 
-		 * 32-bit float format, 11 bits (float) for red, 11 bits (float) for green, 10 bits (float) for blue. Framebuffer 
-		 * only format, not for CPU use. 
-		 */
-		PF_FLOAT_R11G11B10 = 33,
-		/** 
-		 * 32-bit unsigned normalized format, 10 bits (float) for red, 10 bits (float) for green, 10 bits (float) for blue, 
-		 * and two bits for alpha. Framebuffer only format, not for CPU use.
-		 */
-		PF_UNORM_R10G10B10A2 = 34,
-		/** Number of pixel formats currently defined. */
-        PF_COUNT = 35
-    };
-	typedef Vector<PixelFormat> PixelFormatList;
-
-	/**	Flags defining some properties of pixel formats. */
-    enum PixelFormatFlags {
-        /** This format has an alpha channel. */
-        PFF_HASALPHA = 0x00000001,      
-        /**
-		 * This format is compressed. This invalidates the values in elemBytes, elemBits and the bit counts as these might
-		 * not be fixed in a compressed format.
-		 */
-        PFF_COMPRESSED = 0x00000002,
-        /** This is a floating point format. */
-        PFF_FLOAT = 0x00000004,         
-        /** This is a depth format (for depth textures). */
-        PFF_DEPTH = 0x00000008,
-        /** 
-		 * Format is in native endian. Generally true for the 16, 24 and 32 bits formats which can be represented as 
-		 * machine integers.
-		 */
-        PFF_NATIVEENDIAN = 0x00000010
-    };
-    
-	/**	Types used for individual components of a pixel. */
-    enum PixelComponentType
-    {
-        PCT_BYTE = 0,    /**< Byte per component */
-        PCT_SHORT = 1,   /**< Short per component */
-        PCT_FLOAT16 = 2, /**< 16 bit float per component */
-        PCT_FLOAT32 = 3, /**< 32 bit float per component */
-		PCT_PACKED_R11G11B10 = 4, /**< 11 bits for first two components, 10 for third component. */
-		PCT_PACKED_R10G10B10A2 = 5, /**< 10 bits for first three components, 2 bits for last component */
-        PCT_COUNT = 4    /**< Number of pixel types */
-    };
-    
-	/**
-	 * A buffer describing a volume (3D), image (2D) or line (1D) of pixels in memory. Pixels are stored as a succession 
-	 * of "depth" slices, each containing "height" rows of "width" pixels.
-	 *
-	 * As any GpuResourceData this is used primarily for reading and writing from/to a GPU resource, and is normally 
-	 * constructed by the resource itself. However you may still construct it manually and use it for other purposes if 
-	 * needed.
-	 *
-	 * @note	
-	 * You must call allocateInternalBuffer or set the buffer in some other way before reading/writing from this object.
-	 *
-	 * @see		GpuResourceData
-	 */
-    class BS_CORE_EXPORT PixelData : public GpuResourceData
-	{
-    public:
-    	PixelData() {}
-		~PixelData() {}
-
-		/**
-		 * Constructs a new object with an internal buffer capable of holding "extents" volume of pixels, where each pixel 
-		 * is of the specified pixel format. Extent offsets are also stored, but are not used internally.
-		 */
-		PixelData(const PixelVolume& extents, PixelFormat pixelFormat)
-			:mExtents(extents), mFormat(pixelFormat)
-		{
-			setConsecutive();
-		}
-
-		/**
-		 * Constructs a new object with an internal buffer capable of holding volume of pixels described by	provided width, 
-		 * height and depth, where each pixel is of the specified pixel format.
-		 */
-    	PixelData(UINT32 width, UINT32 height, UINT32 depth, PixelFormat pixelFormat)
-			: mExtents(0, 0, 0, width, height, depth), mFormat(pixelFormat)
-    	{
-    		setConsecutive();
-    	}
-
-		PixelData(const PixelData& copy);
-		PixelData& operator=(const PixelData& rhs);
-
-		/**
-		 * Returns the number of pixels that offsets one row from another. This can be "width", but doesn't have to be as
-		 * some buffers require padding.
-		 */
-		UINT32 getRowPitch() const { return mRowPitch; }
-
-		/**
-		 * Returns the number of pixels that offsets one depth slice from another. This can be "width * height", but 
-		 * doesn't have to be as some buffers require padding.
-		 */
-		UINT32 getSlicePitch() const { return mSlicePitch; }
-
-		/**
-		 * Sets the pitch (in pixels) that determines offset between rows of the pixel buffer. Call this before allocating
-		 * the buffer.
-		 */
-		void setRowPitch(UINT32 rowPitch) { mRowPitch = rowPitch; }
-
-		/**
-		 * Sets the pitch (in pixels) that determines offset between depth slices of the pixel buffer. Call this before 
-		 * allocating the buffer.
-		 */
-        void setSlicePitch(UINT32 slicePitch) { mSlicePitch = slicePitch; }
-
-		/**
-		 * Returns the number of extra pixels in a row (non-zero only if rows are not consecutive (row pitch is larger 
-		 * than width)).
-		 */
-        UINT32 getRowSkip() const { return mRowPitch - getWidth(); }
-
-		/**
-		 * Returns the number of extra pixels in a depth slice (non-zero only if slices aren't consecutive (slice pitch is 
-		 * larger than width*height).
-		 */
-        UINT32 getSliceSkip() const { return mSlicePitch - (getHeight() * mRowPitch); }
-
-		/** Returns the pixel format used by the internal buffer for storing the pixels. */
-		PixelFormat getFormat() const { return mFormat; }
-
-		/**	Returns width of the buffer in pixels. */
-		UINT32 getWidth() const { return mExtents.getWidth(); }
-
-		/**	Returns height of the buffer in pixels. */
-		UINT32 getHeight() const { return mExtents.getHeight(); }
-
-		/**	Returns depth of the buffer in pixels. */
-		UINT32 getDepth() const { return mExtents.getDepth(); }
-
-		/**
-		 * Returns left-most start of the pixel volume. This value is not used internally in any way. It is just passed 
-		 * through from the constructor.
-		 */
-		UINT32 getLeft() const { return mExtents.left; }
-
-		/**
-		 * Returns right-most end of the pixel volume. This value is not used internally in any way. It is just passed 
-		 * through from the constructor.
-		 */
-		UINT32 getRight() const { return mExtents.right; }
-
-		/**
-		 * Returns top-most start of the pixel volume. This value is not used internally in any way. It is just passed 
-		 * through from the constructor.
-		 */
-		UINT32 getTop() const { return mExtents.top; }
-
-		/**
-		 * Returns bottom-most end of the pixel volume. This value is not used internally in any way. It is just passed 
-		 * through from the constructor.
-		 */
-		UINT32 getBottom() const { return mExtents.bottom; }
-
-		/**
-		 * Returns front-most start of the pixel volume. This value is not used internally in any way. It is just passed 
-		 * through from the constructor.
-		 */
-		UINT32 getFront() const { return mExtents.front; }
-
-		/**
-		 * Returns back-most end of the pixel volume. This value is not used internally in any way. It is just passed 
-		 * through from the constructor.
-		 */
-		UINT32 getBack() const { return mExtents.back; }
-
-		/** Returns extents of the pixel volume this object is capable of holding. */
-		PixelVolume getExtents() const { return mExtents; }
-
-		/** Return whether this buffer is laid out consecutive in memory (i.e. the pitches are equal to the dimensions). */
-        bool isConsecutive() const 
-		{ 
-			return mRowPitch == getWidth() && mSlicePitch == getWidth()*getHeight(); 
-		}
-
-		/** Return the size (in bytes) this image would take if it was laid out consecutive in memory. */
-      	UINT32 getConsecutiveSize() const;
-
-		/**	Return the size (in bytes) of the buffer this image requires. */
-      	UINT32 getSize() const;
-
-		/**
-		 * Returns pixel data containing a sub-volume of this object. Returned data will not have its own buffer, but will
-		 * instead point to this one. It is up to the caller to ensure this object outlives any sub-volume objects.
-		 */
-      	PixelData getSubVolume(const PixelVolume &def) const;
-        
-		/**	Returns pixel color at the specified coordinates. */
-		Color getColorAt(UINT32 x, UINT32 y, UINT32 z = 0) const;
-
-		/**	Sets the pixel color at the specified coordinates. */
-        void setColorAt(Color const &cv, UINT32 x, UINT32 y, UINT32 z = 0);
-
-		/**
-		 * Converts all the internal data into an array of colors. Array is mapped as such: 
-		 * arrayIdx = x + y * width + z * width * height.
-		 */
-		Vector<Color> getColors() const;
-
-		/**
-		 * Initializes the internal buffer with the provided set of colors. The array should be of width * height * depth 
-		 * size and mapped as such: arrayIdx = x + y * width + z * width * height.
-		 */
-		void setColors(const Vector<Color>& colors);
-
-		/**
-		 * Initializes the internal buffer with the provided set of colors. The array should be of 
-		 * width * height * depth size and mapped as such: arrayIdx = x + y * width + z * width * height.
-		 */
-		void setColors(Color* colors, UINT32 numElements);
-
-		/**
-		 * Constructs a new object with an internal buffer capable of holding "extents" volume of pixels, where each pixel
-		 * is of the specified pixel format. Extent offsets are also stored, but are not used internally.
-		 */
-		static PixelDataPtr create(const PixelVolume &extents, PixelFormat pixelFormat);
-
-		/**
-		 * Constructs a new object with an internal buffer capable of holding volume of pixels described by provided width,
-		 * height and depth, where each pixel is of the specified pixel format.
-		 */
-		static PixelDataPtr create(UINT32 width, UINT32 height, UINT32 depth, PixelFormat pixelFormat);
-
-	private:
-		/**
-		 * Set the rowPitch and slicePitch so that the buffer is laid out consecutive in memory. Does not actually modify
-		 * the buffer itself.
-		 */
-		void setConsecutive()
-		{
-			mRowPitch = getWidth();
-			mSlicePitch = getWidth()*getHeight();
-		}
-
-		/**
-		 * Initializes the internal buffer with the provided set of colors. The array should be of width * height * depth 
-		 * size and mapped as such: arrayIdx = x + y * width + z * width * height.
-		 *
-		 * @note	A generic method that is reused in other more specific setColors() calls.
-		 */
-		template<class T>
-		void setColorsInternal(const T& colors, UINT32 numElements);
-
-		/**	Returns the needed size of the internal buffer, in bytes. */
-		UINT32 getInternalBufferSize() const override;
-
-	private:
-		PixelVolume mExtents;
-        PixelFormat mFormat;
-        UINT32 mRowPitch;
-        UINT32 mSlicePitch;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class PixelDataRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-    };
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPixelVolume.h"
+#include "BsGpuResourceData.h"
+#include "BsIReflectable.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Resources
+	 *  @{
+	 */
+
+	/** Pixel formats usable by images, textures and render surfaces. */
+    enum PixelFormat
+    {
+        /** Unknown pixel format. */
+        PF_UNKNOWN = 0,
+        /** 8-bit pixel format, all bits red. */
+        PF_R8 = 1,
+		/** 2 byte pixel format, 1 byte red, 1 byte green. */
+		PF_R8G8 = 2,
+        /** 24-bit pixel format, 8 bits for red, green and blue. */
+        PF_R8G8B8 = 3,
+        /** 24-bit pixel format, 8 bits for blue, green and red. */
+        PF_B8G8R8 = 4,
+        /** 32-bit pixel format, 8 bits for alpha, red, green and blue. */
+        PF_A8R8G8B8 = 5,
+        /** 32-bit pixel format, 8 bits for blue, green, red and alpha. */
+        PF_A8B8G8R8 = 6,
+        /** 32-bit pixel format, 8 bits for blue, green, red and alpha. */
+        PF_B8G8R8A8 = 7,
+		/** 32-bit pixel format, 8 bits for red, green, blue and alpha. */
+		PF_R8G8B8A8 = 8,
+        /** 
+		 * 32-bit pixel format, 8 bits for red, 8 bits for green, 8 bits for blue. Like PF_A8R8G8B8, but alpha will get 
+		 * discarded.
+		 */
+        PF_X8R8G8B8 = 9,
+        /** 
+		 * 32-bit pixel format, 8 bits for blue, 8 bits for green, 8 bits for red. Like PF_A8B8G8R8, but alpha will get 
+		 * discarded.
+		 */
+        PF_X8B8G8R8 = 10,
+		/** 
+		 * 32-bit pixel format, 8 bits for red, 8 bits for green, 8 bits for blue. Like PF_R8G8B8A8, but alpha will get 
+		 * discarded. 
+		 */
+		PF_R8G8B8X8 = 11,
+		/** 32-bit pixel format, 8 bits for blue, 8 bits for green, 8 bits for red. */
+		/** Like PF_B8G8R8A8, but alpha will get discarded. */
+		PF_B8G8R8X8 = 12,
+		/** 24-bit pixel format, 8 bits for red, green and blue. */
+		PF_BYTE_RGB = PF_R8G8B8,
+		/** 24-bit pixel format, 8 bits for blue, green and red. */
+		PF_BYTE_BGR = PF_B8G8R8,
+		/** 32-bit pixel format, 8 bits for blue, green, red and alpha. */
+		PF_BYTE_BGRA = PF_B8G8R8A8,
+		/** 32-bit pixel format, 8 bits for red, green, blue and alpha. */
+		PF_BYTE_RGBA = PF_R8G8B8A8,      
+        /** DXT1/BC1 format containing opaque RGB or 1-bit alpha RGB. 4 bits per pixel. */
+        PF_BC1 = 13,
+		/** DXT3/BC2 format containing RGB with premultiplied alpha. 4 bits per pixel. */
+		PF_BC1a = 14,
+        /** DXT3/BC2 format containing RGB with explicit alpha. 8 bits per pixel. */
+        PF_BC2 = 15,
+        /** DXT5/BC2 format containing RGB with explicit alpha. 8 bits per pixel. Better alpha gradients than BC2. */
+        PF_BC3 = 16,
+		/** One channel compressed format. 4 bits per pixel. */
+		PF_BC4 = 17,
+		/** Two channel compressed format. 8 bits per pixel. */
+		PF_BC5 = 18,
+		/** Format storing RGB in half (16-bit) floating point format usable for HDR. 8 bits per pixel. */
+		PF_BC6H = 19,
+		/** 
+		 * Format storing RGB with optional alpha channel. Similar to BC1/BC2/BC3 formats but with higher quality and 
+		 * higher decompress overhead. 8 bits per pixel. 
+		 */
+		PF_BC7 = 20,
+		/** 16-bit pixel format, 16 bits (float) for red. */
+        PF_FLOAT16_R = 21,
+		/** 32-bit, 2-channel s10e5 floating point pixel format, 16-bit red, 16-bit green. */
+		PF_FLOAT16_RG = 22,
+        /** 48-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue. */
+        PF_FLOAT16_RGB = 23,
+        /** 
+		 * 64-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue, 16 bits 
+		 * (float) for alpha. 
+		 */
+        PF_FLOAT16_RGBA = 24,
+		/** 32-bit pixel format, 32 bits (float) for red. */
+        PF_FLOAT32_R = 25,
+		/** 64-bit, 2-channel floating point pixel format, 32-bit red, 32-bit green. */
+		PF_FLOAT32_RG = 26,
+        /** 96-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue. */
+        PF_FLOAT32_RGB = 27,
+        /** 
+		 * 128-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue, 32 bits 
+		 * (float) for alpha. 
+		 */
+        PF_FLOAT32_RGBA = 28,
+		/** Depth stencil format, 32bit depth, 8bit stencil + 24 unused. */
+		PF_D32_S8X24 = 29,
+		/** Depth stencil fomrat, 24bit depth + 8bit stencil. */
+		PF_D24S8 = 30,
+		/** Depth format, 32bits. */
+		PF_D32 = 31,
+		/** Depth format, 16bits. */
+		PF_D16 = 32,
+		/** 
+		 * 32-bit float format, 11 bits (float) for red, 11 bits (float) for green, 10 bits (float) for blue. Framebuffer 
+		 * only format, not for CPU use. 
+		 */
+		PF_FLOAT_R11G11B10 = 33,
+		/** 
+		 * 32-bit unsigned normalized format, 10 bits (float) for red, 10 bits (float) for green, 10 bits (float) for blue, 
+		 * and two bits for alpha. Framebuffer only format, not for CPU use.
+		 */
+		PF_UNORM_R10G10B10A2 = 34,
+		/** Number of pixel formats currently defined. */
+        PF_COUNT = 35
+    };
+	typedef Vector<PixelFormat> PixelFormatList;
+
+	/**	Flags defining some properties of pixel formats. */
+    enum PixelFormatFlags {
+        /** This format has an alpha channel. */
+        PFF_HASALPHA = 0x00000001,      
+        /**
+		 * This format is compressed. This invalidates the values in elemBytes, elemBits and the bit counts as these might
+		 * not be fixed in a compressed format.
+		 */
+        PFF_COMPRESSED = 0x00000002,
+        /** This is a floating point format. */
+        PFF_FLOAT = 0x00000004,         
+        /** This is a depth format (for depth textures). */
+        PFF_DEPTH = 0x00000008,
+        /** 
+		 * Format is in native endian. Generally true for the 16, 24 and 32 bits formats which can be represented as 
+		 * machine integers.
+		 */
+        PFF_NATIVEENDIAN = 0x00000010
+    };
+    
+	/**	Types used for individual components of a pixel. */
+    enum PixelComponentType
+    {
+        PCT_BYTE = 0,    /**< Byte per component */
+        PCT_SHORT = 1,   /**< Short per component */
+        PCT_FLOAT16 = 2, /**< 16 bit float per component */
+        PCT_FLOAT32 = 3, /**< 32 bit float per component */
+		PCT_PACKED_R11G11B10 = 4, /**< 11 bits for first two components, 10 for third component. */
+		PCT_PACKED_R10G10B10A2 = 5, /**< 10 bits for first three components, 2 bits for last component */
+        PCT_COUNT = 4    /**< Number of pixel types */
+    };
+    
+	/**
+	 * A buffer describing a volume (3D), image (2D) or line (1D) of pixels in memory. Pixels are stored as a succession 
+	 * of "depth" slices, each containing "height" rows of "width" pixels.
+	 *
+	 * As any GpuResourceData this is used primarily for reading and writing from/to a GPU resource, and is normally 
+	 * constructed by the resource itself. However you may still construct it manually and use it for other purposes if 
+	 * needed.
+	 *
+	 * @note	
+	 * You must call allocateInternalBuffer or set the buffer in some other way before reading/writing from this object.
+	 *
+	 * @see		GpuResourceData
+	 */
+    class BS_CORE_EXPORT PixelData : public GpuResourceData
+	{
+    public:
+    	PixelData() {}
+		~PixelData() {}
+
+		/**
+		 * Constructs a new object with an internal buffer capable of holding "extents" volume of pixels, where each pixel 
+		 * is of the specified pixel format. Extent offsets are also stored, but are not used internally.
+		 */
+		PixelData(const PixelVolume& extents, PixelFormat pixelFormat)
+			:mExtents(extents), mFormat(pixelFormat)
+		{
+			setConsecutive();
+		}
+
+		/**
+		 * Constructs a new object with an internal buffer capable of holding volume of pixels described by	provided width, 
+		 * height and depth, where each pixel is of the specified pixel format.
+		 */
+    	PixelData(UINT32 width, UINT32 height, UINT32 depth, PixelFormat pixelFormat)
+			: mExtents(0, 0, 0, width, height, depth), mFormat(pixelFormat)
+    	{
+    		setConsecutive();
+    	}
+
+		PixelData(const PixelData& copy);
+		PixelData& operator=(const PixelData& rhs);
+
+		/**
+		 * Returns the number of pixels that offsets one row from another. This can be "width", but doesn't have to be as
+		 * some buffers require padding.
+		 */
+		UINT32 getRowPitch() const { return mRowPitch; }
+
+		/**
+		 * Returns the number of pixels that offsets one depth slice from another. This can be "width * height", but 
+		 * doesn't have to be as some buffers require padding.
+		 */
+		UINT32 getSlicePitch() const { return mSlicePitch; }
+
+		/**
+		 * Sets the pitch (in pixels) that determines offset between rows of the pixel buffer. Call this before allocating
+		 * the buffer.
+		 */
+		void setRowPitch(UINT32 rowPitch) { mRowPitch = rowPitch; }
+
+		/**
+		 * Sets the pitch (in pixels) that determines offset between depth slices of the pixel buffer. Call this before 
+		 * allocating the buffer.
+		 */
+        void setSlicePitch(UINT32 slicePitch) { mSlicePitch = slicePitch; }
+
+		/**
+		 * Returns the number of extra pixels in a row (non-zero only if rows are not consecutive (row pitch is larger 
+		 * than width)).
+		 */
+        UINT32 getRowSkip() const { return mRowPitch - getWidth(); }
+
+		/**
+		 * Returns the number of extra pixels in a depth slice (non-zero only if slices aren't consecutive (slice pitch is 
+		 * larger than width*height).
+		 */
+        UINT32 getSliceSkip() const { return mSlicePitch - (getHeight() * mRowPitch); }
+
+		/** Returns the pixel format used by the internal buffer for storing the pixels. */
+		PixelFormat getFormat() const { return mFormat; }
+
+		/**	Returns width of the buffer in pixels. */
+		UINT32 getWidth() const { return mExtents.getWidth(); }
+
+		/**	Returns height of the buffer in pixels. */
+		UINT32 getHeight() const { return mExtents.getHeight(); }
+
+		/**	Returns depth of the buffer in pixels. */
+		UINT32 getDepth() const { return mExtents.getDepth(); }
+
+		/**
+		 * Returns left-most start of the pixel volume. This value is not used internally in any way. It is just passed 
+		 * through from the constructor.
+		 */
+		UINT32 getLeft() const { return mExtents.left; }
+
+		/**
+		 * Returns right-most end of the pixel volume. This value is not used internally in any way. It is just passed 
+		 * through from the constructor.
+		 */
+		UINT32 getRight() const { return mExtents.right; }
+
+		/**
+		 * Returns top-most start of the pixel volume. This value is not used internally in any way. It is just passed 
+		 * through from the constructor.
+		 */
+		UINT32 getTop() const { return mExtents.top; }
+
+		/**
+		 * Returns bottom-most end of the pixel volume. This value is not used internally in any way. It is just passed 
+		 * through from the constructor.
+		 */
+		UINT32 getBottom() const { return mExtents.bottom; }
+
+		/**
+		 * Returns front-most start of the pixel volume. This value is not used internally in any way. It is just passed 
+		 * through from the constructor.
+		 */
+		UINT32 getFront() const { return mExtents.front; }
+
+		/**
+		 * Returns back-most end of the pixel volume. This value is not used internally in any way. It is just passed 
+		 * through from the constructor.
+		 */
+		UINT32 getBack() const { return mExtents.back; }
+
+		/** Returns extents of the pixel volume this object is capable of holding. */
+		PixelVolume getExtents() const { return mExtents; }
+
+		/** 
+		 * Return whether this buffer is laid out consecutive in memory (meaning the pitches are equal to the dimensions). 
+		 */
+        bool isConsecutive() const 
+		{ 
+			return mRowPitch == getWidth() && mSlicePitch == getWidth()*getHeight(); 
+		}
+
+		/** Return the size (in bytes) this image would take if it was laid out consecutive in memory. */
+      	UINT32 getConsecutiveSize() const;
+
+		/**	Return the size (in bytes) of the buffer this image requires. */
+      	UINT32 getSize() const;
+
+		/**
+		 * Returns pixel data containing a sub-volume of this object. Returned data will not have its own buffer, but will
+		 * instead point to this one. It is up to the caller to ensure this object outlives any sub-volume objects.
+		 */
+      	PixelData getSubVolume(const PixelVolume &def) const;
+        
+		/**	Returns pixel color at the specified coordinates. */
+		Color getColorAt(UINT32 x, UINT32 y, UINT32 z = 0) const;
+
+		/**	Sets the pixel color at the specified coordinates. */
+        void setColorAt(Color const &cv, UINT32 x, UINT32 y, UINT32 z = 0);
+
+		/**
+		 * Converts all the internal data into an array of colors. Array is mapped as such: 
+		 * arrayIdx = x + y * width + z * width * height.
+		 */
+		Vector<Color> getColors() const;
+
+		/**
+		 * Initializes the internal buffer with the provided set of colors. The array should be of width * height * depth 
+		 * size and mapped as such: arrayIdx = x + y * width + z * width * height.
+		 */
+		void setColors(const Vector<Color>& colors);
+
+		/**
+		 * Initializes the internal buffer with the provided set of colors. The array should be of 
+		 * width * height * depth size and mapped as such: arrayIdx = x + y * width + z * width * height.
+		 */
+		void setColors(Color* colors, UINT32 numElements);
+
+		/**
+		 * Constructs a new object with an internal buffer capable of holding "extents" volume of pixels, where each pixel
+		 * is of the specified pixel format. Extent offsets are also stored, but are not used internally.
+		 */
+		static PixelDataPtr create(const PixelVolume &extents, PixelFormat pixelFormat);
+
+		/**
+		 * Constructs a new object with an internal buffer capable of holding volume of pixels described by provided width,
+		 * height and depth, where each pixel is of the specified pixel format.
+		 */
+		static PixelDataPtr create(UINT32 width, UINT32 height, UINT32 depth, PixelFormat pixelFormat);
+
+	private:
+		/**
+		 * Set the rowPitch and slicePitch so that the buffer is laid out consecutive in memory. Does not actually modify
+		 * the buffer itself.
+		 */
+		void setConsecutive()
+		{
+			mRowPitch = getWidth();
+			mSlicePitch = getWidth()*getHeight();
+		}
+
+		/**
+		 * Initializes the internal buffer with the provided set of colors. The array should be of width * height * depth 
+		 * size and mapped as such: arrayIdx = x + y * width + z * width * height.
+		 *
+		 * @note	A generic method that is reused in other more specific setColors() calls.
+		 */
+		template<class T>
+		void setColorsInternal(const T& colors, UINT32 numElements);
+
+		/**	Returns the needed size of the internal buffer, in bytes. */
+		UINT32 getInternalBufferSize() const override;
+
+	private:
+		PixelVolume mExtents;
+        PixelFormat mFormat;
+        UINT32 mRowPitch;
+        UINT32 mSlicePitch;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class PixelDataRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+    };
+
+	/** @} */
 }

+ 229 - 229
Source/BansheeCore/Include/BsPixelUtil.h

@@ -1,230 +1,230 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPixelData.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Utility-Core
-	 *  @{
-	 */
-
-	/**	Types of texture compression quality. */
-	enum class CompressionQuality
-	{
-		Fastest,
-		Normal,
-		Production,
-		Highest
-	};
-
-	/**	Mode of the alpha channel in a texture. */
-	enum class AlphaMode
-	{
-		None, /*< Texture has no alpha values. */
-		Transparency, /*< Alpha is in the separate transparency channel. */
-		Premultiplied /*< Alpha values have been pre-multiplied with the color values. */
-	};
-
-	/**	Wrap mode to use when generating mip maps. */
-	enum class MipMapWrapMode
-	{
-		Mirror,
-		Repeat,
-		Clamp
-	};
-
-	/**	Filter to use when generating mip maps. */
-	enum class MipMapFilter
-	{
-		Box,
-		Triangle,
-		Kaiser
-	};
-
-	/**	Options used to control texture compression. */
-	struct CompressionOptions
-	{
-		PixelFormat format = PF_BC1; /*< Format to compress to. Must be a format containing compressed data. */
-		AlphaMode alphaMode = AlphaMode::None; /*< Controls how to (and if) to compress the alpha channel. */
-		bool isNormalMap = false; /*< Determines does the input data represent a normal map. */
-		bool isSRGB = false; /*< Determines has the input data been gamma corrected. */
-		CompressionQuality quality = CompressionQuality::Normal; /*< Compressed image quality. Better compression might take longer to execute but will generate better results. */
-	};
-
-	/**	Options used to control texture mip map generation. */
-	struct MipMapGenOptions
-	{
-		MipMapFilter filter = MipMapFilter::Box; /*< Filter to use when downsamping input data. */
-		MipMapWrapMode wrapMode = MipMapWrapMode::Mirror; /*< Determines how to downsample pixels on borders. */
-		bool isNormalMap = false; /*< Determines does the input data represent a normal map. */
-		bool normalizeMipmaps = false; /*< Should the downsampled values be re-normalized. Only relevant for mip-maps representing normal maps. */
-	};
-
-	/**	Utility methods for converting and managing pixel data and formats. */
-    class BS_CORE_EXPORT PixelUtil 
-	{
-    public:
-		/**	Filtering types to use when scaling images. */
-		enum Filter
-		{
-			FILTER_NEAREST, /*< No filtering is performed and nearest existing value is used. */
-			FILTER_LINEAR /*< Box filter is applied, averaging nearby pixels. */
-		};
-
-		/**	Returns the size of a single pixel of the provided pixel format, in bytes. */
-        static UINT32 getNumElemBytes(PixelFormat format);
-
-		/**	Returns the size of a single pixel of the provided pixel format, in bits. */
-        static UINT32 getNumElemBits( PixelFormat format );
-
-		/**	Returns the size of the memory region required to hold pixels of the provided size ana format. */
-		static UINT32 getMemorySize(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format);
-		
-		/**	Calculates the size of a mip level of a texture with the provided size. */
-		static void getSizeForMipLevel(UINT32 width, UINT32 height, UINT32 depth, UINT32 mipLevel, 
-			UINT32& mipWidth, UINT32& mipHeight, UINT32& mipDepth);
-
-		/**
-		 * Returns property flags for this pixel format.
-		 *
-		 * @see		PixelFormatFlags
-		 */
-        static UINT32 getFlags(PixelFormat format);
-
-		/**	Checks if the provided pixel format has an alpha channel. */
-        static bool hasAlpha(PixelFormat format);
-
-		/**	Checks is the provided pixel format a floating point format. */
-        static bool isFloatingPoint(PixelFormat format);
-
-		/**	Checks is the provided pixel format compressed. */
-        static bool isCompressed(PixelFormat format);
-
-		/**	Checks is the provided pixel format a depth/stencil buffer format. */
-        static bool isDepth(PixelFormat format);
-
-		/**	Checks is the provided format in native endian format. */
-        static bool isNativeEndian(PixelFormat format);
-		
-		/**
-		 * Checks are the provided dimensions valid for the specified pixel format. Some formats (like DXT) require 
-		 * width/height to be multiples of four and some formats dont allow depth larger than 1.
-		 */
-		static bool isValidExtent(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format);
-
-		/**
-		 * Returns the number of bits per each element in the provided pixel format. This will return all zero for 
-		 * compressed and depth/stencil formats.
-		 */
-        static void getBitDepths(PixelFormat format, int rgba[4]);
-
-		/**
-		 * Returns bit masks that determine in what bit range is each channel stored.
-		 *
-		 * @note	
-		 * e.g. if your color is stored in an UINT32 and you want to extract the red channel you should AND the color
-		 * UINT32 with the bit-mask for the red channel and then right shift it by the red channel bit shift amount.
-		 */
-        static void getBitMasks(PixelFormat format, UINT32 rgba[4]);
-
-		/**
-		 * Returns number of bits you need to shift a pixel element in order to move it to the start of the data type.
-		 *
-		 * @note	
-		 * e.g. if your color is stored in an UINT32 and you want to extract the red channel you should AND the color 
-		 * UINT32 with the bit-mask for the red channel and then right shift it by the red channel bit shift amount.
-		 */
-		static void getBitShifts(PixelFormat format, UINT8 rgba[4]);
-
-		/**	Returns the name of the pixel format. */
-        static String getFormatName(PixelFormat srcformat);
-
-		/**
-		 * Returns true if the pixel data in the format can be directly accessed and read. This is generally not true 
-		 * for compressed formats.
-		 */
-        static bool isAccessible(PixelFormat srcformat);
-        
-		/**	Returns the type of an individual pixel element in the provided format. */
-        static PixelComponentType getElementType(PixelFormat format);
-        
-		/**	Returns the number of pixel elements in the provided format. */
-		static UINT32 getNumElements(PixelFormat format);
-
-		/**
-		 * Returns the maximum number of mip maps that can be generated until we reach the minimum size possible. This 
-		 * does not count the base level.
-		 */
-		static UINT32 getMaxMipmaps(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format);
-
-		/**	Writes the color to the provided memory location. */
-        static void packColor(const Color& color, PixelFormat format, void* dest);
-
-		/**
-		 * Writes the color to the provided memory location. If the destination	format is floating point, the byte values
-		 * will be converted into [0.0, 1.0] range.
-		 */
-		static void packColor(UINT8 r, UINT8 g, UINT8 b, UINT8 a, PixelFormat format, void* dest);
-
-		/**
-		 * Writes the color to the provided memory location. If the destination format in non-floating point, the float
-		 * values will be assumed to be in [0.0, 1.0] which	will be converted to integer range. ([0, 255] in the case of bytes)
-		 */
-		static void packColor(float r, float g, float b, float a, const PixelFormat format, void* dest);
-
-		/** Reads the color from the provided memory location and stores it into the provided color object. */
-		static void unpackColor(Color* color, PixelFormat format, const void* src);
-
-		/**
-		 * Reads the color from the provided memory location and stores it into the provided color elements, as bytes 
-		 * clamped to [0, 255] range.
-		 */
-		static void unpackColor(UINT8* r, UINT8* g, UINT8* b, UINT8* a, PixelFormat format, const void* src);
-
-		/**
-		 * Reads the color from the provided memory location and stores it into the provided color elements. If the format 
-		 * is not natively floating point a conversion is done in such a way that returned values range [0.0, 1.0].
-		 */
-        static void unpackColor(float* r, float* g, float* b, float* a, PixelFormat format, const void* src); 
-        
-		/**
-		 * Converts pixels from one format to another. Provided pixel data objects must have previously allocated buffers
-		 * of adequate size and their sizes must match.
-		 */
-        static void bulkPixelConversion(const PixelData& src, PixelData& dst);
-
-		/** Compresses the provided data using the specified compression options.  */
-		static void compress(const PixelData& src, PixelData& dst, const CompressionOptions& options);
-
-		/**
-		 * Generates mip-maps from the provided source data using the specified compression options. Returned list includes
-		 * the base level.
-		 *
-		 * @return	A list of calculated mip-map data. First entry is the largest mip and other follow in order from 
-		 *			largest to smallest.
-		 */
-		static Vector<PixelDataPtr> genMipmaps(const PixelData& src, const MipMapGenOptions& options);
-
-		/**
-		 * Scales pixel data in the source buffer and stores the scaled data in the destination buffer. Provided pixel data
-		 * objects must have previously allocated buffers of adequate size. You may also provided a filtering method to use
-		 * when scaling.
-		 */
-		static void scale(const PixelData& src, PixelData& dst, Filter filter = FILTER_LINEAR);
-
-		/**
-		 * Applies gamma correction to the pixels in the provided buffer.
-		 *
-		 * @param[in]	buffer	Pointer to the buffer containing the pixels.
-		 * @param[in]	gamma	Gamma value to apply.
-		 * @param[in]	size	Size of the buffer in bytes.
-		 * @param[in]	bpp		Number of bits per pixel of the pixels in the buffer.
-		 */
-        static void applyGamma(UINT8* buffer, float gamma, UINT32 size, UINT8 bpp);
-    };
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPixelData.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Utility-Core
+	 *  @{
+	 */
+
+	/**	Types of texture compression quality. */
+	enum class CompressionQuality
+	{
+		Fastest,
+		Normal,
+		Production,
+		Highest
+	};
+
+	/**	Mode of the alpha channel in a texture. */
+	enum class AlphaMode
+	{
+		None, /*< Texture has no alpha values. */
+		Transparency, /*< Alpha is in the separate transparency channel. */
+		Premultiplied /*< Alpha values have been pre-multiplied with the color values. */
+	};
+
+	/**	Wrap mode to use when generating mip maps. */
+	enum class MipMapWrapMode
+	{
+		Mirror,
+		Repeat,
+		Clamp
+	};
+
+	/**	Filter to use when generating mip maps. */
+	enum class MipMapFilter
+	{
+		Box,
+		Triangle,
+		Kaiser
+	};
+
+	/**	Options used to control texture compression. */
+	struct CompressionOptions
+	{
+		PixelFormat format = PF_BC1; /*< Format to compress to. Must be a format containing compressed data. */
+		AlphaMode alphaMode = AlphaMode::None; /*< Controls how to (and if) to compress the alpha channel. */
+		bool isNormalMap = false; /*< Determines does the input data represent a normal map. */
+		bool isSRGB = false; /*< Determines has the input data been gamma corrected. */
+		CompressionQuality quality = CompressionQuality::Normal; /*< Compressed image quality. Better compression might take longer to execute but will generate better results. */
+	};
+
+	/**	Options used to control texture mip map generation. */
+	struct MipMapGenOptions
+	{
+		MipMapFilter filter = MipMapFilter::Box; /*< Filter to use when downsamping input data. */
+		MipMapWrapMode wrapMode = MipMapWrapMode::Mirror; /*< Determines how to downsample pixels on borders. */
+		bool isNormalMap = false; /*< Determines does the input data represent a normal map. */
+		bool normalizeMipmaps = false; /*< Should the downsampled values be re-normalized. Only relevant for mip-maps representing normal maps. */
+	};
+
+	/**	Utility methods for converting and managing pixel data and formats. */
+    class BS_CORE_EXPORT PixelUtil 
+	{
+    public:
+		/**	Filtering types to use when scaling images. */
+		enum Filter
+		{
+			FILTER_NEAREST, /*< No filtering is performed and nearest existing value is used. */
+			FILTER_LINEAR /*< Box filter is applied, averaging nearby pixels. */
+		};
+
+		/**	Returns the size of a single pixel of the provided pixel format, in bytes. */
+        static UINT32 getNumElemBytes(PixelFormat format);
+
+		/**	Returns the size of a single pixel of the provided pixel format, in bits. */
+        static UINT32 getNumElemBits( PixelFormat format );
+
+		/**	Returns the size of the memory region required to hold pixels of the provided size ana format. */
+		static UINT32 getMemorySize(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format);
+		
+		/**	Calculates the size of a mip level of a texture with the provided size. */
+		static void getSizeForMipLevel(UINT32 width, UINT32 height, UINT32 depth, UINT32 mipLevel, 
+			UINT32& mipWidth, UINT32& mipHeight, UINT32& mipDepth);
+
+		/**
+		 * Returns property flags for this pixel format.
+		 *
+		 * @see		PixelFormatFlags
+		 */
+        static UINT32 getFlags(PixelFormat format);
+
+		/**	Checks if the provided pixel format has an alpha channel. */
+        static bool hasAlpha(PixelFormat format);
+
+		/**	Checks is the provided pixel format a floating point format. */
+        static bool isFloatingPoint(PixelFormat format);
+
+		/**	Checks is the provided pixel format compressed. */
+        static bool isCompressed(PixelFormat format);
+
+		/**	Checks is the provided pixel format a depth/stencil buffer format. */
+        static bool isDepth(PixelFormat format);
+
+		/**	Checks is the provided format in native endian format. */
+        static bool isNativeEndian(PixelFormat format);
+		
+		/**
+		 * Checks are the provided dimensions valid for the specified pixel format. Some formats (like DXT) require 
+		 * width/height to be multiples of four and some formats dont allow depth larger than 1.
+		 */
+		static bool isValidExtent(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format);
+
+		/**
+		 * Returns the number of bits per each element in the provided pixel format. This will return all zero for 
+		 * compressed and depth/stencil formats.
+		 */
+        static void getBitDepths(PixelFormat format, int rgba[4]);
+
+		/**
+		 * Returns bit masks that determine in what bit range is each channel stored.
+		 *
+		 * @note	
+		 * For example if your color is stored in an UINT32 and you want to extract the red channel you should AND the color
+		 * UINT32 with the bit-mask for the red channel and then right shift it by the red channel bit shift amount.
+		 */
+        static void getBitMasks(PixelFormat format, UINT32 rgba[4]);
+
+		/**
+		 * Returns number of bits you need to shift a pixel element in order to move it to the start of the data type.
+		 *
+		 * @note	
+		 * For example if your color is stored in an UINT32 and you want to extract the red channel you should AND the color 
+		 * UINT32 with the bit-mask for the red channel and then right shift it by the red channel bit shift amount.
+		 */
+		static void getBitShifts(PixelFormat format, UINT8 rgba[4]);
+
+		/**	Returns the name of the pixel format. */
+        static String getFormatName(PixelFormat srcformat);
+
+		/**
+		 * Returns true if the pixel data in the format can be directly accessed and read. This is generally not true 
+		 * for compressed formats.
+		 */
+        static bool isAccessible(PixelFormat srcformat);
+        
+		/**	Returns the type of an individual pixel element in the provided format. */
+        static PixelComponentType getElementType(PixelFormat format);
+        
+		/**	Returns the number of pixel elements in the provided format. */
+		static UINT32 getNumElements(PixelFormat format);
+
+		/**
+		 * Returns the maximum number of mip maps that can be generated until we reach the minimum size possible. This 
+		 * does not count the base level.
+		 */
+		static UINT32 getMaxMipmaps(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format);
+
+		/**	Writes the color to the provided memory location. */
+        static void packColor(const Color& color, PixelFormat format, void* dest);
+
+		/**
+		 * Writes the color to the provided memory location. If the destination	format is floating point, the byte values
+		 * will be converted into [0.0, 1.0] range.
+		 */
+		static void packColor(UINT8 r, UINT8 g, UINT8 b, UINT8 a, PixelFormat format, void* dest);
+
+		/**
+		 * Writes the color to the provided memory location. If the destination format in non-floating point, the float
+		 * values will be assumed to be in [0.0, 1.0] which	will be converted to integer range. ([0, 255] in the case of bytes)
+		 */
+		static void packColor(float r, float g, float b, float a, const PixelFormat format, void* dest);
+
+		/** Reads the color from the provided memory location and stores it into the provided color object. */
+		static void unpackColor(Color* color, PixelFormat format, const void* src);
+
+		/**
+		 * Reads the color from the provided memory location and stores it into the provided color elements, as bytes 
+		 * clamped to [0, 255] range.
+		 */
+		static void unpackColor(UINT8* r, UINT8* g, UINT8* b, UINT8* a, PixelFormat format, const void* src);
+
+		/**
+		 * Reads the color from the provided memory location and stores it into the provided color elements. If the format 
+		 * is not natively floating point a conversion is done in such a way that returned values range [0.0, 1.0].
+		 */
+        static void unpackColor(float* r, float* g, float* b, float* a, PixelFormat format, const void* src); 
+        
+		/**
+		 * Converts pixels from one format to another. Provided pixel data objects must have previously allocated buffers
+		 * of adequate size and their sizes must match.
+		 */
+        static void bulkPixelConversion(const PixelData& src, PixelData& dst);
+
+		/** Compresses the provided data using the specified compression options.  */
+		static void compress(const PixelData& src, PixelData& dst, const CompressionOptions& options);
+
+		/**
+		 * Generates mip-maps from the provided source data using the specified compression options. Returned list includes
+		 * the base level.
+		 *
+		 * @return	A list of calculated mip-map data. First entry is the largest mip and other follow in order from 
+		 *			largest to smallest.
+		 */
+		static Vector<PixelDataPtr> genMipmaps(const PixelData& src, const MipMapGenOptions& options);
+
+		/**
+		 * Scales pixel data in the source buffer and stores the scaled data in the destination buffer. Provided pixel data
+		 * objects must have previously allocated buffers of adequate size. You may also provided a filtering method to use
+		 * when scaling.
+		 */
+		static void scale(const PixelData& src, PixelData& dst, Filter filter = FILTER_LINEAR);
+
+		/**
+		 * Applies gamma correction to the pixels in the provided buffer.
+		 *
+		 * @param[in]	buffer	Pointer to the buffer containing the pixels.
+		 * @param[in]	gamma	Gamma value to apply.
+		 * @param[in]	size	Size of the buffer in bytes.
+		 * @param[in]	bpp		Number of bits per pixel of the pixels in the buffer.
+		 */
+        static void applyGamma(UINT8* buffer, float gamma, UINT32 size, UINT8 bpp);
+    };
+
+	/** @} */
 }

+ 449 - 449
Source/BansheeCore/Include/BsPlatform.h

@@ -1,450 +1,450 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsInputFwd.h"
-#include "BsVector2I.h"
-#include "BsRect2I.h"
-#include "BsEvent.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Platform
-	 *  @{
-	 */
-
-	/** Contains values representing default mouse cursor types. */
-	enum class PlatformCursorType
-	{
-		Arrow,
-		Wait,
-		IBeam,
-		Help,
-		Hand,
-		SizeAll,
-		SizeNESW,
-		SizeNS,
-		SizeNWSE,
-		SizeWE
-	};
-
-	/**
-	 * Contains values reprenting window non client areas.
-	 *
-	 * @note	These are used for things like resize/move and tell the OS where each of those areas are on our window.
-	 */
-	enum class NonClientAreaBorderType
-	{
-		TopLeft,
-		Top,
-		TopRight,
-		Left,
-		Right,
-		BottomLeft,
-		Bottom,
-		BottomRight
-	};
-
-	/** Types of mouse buttons provided by the OS. */
-	enum class OSMouseButton
-	{
-		Left, Middle, Right, Count
-	};
-
-	/** Describes pointer (mouse, touch) states as reported by the OS. */
-	struct BS_CORE_EXPORT OSPointerButtonStates
-	{
-		OSPointerButtonStates()
-		{
-			mouseButtons[0] = false;
-			mouseButtons[1] = false;
-			mouseButtons[2] = false;
-
-			shift = false;
-			ctrl = false;
-		}
-
-		bool mouseButtons[OSMouseButton::Count];
-		bool shift, ctrl;
-	};
-
-	/** Type of drop event type. This is used when dragging items over drop targets. */
-	enum class OSDropType
-	{
-		FileList,
-		None
-	};
-
-	/**
-	 * Drop targets allow you to register a certain portion of a window as a drop target that accepts certain drop types 
-	 * from the OS (platform) specific drag and drop system. Accepted drop types are provided by the OS and include things
-	 * like file and item dragging.
-	 *
-	 * You will receive events with the specified drop area as long as it is active.
-	 */
-	class BS_CORE_EXPORT OSDropTarget
-	{
-	public:
-		/**
-		 * Triggered when a pointer is being dragged over the drop area. Provides window coordinates of the pointer position.
-		 */
-		Event<void(INT32 x, INT32 y)> onDragOver;
-
-		/**
-		 * Triggered when the user completes a drop while pointer is over the drop area. Provides window coordinates of the 
-		 * pointer position.
-		 */
-		Event<void(INT32 x, INT32 y)> onDrop;
-
-		/**
-		 * Triggered when a pointer enters the drop area. Provides window coordinates of the pointer position.
-		 */
-		Event<void(INT32 x, INT32 y)> onEnter;
-
-		/** Triggered when a pointer leaves the drop area. */
-		Event<void()> onLeave;
-
-		/**	Sets the drop target area, in local window coordinates. */
-		void setArea(INT32 x, INT32 y, UINT32 width, UINT32 height);
-
-		/**	Gets the type of drop that this drop target is looking for. Only valid after a drop has been triggered. */
-		OSDropType getDropType() const { return mDropType; }
-
-		/**	
-		 * Returns a list of files received by the drop target. Only valid after a drop of FileList type has been triggered.
-		 */
-		const Vector<WString>& getFileList() const { return *mFileList; }
-
-		/** Clears all internal values. */
-		void _clear();
-
-		/** Sets the file list and marks the drop event as FileList. */
-		void _setFileList(const Vector<WString>& fileList);
-
-		/** Marks the drop area as inactive or active. */
-		void _setActive(bool active) { mActive = active; }
-
-		/**	Checks is the specified position within the current drop area. Position should be in window local coordinates. */
-		bool _isInside(const Vector2I& pos) const;
-
-		/** Returns true if the drop target is active. */
-		bool _isActive() const { return mActive; }
-	private:
-		friend class Platform;
-
-		OSDropTarget(const RenderWindow* ownerWindow, INT32 x, INT32 y, UINT32 width, UINT32 height);
-		~OSDropTarget();
-
-		/**	Returns a render window this drop target is attached to. */
-		const RenderWindow* getOwnerWindow() const { return mOwnerWindow; }
-	private:
-		INT32 mX, mY;
-		UINT32 mWidth, mHeight;
-		bool mActive;
-		const RenderWindow* mOwnerWindow;
-
-		OSDropType mDropType;
-
-		union
-		{
-			Vector<WString>* mFileList;
-		};
-	};
-
-	/**	Represents a specific non client area used for window resizing. */
-	struct BS_CORE_EXPORT NonClientResizeArea
-	{
-		NonClientAreaBorderType type;
-		Rect2I area;
-	};
-
-	/** Contains a list of window move and resize non client areas. */
-	struct BS_CORE_EXPORT WindowNonClientAreaData
-	{
-		Vector<NonClientResizeArea> resizeAreas;
-		Vector<Rect2I> moveAreas;
-	};
-
-	/**	Provides access to various operating system functions, including the main message pump. */
-	class BS_CORE_EXPORT Platform
-	{
-	public:
-		struct Pimpl;
-
-		Platform() { }
-		virtual ~Platform();
-
-		/**
-		 * Retrieves the cursor position in screen coordinates.
-		 *
-		 * @note	Thread safe.
-		 */
-		static Vector2I getCursorPosition();
-
-		/**
-		 * Moves the cursor to the specified screen position.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void setCursorPosition(const Vector2I& screenPos);
-
-		/**
-		 * Capture mouse to this window so that we get mouse input even if the mouse leaves the window area.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void captureMouse(const RenderWindow& window);
-
-		/**
-		 * Releases the mouse capture set by captureMouse().
-		 *
-		 * @note	Thread safe.
-		 */
-		static void releaseMouseCapture();
-
-		/**
-		 * Checks if provided over screen position is over the specified window.
-		 */
-		static bool isPointOverWindow(const RenderWindow& window, const Vector2I& screenPos);
-
-		/**
-		 * Limit cursor movement to the specified window.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void clipCursorToWindow(const RenderWindow& window);
-
-		/**
-		 * Clip cursor to specific area on the screen.
-		 *
-		 * @note	Thread safe.
-		 */
-
-		static void clipCursorToRect(const Rect2I& screenRect);
-
-		/**
-		 * Disables cursor clipping.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void clipCursorDisable();
-
-		/**
-		 * Hides the cursor.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void hideCursor();
-
-		/**
-		 * Shows the cursor.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void showCursor();
-
-		/**
-		 * Query if the cursor is hidden.
-		 *
-		 * @note	Thread safe.
-		 */
-		static bool isCursorHidden();
-
-		/**
-		 * Sets a cursor using a custom image.
-		 *
-		 * @param[in] 	pixelData	Cursor image data.
-		 * @param[in]	hotSpot		Offset on the cursor image to where the actual input happens (e.g. tip of the Arrow 
-		 *							cursor).
-		 *
-		 * @note	Thread safe.
-		 */
-		static void setCursor(PixelData& pixelData, const Vector2I& hotSpot);
-
-		/**
-		 * Sets an icon for the main application window.
-		 *
-		 * @param[in] 	pixelData	Icon image data. This will be resized to the required icon size, depending on platform
-		 * 							implementation.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void setIcon(const PixelData& pixelData);
-
-		/**
-		 * Sets custom caption non client areas for the specified window. Using custom client areas will override window 
-		 * move/drag operation and trigger when user interacts with the custom area.
-		 *
-		 * @note	
-		 * Thread safe.
-		 * @note
-		 * All provided areas are relative to the specified window. Mostly useful for frameless windows that don't have 
-		 * typical caption bar.
-		 */
-		static void setCaptionNonClientAreas(const RenderWindowCore& window, const Vector<Rect2I>& nonClientAreas);
-
-		/**
-		 * Sets custom non client areas for the specified window. Using custom client areas will override window resize 
-		 * operation and trigger when user interacts with the custom area.
-		 *
-		 * @note	
-		 * Thread safe.
-		 * @note
-		 * All provided areas are relative to the specified window. Mostly useful for frameless windows that don't have 
-		 * typical border.
-		 */
-		static void setResizeNonClientAreas(const RenderWindowCore& window, const Vector<NonClientResizeArea>& nonClientAreas);
-
-		/**
-		 * Resets the non client areas for the specified windows and allows the platform to use the default values.
-		 *
-		 * @note	Thread safe.
-		 */
-		static void resetNonClientAreas(const RenderWindowCore& window);
-
-		/** 
-		 * Causes the current thread to pause execution for the specified amount of time.
-		 *
-		 * @param[in]	duration	Duration in milliseconds. Providing zero will give up the current time-slice.
-		 *
-		 * @note	This method relies on timer granularity being set to 1 millisecond. If it is not, you can expect
-		 *			this method to potentially take significantly longer if you are providing it with low ms values (<10).
-		 */
-		static void sleep(UINT32 duration);
-
-		/**
-		 * Creates a drop target that you can use for tracking OS drag and drop operations performed over a certain area 
-		 * on the specified window.
-		 *
-		 * @param[in]	window	The window on which to track drop operations.
-		 * @param[in]	x	  	The x coordinate of the area to track, relative to window.
-		 * @param[in]	y	  	The y coordinate of the area to track, relative to window.
-		 * @param[in]	width 	The width of the area to track.
-		 * @param[in]	height	The height of the area to track.
-		 * @return				OSDropTarget that you will use to receive all drop data. When no longer needed make sure 
-		 *						to destroy it with destroyDropTarget().
-		 */
-		static OSDropTarget& createDropTarget(const RenderWindow* window, int x, int y, unsigned int width, unsigned int height);
-
-		/** Destroys a drop target previously created with createDropTarget. */
-		static void destroyDropTarget(OSDropTarget& target);
-
-		/**
-		 * Displays a platform specific file/folder open/save dialog.
-		 *
-		 * @param[in]	type		Type of dialog to open.
-		 * @param[in]	defaultPath	Initial path the dialog will be set to once opened.
-		 * @param[in]	filterList	Semi-colon separated list of file names or types to display in the dialog, 
-		 *							e.g. "exe;txt;png". Ignored if dialog is to display folders instead of files.
-		 * @param[out]	paths		Output list of selected file or folder paths (if any).
-		 * @return					True if file was selected and false if selection was canceled.
-		 */
-		static bool openBrowseDialog(FileDialogType type, const Path& defaultPath, const WString& filterList,
-			Vector<Path>& paths);
-
-		/**
-		 * Message pump. Processes OS messages and returns when it's free.
-		 *
-		 * @note	Core thread only.
-		 */
-		static void _messagePump();
-
-		/**
-		 * Called during application start up from the sim thread. Must be called before any other operations are done.
-		 *
-		 * @note	Internal method.
-		 */
-		static void _startUp();
-
-		/**
-		 * Called once per frame from the sim thread.
-		 *
-		 * @note	Sim thread only.
-		 */
-		static void _update();
-
-		/**
-		 * Called once per frame from the core thread.
-		 *
-		 * @note	Core thread only.
-		 */
-		static void _coreUpdate();
-
-		/**
-		 * Called during application shut down from the sim thread.
-		 *
-		 * @note	Sim thread only.
-		 */
-		static void _shutDown();
-
-		/**
-		 * Triggered when a pointer leaves the provided window.
-		 *
-		 * @note	Sim thread only.
-		 */
-		static Event<void(RenderWindowCore*)> onMouseLeftWindow;
-
-		/**
-		 * Triggered whenever the pointer moves.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(const Vector2I&, OSPointerButtonStates)> onCursorMoved;
-
-		/**
-		 * Triggered whenever a pointer button is pressed.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(const Vector2I&, OSMouseButton button, OSPointerButtonStates)> onCursorButtonPressed;
-
-		/**
-		 * Triggered whenever pointer button is released.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(const Vector2I&, OSMouseButton button, OSPointerButtonStates)> onCursorButtonReleased;
-
-		/**
-		 * Triggered whenever a pointer button is double clicked.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(const Vector2I&, OSPointerButtonStates)> onCursorDoubleClick;
-
-		/**
-		 * Triggered whenever an input command is entered.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(InputCommandType)> onInputCommand;
-
-		/**
-		 * Triggered whenever the mouse wheel is scolled.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(float)> onMouseWheelScrolled;
-
-		/**
-		 * Triggered whenever a character is entered.
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void(UINT32)> onCharInput;
-
-		/**
-		 * Triggered whenever mouse capture state for the window is changed (it receives or loses it).
-		 *
-		 * @note	Core thread only.
-		 */
-		static Event<void()> onMouseCaptureChanged;
-	protected:
-		static Pimpl* mData;
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsInputFwd.h"
+#include "BsVector2I.h"
+#include "BsRect2I.h"
+#include "BsEvent.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Platform
+	 *  @{
+	 */
+
+	/** Contains values representing default mouse cursor types. */
+	enum class PlatformCursorType
+	{
+		Arrow,
+		Wait,
+		IBeam,
+		Help,
+		Hand,
+		SizeAll,
+		SizeNESW,
+		SizeNS,
+		SizeNWSE,
+		SizeWE
+	};
+
+	/**
+	 * Contains values reprenting window non client areas.
+	 *
+	 * @note	These are used for things like resize/move and tell the OS where each of those areas are on our window.
+	 */
+	enum class NonClientAreaBorderType
+	{
+		TopLeft,
+		Top,
+		TopRight,
+		Left,
+		Right,
+		BottomLeft,
+		Bottom,
+		BottomRight
+	};
+
+	/** Types of mouse buttons provided by the OS. */
+	enum class OSMouseButton
+	{
+		Left, Middle, Right, Count
+	};
+
+	/** Describes pointer (mouse, touch) states as reported by the OS. */
+	struct BS_CORE_EXPORT OSPointerButtonStates
+	{
+		OSPointerButtonStates()
+		{
+			mouseButtons[0] = false;
+			mouseButtons[1] = false;
+			mouseButtons[2] = false;
+
+			shift = false;
+			ctrl = false;
+		}
+
+		bool mouseButtons[OSMouseButton::Count];
+		bool shift, ctrl;
+	};
+
+	/** Type of drop event type. This is used when dragging items over drop targets. */
+	enum class OSDropType
+	{
+		FileList,
+		None
+	};
+
+	/**
+	 * Drop targets allow you to register a certain portion of a window as a drop target that accepts certain drop types 
+	 * from the OS (platform) specific drag and drop system. Accepted drop types are provided by the OS and include things
+	 * like file and item dragging.
+	 *
+	 * You will receive events with the specified drop area as long as it is active.
+	 */
+	class BS_CORE_EXPORT OSDropTarget
+	{
+	public:
+		/**
+		 * Triggered when a pointer is being dragged over the drop area. Provides window coordinates of the pointer position.
+		 */
+		Event<void(INT32 x, INT32 y)> onDragOver;
+
+		/**
+		 * Triggered when the user completes a drop while pointer is over the drop area. Provides window coordinates of the 
+		 * pointer position.
+		 */
+		Event<void(INT32 x, INT32 y)> onDrop;
+
+		/**
+		 * Triggered when a pointer enters the drop area. Provides window coordinates of the pointer position.
+		 */
+		Event<void(INT32 x, INT32 y)> onEnter;
+
+		/** Triggered when a pointer leaves the drop area. */
+		Event<void()> onLeave;
+
+		/**	Sets the drop target area, in local window coordinates. */
+		void setArea(INT32 x, INT32 y, UINT32 width, UINT32 height);
+
+		/**	Gets the type of drop that this drop target is looking for. Only valid after a drop has been triggered. */
+		OSDropType getDropType() const { return mDropType; }
+
+		/**	
+		 * Returns a list of files received by the drop target. Only valid after a drop of FileList type has been triggered.
+		 */
+		const Vector<WString>& getFileList() const { return *mFileList; }
+
+		/** Clears all internal values. */
+		void _clear();
+
+		/** Sets the file list and marks the drop event as FileList. */
+		void _setFileList(const Vector<WString>& fileList);
+
+		/** Marks the drop area as inactive or active. */
+		void _setActive(bool active) { mActive = active; }
+
+		/**	Checks is the specified position within the current drop area. Position should be in window local coordinates. */
+		bool _isInside(const Vector2I& pos) const;
+
+		/** Returns true if the drop target is active. */
+		bool _isActive() const { return mActive; }
+	private:
+		friend class Platform;
+
+		OSDropTarget(const RenderWindow* ownerWindow, INT32 x, INT32 y, UINT32 width, UINT32 height);
+		~OSDropTarget();
+
+		/**	Returns a render window this drop target is attached to. */
+		const RenderWindow* getOwnerWindow() const { return mOwnerWindow; }
+	private:
+		INT32 mX, mY;
+		UINT32 mWidth, mHeight;
+		bool mActive;
+		const RenderWindow* mOwnerWindow;
+
+		OSDropType mDropType;
+
+		union
+		{
+			Vector<WString>* mFileList;
+		};
+	};
+
+	/**	Represents a specific non client area used for window resizing. */
+	struct BS_CORE_EXPORT NonClientResizeArea
+	{
+		NonClientAreaBorderType type;
+		Rect2I area;
+	};
+
+	/** Contains a list of window move and resize non client areas. */
+	struct BS_CORE_EXPORT WindowNonClientAreaData
+	{
+		Vector<NonClientResizeArea> resizeAreas;
+		Vector<Rect2I> moveAreas;
+	};
+
+	/**	Provides access to various operating system functions, including the main message pump. */
+	class BS_CORE_EXPORT Platform
+	{
+	public:
+		struct Pimpl;
+
+		Platform() { }
+		virtual ~Platform();
+
+		/**
+		 * Retrieves the cursor position in screen coordinates.
+		 *
+		 * @note	Thread safe.
+		 */
+		static Vector2I getCursorPosition();
+
+		/**
+		 * Moves the cursor to the specified screen position.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void setCursorPosition(const Vector2I& screenPos);
+
+		/**
+		 * Capture mouse to this window so that we get mouse input even if the mouse leaves the window area.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void captureMouse(const RenderWindow& window);
+
+		/**
+		 * Releases the mouse capture set by captureMouse().
+		 *
+		 * @note	Thread safe.
+		 */
+		static void releaseMouseCapture();
+
+		/**
+		 * Checks if provided over screen position is over the specified window.
+		 */
+		static bool isPointOverWindow(const RenderWindow& window, const Vector2I& screenPos);
+
+		/**
+		 * Limit cursor movement to the specified window.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void clipCursorToWindow(const RenderWindow& window);
+
+		/**
+		 * Clip cursor to specific area on the screen.
+		 *
+		 * @note	Thread safe.
+		 */
+
+		static void clipCursorToRect(const Rect2I& screenRect);
+
+		/**
+		 * Disables cursor clipping.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void clipCursorDisable();
+
+		/**
+		 * Hides the cursor.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void hideCursor();
+
+		/**
+		 * Shows the cursor.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void showCursor();
+
+		/**
+		 * Query if the cursor is hidden.
+		 *
+		 * @note	Thread safe.
+		 */
+		static bool isCursorHidden();
+
+		/**
+		 * Sets a cursor using a custom image.
+		 *
+		 * @param[in] 	pixelData	Cursor image data.
+		 * @param[in]	hotSpot		Offset on the cursor image to where the actual input happens (for example tip of the
+		 *							Arrow cursor).
+		 *
+		 * @note	Thread safe.
+		 */
+		static void setCursor(PixelData& pixelData, const Vector2I& hotSpot);
+
+		/**
+		 * Sets an icon for the main application window.
+		 *
+		 * @param[in] 	pixelData	Icon image data. This will be resized to the required icon size, depending on platform
+		 * 							implementation.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void setIcon(const PixelData& pixelData);
+
+		/**
+		 * Sets custom caption non client areas for the specified window. Using custom client areas will override window 
+		 * move/drag operation and trigger when user interacts with the custom area.
+		 *
+		 * @note	
+		 * Thread safe.
+		 * @note
+		 * All provided areas are relative to the specified window. Mostly useful for frameless windows that don't have 
+		 * typical caption bar.
+		 */
+		static void setCaptionNonClientAreas(const RenderWindowCore& window, const Vector<Rect2I>& nonClientAreas);
+
+		/**
+		 * Sets custom non client areas for the specified window. Using custom client areas will override window resize 
+		 * operation and trigger when user interacts with the custom area.
+		 *
+		 * @note	
+		 * Thread safe.
+		 * @note
+		 * All provided areas are relative to the specified window. Mostly useful for frameless windows that don't have 
+		 * typical border.
+		 */
+		static void setResizeNonClientAreas(const RenderWindowCore& window, const Vector<NonClientResizeArea>& nonClientAreas);
+
+		/**
+		 * Resets the non client areas for the specified windows and allows the platform to use the default values.
+		 *
+		 * @note	Thread safe.
+		 */
+		static void resetNonClientAreas(const RenderWindowCore& window);
+
+		/** 
+		 * Causes the current thread to pause execution for the specified amount of time.
+		 *
+		 * @param[in]	duration	Duration in milliseconds. Providing zero will give up the current time-slice.
+		 *
+		 * @note	This method relies on timer granularity being set to 1 millisecond. If it is not, you can expect
+		 *			this method to potentially take significantly longer if you are providing it with low ms values (<10).
+		 */
+		static void sleep(UINT32 duration);
+
+		/**
+		 * Creates a drop target that you can use for tracking OS drag and drop operations performed over a certain area 
+		 * on the specified window.
+		 *
+		 * @param[in]	window	The window on which to track drop operations.
+		 * @param[in]	x	  	The x coordinate of the area to track, relative to window.
+		 * @param[in]	y	  	The y coordinate of the area to track, relative to window.
+		 * @param[in]	width 	The width of the area to track.
+		 * @param[in]	height	The height of the area to track.
+		 * @return				OSDropTarget that you will use to receive all drop data. When no longer needed make sure 
+		 *						to destroy it with destroyDropTarget().
+		 */
+		static OSDropTarget& createDropTarget(const RenderWindow* window, int x, int y, unsigned int width, unsigned int height);
+
+		/** Destroys a drop target previously created with createDropTarget. */
+		static void destroyDropTarget(OSDropTarget& target);
+
+		/**
+		 * Displays a platform specific file/folder open/save dialog.
+		 *
+		 * @param[in]	type		Type of dialog to open.
+		 * @param[in]	defaultPath	Initial path the dialog will be set to once opened.
+		 * @param[in]	filterList	Semi-colon separated list of file names or types to display in the dialog, 
+		 *							for example "exe;txt;png". Ignored if dialog is to display folders instead of files.
+		 * @param[out]	paths		Output list of selected file or folder paths (if any).
+		 * @return					True if file was selected and false if selection was canceled.
+		 */
+		static bool openBrowseDialog(FileDialogType type, const Path& defaultPath, const WString& filterList,
+			Vector<Path>& paths);
+
+		/**
+		 * Message pump. Processes OS messages and returns when it's free.
+		 *
+		 * @note	Core thread only.
+		 */
+		static void _messagePump();
+
+		/**
+		 * Called during application start up from the sim thread. Must be called before any other operations are done.
+		 *
+		 * @note	Internal method.
+		 */
+		static void _startUp();
+
+		/**
+		 * Called once per frame from the sim thread.
+		 *
+		 * @note	Sim thread only.
+		 */
+		static void _update();
+
+		/**
+		 * Called once per frame from the core thread.
+		 *
+		 * @note	Core thread only.
+		 */
+		static void _coreUpdate();
+
+		/**
+		 * Called during application shut down from the sim thread.
+		 *
+		 * @note	Sim thread only.
+		 */
+		static void _shutDown();
+
+		/**
+		 * Triggered when a pointer leaves the provided window.
+		 *
+		 * @note	Sim thread only.
+		 */
+		static Event<void(RenderWindowCore*)> onMouseLeftWindow;
+
+		/**
+		 * Triggered whenever the pointer moves.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(const Vector2I&, OSPointerButtonStates)> onCursorMoved;
+
+		/**
+		 * Triggered whenever a pointer button is pressed.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(const Vector2I&, OSMouseButton button, OSPointerButtonStates)> onCursorButtonPressed;
+
+		/**
+		 * Triggered whenever pointer button is released.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(const Vector2I&, OSMouseButton button, OSPointerButtonStates)> onCursorButtonReleased;
+
+		/**
+		 * Triggered whenever a pointer button is double clicked.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(const Vector2I&, OSPointerButtonStates)> onCursorDoubleClick;
+
+		/**
+		 * Triggered whenever an input command is entered.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(InputCommandType)> onInputCommand;
+
+		/**
+		 * Triggered whenever the mouse wheel is scolled.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(float)> onMouseWheelScrolled;
+
+		/**
+		 * Triggered whenever a character is entered.
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void(UINT32)> onCharInput;
+
+		/**
+		 * Triggered whenever mouse capture state for the window is changed (it receives or loses it).
+		 *
+		 * @note	Core thread only.
+		 */
+		static Event<void()> onMouseCaptureChanged;
+	protected:
+		static Pimpl* mData;
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 96 - 94
Source/BansheeCore/Include/BsPrefab.h

@@ -1,95 +1,97 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsGameObject.h"
-#include "BsResource.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Scene
-	 *  @{
-	 */
-
-	/**
-	 * Prefab is a saveable hierarchy of scene objects. In general it can serve as any grouping of scene objects 
-	 * (e.g. a level) or be used as a form of a template instantiated and reused throughout the scene.
-	 */
-	class BS_CORE_EXPORT Prefab : public Resource
-	{
-	public:
-		Prefab();
-		~Prefab();
-
-		/**
-		 * Creates a new prefab from the provided scene object. If the scene object has an existing prefab link it will 
-		 * be broken. After the prefab is created the scene object will be automatically linked to it.
-		 */
-		static HPrefab create(const HSceneObject& sceneObject);
-
-		/**
-		 * Instantiates a prefab by creating an instance of the prefab's scene object hierarchy. The returned hierarchy 
-		 * will be parented to world root by default.
-		 *			
-		 * @return	Instantiated clone of the prefab's scene object hierarchy.
-		 */
-		HSceneObject instantiate();
-
-		/**
-		 * Replaces the contents of this prefab with new contents from the provided object. Object will be automatically
-		 * linked to this prefab, and its previous prefab link (if any) will be broken.
-		 */
-		void update(const HSceneObject& sceneObject);
-
-		/**
-		 * Returns a hash value that can be used for determining if a prefab changed by comparing it to a previously saved
-		 * hash.
-		 */
-		UINT32 getHash() const { return mHash; }
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** Updates any prefab child instances by loading their prefabs and making sure they are up to date. */
-		void _updateChildInstances();
-
-		/**
-		 * Returns a reference to the internal prefab hierarchy. Returned hierarchy is not instantiated and cannot be 
-		 * interacted with in a manner you would with normal scene objects.
-		 */
-		HSceneObject _getRoot() const { return mRoot; }
-
-		/**
-		 * Creates the clone of the prefab's current hierarchy but doesn't instantiate it.
-		 *			
-		 * @return	Clone of the prefab's scene object hierarchy.
-		 */
-		HSceneObject _clone();
-
-		/** @endcond */
-
-	private:
-		/**	Initializes the internal prefab hierarchy. Must be called druing creation. */
-		void initialize(const HSceneObject& sceneObject);
-
-		/**	Creates an empty and uninitialized prefab. */
-		static PrefabPtr createEmpty();
-
-		HSceneObject mRoot;
-		UINT32 mHash;
-		String mUUID;
-		UINT32 mNextLinkId;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-
-	public:
-		friend class PrefabRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsGameObject.h"
+#include "BsResource.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Scene
+	 *  @{
+	 */
+
+	/**
+	 * Prefab is a saveable hierarchy of scene objects. In general it can serve as any grouping of scene objects 
+	 * (for example a level) or be used as a form of a template instantiated and reused throughout the scene.
+	 */
+	class BS_CORE_EXPORT Prefab : public Resource
+	{
+	public:
+		Prefab();
+		~Prefab();
+
+		/**
+		 * Creates a new prefab from the provided scene object. If the scene object has an existing prefab link it will 
+		 * be broken. After the prefab is created the scene object will be automatically linked to it.
+		 */
+		static HPrefab create(const HSceneObject& sceneObject);
+
+		/**
+		 * Instantiates a prefab by creating an instance of the prefab's scene object hierarchy. The returned hierarchy 
+		 * will be parented to world root by default.
+		 *			
+		 * @return	Instantiated clone of the prefab's scene object hierarchy.
+		 */
+		HSceneObject instantiate();
+
+		/**
+		 * Replaces the contents of this prefab with new contents from the provided object. Object will be automatically
+		 * linked to this prefab, and its previous prefab link (if any) will be broken.
+		 */
+		void update(const HSceneObject& sceneObject);
+
+		/**
+		 * Returns a hash value that can be used for determining if a prefab changed by comparing it to a previously saved
+		 * hash.
+		 */
+		UINT32 getHash() const { return mHash; }
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** Updates any prefab child instances by loading their prefabs and making sure they are up to date. */
+		void _updateChildInstances();
+
+		/**
+		 * Returns a reference to the internal prefab hierarchy. Returned hierarchy is not instantiated and cannot be 
+		 * interacted with in a manner you would with normal scene objects.
+		 */
+		HSceneObject _getRoot() const { return mRoot; }
+
+		/**
+		 * Creates the clone of the prefab's current hierarchy but doesn't instantiate it.
+		 *			
+		 * @return	Clone of the prefab's scene object hierarchy.
+		 */
+		HSceneObject _clone();
+
+		/** @} */
+
+	private:
+		/**	Initializes the internal prefab hierarchy. Must be called druing creation. */
+		void initialize(const HSceneObject& sceneObject);
+
+		/**	Creates an empty and uninitialized prefab. */
+		static PrefabPtr createEmpty();
+
+		HSceneObject mRoot;
+		UINT32 mHash;
+		String mUUID;
+		UINT32 mNextLinkId;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+
+	public:
+		friend class PrefabRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 422 - 422
Source/BansheeCore/Include/BsProfilerCPU.h

@@ -1,423 +1,423 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsModule.h"
-#include "BsFrameAlloc.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Profiling
-	 *  @{
-	 */
-
-	class CPUProfilerReport;
-
-	/**
-	 * Provides various performance measuring methods.
-	 * 			
-	 * @note	Thread safe. Matching begin*\end* calls must belong to the same thread though.
-	 */
-	class BS_CORE_EXPORT ProfilerCPU : public Module<ProfilerCPU>
-	{
-		/**	Timer class responsible for tracking elapsed time. */
-		class Timer
-		{
-		public:
-			Timer();
-
-			/** Sets the start time for the timer. */
-			void start();
-
-			/** Stops the timer and calculates the elapsed time from start time to now. */
-			void stop();
-
-			/**	Resets the elapsed time to zero. */
-			void reset();
-
-			double time;
-		private:
-			double startTime;
-
-			/**	Returns time elapsed since CPU was started in millseconds. */
-			static inline double getCurrentTime();
-		};
-
-		/**	Timer class responsible for tracking number of elapsed CPU cycles. */
-		class TimerPrecise
-		{
-		public:
-			TimerPrecise();
-
-			/** Starts the counter marking the current number of executed CPU cycles since CPU was started. */
-			void start();
-
-			/** Ends the counter and calculates the number of CPU cycles between now and the start time. */
-			void stop();
-
-			/**	Resets the cycle count to zero. */
-			void reset();
-
-			UINT64 cycles;
-		private:
-			UINT64 startCycles;
-
-			/** Queries the CPU for the current number of CPU cycles executed since the program was started. */
-			static inline UINT64 getNumCycles();
-		};
-
-		/**
-		 * Contains data about a single profiler sample (counting time in milliseconds).
-		 *	
-		 * @note	
-		 * A sample is created whenever a named profile block is entered. e.g. if you have a function you are profiling, 
-		 * and it gets called 10 times, there will be 10 samples.
-		 */
-		struct ProfileSample
-		{
-			ProfileSample(double _time, UINT64 _numAllocs, UINT64 _numFrees)
-				:time(_time), numAllocs(_numAllocs), numFrees(_numFrees)
-			{ }
-
-			double time;
-			UINT64 numAllocs;
-			UINT64 numFrees;
-		};
-
-		/**
-		 * Contains data about a single precise profiler sample (counting CPU cycles).
-		 *
-		 * @note	
-		 * A sample is created whenever a named profile block is entered. e.g. if you have a function you are profiling, 
-		 * and it gets called 10 times, there will be 10 samples.
-		 */
-		struct PreciseProfileSample
-		{
-			PreciseProfileSample(UINT64 _cycles, UINT64 _numAllocs, UINT64 _numFrees)
-				:cycles(_cycles), numAllocs(_numAllocs), numFrees(_numFrees)
-			{ }
-
-			UINT64 cycles;
-			UINT64 numAllocs;
-			UINT64 numFrees;
-		};
-
-		/**	Contains basic (time based) profiling data contained in a profiling block. */
-		struct ProfileData
-		{
-			ProfileData(FrameAlloc* alloc);
-
-			/** Begins a new sample and records current sample state. Previous sample must not be active. */
-			void beginSample();
-
-			/**
-			 * Records current sample state and creates a new sample based on start and end state. Adds the sample to the 
-			 * sample list.
-			 */
-			void endSample();
-
-			/**
-			 * Removes the last added sample from the sample list and makes it active again. You must call endSample() 
-			 * when done as if you called beginSample().
-			 */
-			void resumeLastSample();
-
-			Vector<ProfileSample, StdFrameAlloc<ProfileSample>> samples;
-			Timer timer;
-
-			UINT64 memAllocs;
-			UINT64 memFrees;
-		};
-
-		/**	Contains precise (CPU cycle based) profiling data contained in a profiling block. */
-		struct PreciseProfileData
-		{
-			PreciseProfileData(FrameAlloc* alloc);
-
-			/** Begins a new sample and records current sample state. Previous sample must not be active. */
-			void beginSample();
-
-			/**
-			 * Records current sample state and creates a new sample based on start and end state. Adds the sample to the 
-			 * sample list.
-			 */
-			void endSample();
-
-			/**
-			 * Removes the last added sample from the sample list and makes it active again. You must call endSample() 
-			 * when done as if you called beginSample.
-			 */
-			void resumeLastSample();
-
-			Vector<PreciseProfileSample, StdFrameAlloc<ProfileSample>> samples;
-			TimerPrecise timer;
-
-			UINT64 memAllocs;
-			UINT64 memFrees;
-		};
-
-		/**
-		 * Contains all sampling information about a single named profiling block. Each block has its own sampling 
-		 * information and optionally child blocks.
-		 */
-		struct ProfiledBlock
-		{
-			ProfiledBlock(FrameAlloc* alloc);
-			~ProfiledBlock();
-
-			/**	Attempts to find a child block with the specified name. Returns null if not found. */
-			ProfiledBlock* findChild(const char* name) const;
-
-			char* name;
-			
-			ProfileData basic;
-			PreciseProfileData precise;
-
-			Vector<ProfiledBlock*, StdFrameAlloc<ProfiledBlock*>> children;
-		};
-
-		/**	CPU sampling type. */
-		enum class ActiveSamplingType
-		{
-			Basic, /**< Sample using milliseconds. */
-			Precise /**< Sample using CPU cycles. */
-		};
-
-		/**	Contains data about the currently active profiling block. */
-		struct ActiveBlock
-		{
-			ActiveBlock()
-				:type(ActiveSamplingType::Basic), block(nullptr)
-			{ }
-
-			ActiveBlock(ActiveSamplingType _type, ProfiledBlock* _block)
-				:type(_type), block(_block)
-			{ }
-
-			ActiveSamplingType type;
-			ProfiledBlock* block;
-		};
-
-		/** Contains data about an active profiling thread. */
-		struct ThreadInfo
-		{
-			ThreadInfo();
-
-			/**
-			 * Starts profiling on the thread. New primary profiling block is created with the given name.
-			 */
-			void begin(const char* _name);
-
-			/**
-			 * Ends profiling on the thread. You should end all samples before calling this, but if you don't they will be 
-			 * terminated automatically.
-			 */
-			void end();
-
-			/**
-			 * 	Deletes all internal profiling data and makes the object ready for another iteration. Should be called 
-			 * after end in order to delete any existing data.
-			 */
-			void reset();
-
-			/**	Gets the primary profiling block used by the thread. */
-			ProfiledBlock* getBlock(const char* name);
-			
-			/** Deletes the provided block. */
-			void releaseBlock(ProfiledBlock* block);
-
-			static BS_THREADLOCAL ThreadInfo* activeThread;
-			bool isActive;
-
-			ProfiledBlock* rootBlock;
-
-			FrameAlloc frameAlloc;
-			ActiveBlock activeBlock;
-			Stack<ActiveBlock, StdFrameAlloc<ActiveBlock>>* activeBlocks;
-		};
-
-	public:
-		ProfilerCPU();
-		~ProfilerCPU();
-
-		/**
-		 * Registers a new thread we will be doing sampling in. This needs to be called before any beginSample*\endSample* 
-		 * calls are made in that thread.
-		 *
-		 * @param[in]	name	Name that will allow you to more easily identify the thread.
-		 */
-		void beginThread(const char* name);
-
-		/**	Ends sampling for the current thread. No beginSample*\endSample* calls after this point. */
-		void endThread();
-
-		/**
-		 * Begins sample measurement. Must be followed by endSample(). 
-		 *
-		 * @param[in]	name	Unique name for the sample you can later use to find the sampling data.
-		 */
-		void beginSample(const char* name);
-
-		/**
-		 * Ends sample measurement.
-		 *
-		 * @param[in]	name	Unique name for the sample. 
-		 * 					
-		 * @note	
-		 * Unique name is primarily needed to more easily identify mismatched begin/end sample pairs. Otherwise the name in 
-		 * beginSample() would be enough.
-		 */
-		void endSample(const char* name);
-
-		/**
-		 * Begins precise sample measurement. Must be followed by endSamplePrecise(). 
-		 *
-		 * @param[in]	name	Unique name for the sample you can later use to find the sampling data.
-		 * 					
-		 * @note	
-		 * This method uses very precise CPU counters to determine variety of data not provided by standard beginSample(). 
-		 * However due to the way these counters work you should not use this method for larger parts of code. It does not 
-		 * consider context switches so if the OS decides to switch context between measurements you will get invalid data.
-		 */
-		void beginSamplePrecise(const char* name);
-
-		/**
-		 * Ends precise sample measurement.
-		 *
-		 * @param[in]	name	Unique name for the sample. 
-		 * 					
-		 * @note	
-		 * Unique name is primarily needed to more easily identify mismatched begin/end sample pairs. Otherwise the name 
-		 * in beginSamplePrecise() would be enough.
-		 */
-		void endSamplePrecise(const char* name);
-
-		/** Clears all sampling data, and ends any unfinished sampling blocks. */
-		void reset();
-
-		/**
-		 * Generates a report from all previously sampled data.
-		 * 			
-		 * @note	Generating a report will stop all in-progress sampling. You should make sure
-		 * 			you call endSample* manually beforehand so this doesn't have to happen.
-		 */
-		CPUProfilerReport generateReport();
-
-	private:
-		/**
-		 * Calculates overhead that the timing and sampling methods themselves introduce so we might get more accurate 
-		 * measurements when creating reports.
-		 */
-		void estimateTimerOverhead();
-
-	private:
-		double mBasicTimerOverhead;
-		UINT64 mPreciseTimerOverhead;
-
-		double mBasicSamplingOverheadMs;
-		double mPreciseSamplingOverheadMs;
-		UINT64 mBasicSamplingOverheadCycles;
-		UINT64 mPreciseSamplingOverheadCycles;
-
-		ProfilerVector<ThreadInfo*> mActiveThreads;
-		BS_MUTEX(mThreadSync);
-	};
-
-	/** Profiling entry containing information about a single CPU profiling block containing timing information. */
-	struct BS_CORE_EXPORT CPUProfilerBasicSamplingEntry
-	{
-		struct BS_CORE_EXPORT Data
-		{
-			Data();
-
-			String name; /**< Name of the profiling block. */
-			UINT32 numCalls; /**< Number of times the block was entered. */
-
-			UINT64 memAllocs; /**< Number of memory allocations that happened within the block. */
-			UINT64 memFrees; /**< Number of memory deallocations that happened within the block. */
-
-			double avgTimeMs; /**< Average time it took to execute the block, per call. In milliseconds. */
-			double maxTimeMs; /**< Maximum time of a single call in the block. In milliseconds. */
-			double totalTimeMs; /**< Total time the block took, across all calls. In milliseconds. */
-
-			double avgSelfTimeMs; /**< Average time it took to execute the block, per call. Ignores time used by child blocks. In milliseconds. */
-			double totalSelfTimeMs; /**< Total time the block took, across all calls. Ignores time used by child blocks. In milliseconds. */
-
-			double estimatedSelfOverheadMs; /**< Estimated overhead of profiling methods, only for this exact block. In milliseconds. */
-			double estimatedOverheadMs; /**< Estimated overhead of profiling methods for this block and all children. In milliseconds. */
-
-			float pctOfParent; /**< Percent of parent block time this block took to execute. Ranging [0.0, 1.0]. */
-		} data;
-
-		ProfilerVector<CPUProfilerBasicSamplingEntry> childEntries;
-	};
-
-	/**
-	 * Profiling entry containing information about a single CPU profiling block containing CPU cycle count based 
-	 * information.
-	 */
-	struct BS_CORE_EXPORT CPUProfilerPreciseSamplingEntry
-	{
-		struct BS_CORE_EXPORT Data
-		{
-			Data();
-
-			String name; /**< Name of the profiling block. */
-			UINT32 numCalls; /**< Number of times the block was entered. */
-
-			UINT64 memAllocs; /**< Number of memory allocations that happened within the block. */
-			UINT64 memFrees; /**< Number of memory deallocations that happened within the block. */
-
-			UINT64 avgCycles; /**< Average number of cycles it took to execute the block, per call. */
-			UINT64 maxCycles; /**< Maximum number of cycles of a single call in the block. */
-			UINT64 totalCycles; /**< Total number of cycles across all calls in the block. */
-
-			UINT64 avgSelfCycles; /**< Average number of cycles it took to execute the block, per call. Ignores cycles used by child blocks. */
-			UINT64 totalSelfCycles; /**< Total number of cycles across all calls in the block. Ignores time used by child blocks. */
-
-			UINT64 estimatedSelfOverhead; /**< Estimated overhead of profiling methods, only for this exact block. In cycles. */
-			UINT64 estimatedOverhead; /**< Estimated overhead of profiling methods for this block and all children. In cycles. */
-
-			float pctOfParent; /**< Percent of parent block cycles used by this block. Ranging [0.0, 1.0]. */
-		} data;
-
-		ProfilerVector<CPUProfilerPreciseSamplingEntry> childEntries;
-	};
-
-	/** CPU profiling report containing all profiling information for a single profiling session. */
-	class BS_CORE_EXPORT CPUProfilerReport
-	{
-	public:
-		CPUProfilerReport();
-
-		/**
-		 * Returns root entry for the basic (time based) sampling data. Root entry always contains the profiling block 
-		 * associated with the entire thread.
-		 */
-		const CPUProfilerBasicSamplingEntry& getBasicSamplingData() const { return mBasicSamplingRootEntry; }
-
-		/**
-		 * Returns root entry for the precise (CPU cycle based) sampling data. Root entry always contains the profiling 
-		 * block associated with the entire thread.
-		 */
-		const CPUProfilerPreciseSamplingEntry& getPreciseSamplingData() const { return mPreciseSamplingRootEntry; }
-
-	private:
-		friend class ProfilerCPU;
-
-		CPUProfilerBasicSamplingEntry mBasicSamplingRootEntry;
-		CPUProfilerPreciseSamplingEntry mPreciseSamplingRootEntry;
-	};
-
-	/** Easier way to access ProfilerCPU. */
-	BS_CORE_EXPORT ProfilerCPU& gProfilerCPU();
-
-	/** Shortcut for profiling a single function call. */
-#define PROFILE_CALL(call, name)							\
-	BansheeEngine::gProfilerCPU().beginSample(##name##);	\
-	call;													\
-	BansheeEngine::gProfilerCPU().endSample(##name##);
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsModule.h"
+#include "BsFrameAlloc.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Profiling
+	 *  @{
+	 */
+
+	class CPUProfilerReport;
+
+	/**
+	 * Provides various performance measuring methods.
+	 * 			
+	 * @note	Thread safe. Matching begin*\end* calls must belong to the same thread though.
+	 */
+	class BS_CORE_EXPORT ProfilerCPU : public Module<ProfilerCPU>
+	{
+		/**	Timer class responsible for tracking elapsed time. */
+		class Timer
+		{
+		public:
+			Timer();
+
+			/** Sets the start time for the timer. */
+			void start();
+
+			/** Stops the timer and calculates the elapsed time from start time to now. */
+			void stop();
+
+			/**	Resets the elapsed time to zero. */
+			void reset();
+
+			double time;
+		private:
+			double startTime;
+
+			/**	Returns time elapsed since CPU was started in millseconds. */
+			static inline double getCurrentTime();
+		};
+
+		/**	Timer class responsible for tracking number of elapsed CPU cycles. */
+		class TimerPrecise
+		{
+		public:
+			TimerPrecise();
+
+			/** Starts the counter marking the current number of executed CPU cycles since CPU was started. */
+			void start();
+
+			/** Ends the counter and calculates the number of CPU cycles between now and the start time. */
+			void stop();
+
+			/**	Resets the cycle count to zero. */
+			void reset();
+
+			UINT64 cycles;
+		private:
+			UINT64 startCycles;
+
+			/** Queries the CPU for the current number of CPU cycles executed since the program was started. */
+			static inline UINT64 getNumCycles();
+		};
+
+		/**
+		 * Contains data about a single profiler sample (counting time in milliseconds).
+		 *	
+		 * @note	
+		 * A sample is created whenever a named profile block is entered. For example if you have a function you are
+		 * profiling, and it gets called 10 times, there will be 10 samples.
+		 */
+		struct ProfileSample
+		{
+			ProfileSample(double _time, UINT64 _numAllocs, UINT64 _numFrees)
+				:time(_time), numAllocs(_numAllocs), numFrees(_numFrees)
+			{ }
+
+			double time;
+			UINT64 numAllocs;
+			UINT64 numFrees;
+		};
+
+		/**
+		 * Contains data about a single precise profiler sample (counting CPU cycles).
+		 *
+		 * @note	
+		 * A sample is created whenever a named profile block is entered. For example if you have a function you are
+		 * profiling, and it gets called 10 times, there will be 10 samples.
+		 */
+		struct PreciseProfileSample
+		{
+			PreciseProfileSample(UINT64 _cycles, UINT64 _numAllocs, UINT64 _numFrees)
+				:cycles(_cycles), numAllocs(_numAllocs), numFrees(_numFrees)
+			{ }
+
+			UINT64 cycles;
+			UINT64 numAllocs;
+			UINT64 numFrees;
+		};
+
+		/**	Contains basic (time based) profiling data contained in a profiling block. */
+		struct ProfileData
+		{
+			ProfileData(FrameAlloc* alloc);
+
+			/** Begins a new sample and records current sample state. Previous sample must not be active. */
+			void beginSample();
+
+			/**
+			 * Records current sample state and creates a new sample based on start and end state. Adds the sample to the 
+			 * sample list.
+			 */
+			void endSample();
+
+			/**
+			 * Removes the last added sample from the sample list and makes it active again. You must call endSample() 
+			 * when done as if you called beginSample().
+			 */
+			void resumeLastSample();
+
+			Vector<ProfileSample, StdFrameAlloc<ProfileSample>> samples;
+			Timer timer;
+
+			UINT64 memAllocs;
+			UINT64 memFrees;
+		};
+
+		/**	Contains precise (CPU cycle based) profiling data contained in a profiling block. */
+		struct PreciseProfileData
+		{
+			PreciseProfileData(FrameAlloc* alloc);
+
+			/** Begins a new sample and records current sample state. Previous sample must not be active. */
+			void beginSample();
+
+			/**
+			 * Records current sample state and creates a new sample based on start and end state. Adds the sample to the 
+			 * sample list.
+			 */
+			void endSample();
+
+			/**
+			 * Removes the last added sample from the sample list and makes it active again. You must call endSample() 
+			 * when done as if you called beginSample.
+			 */
+			void resumeLastSample();
+
+			Vector<PreciseProfileSample, StdFrameAlloc<ProfileSample>> samples;
+			TimerPrecise timer;
+
+			UINT64 memAllocs;
+			UINT64 memFrees;
+		};
+
+		/**
+		 * Contains all sampling information about a single named profiling block. Each block has its own sampling 
+		 * information and optionally child blocks.
+		 */
+		struct ProfiledBlock
+		{
+			ProfiledBlock(FrameAlloc* alloc);
+			~ProfiledBlock();
+
+			/**	Attempts to find a child block with the specified name. Returns null if not found. */
+			ProfiledBlock* findChild(const char* name) const;
+
+			char* name;
+			
+			ProfileData basic;
+			PreciseProfileData precise;
+
+			Vector<ProfiledBlock*, StdFrameAlloc<ProfiledBlock*>> children;
+		};
+
+		/**	CPU sampling type. */
+		enum class ActiveSamplingType
+		{
+			Basic, /**< Sample using milliseconds. */
+			Precise /**< Sample using CPU cycles. */
+		};
+
+		/**	Contains data about the currently active profiling block. */
+		struct ActiveBlock
+		{
+			ActiveBlock()
+				:type(ActiveSamplingType::Basic), block(nullptr)
+			{ }
+
+			ActiveBlock(ActiveSamplingType _type, ProfiledBlock* _block)
+				:type(_type), block(_block)
+			{ }
+
+			ActiveSamplingType type;
+			ProfiledBlock* block;
+		};
+
+		/** Contains data about an active profiling thread. */
+		struct ThreadInfo
+		{
+			ThreadInfo();
+
+			/**
+			 * Starts profiling on the thread. New primary profiling block is created with the given name.
+			 */
+			void begin(const char* _name);
+
+			/**
+			 * Ends profiling on the thread. You should end all samples before calling this, but if you don't they will be 
+			 * terminated automatically.
+			 */
+			void end();
+
+			/**
+			 * 	Deletes all internal profiling data and makes the object ready for another iteration. Should be called 
+			 * after end in order to delete any existing data.
+			 */
+			void reset();
+
+			/**	Gets the primary profiling block used by the thread. */
+			ProfiledBlock* getBlock(const char* name);
+			
+			/** Deletes the provided block. */
+			void releaseBlock(ProfiledBlock* block);
+
+			static BS_THREADLOCAL ThreadInfo* activeThread;
+			bool isActive;
+
+			ProfiledBlock* rootBlock;
+
+			FrameAlloc frameAlloc;
+			ActiveBlock activeBlock;
+			Stack<ActiveBlock, StdFrameAlloc<ActiveBlock>>* activeBlocks;
+		};
+
+	public:
+		ProfilerCPU();
+		~ProfilerCPU();
+
+		/**
+		 * Registers a new thread we will be doing sampling in. This needs to be called before any beginSample*\endSample* 
+		 * calls are made in that thread.
+		 *
+		 * @param[in]	name	Name that will allow you to more easily identify the thread.
+		 */
+		void beginThread(const char* name);
+
+		/**	Ends sampling for the current thread. No beginSample*\endSample* calls after this point. */
+		void endThread();
+
+		/**
+		 * Begins sample measurement. Must be followed by endSample(). 
+		 *
+		 * @param[in]	name	Unique name for the sample you can later use to find the sampling data.
+		 */
+		void beginSample(const char* name);
+
+		/**
+		 * Ends sample measurement.
+		 *
+		 * @param[in]	name	Unique name for the sample. 
+		 * 					
+		 * @note	
+		 * Unique name is primarily needed to more easily identify mismatched begin/end sample pairs. Otherwise the name in 
+		 * beginSample() would be enough.
+		 */
+		void endSample(const char* name);
+
+		/**
+		 * Begins precise sample measurement. Must be followed by endSamplePrecise(). 
+		 *
+		 * @param[in]	name	Unique name for the sample you can later use to find the sampling data.
+		 * 					
+		 * @note	
+		 * This method uses very precise CPU counters to determine variety of data not provided by standard beginSample(). 
+		 * However due to the way these counters work you should not use this method for larger parts of code. It does not 
+		 * consider context switches so if the OS decides to switch context between measurements you will get invalid data.
+		 */
+		void beginSamplePrecise(const char* name);
+
+		/**
+		 * Ends precise sample measurement.
+		 *
+		 * @param[in]	name	Unique name for the sample. 
+		 * 					
+		 * @note	
+		 * Unique name is primarily needed to more easily identify mismatched begin/end sample pairs. Otherwise the name 
+		 * in beginSamplePrecise() would be enough.
+		 */
+		void endSamplePrecise(const char* name);
+
+		/** Clears all sampling data, and ends any unfinished sampling blocks. */
+		void reset();
+
+		/**
+		 * Generates a report from all previously sampled data.
+		 * 			
+		 * @note	Generating a report will stop all in-progress sampling. You should make sure
+		 * 			you call endSample* manually beforehand so this doesn't have to happen.
+		 */
+		CPUProfilerReport generateReport();
+
+	private:
+		/**
+		 * Calculates overhead that the timing and sampling methods themselves introduce so we might get more accurate 
+		 * measurements when creating reports.
+		 */
+		void estimateTimerOverhead();
+
+	private:
+		double mBasicTimerOverhead;
+		UINT64 mPreciseTimerOverhead;
+
+		double mBasicSamplingOverheadMs;
+		double mPreciseSamplingOverheadMs;
+		UINT64 mBasicSamplingOverheadCycles;
+		UINT64 mPreciseSamplingOverheadCycles;
+
+		ProfilerVector<ThreadInfo*> mActiveThreads;
+		BS_MUTEX(mThreadSync);
+	};
+
+	/** Profiling entry containing information about a single CPU profiling block containing timing information. */
+	struct BS_CORE_EXPORT CPUProfilerBasicSamplingEntry
+	{
+		struct BS_CORE_EXPORT Data
+		{
+			Data();
+
+			String name; /**< Name of the profiling block. */
+			UINT32 numCalls; /**< Number of times the block was entered. */
+
+			UINT64 memAllocs; /**< Number of memory allocations that happened within the block. */
+			UINT64 memFrees; /**< Number of memory deallocations that happened within the block. */
+
+			double avgTimeMs; /**< Average time it took to execute the block, per call. In milliseconds. */
+			double maxTimeMs; /**< Maximum time of a single call in the block. In milliseconds. */
+			double totalTimeMs; /**< Total time the block took, across all calls. In milliseconds. */
+
+			double avgSelfTimeMs; /**< Average time it took to execute the block, per call. Ignores time used by child blocks. In milliseconds. */
+			double totalSelfTimeMs; /**< Total time the block took, across all calls. Ignores time used by child blocks. In milliseconds. */
+
+			double estimatedSelfOverheadMs; /**< Estimated overhead of profiling methods, only for this exact block. In milliseconds. */
+			double estimatedOverheadMs; /**< Estimated overhead of profiling methods for this block and all children. In milliseconds. */
+
+			float pctOfParent; /**< Percent of parent block time this block took to execute. Ranging [0.0, 1.0]. */
+		} data;
+
+		ProfilerVector<CPUProfilerBasicSamplingEntry> childEntries;
+	};
+
+	/**
+	 * Profiling entry containing information about a single CPU profiling block containing CPU cycle count based 
+	 * information.
+	 */
+	struct BS_CORE_EXPORT CPUProfilerPreciseSamplingEntry
+	{
+		struct BS_CORE_EXPORT Data
+		{
+			Data();
+
+			String name; /**< Name of the profiling block. */
+			UINT32 numCalls; /**< Number of times the block was entered. */
+
+			UINT64 memAllocs; /**< Number of memory allocations that happened within the block. */
+			UINT64 memFrees; /**< Number of memory deallocations that happened within the block. */
+
+			UINT64 avgCycles; /**< Average number of cycles it took to execute the block, per call. */
+			UINT64 maxCycles; /**< Maximum number of cycles of a single call in the block. */
+			UINT64 totalCycles; /**< Total number of cycles across all calls in the block. */
+
+			UINT64 avgSelfCycles; /**< Average number of cycles it took to execute the block, per call. Ignores cycles used by child blocks. */
+			UINT64 totalSelfCycles; /**< Total number of cycles across all calls in the block. Ignores time used by child blocks. */
+
+			UINT64 estimatedSelfOverhead; /**< Estimated overhead of profiling methods, only for this exact block. In cycles. */
+			UINT64 estimatedOverhead; /**< Estimated overhead of profiling methods for this block and all children. In cycles. */
+
+			float pctOfParent; /**< Percent of parent block cycles used by this block. Ranging [0.0, 1.0]. */
+		} data;
+
+		ProfilerVector<CPUProfilerPreciseSamplingEntry> childEntries;
+	};
+
+	/** CPU profiling report containing all profiling information for a single profiling session. */
+	class BS_CORE_EXPORT CPUProfilerReport
+	{
+	public:
+		CPUProfilerReport();
+
+		/**
+		 * Returns root entry for the basic (time based) sampling data. Root entry always contains the profiling block 
+		 * associated with the entire thread.
+		 */
+		const CPUProfilerBasicSamplingEntry& getBasicSamplingData() const { return mBasicSamplingRootEntry; }
+
+		/**
+		 * Returns root entry for the precise (CPU cycle based) sampling data. Root entry always contains the profiling 
+		 * block associated with the entire thread.
+		 */
+		const CPUProfilerPreciseSamplingEntry& getPreciseSamplingData() const { return mPreciseSamplingRootEntry; }
+
+	private:
+		friend class ProfilerCPU;
+
+		CPUProfilerBasicSamplingEntry mBasicSamplingRootEntry;
+		CPUProfilerPreciseSamplingEntry mPreciseSamplingRootEntry;
+	};
+
+	/** Easier way to access ProfilerCPU. */
+	BS_CORE_EXPORT ProfilerCPU& gProfilerCPU();
+
+	/** Shortcut for profiling a single function call. */
+#define PROFILE_CALL(call, name)							\
+	BansheeEngine::gProfilerCPU().beginSample(##name##);	\
+	call;													\
+	BansheeEngine::gProfilerCPU().endSample(##name##);
+
+	/** @} */
 }

+ 181 - 179
Source/BansheeCore/Include/BsProfilerGPU.h

@@ -1,180 +1,182 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsModule.h"
-#include "BsRenderStats.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Profiling
-	 *  @{
-	 */
-
-	/** Contains various profiler statistics about a single GPU profiling sample. */
-	struct GPUProfileSample
-	{
-		String name; /**< Name of the sample for easier identification. */
-		float timeMs; /**< Time in milliseconds it took to execute the sampled block. */
-
-		UINT32 numDrawCalls; /**< Number of draw calls that happened. */
-		UINT32 numRenderTargetChanges; /**< How many times was render target changed. */
-		UINT32 numPresents; /**< How many times did a buffer swap happen on a double buffered render target. */
-		UINT32 numClears; /**< How many times was render target cleared. */
-
-		UINT32 numVertices; /**< Total number of vertices sent to the GPU. */
-		UINT32 numPrimitives; /**< Total number of primitives sent to the GPU. */
-		UINT32 numDrawnSamples; /**< Number of samples drawn by the GPU. */
-
-		UINT32 numBlendStateChanges; /**< How many times did the blend state change. */
-		UINT32 numRasterizerStateChanges; /**< How many times did the rasterizer state change. */
-		UINT32 numDepthStencilStateChanges; /**< How many times did the depth stencil state change. */
-
-		UINT32 numTextureBinds; /**< How many times was a texture bound. */
-		UINT32 numSamplerBinds; /**< How many times was a sampler bound. */
-		UINT32 numVertexBufferBinds; /**< How many times was a vertex buffer bound. */
-		UINT32 numIndexBufferBinds; /**< How many times was an index buffer bound. */
-		UINT32 numGpuParamBufferBinds; /**< How many times was an GPU parameter buffer bound. */
-		UINT32 numGpuProgramBinds; /**< How many times was a GPU program bound. */
-
-		UINT32 numResourceWrites; /**< How many times were GPU resources written to. */
-		UINT32 numResourceReads; /**< How many times were GPU resources read from. */
-
-		UINT32 numObjectsCreated; /**< How many GPU objects were created. */
-		UINT32 numObjectsDestroyed; /**< How many GPU objects were destroyed. */
-	};
-
-	/** Profiler report containing information about GPU sampling data from a single frame. */
-	struct GPUProfilerReport
-	{
-		GPUProfileSample frameSample; /**< Sample containing data for entire frame. */
-		Vector<GPUProfileSample> samples;
-	};
-
-	/**
-	 * Profiler that measures time and amount of various GPU operations.
-	 *
-	 * @note	Core thread only except where noted otherwise.
-	 */
-	class BS_CORE_EXPORT ProfilerGPU : public Module<ProfilerGPU>
-	{
-	private:
-		struct ActiveSample
-		{
-			ProfilerString sampleName;
-			RenderStatsData startStats;
-			RenderStatsData endStats;
-			TimerQueryPtr activeTimeQuery;
-			OcclusionQueryPtr activeOcclusionQuery;
-		};
-
-		struct ActiveFrame
-		{
-			ActiveSample frameSample;
-			Vector<ActiveSample> samples;
-		};
-
-	public:
-		ProfilerGPU();
-
-		/**
-		 * Signals a start of a new frame. Every frame will generate a separate profiling report. This call must be followed
-		 * by endFrame(), and any sampling operations must happen between beginFrame() and endFrame().
-		 */
-		void beginFrame();
-
-		/**
-		 * Signals an end of the currently sampled frame. Results of the sampling will be available once 
-		 * getNumAvailableReports increments. This may take a while as the sampling is scheduled on the core thread and 
-		 * on the GPU.
-		 */
-		void endFrame();
-
-		/**
-		 * Begins sample measurement. Must be followed by endSample().
-		 *
-		 * @param[in]	name	Unique name for the sample you can later use to find the sampling data.
-		 *
-		 * @note	Must be called between beginFrame()/endFrame() calls.
-		 */
-		void beginSample(const ProfilerString& name);
-
-		/**
-		 * Ends sample measurement.
-		 *
-		 * @param[in]	name	Unique name for the sample.
-		 *
-		 * @note	
-		 * Unique name is primarily needed to more easily identify mismatched begin/end sample pairs. Otherwise the name in 
-		 * beginSample() would be enough. Must be called between beginFrame()/endFrame() calls.
-		 */
-		void endSample(const ProfilerString& name);
-
-		/**
-		 * Returns number of profiling reports that are ready but haven't been retrieved yet. 
-		 *
-		 * @note	
-		 * There is an internal limit of maximum number of available reports, where oldest ones will get deleted so make 
-		 * sure to call this often if you don't want to miss some.
-		 * @note
-		 * Thread safe.
-		 */
-		UINT32 getNumAvailableReports();
-
-		/**
-		 * Gets the oldest report available and removes it from the internal list. Throws an exception if no reports are 
-		 * available.
-		 *
-		 * @note	Thread safe.
-		 */
-		GPUProfilerReport getNextReport();
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * To be called once per frame from the Core thread.
-		 */
-		void _update();
-
-		/** @endcond */
-
-	private:
-		/** Assigns start values for the provided sample. */
-		void beginSampleInternal(ActiveSample& sample);
-
-		/**	Assigns end values for the provided sample. */
-		void endSampleInternal(ActiveSample& sample);
-
-		/**	Creates a new timer query or returns an existing free query. */
-		TimerQueryPtr getTimerQuery() const;
-
-		/**	Creates a new occlusion query or returns an existing free query. */
-		OcclusionQueryPtr getOcclusionQuery() const;
-
-		/**
-		 * Interprets the active frame results and generates a profiler report for the frame. Provided frame queries must 
-		 * have finished before calling this.
-		 */
-		GPUProfilerReport resolveFrame(ActiveFrame& frame);
-
-		/** Resolves an active sample and converts it to report sample. */
-		void resolveSample(const ActiveSample& sample, GPUProfileSample& reportSample);
-
-	private:
-		ActiveFrame mActiveFrame;
-		bool mIsFrameActive;
-		Stack<UINT32> mActiveSampleIndexes;
-
-		Queue<ActiveFrame> mUnresolvedFrames;
-		Queue<GPUProfilerReport> mReadyReports;
-
-		mutable Stack<TimerQueryPtr> mFreeTimerQueries;
-		mutable Stack<OcclusionQueryPtr> mFreeOcclusionQueries;
-
-		BS_MUTEX(mMutex);
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsModule.h"
+#include "BsRenderStats.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Profiling
+	 *  @{
+	 */
+
+	/** Contains various profiler statistics about a single GPU profiling sample. */
+	struct GPUProfileSample
+	{
+		String name; /**< Name of the sample for easier identification. */
+		float timeMs; /**< Time in milliseconds it took to execute the sampled block. */
+
+		UINT32 numDrawCalls; /**< Number of draw calls that happened. */
+		UINT32 numRenderTargetChanges; /**< How many times was render target changed. */
+		UINT32 numPresents; /**< How many times did a buffer swap happen on a double buffered render target. */
+		UINT32 numClears; /**< How many times was render target cleared. */
+
+		UINT32 numVertices; /**< Total number of vertices sent to the GPU. */
+		UINT32 numPrimitives; /**< Total number of primitives sent to the GPU. */
+		UINT32 numDrawnSamples; /**< Number of samples drawn by the GPU. */
+
+		UINT32 numBlendStateChanges; /**< How many times did the blend state change. */
+		UINT32 numRasterizerStateChanges; /**< How many times did the rasterizer state change. */
+		UINT32 numDepthStencilStateChanges; /**< How many times did the depth stencil state change. */
+
+		UINT32 numTextureBinds; /**< How many times was a texture bound. */
+		UINT32 numSamplerBinds; /**< How many times was a sampler bound. */
+		UINT32 numVertexBufferBinds; /**< How many times was a vertex buffer bound. */
+		UINT32 numIndexBufferBinds; /**< How many times was an index buffer bound. */
+		UINT32 numGpuParamBufferBinds; /**< How many times was an GPU parameter buffer bound. */
+		UINT32 numGpuProgramBinds; /**< How many times was a GPU program bound. */
+
+		UINT32 numResourceWrites; /**< How many times were GPU resources written to. */
+		UINT32 numResourceReads; /**< How many times were GPU resources read from. */
+
+		UINT32 numObjectsCreated; /**< How many GPU objects were created. */
+		UINT32 numObjectsDestroyed; /**< How many GPU objects were destroyed. */
+	};
+
+	/** Profiler report containing information about GPU sampling data from a single frame. */
+	struct GPUProfilerReport
+	{
+		GPUProfileSample frameSample; /**< Sample containing data for entire frame. */
+		Vector<GPUProfileSample> samples;
+	};
+
+	/**
+	 * Profiler that measures time and amount of various GPU operations.
+	 *
+	 * @note	Core thread only except where noted otherwise.
+	 */
+	class BS_CORE_EXPORT ProfilerGPU : public Module<ProfilerGPU>
+	{
+	private:
+		struct ActiveSample
+		{
+			ProfilerString sampleName;
+			RenderStatsData startStats;
+			RenderStatsData endStats;
+			TimerQueryPtr activeTimeQuery;
+			OcclusionQueryPtr activeOcclusionQuery;
+		};
+
+		struct ActiveFrame
+		{
+			ActiveSample frameSample;
+			Vector<ActiveSample> samples;
+		};
+
+	public:
+		ProfilerGPU();
+
+		/**
+		 * Signals a start of a new frame. Every frame will generate a separate profiling report. This call must be followed
+		 * by endFrame(), and any sampling operations must happen between beginFrame() and endFrame().
+		 */
+		void beginFrame();
+
+		/**
+		 * Signals an end of the currently sampled frame. Results of the sampling will be available once 
+		 * getNumAvailableReports increments. This may take a while as the sampling is scheduled on the core thread and 
+		 * on the GPU.
+		 */
+		void endFrame();
+
+		/**
+		 * Begins sample measurement. Must be followed by endSample().
+		 *
+		 * @param[in]	name	Unique name for the sample you can later use to find the sampling data.
+		 *
+		 * @note	Must be called between beginFrame()/endFrame() calls.
+		 */
+		void beginSample(const ProfilerString& name);
+
+		/**
+		 * Ends sample measurement.
+		 *
+		 * @param[in]	name	Unique name for the sample.
+		 *
+		 * @note	
+		 * Unique name is primarily needed to more easily identify mismatched begin/end sample pairs. Otherwise the name in 
+		 * beginSample() would be enough. Must be called between beginFrame()/endFrame() calls.
+		 */
+		void endSample(const ProfilerString& name);
+
+		/**
+		 * Returns number of profiling reports that are ready but haven't been retrieved yet. 
+		 *
+		 * @note	
+		 * There is an internal limit of maximum number of available reports, where oldest ones will get deleted so make 
+		 * sure to call this often if you don't want to miss some.
+		 * @note
+		 * Thread safe.
+		 */
+		UINT32 getNumAvailableReports();
+
+		/**
+		 * Gets the oldest report available and removes it from the internal list. Throws an exception if no reports are 
+		 * available.
+		 *
+		 * @note	Thread safe.
+		 */
+		GPUProfilerReport getNextReport();
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * To be called once per frame from the Core thread.
+		 */
+		void _update();
+
+		/** @} */
+
+	private:
+		/** Assigns start values for the provided sample. */
+		void beginSampleInternal(ActiveSample& sample);
+
+		/**	Assigns end values for the provided sample. */
+		void endSampleInternal(ActiveSample& sample);
+
+		/**	Creates a new timer query or returns an existing free query. */
+		TimerQueryPtr getTimerQuery() const;
+
+		/**	Creates a new occlusion query or returns an existing free query. */
+		OcclusionQueryPtr getOcclusionQuery() const;
+
+		/**
+		 * Interprets the active frame results and generates a profiler report for the frame. Provided frame queries must 
+		 * have finished before calling this.
+		 */
+		GPUProfilerReport resolveFrame(ActiveFrame& frame);
+
+		/** Resolves an active sample and converts it to report sample. */
+		void resolveSample(const ActiveSample& sample, GPUProfileSample& reportSample);
+
+	private:
+		ActiveFrame mActiveFrame;
+		bool mIsFrameActive;
+		Stack<UINT32> mActiveSampleIndexes;
+
+		Queue<ActiveFrame> mUnresolvedFrames;
+		Queue<GPUProfilerReport> mReadyReports;
+
+		mutable Stack<TimerQueryPtr> mFreeTimerQueries;
+		mutable Stack<OcclusionQueryPtr> mFreeOcclusionQueries;
+
+		BS_MUTEX(mMutex);
+	};
+
+	/** @} */
 }

+ 224 - 224
Source/BansheeCore/Include/BsRasterizerState.h

@@ -1,225 +1,225 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsIReflectable.h"
-#include "BsCoreObject.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Structure that describes pipeline rasterizer state. Used for initializing a RasterizerState. */
-	struct BS_CORE_EXPORT RASTERIZER_STATE_DESC
-	{
-		RASTERIZER_STATE_DESC()
-			: polygonMode(PM_SOLID)
-			, cullMode(CULL_COUNTERCLOCKWISE)
-			, depthBias(0)
-			, depthBiasClamp(0.0f)
-			, slopeScaledDepthBias(0.0f)
-			, depthClipEnable(true)
-			, scissorEnable(false)
-			, multisampleEnable(true)
-			, antialiasedLineEnable(false)
-		{ }
-
-		bool operator==(const RASTERIZER_STATE_DESC& rhs) const;
-
-		PolygonMode polygonMode;
-		CullingMode cullMode;
-
-		float depthBias;
-		float depthBiasClamp;
-		float slopeScaledDepthBias;
-
-		bool depthClipEnable;
-		bool scissorEnable;
-		bool multisampleEnable;
-		bool antialiasedLineEnable;
-	};
-
-	/** Properties of RasterizerState. Shared between sim and core thread versions of RasterizerState. */
-	class BS_CORE_EXPORT RasterizerProperties
-	{
-	public:
-		RasterizerProperties(const RASTERIZER_STATE_DESC& desc);
-
-		/** Polygon mode allows you to draw polygons as solid objects or as wireframe by just drawing their edges. */
-		PolygonMode getPolygonMode() const { return mData.polygonMode; }
-
-		/**
-		 * Sets vertex winding order. Faces that contain vertices with this order will be culled and not rasterized. Used 
-		 * primarily for saving cycles by not rendering backfacing faces.
-		 */
-		CullingMode getCullMode() const { return mData.cullMode; }
-
-		/**
-		 * Represents a constant depth bias that will offset the depth values of new pixels by the specified amount.
-		 *
-		 * @note		This is useful if you want to avoid z fighting for objects at the same or similar depth.
-		 */
-		float getDepthBias() const { return mData.depthBias; }
-
-		/**	Maximum depth bias value. */
-		float getDepthBiasClamp() const { return mData.depthBiasClamp; }
-
-		/**
-		 * Represents a dynamic depth bias that increases as the slope of the rendered polygons surface increases. 
-		 * Resulting value offsets depth values of new pixels. This offset will be added on top of the constant depth bias.
-		 *
-		 * @note	This is useful if you want to avoid z fighting for objects at the same or similar depth.
-		 */
-		float getSlopeScaledDepthBias() const { return mData.slopeScaledDepthBias; }
-
-		/**
-		 * If true, clipping of polygons past the far Z plane is enabled. This ensures proper Z ordering for polygons 
-		 * outside of valid depth range (otherwise they all have the same depth). It can be useful to disable if you are 
-		 * performing stencil operations that count on objects having a front and a back (like stencil shadow) and don't 
-		 * want to clip the back.
-		 */
-		bool getDepthClipEnable() const { return mData.depthClipEnable; }
-
-		/**
-		 * Scissor rectangle allows you to cull all pixels outside of the scissor rectangle.
-		 *			
-		 * @see		RenderAPICore::setScissorRect
-		 */
-		bool getScissorEnable() const { return mData.scissorEnable; }
-
-		/**
-		 * Determines how are samples in multi-sample render targets handled. If disabled all samples in the render target 
-		 * will be written the same value, and if enabled each sample will be generated separately.
-		 *			
-		 * @note	In order to get an antialiased image you need to both enable this option and use a MSAA render target.
-		 */
-		bool getMultisampleEnable() const { return mData.multisampleEnable; }
-
-		/**
-		 * Determines should the lines be antialiased. This is separate from multi-sample antialiasing setting as lines can
-		 * be antialiased without multi-sampling.
-		 *
-		 * @note	This setting is usually ignored if MSAA is used, as that provides sufficient antialiasing.
-		 */
-		bool getAntialiasedLineEnable() const { return mData.antialiasedLineEnable; }
-
-		/** Returns the hash value generated from the rasterizer state properties. */
-		UINT64 getHash() const { return mHash; }
-
-	protected:
-		friend class RasterizerState;
-		friend class RasterizerStateCore;
-		friend class RasterizerStateRTTI;
-
-		RASTERIZER_STATE_DESC mData;
-		UINT64 mHash;
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Core thread version of RasterizerState.
-	 *
-	 * @note	Core thread.
-	 */
-	class BS_CORE_EXPORT RasterizerStateCore : public CoreObjectCore
-	{
-	public:
-		virtual ~RasterizerStateCore();
-
-		/** Returns information about the rasterizer state. */
-		const RasterizerProperties& getProperties() const;
-
-		/**	Returns a unique state ID. Only the lowest 10 bits are used. */
-		UINT32 getId() const { return mId; }
-
-		/** Returns the default rasterizer state. */
-		static const SPtr<RasterizerStateCore>& getDefault();
-
-	protected:
-		friend class RenderStateCoreManager;
-
-		RasterizerStateCore(const RASTERIZER_STATE_DESC& desc, UINT32 id);
-
-		/** @copydoc CoreObjectCore::initialize */
-		void initialize() override;
-
-		/**	Creates any API-specific state objects. */
-		virtual void createInternal() { }
-
-		RasterizerProperties mProperties;
-		UINT32 mId;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Render system pipeline state that allows you to modify how an object is rasterized. i.e. how are polygons converted
-	 * to pixels.
-	 *
-	 * @note	Rasterizer states are immutable. Sim thread only.
-	 */
-	class BS_CORE_EXPORT RasterizerState : public IReflectable, public CoreObject
-	{
-	public:
-		virtual ~RasterizerState();
-
-		/**	Returns information about the rasterizer state. */
-		const RasterizerProperties& getProperties() const;
-
-		/** Retrieves a core implementation of the rasterizer state usable only from the core thread. */
-		SPtr<RasterizerStateCore> getCore() const;
-
-		/** Creates a new rasterizer state using the specified rasterizer state descriptor structure. */
-		static RasterizerStatePtr create(const RASTERIZER_STATE_DESC& desc);
-
-		/**	Returns the default rasterizer state. */
-		static const RasterizerStatePtr& getDefault();
-
-		/**	Generates a hash value from a rasterizer state descriptor. */
-		static UINT64 generateHash(const RASTERIZER_STATE_DESC& desc);
-
-	protected:
-		friend class RenderStateManager;
-
-		RasterizerState(const RASTERIZER_STATE_DESC& desc);
-		
-		/** @copydoc CoreObjectCore::createCore */
-		SPtr<CoreObjectCore> createCore() const override;
-
-		RasterizerProperties mProperties;
-		mutable UINT32 mId;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-
-	public:
-		friend class RasterizerStateRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;	
-	};
-
-	/** @} */
-}
-
-/** @cond STDLIB */
-/** @addtogroup RenderAPI
- *  @{
- */
-
-/**	Hash value generator for RASTERIZER_STATE_DESC. */
-template<>
-struct std::hash<BansheeEngine::RASTERIZER_STATE_DESC>
-{
-	size_t operator()(const BansheeEngine::RASTERIZER_STATE_DESC& value) const
-	{
-		return (size_t)BansheeEngine::RasterizerState::generateHash(value);
-	}
-};
-
-/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsIReflectable.h"
+#include "BsCoreObject.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Structure that describes pipeline rasterizer state. Used for initializing a RasterizerState. */
+	struct BS_CORE_EXPORT RASTERIZER_STATE_DESC
+	{
+		RASTERIZER_STATE_DESC()
+			: polygonMode(PM_SOLID)
+			, cullMode(CULL_COUNTERCLOCKWISE)
+			, depthBias(0)
+			, depthBiasClamp(0.0f)
+			, slopeScaledDepthBias(0.0f)
+			, depthClipEnable(true)
+			, scissorEnable(false)
+			, multisampleEnable(true)
+			, antialiasedLineEnable(false)
+		{ }
+
+		bool operator==(const RASTERIZER_STATE_DESC& rhs) const;
+
+		PolygonMode polygonMode;
+		CullingMode cullMode;
+
+		float depthBias;
+		float depthBiasClamp;
+		float slopeScaledDepthBias;
+
+		bool depthClipEnable;
+		bool scissorEnable;
+		bool multisampleEnable;
+		bool antialiasedLineEnable;
+	};
+
+	/** Properties of RasterizerState. Shared between sim and core thread versions of RasterizerState. */
+	class BS_CORE_EXPORT RasterizerProperties
+	{
+	public:
+		RasterizerProperties(const RASTERIZER_STATE_DESC& desc);
+
+		/** Polygon mode allows you to draw polygons as solid objects or as wireframe by just drawing their edges. */
+		PolygonMode getPolygonMode() const { return mData.polygonMode; }
+
+		/**
+		 * Sets vertex winding order. Faces that contain vertices with this order will be culled and not rasterized. Used 
+		 * primarily for saving cycles by not rendering backfacing faces.
+		 */
+		CullingMode getCullMode() const { return mData.cullMode; }
+
+		/**
+		 * Represents a constant depth bias that will offset the depth values of new pixels by the specified amount.
+		 *
+		 * @note		This is useful if you want to avoid z fighting for objects at the same or similar depth.
+		 */
+		float getDepthBias() const { return mData.depthBias; }
+
+		/**	Maximum depth bias value. */
+		float getDepthBiasClamp() const { return mData.depthBiasClamp; }
+
+		/**
+		 * Represents a dynamic depth bias that increases as the slope of the rendered polygons surface increases. 
+		 * Resulting value offsets depth values of new pixels. This offset will be added on top of the constant depth bias.
+		 *
+		 * @note	This is useful if you want to avoid z fighting for objects at the same or similar depth.
+		 */
+		float getSlopeScaledDepthBias() const { return mData.slopeScaledDepthBias; }
+
+		/**
+		 * If true, clipping of polygons past the far Z plane is enabled. This ensures proper Z ordering for polygons 
+		 * outside of valid depth range (otherwise they all have the same depth). It can be useful to disable if you are 
+		 * performing stencil operations that count on objects having a front and a back (like stencil shadow) and don't 
+		 * want to clip the back.
+		 */
+		bool getDepthClipEnable() const { return mData.depthClipEnable; }
+
+		/**
+		 * Scissor rectangle allows you to cull all pixels outside of the scissor rectangle.
+		 *			
+		 * @see		RenderAPICore::setScissorRect
+		 */
+		bool getScissorEnable() const { return mData.scissorEnable; }
+
+		/**
+		 * Determines how are samples in multi-sample render targets handled. If disabled all samples in the render target 
+		 * will be written the same value, and if enabled each sample will be generated separately.
+		 *			
+		 * @note	In order to get an antialiased image you need to both enable this option and use a MSAA render target.
+		 */
+		bool getMultisampleEnable() const { return mData.multisampleEnable; }
+
+		/**
+		 * Determines should the lines be antialiased. This is separate from multi-sample antialiasing setting as lines can
+		 * be antialiased without multi-sampling.
+		 *
+		 * @note	This setting is usually ignored if MSAA is used, as that provides sufficient antialiasing.
+		 */
+		bool getAntialiasedLineEnable() const { return mData.antialiasedLineEnable; }
+
+		/** Returns the hash value generated from the rasterizer state properties. */
+		UINT64 getHash() const { return mHash; }
+
+	protected:
+		friend class RasterizerState;
+		friend class RasterizerStateCore;
+		friend class RasterizerStateRTTI;
+
+		RASTERIZER_STATE_DESC mData;
+		UINT64 mHash;
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Core thread version of RasterizerState.
+	 *
+	 * @note	Core thread.
+	 */
+	class BS_CORE_EXPORT RasterizerStateCore : public CoreObjectCore
+	{
+	public:
+		virtual ~RasterizerStateCore();
+
+		/** Returns information about the rasterizer state. */
+		const RasterizerProperties& getProperties() const;
+
+		/**	Returns a unique state ID. Only the lowest 10 bits are used. */
+		UINT32 getId() const { return mId; }
+
+		/** Returns the default rasterizer state. */
+		static const SPtr<RasterizerStateCore>& getDefault();
+
+	protected:
+		friend class RenderStateCoreManager;
+
+		RasterizerStateCore(const RASTERIZER_STATE_DESC& desc, UINT32 id);
+
+		/** @copydoc CoreObjectCore::initialize */
+		void initialize() override;
+
+		/**	Creates any API-specific state objects. */
+		virtual void createInternal() { }
+
+		RasterizerProperties mProperties;
+		UINT32 mId;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Render system pipeline state that allows you to modify how an object is rasterized (how are polygons converted
+	 * to pixels).
+	 *
+	 * @note	Rasterizer states are immutable. Sim thread only.
+	 */
+	class BS_CORE_EXPORT RasterizerState : public IReflectable, public CoreObject
+	{
+	public:
+		virtual ~RasterizerState();
+
+		/**	Returns information about the rasterizer state. */
+		const RasterizerProperties& getProperties() const;
+
+		/** Retrieves a core implementation of the rasterizer state usable only from the core thread. */
+		SPtr<RasterizerStateCore> getCore() const;
+
+		/** Creates a new rasterizer state using the specified rasterizer state descriptor structure. */
+		static RasterizerStatePtr create(const RASTERIZER_STATE_DESC& desc);
+
+		/**	Returns the default rasterizer state. */
+		static const RasterizerStatePtr& getDefault();
+
+		/**	Generates a hash value from a rasterizer state descriptor. */
+		static UINT64 generateHash(const RASTERIZER_STATE_DESC& desc);
+
+	protected:
+		friend class RenderStateManager;
+
+		RasterizerState(const RASTERIZER_STATE_DESC& desc);
+		
+		/** @copydoc CoreObjectCore::createCore */
+		SPtr<CoreObjectCore> createCore() const override;
+
+		RasterizerProperties mProperties;
+		mutable UINT32 mId;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+
+	public:
+		friend class RasterizerStateRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;	
+	};
+
+	/** @} */
+}
+
+/** @cond STDLIB */
+/** @addtogroup RenderAPI
+ *  @{
+ */
+
+/**	Hash value generator for RASTERIZER_STATE_DESC. */
+template<>
+struct std::hash<BansheeEngine::RASTERIZER_STATE_DESC>
+{
+	size_t operator()(const BansheeEngine::RASTERIZER_STATE_DESC& value) const
+	{
+		return (size_t)BansheeEngine::RasterizerState::generateHash(value);
+	}
+};
+
+/** @} */
 /** @endcond */

+ 1 - 1
Source/BansheeCore/Include/BsRenderAPI.h

@@ -373,7 +373,7 @@ namespace BansheeEngine
 			UINT16 stencil = 0, UINT8 targetMask = 0xFF) = 0;
 
 		/**
-		 * Clears the currently active viewport (i.e. it clears just a sub-area of a render-target that is covered by the 
+		 * Clears the currently active viewport (meaning it clears just a sub-area of a render-target that is covered by the 
 		 * viewport, as opposed to clearRenderTarget() which always clears the entire render target).
 		 *
 		 * @param[in]	buffers		Combination of one or more elements of FrameBufferType denoting which buffers are to be

+ 207 - 207
Source/BansheeCore/Include/BsRenderTarget.h

@@ -1,207 +1,207 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPixelUtil.h"
-#include "BsViewport.h"
-#include "BsCoreObject.h"
-#include "BsEvent.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Structure that contains information about what part of the texture represents the render surface. */
-	struct BS_CORE_EXPORT RENDER_SURFACE_DESC
-	{
-		HTexture texture;
-		UINT32 face;
-		UINT32 mipLevel;
-	};
-
-	/**
-	 * @see		RENDER_SURFACE_DESC
-	 *
-	 * @note	References core textures instead of texture handles.
-	 */
-	struct BS_CORE_EXPORT RENDER_SURFACE_CORE_DESC
-	{
-		SPtr<TextureCore> texture;
-		UINT32 face;
-		UINT32 mipLevel;
-	};
-
-	/** Contains various properties that describe a render target. */
-	class BS_CORE_EXPORT RenderTargetProperties
-	{
-	public:
-		virtual ~RenderTargetProperties() { }
-
-		/**
-		 * Returns width of the render target, in pixels.
-		 * 
-		 * @note	Sim thread only.
-		 */
-        UINT32 getWidth() const { return mWidth; }
-
-		/**
-		 * Returns height of the render target, in pixels.
-		 *
-		 * @note	Sim thread only.
-		 */
-        UINT32 getHeight() const { return mHeight; }
-
-		/** Gets the number of samples used for multisampling. (0 or 1 if multisampling is not used). */
-		UINT32 getMultisampleCount() const { return mMultisampleCount; }
-
-		/**
-		 * Returns true if the render target will wait for vertical sync before swapping buffers. This will eliminate 
-		 * tearing but may increase input latency.
-		 */
-		bool getVSync() const { return mVSync; }
-
-		/**
-		 * Returns how often should the frame be presented in respect to display device refresh rate. Normal value is 1 
-		 * where it will match the refresh rate. Higher values will decrease the frame rate (e.g. present interval of 2 on
-		 * 60Hz refresh rate will display at most 30 frames per second).
-		 */
-		UINT32 getVSyncInterval() const { return mVSyncInterval; }
-
-		/** Returns true if pixels written to the render target will be gamma corrected. */
-		bool isHwGammaEnabled() const { return mHwGamma; }
-
-		/**
-		 * Returns true if the render target can be used for rendering.
-		 *
-		 * @note	Core thread only.
-		 */
-		bool isActive() const { return mActive; }
-
-		/**
-		 * Controls in what order is the render target rendered to compared to other render targets. Targets with higher 
-		 * priority will be rendered before ones with lower priority.
-		 */
-		INT32 getPriority() const { return mPriority; }
-
-		/** Returns true if the render target is a render window. */
-		bool isWindow() const { return mIsWindow; }
-
-		/**
-		 * Does the texture need to be vertically flipped because of different screen space coordinate systems.	(i.e. is 
-		 * origin top left or bottom left. Engine default is top left.)
-		 */
-		bool requiresTextureFlipping() const { return mRequiresTextureFlipping; }
-
-	protected:
-		friend class RenderTargetCore;
-		friend class RenderTarget;
-
-		UINT32 mWidth = 0;
-		UINT32 mHeight = 0;
-		UINT32 mColorDepth = 32;
-
-		INT32 mPriority = 0;
-		UINT32 mVSyncInterval = 1;
-
-		bool mActive = true;
-		bool mHwGamma = false;
-		bool mVSync = false;
-		bool mRequiresTextureFlipping = false;
-		bool mIsWindow = false;
-
-		UINT32 mMultisampleCount = 0;
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Provides access to internal render target implementation usable only from the core thread.
-	 *
-	 * @note	Core thread only.
-	 */
-	class BS_CORE_EXPORT RenderTargetCore : public CoreObjectCore
-	{
-	public:
-		/** Frame buffer type when double-buffering is used. */
-		enum FrameBuffer
-		{
-			FB_FRONT,
-			FB_BACK,
-			FB_AUTO
-		};
-
-		RenderTargetCore();
-		virtual ~RenderTargetCore() { }
-
-		/**
-		 * Sets a priority that determines in which orders the render targets the processed.
-		 * 			
-		 * @param[in]	priority	The priority. Higher value means the target will be rendered sooner.
-		 */
-		void setPriority(INT32 priority);
-
-		/** Swaps the frame buffers to display the next frame. */
-		virtual void swapBuffers() {};
-
-		/** Queries the render target for a custom attribute. This may be anything and is implementation specific. */
-		virtual void getCustomAttribute(const String& name, void* pData) const;
-
-		/**	Returns properties that describe the render target. */
-		const RenderTargetProperties& getProperties() const;
-
-	protected:
-		friend class RenderTarget;
-
-		/**	Returns properties that describe the render target. */
-		virtual const RenderTargetProperties& getPropertiesInternal() const = 0;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Render target is a frame buffer or a texture that the render system renders the scene to.
-	 *
-	 * @note	
-	 * Sim thread unless noted otherwise. Retrieve core implementation from getCore() for core thread only functionality.
-	 */
-    class BS_CORE_EXPORT RenderTarget : public CoreObject
-    {
-    public:
-		RenderTarget();
-		virtual ~RenderTarget() { }
-
-		/** Queries the render target for a custom attribute. This may be anything and is implementation specific. */
-		virtual void getCustomAttribute(const String& name, void* pData) const;
-
-		/** @copydoc RenderTargetCore::setPriority */
-		void setPriority(CoreAccessor& accessor, INT32 priority);
-
-		/**
-		 * Returns properties that describe the render target.
-		 *
-		 * @note	Sim thread only.
-		 */
-		const RenderTargetProperties& getProperties() const;
-
-		/** Retrieves a core implementation of a render target usable only from the core thread. */
-		SPtr<RenderTargetCore> getCore() const;
-
-		/**
-		 * Event that gets triggered whenever the render target is resized.
-		 *
-		 * @note	Sim thread only.
-		 */
-		mutable Event<void()> onResized;
-
-    protected:
-		friend class RenderTargetCore;
-
-		/**	Returns properties that describe the render target. */
-		virtual const RenderTargetProperties& getPropertiesInternal() const = 0;
-    };
-
-	/** @} */
-}
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPixelUtil.h"
+#include "BsViewport.h"
+#include "BsCoreObject.h"
+#include "BsEvent.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Structure that contains information about what part of the texture represents the render surface. */
+	struct BS_CORE_EXPORT RENDER_SURFACE_DESC
+	{
+		HTexture texture;
+		UINT32 face;
+		UINT32 mipLevel;
+	};
+
+	/**
+	 * @see		RENDER_SURFACE_DESC
+	 *
+	 * @note	References core textures instead of texture handles.
+	 */
+	struct BS_CORE_EXPORT RENDER_SURFACE_CORE_DESC
+	{
+		SPtr<TextureCore> texture;
+		UINT32 face;
+		UINT32 mipLevel;
+	};
+
+	/** Contains various properties that describe a render target. */
+	class BS_CORE_EXPORT RenderTargetProperties
+	{
+	public:
+		virtual ~RenderTargetProperties() { }
+
+		/**
+		 * Returns width of the render target, in pixels.
+		 * 
+		 * @note	Sim thread only.
+		 */
+        UINT32 getWidth() const { return mWidth; }
+
+		/**
+		 * Returns height of the render target, in pixels.
+		 *
+		 * @note	Sim thread only.
+		 */
+        UINT32 getHeight() const { return mHeight; }
+
+		/** Gets the number of samples used for multisampling. (0 or 1 if multisampling is not used). */
+		UINT32 getMultisampleCount() const { return mMultisampleCount; }
+
+		/**
+		 * Returns true if the render target will wait for vertical sync before swapping buffers. This will eliminate 
+		 * tearing but may increase input latency.
+		 */
+		bool getVSync() const { return mVSync; }
+
+		/**
+		 * Returns how often should the frame be presented in respect to display device refresh rate. Normal value is 1 
+		 * where it will match the refresh rate. Higher values will decrease the frame rate (for example present interval of
+		 * 2 on 60Hz refresh rate will display at most 30 frames per second).
+		 */
+		UINT32 getVSyncInterval() const { return mVSyncInterval; }
+
+		/** Returns true if pixels written to the render target will be gamma corrected. */
+		bool isHwGammaEnabled() const { return mHwGamma; }
+
+		/**
+		 * Returns true if the render target can be used for rendering.
+		 *
+		 * @note	Core thread only.
+		 */
+		bool isActive() const { return mActive; }
+
+		/**
+		 * Controls in what order is the render target rendered to compared to other render targets. Targets with higher 
+		 * priority will be rendered before ones with lower priority.
+		 */
+		INT32 getPriority() const { return mPriority; }
+
+		/** Returns true if the render target is a render window. */
+		bool isWindow() const { return mIsWindow; }
+
+		/**
+		 * Does the texture need to be vertically flipped because of different screen space coordinate systems.	(Determines
+		 * is origin top left or bottom left. Engine default is top left.)
+		 */
+		bool requiresTextureFlipping() const { return mRequiresTextureFlipping; }
+
+	protected:
+		friend class RenderTargetCore;
+		friend class RenderTarget;
+
+		UINT32 mWidth = 0;
+		UINT32 mHeight = 0;
+		UINT32 mColorDepth = 32;
+
+		INT32 mPriority = 0;
+		UINT32 mVSyncInterval = 1;
+
+		bool mActive = true;
+		bool mHwGamma = false;
+		bool mVSync = false;
+		bool mRequiresTextureFlipping = false;
+		bool mIsWindow = false;
+
+		UINT32 mMultisampleCount = 0;
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Provides access to internal render target implementation usable only from the core thread.
+	 *
+	 * @note	Core thread only.
+	 */
+	class BS_CORE_EXPORT RenderTargetCore : public CoreObjectCore
+	{
+	public:
+		/** Frame buffer type when double-buffering is used. */
+		enum FrameBuffer
+		{
+			FB_FRONT,
+			FB_BACK,
+			FB_AUTO
+		};
+
+		RenderTargetCore();
+		virtual ~RenderTargetCore() { }
+
+		/**
+		 * Sets a priority that determines in which orders the render targets the processed.
+		 * 			
+		 * @param[in]	priority	The priority. Higher value means the target will be rendered sooner.
+		 */
+		void setPriority(INT32 priority);
+
+		/** Swaps the frame buffers to display the next frame. */
+		virtual void swapBuffers() {};
+
+		/** Queries the render target for a custom attribute. This may be anything and is implementation specific. */
+		virtual void getCustomAttribute(const String& name, void* pData) const;
+
+		/**	Returns properties that describe the render target. */
+		const RenderTargetProperties& getProperties() const;
+
+	protected:
+		friend class RenderTarget;
+
+		/**	Returns properties that describe the render target. */
+		virtual const RenderTargetProperties& getPropertiesInternal() const = 0;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Render target is a frame buffer or a texture that the render system renders the scene to.
+	 *
+	 * @note	
+	 * Sim thread unless noted otherwise. Retrieve core implementation from getCore() for core thread only functionality.
+	 */
+    class BS_CORE_EXPORT RenderTarget : public CoreObject
+    {
+    public:
+		RenderTarget();
+		virtual ~RenderTarget() { }
+
+		/** Queries the render target for a custom attribute. This may be anything and is implementation specific. */
+		virtual void getCustomAttribute(const String& name, void* pData) const;
+
+		/** @copydoc RenderTargetCore::setPriority */
+		void setPriority(CoreAccessor& accessor, INT32 priority);
+
+		/**
+		 * Returns properties that describe the render target.
+		 *
+		 * @note	Sim thread only.
+		 */
+		const RenderTargetProperties& getProperties() const;
+
+		/** Retrieves a core implementation of a render target usable only from the core thread. */
+		SPtr<RenderTargetCore> getCore() const;
+
+		/**
+		 * Event that gets triggered whenever the render target is resized.
+		 *
+		 * @note	Sim thread only.
+		 */
+		mutable Event<void()> onResized;
+
+    protected:
+		friend class RenderTargetCore;
+
+		/**	Returns properties that describe the render target. */
+		virtual const RenderTargetProperties& getPropertiesInternal() const = 0;
+    };
+
+	/** @} */
+}

+ 301 - 298
Source/BansheeCore/Include/BsRenderWindow.h

@@ -1,298 +1,301 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsRenderTarget.h"
-#include "BsVideoModeInfo.h"
-#include "BsVector2I.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Structure that is used for initializing a render window. */
-	struct BS_CORE_EXPORT RENDER_WINDOW_DESC
-	{
-		RENDER_WINDOW_DESC()
-		: vsync(false), vsyncInterval(1), fullscreen(false), hidden(false), depthBuffer(true)
-			, multisampleCount(0), multisampleHint(""), gamma(false), left(-1), top(-1)
-			, title(""), border(WindowBorder::Normal), outerDimensions(false), enableDoubleClick(true)
-			, toolWindow(false), modal(false), hideUntilSwap(false)
-		{ }
-
-		VideoMode videoMode; /**< A set of frame buffer options. */
-		bool fullscreen; /**< Should the window be opened in fullscreen mode. */
-		bool vsync; /**< Should the window wait for vertical sync before swapping buffers. */
-		UINT32 vsyncInterval; /**< Determines how many vsync intervals occur per frame. FPS = refreshRate/interval. Usually 1 when vsync active. */
-		bool hidden; /**< Should the window be hidden initially. */
-		bool depthBuffer; /**< Should the window be created with a depth/stencil buffer. */
-		UINT32 multisampleCount; /**< If higher than 1, texture containing multiple samples per pixel is created. */
-		String multisampleHint; /**< Hint about what kind of multisampling to use. Render system specific. */
-		bool gamma; /**< Should the written color pixels be gamma corrected before write. */
-		INT32 left; /**< Window origin on X axis in pixels. -1 == screen center. Relative to monitor provided in videoMode. */
-		INT32 top; /**< Window origin on Y axis in pixels. -1 == screen center. Relative to monitor provided in videoMode. */
-		String title; /**< Title of the window. */
-		WindowBorder border; /**< Type of border to create the window with. */
-		bool outerDimensions; /**< Do our dimensions include space for things like title-bar and border. */
-		bool enableDoubleClick; /**< Does window accept double-clicks. */
-		bool toolWindow; /**< Tool windows have a different style than normal windows and can be created with no border or title bar. */
-		bool modal; /**< When a modal window is open all other windows will be locked until modal window is closed. */
-		bool hideUntilSwap; /** < Window will be created as hidden and only be shown when the first framebuffer swap happens. */
-
-		NameValuePairList platformSpecific; /**< Platform-specific creation options. */
-	};
-
-	/**	Contains various properties that describe a render window. */
-	class BS_CORE_EXPORT RenderWindowProperties : public RenderTargetProperties
-	{
-	public:
-		RenderWindowProperties(const RENDER_WINDOW_DESC& desc);
-		virtual ~RenderWindowProperties() { }
-
-		/**	Gets the horizontal origin of the window in pixels. */
-		INT32 getLeft() const { return mLeft; }
-
-		/**	Gets the vertical origin of the window in pixels. */
-		INT32 getTop() const { return mTop; }
-
-		/**	Indicates whether the window currently has keyboard focus. */
-		bool hasFocus() const { return mHasFocus; }
-
-		/**	Returns true if window is running in fullscreen mode. */
-		bool isFullScreen() const { return mIsFullScreen; }
-
-		/**	Returns true if the window is modal (blocks interaction with any non-modal window until closed). */
-		bool isModal() const { return mIsModal; }
-
-		/**	Returns true if the window is hidden. */
-		bool isHidden() const { return mHidden; }
-
-		/**	Returns true if the window is maximized. */
-		bool isMaximized() const { return mIsMaximized; }
-
-	protected:
-		friend class RenderWindowCore;
-		friend class RenderWindow;
-
-		bool mIsFullScreen = false;
-		INT32 mLeft = 0;
-		INT32 mTop = 0;
-		bool mHasFocus = false;
-		bool mHidden = false;
-		bool mIsModal = false;
-		bool mIsMaximized = false;
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Provides access to internal render window implementation usable only from the core thread.
-	 *
-	 * @note	Core thread only.
-	 */
-	class BS_CORE_EXPORT RenderWindowCore : public RenderTargetCore
-	{
-	public:
-		RenderWindowCore(const RENDER_WINDOW_DESC& desc, UINT32 windowId);
-		virtual ~RenderWindowCore();
-
-		/** 
-		 * Switches the window to fullscreen mode. Child windows cannot go into fullscreen mode.
-		 *
-		 * @param[in]	width		Width of the window frame buffer in pixels.
-		 * @param[in]	height		Height of the window frame buffer in pixels.
-		 * @param[in]	refreshRate	Refresh rate of the window in Hertz.
-		 * @param[in]	monitorIdx	Index of the monitor to go fullscreen on.
-		 *
-		 * @note	If the exact provided mode isn't available, closest one is used instead.
-		 */
-		virtual void setFullscreen(UINT32 width, UINT32 height, float refreshRate = 60.0f, UINT32 monitorIdx = 0) { }
-
-		/**
-		 * Switches the window to fullscreen mode. Child windows cannot go into fullscreen mode.
-		 *
-		 * @param[in]	videoMode	Mode retrieved from VideoModeInfo in RenderAPI.
-		 */
-		virtual void setFullscreen(const VideoMode& mode) { }
-
-		/**
-		 * Switches the window to windowed mode.
-		 *
-		 * @param[in]	Window width in pixels.
-		 * @param[in]	Window height in pixels.
-		 */
-		virtual void setWindowed(UINT32 width, UINT32 height) { }
-
-        /**	Hide or show the window. */
-        virtual void setHidden(bool hidden);
-
-		/**	Makes the render target active or inactive. (e.g. for a window, it will hide or restore the window). */
-		virtual void setActive(bool state);
-
-		/**	Minimizes the window to the taskbar. */
-		virtual void minimize() { }
-
-		/**	Maximizes the window over the entire current screen. */
-		virtual void maximize() { }
-
-		/**	Restores the window to original position and size if it is minimized or maximized. */
-		virtual void restore() { }
-
-        /**	Change the size of the window. */
-        virtual void resize(UINT32 width, UINT32 height) = 0;
-
-        /**	Reposition the window. */
-        virtual void move(INT32 left, INT32 top) = 0;
-
-		/**	Returns properties that describe the render window. */
-		const RenderWindowProperties& getProperties() const;
-
-		/**
-		 * Called when window is moved or resized.
-		 *
-		 * @note	Core thread.
-		 */
-		virtual void _windowMovedOrResized();
-
-		/**
-		 * Called when window has received focus.
-		 *
-		 * @note	Core thread.
-		 */
-		virtual void _windowFocusReceived();
-
-		/**
-		 * Called when window has lost focus.
-		 *
-		 * @note	Core thread.
-		 */
-		virtual void _windowFocusLost();
-
-		/**
-		 * Called when window has been maximized.
-		 *
-		 * @note	Core thread.
-		 */
-		virtual void _notifyMaximized();
-
-		/**
-		 * Called when window has been minimized.
-		 *
-		 * @note	Core thread.
-		 */
-		virtual void _notifyMinimized();
-
-		/**
-		 * Called when window has been restored from minimized or maximized state.
-		 *
-		 * @note	Core thread.
-		 */
-		virtual void _notifyRestored();
-
-	protected:
-		friend class RenderWindow;
-		friend class RenderWindowManager;
-		friend class RenderWindowCoreManager;
-
-		/**
-		 * Returns window properties that are always kept in sync between core and sim threads.
-		 *
-		 * @note	Used for keeping up what are the most up to date settings.
-		 */
-		virtual RenderWindowProperties& getSyncedProperties() = 0;
-
-		/** Updates window properties from the synced property data. */
-		virtual void syncProperties() = 0;
-
-		RENDER_WINDOW_DESC mDesc;
-		SpinLock mLock;
-		UINT32 mWindowId;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Render target specialization that allows you to render into window frame buffer(s).
-	 *
-	 * @note	Sim thread only. Retrieve core implementation from getCore() for core thread only functionality.
-	 */
-    class BS_CORE_EXPORT RenderWindow : public RenderTarget
-    {
-    public:
-		virtual ~RenderWindow() { }
-
-		/** @copydoc RenderTarget::destroy */
-		virtual void destroy() override;	
-
-		/**	Converts screen position into window local position. */
-		virtual Vector2I screenToWindowPos(const Vector2I& screenPos) const = 0;
-
-		/**	Converts window local position to screen position. */
-		virtual Vector2I windowToScreenPos(const Vector2I& windowPos) const = 0;
-
-		/**	Resize the window to specified width and height in pixels. */
-		void resize(CoreAccessor& accessor, UINT32 width, UINT32 height);
-
-		/**	Move the window to specified screen coordinates. */
-		void move(CoreAccessor& accessor, INT32 left, INT32 top);
-
-		/**	Hide the window. (Does not destroy it, just hides it). */
-		void hide(CoreAccessor& accessor);
-
-		/**	Shows a previously hidden window. */
-		void show(CoreAccessor& accessor);
-
-		/** @copydoc RenderWindowCore::minimize */
-		void minimize(CoreAccessor& accessor);
-
-		/** @copydoc RenderWindowCore::maximize */
-		void maximize(CoreAccessor& accessor);
-
-		/** @copydoc RenderWindowCore::restore */
-		void restore(CoreAccessor& accessor);
-
-		/** @copydoc RenderWindowCore::setFullscreen(UINT32, UINT32, float, UINT32) */
-		void setFullscreen(CoreAccessor& accessor, UINT32 width, UINT32 height, float refreshRate = 60.0f, UINT32 monitorIdx = 0);
-
-		/** @copydoc RenderWindowCore::setFullscreen(const VideoMode&) */
-		void setFullscreen(CoreAccessor& accessor, const VideoMode& mode);
-
-		/** @copydoc RenderWindowCore::setWindowed */
-		void setWindowed(CoreAccessor& accessor, UINT32 width, UINT32 height);
-
-		/**	Retrieves a core implementation of a render window usable only from the core thread. */
-		SPtr<RenderWindowCore> getCore() const;
-
-		/**	Returns properties that describe the render window. */
-		const RenderWindowProperties& getProperties() const;
-
-		/**
-		 * Creates a new render window using the specified options. Optionally makes the created window a child of another 
-		 * window.
-		 */
-		static RenderWindowPtr create(RENDER_WINDOW_DESC& desc, RenderWindowPtr parentWindow = nullptr);
-
-    protected:
-		friend class RenderWindowManager;
-
-		RenderWindow(const RENDER_WINDOW_DESC& desc, UINT32 windowId);
-
-		/** Returns render window properties that may be edited. */
-		RenderWindowProperties& getMutableProperties();
-
-		/** @copydoc RenderTarget::createCore */
-		SPtr<CoreObjectCore> createCore() const override;
-
-		/**	Updates window properties from the synced property data. */
-		virtual void syncProperties() = 0;
-
-	protected:
-		RENDER_WINDOW_DESC mDesc;
-		UINT32 mWindowId;
-    };
-
-	/** @} */
-}
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsRenderTarget.h"
+#include "BsVideoModeInfo.h"
+#include "BsVector2I.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Structure that is used for initializing a render window. */
+	struct BS_CORE_EXPORT RENDER_WINDOW_DESC
+	{
+		RENDER_WINDOW_DESC()
+		: vsync(false), vsyncInterval(1), fullscreen(false), hidden(false), depthBuffer(true)
+			, multisampleCount(0), multisampleHint(""), gamma(false), left(-1), top(-1)
+			, title(""), border(WindowBorder::Normal), outerDimensions(false), enableDoubleClick(true)
+			, toolWindow(false), modal(false), hideUntilSwap(false)
+		{ }
+
+		VideoMode videoMode; /**< A set of frame buffer options. */
+		bool fullscreen; /**< Should the window be opened in fullscreen mode. */
+		bool vsync; /**< Should the window wait for vertical sync before swapping buffers. */
+		UINT32 vsyncInterval; /**< Determines how many vsync intervals occur per frame. FPS = refreshRate/interval. Usually 1 when vsync active. */
+		bool hidden; /**< Should the window be hidden initially. */
+		bool depthBuffer; /**< Should the window be created with a depth/stencil buffer. */
+		UINT32 multisampleCount; /**< If higher than 1, texture containing multiple samples per pixel is created. */
+		String multisampleHint; /**< Hint about what kind of multisampling to use. Render system specific. */
+		bool gamma; /**< Should the written color pixels be gamma corrected before write. */
+		INT32 left; /**< Window origin on X axis in pixels. -1 == screen center. Relative to monitor provided in videoMode. */
+		INT32 top; /**< Window origin on Y axis in pixels. -1 == screen center. Relative to monitor provided in videoMode. */
+		String title; /**< Title of the window. */
+		WindowBorder border; /**< Type of border to create the window with. */
+		bool outerDimensions; /**< Do our dimensions include space for things like title-bar and border. */
+		bool enableDoubleClick; /**< Does window accept double-clicks. */
+		bool toolWindow; /**< Tool windows have a different style than normal windows and can be created with no border or title bar. */
+		bool modal; /**< When a modal window is open all other windows will be locked until modal window is closed. */
+		bool hideUntilSwap; /** < Window will be created as hidden and only be shown when the first framebuffer swap happens. */
+
+		NameValuePairList platformSpecific; /**< Platform-specific creation options. */
+	};
+
+	/**	Contains various properties that describe a render window. */
+	class BS_CORE_EXPORT RenderWindowProperties : public RenderTargetProperties
+	{
+	public:
+		RenderWindowProperties(const RENDER_WINDOW_DESC& desc);
+		virtual ~RenderWindowProperties() { }
+
+		/**	Gets the horizontal origin of the window in pixels. */
+		INT32 getLeft() const { return mLeft; }
+
+		/**	Gets the vertical origin of the window in pixels. */
+		INT32 getTop() const { return mTop; }
+
+		/**	Indicates whether the window currently has keyboard focus. */
+		bool hasFocus() const { return mHasFocus; }
+
+		/**	Returns true if window is running in fullscreen mode. */
+		bool isFullScreen() const { return mIsFullScreen; }
+
+		/**	Returns true if the window is modal (blocks interaction with any non-modal window until closed). */
+		bool isModal() const { return mIsModal; }
+
+		/**	Returns true if the window is hidden. */
+		bool isHidden() const { return mHidden; }
+
+		/**	Returns true if the window is maximized. */
+		bool isMaximized() const { return mIsMaximized; }
+
+	protected:
+		friend class RenderWindowCore;
+		friend class RenderWindow;
+
+		bool mIsFullScreen = false;
+		INT32 mLeft = 0;
+		INT32 mTop = 0;
+		bool mHasFocus = false;
+		bool mHidden = false;
+		bool mIsModal = false;
+		bool mIsMaximized = false;
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Provides access to internal render window implementation usable only from the core thread.
+	 *
+	 * @note	Core thread only.
+	 */
+	class BS_CORE_EXPORT RenderWindowCore : public RenderTargetCore
+	{
+	public:
+		RenderWindowCore(const RENDER_WINDOW_DESC& desc, UINT32 windowId);
+		virtual ~RenderWindowCore();
+
+		/** 
+		 * Switches the window to fullscreen mode. Child windows cannot go into fullscreen mode.
+		 *
+		 * @param[in]	width		Width of the window frame buffer in pixels.
+		 * @param[in]	height		Height of the window frame buffer in pixels.
+		 * @param[in]	refreshRate	Refresh rate of the window in Hertz.
+		 * @param[in]	monitorIdx	Index of the monitor to go fullscreen on.
+		 *
+		 * @note	If the exact provided mode isn't available, closest one is used instead.
+		 */
+		virtual void setFullscreen(UINT32 width, UINT32 height, float refreshRate = 60.0f, UINT32 monitorIdx = 0) { }
+
+		/**
+		 * Switches the window to fullscreen mode. Child windows cannot go into fullscreen mode.
+		 *
+		 * @param[in]	videoMode	Mode retrieved from VideoModeInfo in RenderAPI.
+		 */
+		virtual void setFullscreen(const VideoMode& mode) { }
+
+		/**
+		 * Switches the window to windowed mode.
+		 *
+		 * @param[in]	Window width in pixels.
+		 * @param[in]	Window height in pixels.
+		 */
+		virtual void setWindowed(UINT32 width, UINT32 height) { }
+
+        /**	Hide or show the window. */
+        virtual void setHidden(bool hidden);
+
+		/**
+		 * Makes the render target active or inactive. (for example in the case of a window, it will hide or restore the
+		 * window). 
+		 */
+		virtual void setActive(bool state);
+
+		/**	Minimizes the window to the taskbar. */
+		virtual void minimize() { }
+
+		/**	Maximizes the window over the entire current screen. */
+		virtual void maximize() { }
+
+		/**	Restores the window to original position and size if it is minimized or maximized. */
+		virtual void restore() { }
+
+        /**	Change the size of the window. */
+        virtual void resize(UINT32 width, UINT32 height) = 0;
+
+        /**	Reposition the window. */
+        virtual void move(INT32 left, INT32 top) = 0;
+
+		/**	Returns properties that describe the render window. */
+		const RenderWindowProperties& getProperties() const;
+
+		/**
+		 * Called when window is moved or resized.
+		 *
+		 * @note	Core thread.
+		 */
+		virtual void _windowMovedOrResized();
+
+		/**
+		 * Called when window has received focus.
+		 *
+		 * @note	Core thread.
+		 */
+		virtual void _windowFocusReceived();
+
+		/**
+		 * Called when window has lost focus.
+		 *
+		 * @note	Core thread.
+		 */
+		virtual void _windowFocusLost();
+
+		/**
+		 * Called when window has been maximized.
+		 *
+		 * @note	Core thread.
+		 */
+		virtual void _notifyMaximized();
+
+		/**
+		 * Called when window has been minimized.
+		 *
+		 * @note	Core thread.
+		 */
+		virtual void _notifyMinimized();
+
+		/**
+		 * Called when window has been restored from minimized or maximized state.
+		 *
+		 * @note	Core thread.
+		 */
+		virtual void _notifyRestored();
+
+	protected:
+		friend class RenderWindow;
+		friend class RenderWindowManager;
+		friend class RenderWindowCoreManager;
+
+		/**
+		 * Returns window properties that are always kept in sync between core and sim threads.
+		 *
+		 * @note	Used for keeping up what are the most up to date settings.
+		 */
+		virtual RenderWindowProperties& getSyncedProperties() = 0;
+
+		/** Updates window properties from the synced property data. */
+		virtual void syncProperties() = 0;
+
+		RENDER_WINDOW_DESC mDesc;
+		SpinLock mLock;
+		UINT32 mWindowId;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Render target specialization that allows you to render into window frame buffer(s).
+	 *
+	 * @note	Sim thread only. Retrieve core implementation from getCore() for core thread only functionality.
+	 */
+    class BS_CORE_EXPORT RenderWindow : public RenderTarget
+    {
+    public:
+		virtual ~RenderWindow() { }
+
+		/** @copydoc RenderTarget::destroy */
+		virtual void destroy() override;	
+
+		/**	Converts screen position into window local position. */
+		virtual Vector2I screenToWindowPos(const Vector2I& screenPos) const = 0;
+
+		/**	Converts window local position to screen position. */
+		virtual Vector2I windowToScreenPos(const Vector2I& windowPos) const = 0;
+
+		/**	Resize the window to specified width and height in pixels. */
+		void resize(CoreAccessor& accessor, UINT32 width, UINT32 height);
+
+		/**	Move the window to specified screen coordinates. */
+		void move(CoreAccessor& accessor, INT32 left, INT32 top);
+
+		/**	Hide the window. (Does not destroy it, just hides it). */
+		void hide(CoreAccessor& accessor);
+
+		/**	Shows a previously hidden window. */
+		void show(CoreAccessor& accessor);
+
+		/** @copydoc RenderWindowCore::minimize */
+		void minimize(CoreAccessor& accessor);
+
+		/** @copydoc RenderWindowCore::maximize */
+		void maximize(CoreAccessor& accessor);
+
+		/** @copydoc RenderWindowCore::restore */
+		void restore(CoreAccessor& accessor);
+
+		/** @copydoc RenderWindowCore::setFullscreen(UINT32, UINT32, float, UINT32) */
+		void setFullscreen(CoreAccessor& accessor, UINT32 width, UINT32 height, float refreshRate = 60.0f, UINT32 monitorIdx = 0);
+
+		/** @copydoc RenderWindowCore::setFullscreen(const VideoMode&) */
+		void setFullscreen(CoreAccessor& accessor, const VideoMode& mode);
+
+		/** @copydoc RenderWindowCore::setWindowed */
+		void setWindowed(CoreAccessor& accessor, UINT32 width, UINT32 height);
+
+		/**	Retrieves a core implementation of a render window usable only from the core thread. */
+		SPtr<RenderWindowCore> getCore() const;
+
+		/**	Returns properties that describe the render window. */
+		const RenderWindowProperties& getProperties() const;
+
+		/**
+		 * Creates a new render window using the specified options. Optionally makes the created window a child of another 
+		 * window.
+		 */
+		static RenderWindowPtr create(RENDER_WINDOW_DESC& desc, RenderWindowPtr parentWindow = nullptr);
+
+    protected:
+		friend class RenderWindowManager;
+
+		RenderWindow(const RENDER_WINDOW_DESC& desc, UINT32 windowId);
+
+		/** Returns render window properties that may be edited. */
+		RenderWindowProperties& getMutableProperties();
+
+		/** @copydoc RenderTarget::createCore */
+		SPtr<CoreObjectCore> createCore() const override;
+
+		/**	Updates window properties from the synced property data. */
+		virtual void syncProperties() = 0;
+
+	protected:
+		RENDER_WINDOW_DESC mDesc;
+		UINT32 mWindowId;
+    };
+
+	/** @} */
+}

+ 401 - 399
Source/BansheeCore/Include/BsResourceHandle.h

@@ -1,400 +1,402 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsIReflectable.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	/** @cond INTERNAL */
-
-	/**	Data that is shared between all resource handles. */
-	struct BS_CORE_EXPORT ResourceHandleData
-	{
-		ResourceHandleData()
-			:mIsCreated(false), mRefCount(0)
-		{ }
-
-		SPtr<Resource> mPtr;
-		String mUUID;
-		bool mIsCreated;	
-		UINT32 mRefCount;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Represents a handle to a resource. Handles are similar to a smart pointers, but they have two advantages:
-	 *	- When loading a resource asynchronously you can be immediately returned the handle that you may use throughout
-	 *    the engine. The handle will be made valid as soon as the resource is loaded.
-	 *	- Handles can be serialized and deserialized, therefore saving/restoring references to their original resource.
-	 */
-	class BS_CORE_EXPORT ResourceHandleBase : public IReflectable
-	{
-	public:
-		virtual ~ResourceHandleBase();
-
-		/**
-		 * Checks if the resource is loaded. Until resource is loaded this handle is invalid and you may not get the 
-		 * internal resource from it.
-		 *
-		 * @param[in]	checkDependencies	If true, and if resource has any dependencies, this method will also check if 
-		 *									they are loaded.
-		 */
-		bool isLoaded(bool checkDependencies = true) const;
-
-		/**
-		 * Blocks the current thread until the resource is fully loaded.
-		 * 			
-		 * @note	Careful not to call this on the thread that does the loading.
-		 */
-		void blockUntilLoaded(bool waitForDependencies = true) const;
-
-		/**
-		 * Releases an internal reference to this resource held by the resources system, if there is one.
-		 * 			
-		 * @see		Resources::release(ResourceHandleBase&)
-		 */
-		void release();
-
-		/** Returns the UUID of the resource the handle is referring to. */
-		const String& getUUID() const { return mData != nullptr ? mData->mUUID : StringUtil::BLANK; }
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**	Gets the handle data. For internal use only. */
-		const SPtr<ResourceHandleData>& getHandleData() const { return mData; }
-
-		/** @endcond */
-	protected:
-		ResourceHandleBase();
-
-		/**	Destroys the resource the handle is pointing to. */
-		void destroy();
-
-		/**
-		 * Sets the created flag to true and assigns the resource pointer. Called by the constructors, or if you 
-		 * constructed just using a UUID, then you need to call this manually before you can access the resource from 
-		 * this handle.
-		 * 			
-		 * @note	
-		 * This is needed because two part construction is required due to  multithreaded nature of resource loading.
-		 * @note
-		 * Internal method.
-		 */
-		void setHandleData(const SPtr<Resource>& ptr, const String& uuid);
-
-		/** Increments the reference count of the handle. Only to be used by Resources for keeping internal references. */
-		void addInternalRef();
-
-		/** Decrements the reference count of the handle. Only to be used by ::Resources for keeping internal references. */
-		void removeInternalRef();
-
-		/** 
-		 * @note	
-		 * All handles to the same source must share this same handle data. Otherwise things like counting number of 
-		 * references or replacing pointed to resource become impossible without additional logic. */
-		SPtr<ResourceHandleData> mData;
-
-	private:
-		friend class Resources;
-
-		BS_STATIC_THREAD_SYNCHRONISER(mResourceCreatedCondition)
-		BS_STATIC_MUTEX(mResourceCreatedMutex)
-
-	protected:
-		inline void throwIfNotLoaded() const;
-	};
-
-	/**
-	 * @copydoc	ResourceHandleBase
-	 *
-	 * Handles differences in reference counting depending if the handle is normal or weak.
-	 */
-	template <bool WeakHandle>
-	class BS_CORE_EXPORT TResourceHandleBase : public ResourceHandleBase { };
-
-	/**	Specialization of TResourceHandleBase for weak handles. Weak handles do no reference counting. */
-	template<>
-	class BS_CORE_EXPORT TResourceHandleBase<true> : public ResourceHandleBase
-	{
-	public:
-		virtual ~TResourceHandleBase() { }
-
-	protected:
-		void addRef() { };
-		void releaseRef() { };
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class WeakResourceHandleRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/**	Specialization of TResourceHandleBase for normal (non-weak) handles. */
-	template<>
-	class BS_CORE_EXPORT TResourceHandleBase<false> : public ResourceHandleBase
-	{
-	public:
-		virtual ~TResourceHandleBase() { }
-
-	protected:
-		void addRef() { if (mData) mData->mRefCount++; };
-		void releaseRef() 
-		{ 
-			if (mData)
-			{
-				mData->mRefCount--;
-
-				if (mData->mRefCount == 0)
-					destroy();
-			}
-		};
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class WeakResourceHandleRTTI;
-		friend class ResourceHandleRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @copydoc ResourceHandleBase */
-	template <typename T, bool WeakHandle>
-	class TResourceHandle : public TResourceHandleBase<WeakHandle>
-	{
-	public:
-		TResourceHandle()
-			:TResourceHandleBase()
-		{ }
-
-		/**	Copy constructor. */
-		TResourceHandle(const TResourceHandle<T, WeakHandle>& ptr)
-			:TResourceHandleBase()
-		{
-			mData = ptr.getHandleData();
-
-			addRef();
-		}
-
-		virtual ~TResourceHandle()
-		{
-			releaseRef();
-		}
-
-		/**	Converts a specific handle to generic Resource handle. */
-		operator TResourceHandle<Resource, WeakHandle>() const
-		{
-			TResourceHandle<Resource, WeakHandle> handle;
-			handle.setHandleData(getHandleData());
-
-			return handle;
-		}
-
-		/**
-		 * Returns internal resource pointer.
-		 *
-		 * @note	Throws exception if handle is invalid.
-		 */
-		T* operator->() const { return get(); }
-
-		/**
-		 * Returns internal resource pointer and dereferences it.
-		 *
-		 * @note	Throws exception if handle is invalid.
-		 */
-		T& operator*() const { return *get(); }
-
-		/** Clears the handle making it invalid and releases any references held to the resource. */
-		TResourceHandle<T, WeakHandle>& operator=(std::nullptr_t ptr)
-		{ 	
-			releaseRef();
-
-			mData = nullptr;
-			return *this;
-		}
-
-		/**	Normal assignment operator. */
-		TResourceHandle<T, WeakHandle>& operator=(const TResourceHandle<T, WeakHandle>& rhs)
-		{ 	
-			setHandleData(rhs.getHandleData());
-			return *this;
-		}
-
-		template<class _Ty>
-		struct Bool_struct
-		{
-			int _Member;
-		};
-
-		/**
-		 * Allows direct conversion of handle to bool.
-		 *
-		 * @note	This is needed because we can't directly convert to bool since then we can assign pointer to bool and 
-		 *			that's weird.
-		 */
-		operator int Bool_struct<T>::*() const
-		{
-			return ((mData != nullptr && !mData->mUUID.empty()) ? &Bool_struct<T>::_Member : 0);
-		}
-
-		/**
-		 * Returns internal resource pointer and dereferences it.
-		 *
-		 * @note	Throws exception if handle is invalid.
-		 */
-		T* get() const 
-		{ 
-			throwIfNotLoaded();
-
-			return reinterpret_cast<T*>(mData->mPtr.get()); 
-		}
-
-		/**
-		 * Returns the internal shared pointer to the resource.
-		 *
-		 * @note	Throws exception if handle is invalid.
-		 */
-		SPtr<T> getInternalPtr() const
-		{ 
-			throwIfNotLoaded();
-
-			return std::static_pointer_cast<T>(mData->mPtr); 
-		}
-
-		/** Converts a handle into a weak handle. */
-		TResourceHandle<T, true> getWeak() const
-		{
-			TResourceHandle<T, true> handle;
-			handle.setHandleData(getHandleData());
-
-			return handle;
-		}
-
-	protected:
-		friend Resources;
-		template<class _T, bool _Weak>
-		friend class TResourceHandle;
-		template<class _Ty1, class _Ty2, bool Weak>
-		friend TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other);
-
-		/**
-		 * Constructs a new valid handle for the provided resource with the provided UUID.
-		 *			
-		 * @note	Handle will take ownership of the provided resource pointer, so make sure you don't delete it elsewhere.
-		 */
-		explicit TResourceHandle(T* ptr, const String& uuid)
-			:TResourceHandleBase()
-		{
-			mData = bs_shared_ptr_new<ResourceHandleData>();
-			addRef();
-
-			setHandleData(std::shared_ptr<Resource>(ptr, uuid));
-		}
-
-		/**
-		 * Constructs an invalid handle with the specified UUID. You must call setHandleData() with the actual resource 
-		 * pointer to make the handle valid.
-		 */
-		TResourceHandle(const String& uuid)
-			:TResourceHandleBase()
-		{
-			mData = bs_shared_ptr_new<ResourceHandleData>();
-			mData->mUUID = uuid;
-
-			addRef();
-		}
-
-		/**	Constructs a new valid handle for the provided resource with the provided UUID. */
-		TResourceHandle(const SPtr<T> ptr, const String& uuid)
-			:TResourceHandleBase()
-		{
-			mData = bs_shared_ptr_new<ResourceHandleData>();
-			addRef();
-
-			setHandleData(ptr, uuid);
-		}
-
-		/**	Replaces the internal handle data pointer, effectively transforming the handle into a different handle. */
-		void setHandleData(const SPtr<ResourceHandleData>& data)
-		{
-			releaseRef();
-			mData = data;
-			addRef();
-		}
-
-		/**	Converts a weak handle into a normal handle. */
-		TResourceHandle<T, false> lock() const
-		{
-			TResourceHandle<Resource, false> handle;
-			handle.setHandleData(getHandleData());
-
-			return handle;
-		}
-
-		using TResourceHandleBase::setHandleData;
-	};
-
-	/**	Checks if two handles point to the same resource. */
-	template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
-	bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right)
-	{	
-		if(_Left.getHandleData() != nullptr && _Right.getHandleData() != nullptr)
-			return _Left.getHandleData()->mPtr == _Right.getHandleData()->mPtr;
-
-		return _Left.getHandleData() == _Right.getHandleData();
-	}
-
-	/**	Checks if a handle is null. */
-	template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
-	bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, std::nullptr_t  _Right)
-	{	
-		return _Left.getHandleData() == nullptr || _Left.getHandleData()->mUUID.empty();
-	}
-
-	template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
-	bool operator!=(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right)
-	{	
-		return (!(_Left == _Right));
-	}
-
-	/** @} */
-
-	/** @addtogroup Resources
-	 *  @{
-	 */
-
-	 /** @copydoc ResourceHandleBase */
-	template <typename T>
-	using ResourceHandle = TResourceHandle<T, false>;
-
-	/** 
-	 * @copydoc ResourceHandleBase 
-	 *
-	 * Weak handles don't prevent the resource from being unloaded.
-	 */
-	template <typename T>
-	using WeakResourceHandle = TResourceHandle<T, true>;
-
-	/**	Casts one resource handle to another. */
-	template<class _Ty1, class _Ty2, bool Weak>
-	TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other)
-	{
-		TResourceHandle<_Ty1, Weak> handle;
-		handle.setHandleData(other.getHandleData());
-
-		return handle;
-	}
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsIReflectable.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	/** @cond INTERNAL */
+
+	/**	Data that is shared between all resource handles. */
+	struct BS_CORE_EXPORT ResourceHandleData
+	{
+		ResourceHandleData()
+			:mIsCreated(false), mRefCount(0)
+		{ }
+
+		SPtr<Resource> mPtr;
+		String mUUID;
+		bool mIsCreated;	
+		UINT32 mRefCount;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Represents a handle to a resource. Handles are similar to a smart pointers, but they have two advantages:
+	 *	- When loading a resource asynchronously you can be immediately returned the handle that you may use throughout
+	 *    the engine. The handle will be made valid as soon as the resource is loaded.
+	 *	- Handles can be serialized and deserialized, therefore saving/restoring references to their original resource.
+	 */
+	class BS_CORE_EXPORT ResourceHandleBase : public IReflectable
+	{
+	public:
+		virtual ~ResourceHandleBase();
+
+		/**
+		 * Checks if the resource is loaded. Until resource is loaded this handle is invalid and you may not get the 
+		 * internal resource from it.
+		 *
+		 * @param[in]	checkDependencies	If true, and if resource has any dependencies, this method will also check if 
+		 *									they are loaded.
+		 */
+		bool isLoaded(bool checkDependencies = true) const;
+
+		/**
+		 * Blocks the current thread until the resource is fully loaded.
+		 * 			
+		 * @note	Careful not to call this on the thread that does the loading.
+		 */
+		void blockUntilLoaded(bool waitForDependencies = true) const;
+
+		/**
+		 * Releases an internal reference to this resource held by the resources system, if there is one.
+		 * 			
+		 * @see		Resources::release(ResourceHandleBase&)
+		 */
+		void release();
+
+		/** Returns the UUID of the resource the handle is referring to. */
+		const String& getUUID() const { return mData != nullptr ? mData->mUUID : StringUtil::BLANK; }
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**	Gets the handle data. For internal use only. */
+		const SPtr<ResourceHandleData>& getHandleData() const { return mData; }
+
+		/** @} */
+	protected:
+		ResourceHandleBase();
+
+		/**	Destroys the resource the handle is pointing to. */
+		void destroy();
+
+		/**
+		 * Sets the created flag to true and assigns the resource pointer. Called by the constructors, or if you 
+		 * constructed just using a UUID, then you need to call this manually before you can access the resource from 
+		 * this handle.
+		 * 			
+		 * @note	
+		 * This is needed because two part construction is required due to  multithreaded nature of resource loading.
+		 * @note
+		 * Internal method.
+		 */
+		void setHandleData(const SPtr<Resource>& ptr, const String& uuid);
+
+		/** Increments the reference count of the handle. Only to be used by Resources for keeping internal references. */
+		void addInternalRef();
+
+		/** Decrements the reference count of the handle. Only to be used by ::Resources for keeping internal references. */
+		void removeInternalRef();
+
+		/** 
+		 * @note	
+		 * All handles to the same source must share this same handle data. Otherwise things like counting number of 
+		 * references or replacing pointed to resource become impossible without additional logic. */
+		SPtr<ResourceHandleData> mData;
+
+	private:
+		friend class Resources;
+
+		BS_STATIC_THREAD_SYNCHRONISER(mResourceCreatedCondition)
+		BS_STATIC_MUTEX(mResourceCreatedMutex)
+
+	protected:
+		inline void throwIfNotLoaded() const;
+	};
+
+	/**
+	 * @copydoc	ResourceHandleBase
+	 *
+	 * Handles differences in reference counting depending if the handle is normal or weak.
+	 */
+	template <bool WeakHandle>
+	class BS_CORE_EXPORT TResourceHandleBase : public ResourceHandleBase { };
+
+	/**	Specialization of TResourceHandleBase for weak handles. Weak handles do no reference counting. */
+	template<>
+	class BS_CORE_EXPORT TResourceHandleBase<true> : public ResourceHandleBase
+	{
+	public:
+		virtual ~TResourceHandleBase() { }
+
+	protected:
+		void addRef() { };
+		void releaseRef() { };
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class WeakResourceHandleRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/**	Specialization of TResourceHandleBase for normal (non-weak) handles. */
+	template<>
+	class BS_CORE_EXPORT TResourceHandleBase<false> : public ResourceHandleBase
+	{
+	public:
+		virtual ~TResourceHandleBase() { }
+
+	protected:
+		void addRef() { if (mData) mData->mRefCount++; };
+		void releaseRef() 
+		{ 
+			if (mData)
+			{
+				mData->mRefCount--;
+
+				if (mData->mRefCount == 0)
+					destroy();
+			}
+		};
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class WeakResourceHandleRTTI;
+		friend class ResourceHandleRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @copydoc ResourceHandleBase */
+	template <typename T, bool WeakHandle>
+	class TResourceHandle : public TResourceHandleBase<WeakHandle>
+	{
+	public:
+		TResourceHandle()
+			:TResourceHandleBase()
+		{ }
+
+		/**	Copy constructor. */
+		TResourceHandle(const TResourceHandle<T, WeakHandle>& ptr)
+			:TResourceHandleBase()
+		{
+			mData = ptr.getHandleData();
+
+			addRef();
+		}
+
+		virtual ~TResourceHandle()
+		{
+			releaseRef();
+		}
+
+		/**	Converts a specific handle to generic Resource handle. */
+		operator TResourceHandle<Resource, WeakHandle>() const
+		{
+			TResourceHandle<Resource, WeakHandle> handle;
+			handle.setHandleData(getHandleData());
+
+			return handle;
+		}
+
+		/**
+		 * Returns internal resource pointer.
+		 *
+		 * @note	Throws exception if handle is invalid.
+		 */
+		T* operator->() const { return get(); }
+
+		/**
+		 * Returns internal resource pointer and dereferences it.
+		 *
+		 * @note	Throws exception if handle is invalid.
+		 */
+		T& operator*() const { return *get(); }
+
+		/** Clears the handle making it invalid and releases any references held to the resource. */
+		TResourceHandle<T, WeakHandle>& operator=(std::nullptr_t ptr)
+		{ 	
+			releaseRef();
+
+			mData = nullptr;
+			return *this;
+		}
+
+		/**	Normal assignment operator. */
+		TResourceHandle<T, WeakHandle>& operator=(const TResourceHandle<T, WeakHandle>& rhs)
+		{ 	
+			setHandleData(rhs.getHandleData());
+			return *this;
+		}
+
+		template<class _Ty>
+		struct Bool_struct
+		{
+			int _Member;
+		};
+
+		/**
+		 * Allows direct conversion of handle to bool.
+		 *
+		 * @note	This is needed because we can't directly convert to bool since then we can assign pointer to bool and 
+		 *			that's weird.
+		 */
+		operator int Bool_struct<T>::*() const
+		{
+			return ((mData != nullptr && !mData->mUUID.empty()) ? &Bool_struct<T>::_Member : 0);
+		}
+
+		/**
+		 * Returns internal resource pointer and dereferences it.
+		 *
+		 * @note	Throws exception if handle is invalid.
+		 */
+		T* get() const 
+		{ 
+			throwIfNotLoaded();
+
+			return reinterpret_cast<T*>(mData->mPtr.get()); 
+		}
+
+		/**
+		 * Returns the internal shared pointer to the resource.
+		 *
+		 * @note	Throws exception if handle is invalid.
+		 */
+		SPtr<T> getInternalPtr() const
+		{ 
+			throwIfNotLoaded();
+
+			return std::static_pointer_cast<T>(mData->mPtr); 
+		}
+
+		/** Converts a handle into a weak handle. */
+		TResourceHandle<T, true> getWeak() const
+		{
+			TResourceHandle<T, true> handle;
+			handle.setHandleData(getHandleData());
+
+			return handle;
+		}
+
+	protected:
+		friend Resources;
+		template<class _T, bool _Weak>
+		friend class TResourceHandle;
+		template<class _Ty1, class _Ty2, bool Weak>
+		friend TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other);
+
+		/**
+		 * Constructs a new valid handle for the provided resource with the provided UUID.
+		 *			
+		 * @note	Handle will take ownership of the provided resource pointer, so make sure you don't delete it elsewhere.
+		 */
+		explicit TResourceHandle(T* ptr, const String& uuid)
+			:TResourceHandleBase()
+		{
+			mData = bs_shared_ptr_new<ResourceHandleData>();
+			addRef();
+
+			setHandleData(std::shared_ptr<Resource>(ptr, uuid));
+		}
+
+		/**
+		 * Constructs an invalid handle with the specified UUID. You must call setHandleData() with the actual resource 
+		 * pointer to make the handle valid.
+		 */
+		TResourceHandle(const String& uuid)
+			:TResourceHandleBase()
+		{
+			mData = bs_shared_ptr_new<ResourceHandleData>();
+			mData->mUUID = uuid;
+
+			addRef();
+		}
+
+		/**	Constructs a new valid handle for the provided resource with the provided UUID. */
+		TResourceHandle(const SPtr<T> ptr, const String& uuid)
+			:TResourceHandleBase()
+		{
+			mData = bs_shared_ptr_new<ResourceHandleData>();
+			addRef();
+
+			setHandleData(ptr, uuid);
+		}
+
+		/**	Replaces the internal handle data pointer, effectively transforming the handle into a different handle. */
+		void setHandleData(const SPtr<ResourceHandleData>& data)
+		{
+			releaseRef();
+			mData = data;
+			addRef();
+		}
+
+		/**	Converts a weak handle into a normal handle. */
+		TResourceHandle<T, false> lock() const
+		{
+			TResourceHandle<Resource, false> handle;
+			handle.setHandleData(getHandleData());
+
+			return handle;
+		}
+
+		using TResourceHandleBase::setHandleData;
+	};
+
+	/**	Checks if two handles point to the same resource. */
+	template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
+	bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right)
+	{	
+		if(_Left.getHandleData() != nullptr && _Right.getHandleData() != nullptr)
+			return _Left.getHandleData()->mPtr == _Right.getHandleData()->mPtr;
+
+		return _Left.getHandleData() == _Right.getHandleData();
+	}
+
+	/**	Checks if a handle is null. */
+	template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
+	bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, std::nullptr_t  _Right)
+	{	
+		return _Left.getHandleData() == nullptr || _Left.getHandleData()->mUUID.empty();
+	}
+
+	template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
+	bool operator!=(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right)
+	{	
+		return (!(_Left == _Right));
+	}
+
+	/** @} */
+
+	/** @addtogroup Resources
+	 *  @{
+	 */
+
+	 /** @copydoc ResourceHandleBase */
+	template <typename T>
+	using ResourceHandle = TResourceHandle<T, false>;
+
+	/** 
+	 * @copydoc ResourceHandleBase 
+	 *
+	 * Weak handles don't prevent the resource from being unloaded.
+	 */
+	template <typename T>
+	using WeakResourceHandle = TResourceHandle<T, true>;
+
+	/**	Casts one resource handle to another. */
+	template<class _Ty1, class _Ty2, bool Weak>
+	TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other)
+	{
+		TResourceHandle<_Ty1, Weak> handle;
+		handle.setHandleData(other.getHandleData());
+
+		return handle;
+	}
+
+	/** @} */
 }

+ 87 - 87
Source/BansheeCore/Include/BsResourceListenerManager.h

@@ -1,88 +1,88 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsModule.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Resources
-	 *  @{
-	 */
-
-	/**
-	 * Handles all active implementations of IResourceListener interface and notifies them when events they're listening 
-	 * to occur.
-	 *
-	 * @see		IResourceListener
-	 */
-	class BS_CORE_EXPORT ResourceListenerManager : public Module<ResourceListenerManager>
-	{
-	public:
-		ResourceListenerManager();
-		~ResourceListenerManager();
-
-		/**	Register a new listener to notify for events. */
-		void registerListener(IResourceListener* listener);
-
-		/**	Unregister a listener so it will no longer receive notifications. */
-		void unregisterListener(IResourceListener* listener);
-
-		/**
-		 * Marks the listener as dirty which forces the manager to updates its internal list of resources for the 
-		 * listener.
-		 */
-		void markListenerDirty(IResourceListener* listener);
-
-		/**	Refreshes the resource maps based on dirty listeners and sends out the necessary events. */
-		void update();
-
-		/**
-		 * Forces the listener to send out events about the specified resource immediately, instead of waiting for the 
-		 * next update() call.
-		 */
-		void notifyListeners(const String& resourceUUID);
-
-	private:
-		/**	Triggered by the resources system when a resource has finished loading. */
-		void onResourceLoaded(const HResource& resource);
-
-		/**	Triggered by the resources system after a resource handle is modified (i.e. points to a new resource). */
-		void onResourceModified(const HResource& resource);
-
-		/**	Sends resource loaded event to all listeners referencing this resource. */
-		void sendResourceLoaded(const HResource& resource);
-
-		/**	Sends resource modified event to all listeners referencing this resource. */
-		void sendResourceModified(const HResource& resource);
-
-		/**	Clears all the stored dependencies for the listener. */
-		void clearDependencies(IResourceListener* listener);
-
-		/**	Registers all the resource dependencies for the listener. */
-		void addDependencies(IResourceListener* listener);
-
-		HEvent mResourceLoadedConn;
-		HEvent mResourceModifiedConn;
-		
-		Set<IResourceListener*> mDirtyListeners;
-		Map<UINT64, Vector<IResourceListener*>> mResourceToListenerMap;
-		Map<IResourceListener*, Vector<UINT64>> mListenerToResourceMap;
-
-		Map<String, HResource> mLoadedResources;
-		Map<String, HResource> mModifiedResources;
-
-		Vector<HResource> mTempResourceBuffer;
-
-		BS_RECURSIVE_MUTEX(mMutex);
-
-#if BS_DEBUG_MODE
-		Set<IResourceListener*> mActiveListeners;
-#endif
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsModule.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Resources
+	 *  @{
+	 */
+
+	/**
+	 * Handles all active implementations of IResourceListener interface and notifies them when events they're listening 
+	 * to occur.
+	 *
+	 * @see		IResourceListener
+	 */
+	class BS_CORE_EXPORT ResourceListenerManager : public Module<ResourceListenerManager>
+	{
+	public:
+		ResourceListenerManager();
+		~ResourceListenerManager();
+
+		/**	Register a new listener to notify for events. */
+		void registerListener(IResourceListener* listener);
+
+		/**	Unregister a listener so it will no longer receive notifications. */
+		void unregisterListener(IResourceListener* listener);
+
+		/**
+		 * Marks the listener as dirty which forces the manager to updates its internal list of resources for the 
+		 * listener.
+		 */
+		void markListenerDirty(IResourceListener* listener);
+
+		/**	Refreshes the resource maps based on dirty listeners and sends out the necessary events. */
+		void update();
+
+		/**
+		 * Forces the listener to send out events about the specified resource immediately, instead of waiting for the 
+		 * next update() call.
+		 */
+		void notifyListeners(const String& resourceUUID);
+
+	private:
+		/**	Triggered by the resources system when a resource has finished loading. */
+		void onResourceLoaded(const HResource& resource);
+
+		/**	Triggered by the resources system after a resource handle is modified (points to a new resource). */
+		void onResourceModified(const HResource& resource);
+
+		/**	Sends resource loaded event to all listeners referencing this resource. */
+		void sendResourceLoaded(const HResource& resource);
+
+		/**	Sends resource modified event to all listeners referencing this resource. */
+		void sendResourceModified(const HResource& resource);
+
+		/**	Clears all the stored dependencies for the listener. */
+		void clearDependencies(IResourceListener* listener);
+
+		/**	Registers all the resource dependencies for the listener. */
+		void addDependencies(IResourceListener* listener);
+
+		HEvent mResourceLoadedConn;
+		HEvent mResourceModifiedConn;
+		
+		Set<IResourceListener*> mDirtyListeners;
+		Map<UINT64, Vector<IResourceListener*>> mResourceToListenerMap;
+		Map<IResourceListener*, Vector<UINT64>> mListenerToResourceMap;
+
+		Map<String, HResource> mLoadedResources;
+		Map<String, HResource> mModifiedResources;
+
+		Vector<HResource> mTempResourceBuffer;
+
+		BS_RECURSIVE_MUTEX(mMutex);
+
+#if BS_DEBUG_MODE
+		Set<IResourceListener*> mActiveListeners;
+#endif
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 4 - 2
Source/BansheeCore/Include/BsResources.h

@@ -262,7 +262,9 @@ namespace BansheeEngine
 		Event<void(const HResource&)> onResourceModified;
 
 	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**
 		 * Creates a new resource handle from a resource pointer. 
@@ -274,7 +276,7 @@ namespace BansheeEngine
 		/** Returns an existing handle for the specified UUID if one exists, or creates a new one. */
 		HResource _getResourceHandle(const String& uuid);
 
-		/** @endcond */
+		/** @} */
 	private:
 		friend class ResourceHandleBase;
 

+ 367 - 365
Source/BansheeCore/Include/BsRigidbody.h

@@ -1,366 +1,368 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsPhysicsCommon.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Physics
-	 *  @{
-	 */
-
-	/** Type of force or torque that can be applied to a rigidbody. */
-	enum class ForceMode
-	{
-		Force, /**< Value applied is a force. */
-		Impulse, /**< Value applied is an impulse (i.e. a direct change in its linear or angular momentum). */
-		Velocity, /**< Value applied is velocity. */
-		Acceleration /**< Value applied is accelearation. */
-	};
-
-	/** Type of force that can be applied to a rigidbody at an arbitrary point. */
-	enum class PointForceMode
-	{
-		Force, /**< Value applied is a force. */
-		Impulse, /**< Value applied is an impulse (i.e. a direct change in its linear or angular momentum). */
-	};
-
-	/**
-	 * Rigidbody is a dynamic physics object that can be moved using forces (or directly). It will interact with other
-	 * static and dynamic physics objects in the scene accordingly (i.e. it will push other non-kinematic rigidbodies, 
-	 * and collide with static objects).
-	 *
-	 * The shape and mass of a rigidbody is governed by its colliders. You must attach at least one collider for the 
-	 * rigidbody to be valid.
-	 */
-	class BS_CORE_EXPORT Rigidbody
-	{
-	public:
-		/** Flags that control options of a Rigidbody object. */
-		enum class Flag
-		{
-			/** No options. */
-			None = 0x00,
-			/** Automatically calculate center of mass transform and inertia tensors from child shapes (colliders). */
-			AutoTensors = 0x01,
-			/** Calculate mass distribution from child shapes (colliders). Only relevant when auto-tensors is on. */
-			AutoMass = 0x02,
-			/** 
-			 * Enables continous collision detection. This can prevent fast moving bodies from tunneling through each other.
-			 * This must also be enabled globally in Physics otherwise the flag will be ignored.
-			 */
-			CCD = 0x04
-		};
-
-		/** Determines interpolation mode for a rigidbody transform during physics simulation. */
-		enum class InterpolationMode
-		{
-			/** 
-			 * No interpolation is performed, physics transform is copied straight to the rigidbody when physics tick is 
-			 * done. 
-			 */
-			None, 
-			/** 
-			 * Physics transfrom from the most recent tick is saved and slowly interpolated to during the following render 
-			 * frames. This can improve smoothness of the visible movement at framerates higher than the physics simulation 
-			 * but will introduce a delay of one physics tick to all such objects. This can create slight inconsistencies as
-			 * non-interpolated objects will have no such delay, as well as cause input lag due to the delayed reaction.
-			 */
-			Interpolate, 
-			/** 
-			 * Physics transform movement will be extrapolated from the last physics simulation tick. This will improve
-			 * smoothness of visible movement at framerates higher than the physics simulation. Unlike Interpolate it will
-			 * not introduce an input delay, but will introduce an error as the exact position/rotation of the objects is
-			 * extrapolated from the last frame's movement and velocities. 
-			 */
-			Extrapolate
-		};
-
-		/** 
-		 * Constructs a new rigidbody. 
-		 *
-		 * @param[in]	linkedSO	Scene object that owns this rigidbody. All physics updates applied to this object
-		 *							will be transfered to this scene object (i.e. the movement/rotation resulting from
-		 *							those updates).
-		 */
-		Rigidbody(const HSceneObject& linkedSO);
-		virtual ~Rigidbody();
-
-		/** 
-		 * Moves the rigidbody to a specific position. This method will ensure physically correct movement, i.e. the body
-		 * will collide with other objects along the way.
-		 */
-		virtual void move(const Vector3& position) = 0;
-
-		/** 
-		 * Rotates the rigidbody. This method will ensure physically correct rotation, i.e. the body will collide with other
-		 * objects along the way.
-		 */
-		virtual void rotate(const Quaternion& rotation) = 0;
-
-		/** Returns the current position of the rigidbody. */
-		virtual Vector3 getPosition() const = 0;
-
-		/** Returns the current rotation of the rigidbody. */
-		virtual Quaternion getRotation() const = 0;
-
-		/** 
-		 * Moves and rotates the rigidbody to a specific position. Unlike move() and rotate() this will not transform the
-		 * body in a physically correct manner, but will instead "teleport" it immediately to the specified position and
-		 * rotation.
-		 */
-		virtual void setTransform(const Vector3& pos, const Quaternion& rot) = 0;
-
-		/** 
-		 * Sets the mass of the object and all of its collider shapes. Only relevant if Flag::AutoMass or Flag::AutoTensors
-		 * is turned off. Value of zero means the object is immovable (but can be rotated).
-		 */
-		virtual void setMass(float mass) = 0;
-
-		/** 
-		 * Returns the mass of the object. This may be mass manually set by setMass(), or the mass of all child colliders,
-		 * depending if the mass is calculated automatically or not.
-		 */
-		virtual float getMass() const = 0;
-
-		/** 
-		 * Sets if the body is kinematic. Kinematic body will not move in response to external forces (e.g. gravity, or
-		 * another object pushing it), essentially behaving like collider. Unlike a collider though, you can still move
-		 * the object and have other dynamic objects respond correctly (i.e. it will push other objects).
-		 */
-		virtual void setIsKinematic(bool kinematic) = 0;
-
-		/** Checks if the body is kinematic. */
-		virtual bool getIsKinematic() const = 0;
-
-		/** 
-		 * Checks if the body is sleeping. Objects that aren't moved/rotated for a while are put to sleep to reduce load
-		 * on the physics system. 
-		 */
-		virtual bool isSleeping() const = 0;
-
-		/** Forces the object to sleep. Useful if you know the object will not move in any significant way for a while. */
-		virtual void sleep() = 0;
-
-		/** 
-		 * Wakes an object up. Useful if you modified properties of this object, and potentially surrounding objects which
-		 * might result in the object being moved by physics (although the physics system will automatically wake the
-		 * object up for majority of such cases).
-		 */
-		virtual void wakeUp() = 0;
-
-		/** Sets a threshold of force and torque under which the object will be considered to be put to sleep. */
-		virtual void setSleepThreshold(float threshold) = 0;
-
-		/** Gets a threshold of force and torque under which the object will be considered to be put to sleep. */
-		virtual float getSleepThreshold() const = 0;
-
-		/** Sets whether or not the rigidbody will have the global gravity force applied to it. */
-		virtual void setUseGravity(bool gravity) = 0;
-
-		/** Gets whether or not the rigidbody will have the global gravity force applied to it. */
-		virtual bool getUseGravity() const = 0;
-
-		/** Sets the linear velocity of the body. */
-		virtual void setVelocity(const Vector3& velocity) = 0;
-
-		/** Returns the current linear velocity of the body. */
-		virtual Vector3 getVelocity() const = 0;
-
-		/** Sets the angular velocity of the body. */
-		virtual void setAngularVelocity(const Vector3& velocity) = 0;
-
-		/** Returns the current angular velocity of the body. */
-		virtual Vector3 getAngularVelocity() const = 0;
-
-		/** Sets the linear drag of the body. Higher drag values means the object resists linear movement more. */
-		virtual void setDrag(float drag) = 0;
-
-		/** Gets the linear drag of the body. Higher drag values means the object resists linear movement more. */
-		virtual float getDrag() const = 0;
-
-		/** Sets the angular drag of the body. Higher drag values means the object resists angular movement more. */
-		virtual void setAngularDrag(float drag) = 0;
-
-		/** Gets the angular drag of the body. Higher drag values means the object resists angular movement more. */
-		virtual float getAngularDrag() const = 0;
-
-		/** 
-		 * Sets the inertia tensor in local mass space. Inertia tensor determines how difficult is to rotate the object.
-		 * Values of zero in the inertia tensor mean the object will be unable to rotate around a specific axis. Only 
-		 * relevant if Flag::AutoTensors is turned off.
-		 */
-		virtual void setInertiaTensor(const Vector3& tensor) = 0;
-
-		/** Gets the inertia tensor in local mass space.  */
-		virtual Vector3 getInertiaTensor() const = 0;
-
-		/** Returns the maximum angular velocity of the rigidbody. Velocity will be clamped to this value. */
-		virtual void setMaxAngularVelocity(float maxVelocity) = 0;
-
-		/** Gets the maximum angular velocity of the rigidbody. */
-		virtual float getMaxAngularVelocity() const = 0;
-
-		/**
-		 * Sets the rigidbody's center of mass transform. Only relevant if Flag::AutoTensors is turned off.
-		 *
-		 * @param[in]	position	Position of the center of mass.
-		 * @param[in]	rotation	Rotation that determines orientation of the inertia tensor (rotation of the center of 
-		 *							mass frame).
-		 */
-		virtual void setCenterOfMass(const Vector3& position, const Quaternion& rotation) = 0;
-
-		/** Returns the position of the center of mass. */
-		virtual Vector3 getCenterOfMassPosition() const = 0;
-
-		/** Returns the rotation of the inertia tensor. */
-		virtual Quaternion getCenterOfMassRotation() const = 0;
-
-		/** 
-		 * Sets the number of iterations to use when solving for position. Higher values can improve precision and 
-		 * numerical stability of the simulation. 
-		 */
-		virtual void setPositionSolverCount(UINT32 count) = 0;
-
-		/** Gets the number of iterations to use when solving for position. */
-		virtual UINT32 getPositionSolverCount() const = 0;
-
-
-		/** 
-		 * Sets the number of iterations to use when solving for velocity. Higher values can improve precision and 
-		 * numerical stability of the simulation. 
-		 */
-		virtual void setVelocitySolverCount(UINT32 count) = 0;
-
-		/** Gets the number of iterations to use when solving for velocity. */
-		virtual UINT32 getVelocitySolverCount() const = 0;
-
-		/** Sets interpolation mode that controls how is the rigidbody transfrom updated from the physics simulation. */
-		virtual void setInterpolationMode(InterpolationMode value) { mInterpolationMode = value; }
-
-		/** Gets interpolation mode that controls how is the rigidbody transfrom updated from the physics simulation. */
-		virtual InterpolationMode getInterpolationMode() const { return mInterpolationMode; }
-
-		/** Sets flags that control the behaviour of the rigidbody. */
-		virtual void setFlags(Flag flags) { mFlags = flags; }
-
-		/** Gets flags that control the behaviour of the rigidbody. */
-		virtual Flag getFlags() const { return mFlags; }
-
-		/** 
-		 * Applies a force to the center of the mass of the rigidbody. This will produce linear momentum.
-		 *
-		 * @param[in]	force		Force to apply.
-		 * @param[in]	mode		Determines what is the type of @p force.
-		 */
-		virtual void addForce(const Vector3& force, ForceMode mode = ForceMode::Force) = 0;
-
-		/** 
-		 * Applies a torque to the rigidbody. This will produce angular momentum.
-		 *
-		 * @param[in]	torque		Torque to apply.
-		 * @param[in]	mode		Determines what is the type of @p torque.
-		 */
-		virtual void addTorque(const Vector3& torque, ForceMode mode = ForceMode::Force) = 0;
-
-		/** 
-		 * Applies a force to a specific point on the rigidbody. This will in most cases produce both linear and angular
-		 * momentum.
-		 *
-		 * @param[in]	force		Force to apply.
-		 * @param[in]	position	World position to apply the force at.
-		 * @param[in]	mode		Determines what is the type of @p force.
-		 */
-		virtual void addForceAtPoint(const Vector3& force, const Vector3& position, 
-			PointForceMode mode = PointForceMode::Force) = 0;
-
-		/** 
-		 * Returns the total (linear + angular) velocity at a specific point. 
-		 *
-		 * @param[in]	point	Point in world space.
-		 * @return				Total velocity of the point.
-		 */
-		virtual Vector3 getVelocityAtPoint(const Vector3& point) const = 0;
-
-		/** Registers a new collider as a child of this rigidbody. */
-		virtual void addCollider(FCollider* collider) = 0;
-
-		/** Removes a collider from the child list of this rigidbody. */
-		virtual void removeCollider(FCollider* collider) = 0;
-
-		/** Removes all colliders from the child list of this rigidbody. */
-		virtual void removeColliders() = 0;
-
-		/** 
-		 * Recalculates rigidbody's mass, inertia tensors and center of mass depending on the currently set child colliders.
-		 * This should be called whenever relevant child collider properties change (like mass or shape).
-		 *
-		 * If automatic tensor calculation is turned off then this will do nothing. If automatic mass calculation is turned
-		 * off then this will use the mass set directly on the body using setMass().
-		 */
-		virtual void updateMassDistribution() { }
-
-		/** 
-		 * Creates a new rigidbody. 
-		 *
-		 * @param[in]	linkedSO	Scene object that owns this rigidbody. All physics updates applied to this object
-		 *							will be transfered to this scene object (i.e. the movement/rotation resulting from
-		 *							those updates).
-		 */
-		static SPtr<Rigidbody> create(const HSceneObject& linkedSO);
-
-		/** Triggered when one of the colliders owned by the rigidbody starts colliding with another object. */
-		Event<void(const CollisionData&)> onCollisionBegin;
-
-		/** Triggered when a previously colliding collider stays in collision. Triggered once per frame. */
-		Event<void(const CollisionData&)> onCollisionStay;
-
-		/** Triggered when one of the colliders owned by the rigidbody stops colliding with another object. */
-		Event<void(const CollisionData&)> onCollisionEnd;
-
-		/** @cond INTERNAL */
-
-		/** 
-		 * Sets the priority of the physics update. Bodies with a higher priority will be updated before the bodies with
-		 * lower priority. This allows you to control the order of updated in case rigidbodies are in some way dependant.
-		 */
-		void _setPriority(UINT32 priority);
-
-		/** Sets a unique ID of the rigidbody, so it can be recognized by the physics system. */
-		void _setPhysicsId(UINT32 id) { mPhysicsId = id; }
-
-		/** 
-		 * Applies new transform values retrieved from the most recent physics update (i.e. values resulting from physics 
-		 * simulation). 
-		 */
-		void _setTransform(const Vector3& position, const Quaternion& rotation);
-
-		/** 
-		 * Sets the object that owns this physics object, if any. Used for high level systems so they can easily map their
-		 * high level physics objects from the low level ones returned by various queries and events.
-		 */
-		void _setOwner(PhysicsOwnerType type, void* owner) { mOwner.type = type; mOwner.ownerData = owner; }
-
-		/** 
-		 * Gets the object that owns this physics object, if any. Used for high level systems so they can easily map their
-		 * high level physics objects from the low level ones returned by various queries and events.
-		 */
-		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
-
-		/** @endcond */
-
-	protected:
-		friend class FCollider;
-
-		Flag mFlags = Flag::None;
-		InterpolationMode mInterpolationMode = InterpolationMode::None;
-		PhysicsObjectOwner mOwner;
-		UINT32 mPriority = 0;
-		UINT32 mPhysicsId = 0;
-		HSceneObject mLinkedSO;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsPhysicsCommon.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Physics
+	 *  @{
+	 */
+
+	/** Type of force or torque that can be applied to a rigidbody. */
+	enum class ForceMode
+	{
+		Force, /**< Value applied is a force. */
+		Impulse, /**< Value applied is an impulse (a direct change in its linear or angular momentum). */
+		Velocity, /**< Value applied is velocity. */
+		Acceleration /**< Value applied is accelearation. */
+	};
+
+	/** Type of force that can be applied to a rigidbody at an arbitrary point. */
+	enum class PointForceMode
+	{
+		Force, /**< Value applied is a force. */
+		Impulse, /**< Value applied is an impulse (a direct change in its linear or angular momentum). */
+	};
+
+	/**
+	 * Rigidbody is a dynamic physics object that can be moved using forces (or directly). It will interact with other
+	 * static and dynamic physics objects in the scene accordingly (it will push other non-kinematic rigidbodies, 
+	 * and collide with static objects).
+	 *
+	 * The shape and mass of a rigidbody is governed by its colliders. You must attach at least one collider for the 
+	 * rigidbody to be valid.
+	 */
+	class BS_CORE_EXPORT Rigidbody
+	{
+	public:
+		/** Flags that control options of a Rigidbody object. */
+		enum class Flag
+		{
+			/** No options. */
+			None = 0x00,
+			/** Automatically calculate center of mass transform and inertia tensors from child shapes (colliders). */
+			AutoTensors = 0x01,
+			/** Calculate mass distribution from child shapes (colliders). Only relevant when auto-tensors is on. */
+			AutoMass = 0x02,
+			/** 
+			 * Enables continous collision detection. This can prevent fast moving bodies from tunneling through each other.
+			 * This must also be enabled globally in Physics otherwise the flag will be ignored.
+			 */
+			CCD = 0x04
+		};
+
+		/** Determines interpolation mode for a rigidbody transform during physics simulation. */
+		enum class InterpolationMode
+		{
+			/** 
+			 * No interpolation is performed, physics transform is copied straight to the rigidbody when physics tick is 
+			 * done. 
+			 */
+			None, 
+			/** 
+			 * Physics transfrom from the most recent tick is saved and slowly interpolated to during the following render 
+			 * frames. This can improve smoothness of the visible movement at framerates higher than the physics simulation 
+			 * but will introduce a delay of one physics tick to all such objects. This can create slight inconsistencies as
+			 * non-interpolated objects will have no such delay, as well as cause input lag due to the delayed reaction.
+			 */
+			Interpolate, 
+			/** 
+			 * Physics transform movement will be extrapolated from the last physics simulation tick. This will improve
+			 * smoothness of visible movement at framerates higher than the physics simulation. Unlike Interpolate it will
+			 * not introduce an input delay, but will introduce an error as the exact position/rotation of the objects is
+			 * extrapolated from the last frame's movement and velocities. 
+			 */
+			Extrapolate
+		};
+
+		/** 
+		 * Constructs a new rigidbody. 
+		 *
+		 * @param[in]	linkedSO	Scene object that owns this rigidbody. All physics updates applied to this object
+		 *							will be transfered to this scene object (the movement/rotation resulting from
+		 *							those updates).
+		 */
+		Rigidbody(const HSceneObject& linkedSO);
+		virtual ~Rigidbody();
+
+		/** 
+		 * Moves the rigidbody to a specific position. This method will ensure physically correct movement, meaning the body
+		 * will collide with other objects along the way.
+		 */
+		virtual void move(const Vector3& position) = 0;
+
+		/** 
+		 * Rotates the rigidbody. This method will ensure physically correct rotation, meaning the body will collide with 
+		 * other objects along the way.
+		 */
+		virtual void rotate(const Quaternion& rotation) = 0;
+
+		/** Returns the current position of the rigidbody. */
+		virtual Vector3 getPosition() const = 0;
+
+		/** Returns the current rotation of the rigidbody. */
+		virtual Quaternion getRotation() const = 0;
+
+		/** 
+		 * Moves and rotates the rigidbody to a specific position. Unlike move() and rotate() this will not transform the
+		 * body in a physically correct manner, but will instead "teleport" it immediately to the specified position and
+		 * rotation.
+		 */
+		virtual void setTransform(const Vector3& pos, const Quaternion& rot) = 0;
+
+		/** 
+		 * Sets the mass of the object and all of its collider shapes. Only relevant if Flag::AutoMass or Flag::AutoTensors
+		 * is turned off. Value of zero means the object is immovable (but can be rotated).
+		 */
+		virtual void setMass(float mass) = 0;
+
+		/** 
+		 * Returns the mass of the object. This may be mass manually set by setMass(), or the mass of all child colliders,
+		 * depending if the mass is calculated automatically or not.
+		 */
+		virtual float getMass() const = 0;
+
+		/** 
+		 * Sets if the body is kinematic. Kinematic body will not move in response to external forces (for example gravity,
+		 * or another object pushing it), essentially behaving like collider. Unlike a collider though, you can still move
+		 * the object and have other dynamic objects respond correctly (meaning it will push other objects).
+		 */
+		virtual void setIsKinematic(bool kinematic) = 0;
+
+		/** Checks if the body is kinematic. */
+		virtual bool getIsKinematic() const = 0;
+
+		/** 
+		 * Checks if the body is sleeping. Objects that aren't moved/rotated for a while are put to sleep to reduce load
+		 * on the physics system. 
+		 */
+		virtual bool isSleeping() const = 0;
+
+		/** Forces the object to sleep. Useful if you know the object will not move in any significant way for a while. */
+		virtual void sleep() = 0;
+
+		/** 
+		 * Wakes an object up. Useful if you modified properties of this object, and potentially surrounding objects which
+		 * might result in the object being moved by physics (although the physics system will automatically wake the
+		 * object up for majority of such cases).
+		 */
+		virtual void wakeUp() = 0;
+
+		/** Sets a threshold of force and torque under which the object will be considered to be put to sleep. */
+		virtual void setSleepThreshold(float threshold) = 0;
+
+		/** Gets a threshold of force and torque under which the object will be considered to be put to sleep. */
+		virtual float getSleepThreshold() const = 0;
+
+		/** Sets whether or not the rigidbody will have the global gravity force applied to it. */
+		virtual void setUseGravity(bool gravity) = 0;
+
+		/** Gets whether or not the rigidbody will have the global gravity force applied to it. */
+		virtual bool getUseGravity() const = 0;
+
+		/** Sets the linear velocity of the body. */
+		virtual void setVelocity(const Vector3& velocity) = 0;
+
+		/** Returns the current linear velocity of the body. */
+		virtual Vector3 getVelocity() const = 0;
+
+		/** Sets the angular velocity of the body. */
+		virtual void setAngularVelocity(const Vector3& velocity) = 0;
+
+		/** Returns the current angular velocity of the body. */
+		virtual Vector3 getAngularVelocity() const = 0;
+
+		/** Sets the linear drag of the body. Higher drag values means the object resists linear movement more. */
+		virtual void setDrag(float drag) = 0;
+
+		/** Gets the linear drag of the body. Higher drag values means the object resists linear movement more. */
+		virtual float getDrag() const = 0;
+
+		/** Sets the angular drag of the body. Higher drag values means the object resists angular movement more. */
+		virtual void setAngularDrag(float drag) = 0;
+
+		/** Gets the angular drag of the body. Higher drag values means the object resists angular movement more. */
+		virtual float getAngularDrag() const = 0;
+
+		/** 
+		 * Sets the inertia tensor in local mass space. Inertia tensor determines how difficult is to rotate the object.
+		 * Values of zero in the inertia tensor mean the object will be unable to rotate around a specific axis. Only 
+		 * relevant if Flag::AutoTensors is turned off.
+		 */
+		virtual void setInertiaTensor(const Vector3& tensor) = 0;
+
+		/** Gets the inertia tensor in local mass space.  */
+		virtual Vector3 getInertiaTensor() const = 0;
+
+		/** Returns the maximum angular velocity of the rigidbody. Velocity will be clamped to this value. */
+		virtual void setMaxAngularVelocity(float maxVelocity) = 0;
+
+		/** Gets the maximum angular velocity of the rigidbody. */
+		virtual float getMaxAngularVelocity() const = 0;
+
+		/**
+		 * Sets the rigidbody's center of mass transform. Only relevant if Flag::AutoTensors is turned off.
+		 *
+		 * @param[in]	position	Position of the center of mass.
+		 * @param[in]	rotation	Rotation that determines orientation of the inertia tensor (rotation of the center of 
+		 *							mass frame).
+		 */
+		virtual void setCenterOfMass(const Vector3& position, const Quaternion& rotation) = 0;
+
+		/** Returns the position of the center of mass. */
+		virtual Vector3 getCenterOfMassPosition() const = 0;
+
+		/** Returns the rotation of the inertia tensor. */
+		virtual Quaternion getCenterOfMassRotation() const = 0;
+
+		/** 
+		 * Sets the number of iterations to use when solving for position. Higher values can improve precision and 
+		 * numerical stability of the simulation. 
+		 */
+		virtual void setPositionSolverCount(UINT32 count) = 0;
+
+		/** Gets the number of iterations to use when solving for position. */
+		virtual UINT32 getPositionSolverCount() const = 0;
+
+
+		/** 
+		 * Sets the number of iterations to use when solving for velocity. Higher values can improve precision and 
+		 * numerical stability of the simulation. 
+		 */
+		virtual void setVelocitySolverCount(UINT32 count) = 0;
+
+		/** Gets the number of iterations to use when solving for velocity. */
+		virtual UINT32 getVelocitySolverCount() const = 0;
+
+		/** Sets interpolation mode that controls how is the rigidbody transfrom updated from the physics simulation. */
+		virtual void setInterpolationMode(InterpolationMode value) { mInterpolationMode = value; }
+
+		/** Gets interpolation mode that controls how is the rigidbody transfrom updated from the physics simulation. */
+		virtual InterpolationMode getInterpolationMode() const { return mInterpolationMode; }
+
+		/** Sets flags that control the behaviour of the rigidbody. */
+		virtual void setFlags(Flag flags) { mFlags = flags; }
+
+		/** Gets flags that control the behaviour of the rigidbody. */
+		virtual Flag getFlags() const { return mFlags; }
+
+		/** 
+		 * Applies a force to the center of the mass of the rigidbody. This will produce linear momentum.
+		 *
+		 * @param[in]	force		Force to apply.
+		 * @param[in]	mode		Determines what is the type of @p force.
+		 */
+		virtual void addForce(const Vector3& force, ForceMode mode = ForceMode::Force) = 0;
+
+		/** 
+		 * Applies a torque to the rigidbody. This will produce angular momentum.
+		 *
+		 * @param[in]	torque		Torque to apply.
+		 * @param[in]	mode		Determines what is the type of @p torque.
+		 */
+		virtual void addTorque(const Vector3& torque, ForceMode mode = ForceMode::Force) = 0;
+
+		/** 
+		 * Applies a force to a specific point on the rigidbody. This will in most cases produce both linear and angular
+		 * momentum.
+		 *
+		 * @param[in]	force		Force to apply.
+		 * @param[in]	position	World position to apply the force at.
+		 * @param[in]	mode		Determines what is the type of @p force.
+		 */
+		virtual void addForceAtPoint(const Vector3& force, const Vector3& position, 
+			PointForceMode mode = PointForceMode::Force) = 0;
+
+		/** 
+		 * Returns the total (linear + angular) velocity at a specific point. 
+		 *
+		 * @param[in]	point	Point in world space.
+		 * @return				Total velocity of the point.
+		 */
+		virtual Vector3 getVelocityAtPoint(const Vector3& point) const = 0;
+
+		/** Registers a new collider as a child of this rigidbody. */
+		virtual void addCollider(FCollider* collider) = 0;
+
+		/** Removes a collider from the child list of this rigidbody. */
+		virtual void removeCollider(FCollider* collider) = 0;
+
+		/** Removes all colliders from the child list of this rigidbody. */
+		virtual void removeColliders() = 0;
+
+		/** 
+		 * Recalculates rigidbody's mass, inertia tensors and center of mass depending on the currently set child colliders.
+		 * This should be called whenever relevant child collider properties change (like mass or shape).
+		 *
+		 * If automatic tensor calculation is turned off then this will do nothing. If automatic mass calculation is turned
+		 * off then this will use the mass set directly on the body using setMass().
+		 */
+		virtual void updateMassDistribution() { }
+
+		/** 
+		 * Creates a new rigidbody. 
+		 *
+		 * @param[in]	linkedSO	Scene object that owns this rigidbody. All physics updates applied to this object
+		 *							will be transfered to this scene object (the movement/rotation resulting from
+		 *							those updates).
+		 */
+		static SPtr<Rigidbody> create(const HSceneObject& linkedSO);
+
+		/** Triggered when one of the colliders owned by the rigidbody starts colliding with another object. */
+		Event<void(const CollisionData&)> onCollisionBegin;
+
+		/** Triggered when a previously colliding collider stays in collision. Triggered once per frame. */
+		Event<void(const CollisionData&)> onCollisionStay;
+
+		/** Triggered when one of the colliders owned by the rigidbody stops colliding with another object. */
+		Event<void(const CollisionData&)> onCollisionEnd;
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** 
+		 * Sets the priority of the physics update. Bodies with a higher priority will be updated before the bodies with
+		 * lower priority. This allows you to control the order of updated in case rigidbodies are in some way dependant.
+		 */
+		void _setPriority(UINT32 priority);
+
+		/** Sets a unique ID of the rigidbody, so it can be recognized by the physics system. */
+		void _setPhysicsId(UINT32 id) { mPhysicsId = id; }
+
+		/** 
+		 * Applies new transform values retrieved from the most recent physics update (values resulting from physics 
+		 * simulation). 
+		 */
+		void _setTransform(const Vector3& position, const Quaternion& rotation);
+
+		/** 
+		 * Sets the object that owns this physics object, if any. Used for high level systems so they can easily map their
+		 * high level physics objects from the low level ones returned by various queries and events.
+		 */
+		void _setOwner(PhysicsOwnerType type, void* owner) { mOwner.type = type; mOwner.ownerData = owner; }
+
+		/** 
+		 * Gets the object that owns this physics object, if any. Used for high level systems so they can easily map their
+		 * high level physics objects from the low level ones returned by various queries and events.
+		 */
+		void* _getOwner(PhysicsOwnerType type) const { return mOwner.type == type ? mOwner.ownerData : nullptr; }
+
+		/** @} */
+
+	protected:
+		friend class FCollider;
+
+		Flag mFlags = Flag::None;
+		InterpolationMode mInterpolationMode = InterpolationMode::None;
+		PhysicsObjectOwner mOwner;
+		UINT32 mPriority = 0;
+		UINT32 mPhysicsId = 0;
+		HSceneObject mLinkedSO;
+	};
+
+	/** @} */
 }

+ 4 - 2
Source/BansheeCore/Include/BsSceneObject.h

@@ -94,7 +94,9 @@ namespace BansheeEngine
 		bool hasFlag(UINT32 flag) const;
 
 	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/** Register the scene object with the scene and activate all of its components. */
 		void _instantiate();
@@ -126,7 +128,7 @@ namespace BansheeEngine
 		/** Assigns a new prefab diff object. Caller must ensure the prefab diff was generated for this object. */
 		void _setPrefabDiff(const PrefabDiffPtr& diff) { mPrefabDiff = diff; }
 
-		/** @endcond */
+		/** @} */
 
 	private:
 		SceneObject(const String& name, UINT32 flags);

+ 6 - 3
Source/BansheeCore/Include/BsShader.h

@@ -185,7 +185,8 @@ namespace BansheeEngine
 		 * @note	
 		 * This is useful when you want all your opaque objects to be rendered before you start drawing your transparent 
 		 * ones. Or to render your overlays after everything else. Values provided in QueuePriority are just for general 
-		 * guidance and feel free to increase them or decrease them for finer tuning. (e.g. QueuePriority::Opaque + 1).
+		 * guidance and feel free to increase them or decrease them for finer tuning. (for example QueuePriority::Opaque + 
+		 * 1).
 		 */
 		INT32 queuePriority;
 
@@ -431,7 +432,9 @@ namespace BansheeEngine
 		static ShaderPtr createEmpty();
 
 	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**
 		 * Creates a new shader object using the provided descriptor and techniques.
@@ -440,7 +443,7 @@ namespace BansheeEngine
 		 */
 		static ShaderPtr _createPtr(const String& name, const SHADER_DESC& desc, const Vector<SPtr<Technique>>& techniques);
 
-		/** @endcond */
+		/** @} */
 
 	private:
 		Shader(const String& name, const SHADER_DESC& desc, const Vector<SPtr<Technique>>& techniques, UINT32 id);

+ 51 - 49
Source/BansheeCore/Include/BsShaderInclude.h

@@ -1,50 +1,52 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsResource.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Resources
-	 *  @{
-	 */
-
-	/**	Raw text resource that serves as an include file for shaders. */
-	class BS_CORE_EXPORT ShaderInclude : public Resource
-	{
-	public:
-		/**	Text of the include file. */
-		const String& getString() const { return mString; }
-
-		/**	Creates a new include file resource with the specified include string. */
-		static HShaderInclude create(const String& includeString);
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Creates an include file resource with the specified include string.
-		 *
-		 * @note	Internal method. Use create() for normal use.
-		 */
-		static ShaderIncludePtr _createPtr(const String& includeString);
-
-		/** @endcond */
-	private:
-		ShaderInclude(const String& includeString);
-
-		String mString;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class ShaderIncludeRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsResource.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Resources
+	 *  @{
+	 */
+
+	/**	Raw text resource that serves as an include file for shaders. */
+	class BS_CORE_EXPORT ShaderInclude : public Resource
+	{
+	public:
+		/**	Text of the include file. */
+		const String& getString() const { return mString; }
+
+		/**	Creates a new include file resource with the specified include string. */
+		static HShaderInclude create(const String& includeString);
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Creates an include file resource with the specified include string.
+		 *
+		 * @note	Internal method. Use create() for normal use.
+		 */
+		static ShaderIncludePtr _createPtr(const String& includeString);
+
+		/** @} */
+	private:
+		ShaderInclude(const String& includeString);
+
+		String mString;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class ShaderIncludeRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 34 - 34
Source/BansheeCore/Include/BsShaderIncludeImporter.h

@@ -1,35 +1,35 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsSpecificImporter.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Importer
-	 *  @{
-	 */
-
-	/**
-	 * Importer using for importing GPU program (i.e. shader) include files. Include files are just text files ending with 
-	 * ".bslinc" extension.
-	 */
-	class BS_CORE_EXPORT ShaderIncludeImporter : public SpecificImporter
-	{
-	public:
-		ShaderIncludeImporter();
-		virtual ~ShaderIncludeImporter();
-
-		/** @copydoc SpecificImporter::isExtensionSupported */
-		virtual bool isExtensionSupported(const WString& ext) const override;
-
-		/** @copydoc SpecificImporter::isMagicNumberSupported */
-		virtual bool isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const override;
-
-		/** @copydoc SpecificImporter::import */
-		virtual ResourcePtr import(const Path& filePath, ConstImportOptionsPtr importOptions) override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsSpecificImporter.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Importer
+	 *  @{
+	 */
+
+	/**
+	 * Importer using for importing GPU program (shader) include files. Include files are just text files ending with 
+	 * ".bslinc" extension.
+	 */
+	class BS_CORE_EXPORT ShaderIncludeImporter : public SpecificImporter
+	{
+	public:
+		ShaderIncludeImporter();
+		virtual ~ShaderIncludeImporter();
+
+		/** @copydoc SpecificImporter::isExtensionSupported */
+		virtual bool isExtensionSupported(const WString& ext) const override;
+
+		/** @copydoc SpecificImporter::isMagicNumberSupported */
+		virtual bool isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const override;
+
+		/** @copydoc SpecificImporter::import */
+		virtual ResourcePtr import(const Path& filePath, ConstImportOptionsPtr importOptions) override;
+	};
+
+	/** @} */
 }

+ 84 - 84
Source/BansheeCore/Include/BsSpecificImporter.h

@@ -1,85 +1,85 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Importer
-	 *  @{
-	 */
-
-	/** 
-	 * Contains a resource that was imported from a file that contains multiple resources (e.g. an animation from an FBX 
-	 * file). 
-	 */
-	struct SubResourceRaw
-	{
-		WString name; /**< Unique name of the sub-resource. */
-		SPtr<Resource> value; /**< Contents of the sub-resource. */
-	};
-
-	/**
-	 * Abstract class that is to be specialized in convertinga certain asset type into an engine usable resource. 
-	 * (e.g. a .png file into an engine usable texture).
-	 * 			
-	 * On initialization this class must register itself with the Importer module, which delegates asset import calls to a 
-	 * specific importer.
-	 */
-	class BS_CORE_EXPORT SpecificImporter
-	{
-	public:
-		SpecificImporter() {}
-		virtual ~SpecificImporter() {}
-
-		/**
-		 * Check is the provided extension supported by this importer.
-		 *
-		 * @note	Provided extension should be without the leading dot.
-		 */
-		virtual bool isExtensionSupported(const WString& ext) const = 0;
-
-		/** Check if the provided magic number is supported by this importer. */
-		virtual bool isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const = 0; 
-
-		/**
-		 * Imports the given file. If file contains more than one resource only the primary resource is imported (e.g. for
-		 * an FBX a mesh would be imported, but animations ignored).
-		 *
-		 * @param[in]	filePath	Pathname of the file, with file extension.
-		 * @return					null if it fails, otherwise the loaded object.
-		 */
-		virtual ResourcePtr import(const Path& filePath, ConstImportOptionsPtr importOptions) = 0;
-
-		/**
-		 * Imports the given file. This method returns all imported resources, which is relevant for files that can contain
-		 * multiple resources (e.g. an FBX which may contain both a mesh and animations). 
-		 *
-		 * @param[in]	filePath	Pathname of the file, with file extension.
-		 * @return					Empty array if it fails, otherwise the loaded objects. First element is always the 
-		 *							primary resource.
-		 */
-		virtual Vector<SubResourceRaw> importAll(const Path& filePath, ConstImportOptionsPtr importOptions);
-
-		/**
-		 * Creates import options specific for this importer. Import options are provided when calling import() in order 
-		 * to customize the import, and provide additional information.
-		 */
-		virtual ImportOptionsPtr createImportOptions() const;
-
-		/**
-		 * Gets the default import options.
-		 *
-		 * @return	The default import options.
-		 */
-		ConstImportOptionsPtr getDefaultImportOptions() const;
-
-	private:
-		mutable ConstImportOptionsPtr mDefaultImportOptions;
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Importer
+	 *  @{
+	 */
+
+	/** 
+	 * Contains a resource that was imported from a file that contains multiple resources (for example an animation from an
+	 * FBX file). 
+	 */
+	struct SubResourceRaw
+	{
+		WString name; /**< Unique name of the sub-resource. */
+		SPtr<Resource> value; /**< Contents of the sub-resource. */
+	};
+
+	/**
+	 * Abstract class that is to be specialized in convertinga certain asset type into an engine usable resource. 
+	 * (for example a .png file into an engine usable texture).
+	 * 			
+	 * On initialization this class must register itself with the Importer module, which delegates asset import calls to a 
+	 * specific importer.
+	 */
+	class BS_CORE_EXPORT SpecificImporter
+	{
+	public:
+		SpecificImporter() {}
+		virtual ~SpecificImporter() {}
+
+		/**
+		 * Check is the provided extension supported by this importer.
+		 *
+		 * @note	Provided extension should be without the leading dot.
+		 */
+		virtual bool isExtensionSupported(const WString& ext) const = 0;
+
+		/** Check if the provided magic number is supported by this importer. */
+		virtual bool isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const = 0; 
+
+		/**
+		 * Imports the given file. If file contains more than one resource only the primary resource is imported (for 
+		 * example for an FBX a mesh would be imported, but animations ignored).
+		 *
+		 * @param[in]	filePath	Pathname of the file, with file extension.
+		 * @return					null if it fails, otherwise the loaded object.
+		 */
+		virtual ResourcePtr import(const Path& filePath, ConstImportOptionsPtr importOptions) = 0;
+
+		/**
+		 * Imports the given file. This method returns all imported resources, which is relevant for files that can contain
+		 * multiple resources (for example an FBX which may contain both a mesh and animations). 
+		 *
+		 * @param[in]	filePath	Pathname of the file, with file extension.
+		 * @return					Empty array if it fails, otherwise the loaded objects. First element is always the 
+		 *							primary resource.
+		 */
+		virtual Vector<SubResourceRaw> importAll(const Path& filePath, ConstImportOptionsPtr importOptions);
+
+		/**
+		 * Creates import options specific for this importer. Import options are provided when calling import() in order 
+		 * to customize the import, and provide additional information.
+		 */
+		virtual ImportOptionsPtr createImportOptions() const;
+
+		/**
+		 * Gets the default import options.
+		 *
+		 * @return	The default import options.
+		 */
+		ConstImportOptionsPtr getDefaultImportOptions() const;
+
+	private:
+		mutable ConstImportOptionsPtr mDefaultImportOptions;
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 334 - 332
Source/BansheeCore/Include/BsStringTable.h

@@ -1,333 +1,335 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsResource.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Localization
-	 *  @{
-	 */
-
-	/** Loosely based on ISO 639-1 two letter language codes */
-	enum class Language
-	{
-		Afar, 
-		Abkhazian, 
-		Avestan, 
-		Afrikaans, 
-		Akan, 
-		Amharic, 
-		Aragonese, 
-		Arabic, 
-		Assamese, 
-		Avaric, 
-		Aymara, 
-		Azerbaijani, 
-		Bashkir, 
-		Belarusian, 
-		Bulgarian, 
-		Bihari, 
-		Bislama, 
-		Bambara, 
-		Bengali, 
-		Tibetan, 
-		Breton, 
-		Bosnian, 
-		Catalan, 
-		Chechen, 
-		Chamorro, 
-		Corsican, 
-		Cree, 
-		Czech, 
-		ChurchSlavic,
-		Chuvash, 
-		Welsh, 
-		Danish, 
-		German, 
-		Maldivian, 
-		Bhutani, 
-		Ewe, 		
-		Greek, 
-		EnglishUK, 
-		EnglishUS,
-		Esperanto, 
-		Spanish, 
-		Estonian, 
-		Basque, 
-		Persian, 
-		Fulah, 
-		Finnish, 
-		Fijian, 
-		Faroese, 
-		French, 
-		WesternFrisian, 
-		Irish, 
-		ScottishGaelic, 
-		Galician, 
-		Guarani, 
-		Gujarati, 
-		Manx, 
-		Hausa, 
-		Hebrew, 
-		Hindi, 
-		HiriMotu, 
-		Croatian, 
-		Haitian, 
-		Hungarian, 
-		Armenian, 
-		Herero, 
-		Interlingua, 
-		Indonesian, 
-		Interlingue, 
-		Igbo, 
-		SichuanYi, 
-		Inupiak, 
-		Ido, 
-		Icelandic, 
-		Italian, 
-		Inuktitut, 
-		Japanese, 
-		Javanese, 
-		Georgian, 
-		Kongo, 
-		Kikuyu, 
-		Kuanyama, 
-		Kazakh, 
-		Kalaallisut, 
-		Cambodian, 
-		Kannada, 
-		Korean, 
-		Kanuri, 
-		Kashmiri, 
-		Kurdish, 
-		Komi, 
-		Cornish, 
-		Kirghiz, 
-		Latin, 
-		Luxembourgish, 
-		Ganda, 
-		Limburgish,
-		Lingala, 
-		Laotian, 
-		Lithuanian, 
-		LubaKatanga, 
-		Latvian,
-		Malagasy, 
-		Marshallese, 
-		Maori, 
-		Macedonian, 
-		Malayalam, 
-		Mongolian, 
-		Moldavian, 
-		Marathi, 
-		Malay, 
-		Maltese, 
-		Burmese, 
-		Nauru, 
-		NorwegianBokmal, 
-		Ndebele, 
-		Nepali, 
-		Ndonga, 
-		Dutch, 
-		NorwegianNynorsk, 
-		Norwegian, 
-		Navaho, 
-		Nyanja, 
-		Provençal, 
-		Ojibwa, 
-		Oromo, 
-		Oriya, 
-		Ossetic, 
-		Punjabi, 
-		Pali, 
-		Polish, 
-		Pushto, 
-		Portuguese, 
-		Quechua, 
-		Romansh, 
-		Kirundi, 
-		Romanian, 
-		Russian, 
-		Kinyarwanda, 
-		Sanskrit, 
-		Sardinian, 
-		Sindhi, 
-		NorthernSami, 
-		Sangro, 
-		Sinhalese, 
-		Slovak, 
-		Slovenian, 
-		Samoan, 
-		Shona, 
-		Somali, 
-		Albanian, 
-		Serbian, 
-		Swati,
-		Sesotho,
-		Sundanese, 
-		Swedish, 
-		Swahili, 
-		Tamil, 
-		Telugu, 
-		Tajik, 
-		Thai, 
-		Tigrinya, 
-		Turkmen, 
-		Tagalog, 
-		Setswana, 
-		Tonga, 
-		Turkish, 
-		Tsonga, 
-		Tatar,
-		Twi, 
-		Tahitian, 
-		Uighur, 
-		Ukrainian, 
-		Urdu, 
-		Uzbek, 
-		Venda, 
-		Vietnamese, 
-		Volapuk, 
-		Walloon, 
-		Wolof, 
-		Xhosa, 
-		Yiddish, 
-		Yoruba, 
-		Zhuang,
-		Chinese,
-		Zulu,
-		Count // Number of entries
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Internal data used for representing a localized string instance. e.g. a specific instance of a localized string 
-	 * using specific parameters.
-	 */
-	struct LocalizedStringData
-	{
-		struct ParamOffset
-		{
-			ParamOffset()
-				:paramIdx(0), location(0)
-			{ }
-
-			ParamOffset(UINT32 _paramIdx, UINT32 _location)
-				:paramIdx(_paramIdx), location(_location)
-			{ }
-
-			UINT32 paramIdx;
-			UINT32 location;
-		};
-
-		LocalizedStringData();
-		~LocalizedStringData();
-
-		WString string;
-		UINT32 numParameters;
-		ParamOffset* parameterOffsets; 
-
-		void concatenateString(WString& outputString, WString* parameters, UINT32 numParameterValues) const;
-		void updateString(const WString& string);
-	};
-
-	/** Data for a single language in the string table. */
-	struct LanguageData
-	{
-		UnorderedMap<WString, SPtr<LocalizedStringData>> strings;
-	};
-
-	/** @endcond */
-
-	/** Used for string localization. Stores strings and their translations in various languages. */
-	class BS_CORE_EXPORT StringTable : public Resource
-	{
-		// TODO - When editing string table I will need to ensure that all languages of the same string have the same number of parameters
-
-	public:
-		StringTable();
-		~StringTable();
-
-		/** Returns all identifiers in the table. */
-		const UnorderedSet<WString>& getIdentifiers() const { return mIdentifiers; }
-
-		/**	Adds or modifies string translation for the specified language. */
-		void setString(const WString& identifier, Language language, const WString& string);
-
-		/**	Returns a string translation for the specified language. Returns the identifier itself if one doesn't exist. */
-		WString getString(const WString& identifier, Language language);
-
-		/** Removes the string described by identifier, from all languages. */
-		void removeString(const WString& identifier);
-
-		/**
-		 * Gets a string data for the specified string identifier and currently active language.
-		 *
-		 * @param[in]	identifier		   	Unique string identifier.
-		 * @param[in]	insertIfNonExisting	If true, a new string data for the specified identifier and language will be 
-		 *									added to the table if data doesn't already exist. The data will use the 
-		 *									identifier as the translation string.
-		 * @return							The string data. Don't store reference to this data as it may get deleted.
-		 */
-		SPtr<LocalizedStringData> getStringData(const WString& identifier, bool insertIfNonExisting = true);
-
-		/**
-		 * Gets a string data for the specified string identifier and language.
-		 *
-		 * @param[in]	identifier		   	Unique string identifier.
-		 * @param[in]	language		   	Language.
-		 * @param[in]	insertIfNonExisting	If true, a new string data for the specified identifier and language will be 
-		 *									added to the table if data doesn't already exist. The data will use the 
-		 *									identifier as the translation string.
-		 * @return							The string data. Don't store reference to this data as it may get deleted.
-		 */
-		SPtr<LocalizedStringData> getStringData(const WString& identifier, Language language, bool insertIfNonExisting = true);
-
-		/** Creates a new empty string table resource. */
-		static HStringTable create();
-
-		static const Language DEFAULT_LANGUAGE;
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Creates a new empty string table resource.
-		 *
-		 * @note	Internal method. Use create() for normal use.
-		 */
-		static SPtr<StringTable> _createPtr();
-
-		/** @endcond */
-	private:
-		friend class HString;
-		friend class StringTableManager;
-
-		/** Gets the currently active language. */
-		Language getActiveLanguage() const { return mActiveLanguage; }
-
-		/** Changes the currently active language. Any newly created strings will use this value. */
-		void setActiveLanguage(Language language);
-
-		Language mActiveLanguage;
-		LanguageData* mActiveLanguageData;
-		LanguageData* mDefaultLanguageData;
-
-		LanguageData* mAllLanguages;
-
-		UnorderedSet<WString> mIdentifiers;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class StringTableRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsResource.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Localization
+	 *  @{
+	 */
+
+	/** Loosely based on ISO 639-1 two letter language codes */
+	enum class Language
+	{
+		Afar, 
+		Abkhazian, 
+		Avestan, 
+		Afrikaans, 
+		Akan, 
+		Amharic, 
+		Aragonese, 
+		Arabic, 
+		Assamese, 
+		Avaric, 
+		Aymara, 
+		Azerbaijani, 
+		Bashkir, 
+		Belarusian, 
+		Bulgarian, 
+		Bihari, 
+		Bislama, 
+		Bambara, 
+		Bengali, 
+		Tibetan, 
+		Breton, 
+		Bosnian, 
+		Catalan, 
+		Chechen, 
+		Chamorro, 
+		Corsican, 
+		Cree, 
+		Czech, 
+		ChurchSlavic,
+		Chuvash, 
+		Welsh, 
+		Danish, 
+		German, 
+		Maldivian, 
+		Bhutani, 
+		Ewe, 		
+		Greek, 
+		EnglishUK, 
+		EnglishUS,
+		Esperanto, 
+		Spanish, 
+		Estonian, 
+		Basque, 
+		Persian, 
+		Fulah, 
+		Finnish, 
+		Fijian, 
+		Faroese, 
+		French, 
+		WesternFrisian, 
+		Irish, 
+		ScottishGaelic, 
+		Galician, 
+		Guarani, 
+		Gujarati, 
+		Manx, 
+		Hausa, 
+		Hebrew, 
+		Hindi, 
+		HiriMotu, 
+		Croatian, 
+		Haitian, 
+		Hungarian, 
+		Armenian, 
+		Herero, 
+		Interlingua, 
+		Indonesian, 
+		Interlingue, 
+		Igbo, 
+		SichuanYi, 
+		Inupiak, 
+		Ido, 
+		Icelandic, 
+		Italian, 
+		Inuktitut, 
+		Japanese, 
+		Javanese, 
+		Georgian, 
+		Kongo, 
+		Kikuyu, 
+		Kuanyama, 
+		Kazakh, 
+		Kalaallisut, 
+		Cambodian, 
+		Kannada, 
+		Korean, 
+		Kanuri, 
+		Kashmiri, 
+		Kurdish, 
+		Komi, 
+		Cornish, 
+		Kirghiz, 
+		Latin, 
+		Luxembourgish, 
+		Ganda, 
+		Limburgish,
+		Lingala, 
+		Laotian, 
+		Lithuanian, 
+		LubaKatanga, 
+		Latvian,
+		Malagasy, 
+		Marshallese, 
+		Maori, 
+		Macedonian, 
+		Malayalam, 
+		Mongolian, 
+		Moldavian, 
+		Marathi, 
+		Malay, 
+		Maltese, 
+		Burmese, 
+		Nauru, 
+		NorwegianBokmal, 
+		Ndebele, 
+		Nepali, 
+		Ndonga, 
+		Dutch, 
+		NorwegianNynorsk, 
+		Norwegian, 
+		Navaho, 
+		Nyanja, 
+		Provençal, 
+		Ojibwa, 
+		Oromo, 
+		Oriya, 
+		Ossetic, 
+		Punjabi, 
+		Pali, 
+		Polish, 
+		Pushto, 
+		Portuguese, 
+		Quechua, 
+		Romansh, 
+		Kirundi, 
+		Romanian, 
+		Russian, 
+		Kinyarwanda, 
+		Sanskrit, 
+		Sardinian, 
+		Sindhi, 
+		NorthernSami, 
+		Sangro, 
+		Sinhalese, 
+		Slovak, 
+		Slovenian, 
+		Samoan, 
+		Shona, 
+		Somali, 
+		Albanian, 
+		Serbian, 
+		Swati,
+		Sesotho,
+		Sundanese, 
+		Swedish, 
+		Swahili, 
+		Tamil, 
+		Telugu, 
+		Tajik, 
+		Thai, 
+		Tigrinya, 
+		Turkmen, 
+		Tagalog, 
+		Setswana, 
+		Tonga, 
+		Turkish, 
+		Tsonga, 
+		Tatar,
+		Twi, 
+		Tahitian, 
+		Uighur, 
+		Ukrainian, 
+		Urdu, 
+		Uzbek, 
+		Venda, 
+		Vietnamese, 
+		Volapuk, 
+		Walloon, 
+		Wolof, 
+		Xhosa, 
+		Yiddish, 
+		Yoruba, 
+		Zhuang,
+		Chinese,
+		Zulu,
+		Count // Number of entries
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Internal data used for representing a localized string instance. for example a specific instance of a localized
+	 * string using specific parameters.
+	 */
+	struct LocalizedStringData
+	{
+		struct ParamOffset
+		{
+			ParamOffset()
+				:paramIdx(0), location(0)
+			{ }
+
+			ParamOffset(UINT32 _paramIdx, UINT32 _location)
+				:paramIdx(_paramIdx), location(_location)
+			{ }
+
+			UINT32 paramIdx;
+			UINT32 location;
+		};
+
+		LocalizedStringData();
+		~LocalizedStringData();
+
+		WString string;
+		UINT32 numParameters;
+		ParamOffset* parameterOffsets; 
+
+		void concatenateString(WString& outputString, WString* parameters, UINT32 numParameterValues) const;
+		void updateString(const WString& string);
+	};
+
+	/** Data for a single language in the string table. */
+	struct LanguageData
+	{
+		UnorderedMap<WString, SPtr<LocalizedStringData>> strings;
+	};
+
+	/** @endcond */
+
+	/** Used for string localization. Stores strings and their translations in various languages. */
+	class BS_CORE_EXPORT StringTable : public Resource
+	{
+		// TODO - When editing string table I will need to ensure that all languages of the same string have the same number of parameters
+
+	public:
+		StringTable();
+		~StringTable();
+
+		/** Returns all identifiers in the table. */
+		const UnorderedSet<WString>& getIdentifiers() const { return mIdentifiers; }
+
+		/**	Adds or modifies string translation for the specified language. */
+		void setString(const WString& identifier, Language language, const WString& string);
+
+		/**	Returns a string translation for the specified language. Returns the identifier itself if one doesn't exist. */
+		WString getString(const WString& identifier, Language language);
+
+		/** Removes the string described by identifier, from all languages. */
+		void removeString(const WString& identifier);
+
+		/**
+		 * Gets a string data for the specified string identifier and currently active language.
+		 *
+		 * @param[in]	identifier		   	Unique string identifier.
+		 * @param[in]	insertIfNonExisting	If true, a new string data for the specified identifier and language will be 
+		 *									added to the table if data doesn't already exist. The data will use the 
+		 *									identifier as the translation string.
+		 * @return							The string data. Don't store reference to this data as it may get deleted.
+		 */
+		SPtr<LocalizedStringData> getStringData(const WString& identifier, bool insertIfNonExisting = true);
+
+		/**
+		 * Gets a string data for the specified string identifier and language.
+		 *
+		 * @param[in]	identifier		   	Unique string identifier.
+		 * @param[in]	language		   	Language.
+		 * @param[in]	insertIfNonExisting	If true, a new string data for the specified identifier and language will be 
+		 *									added to the table if data doesn't already exist. The data will use the 
+		 *									identifier as the translation string.
+		 * @return							The string data. Don't store reference to this data as it may get deleted.
+		 */
+		SPtr<LocalizedStringData> getStringData(const WString& identifier, Language language, bool insertIfNonExisting = true);
+
+		/** Creates a new empty string table resource. */
+		static HStringTable create();
+
+		static const Language DEFAULT_LANGUAGE;
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Creates a new empty string table resource.
+		 *
+		 * @note	Internal method. Use create() for normal use.
+		 */
+		static SPtr<StringTable> _createPtr();
+
+		/** @} */
+	private:
+		friend class HString;
+		friend class StringTableManager;
+
+		/** Gets the currently active language. */
+		Language getActiveLanguage() const { return mActiveLanguage; }
+
+		/** Changes the currently active language. Any newly created strings will use this value. */
+		void setActiveLanguage(Language language);
+
+		Language mActiveLanguage;
+		LanguageData* mActiveLanguageData;
+		LanguageData* mDefaultLanguageData;
+
+		LanguageData* mAllLanguages;
+
+		UnorderedSet<WString> mIdentifiers;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class StringTableRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
 }

+ 1 - 1
Source/BansheeCore/Include/BsTextData.h

@@ -144,7 +144,7 @@ namespace BansheeEngine
 			 */
 			UINT32 fillBuffer(UINT32 page, Vector2* vertices, Vector2* uvs, UINT32* indexes, UINT32 offset, UINT32 size) const;
 
-			/**	Checks are we at a word boundary (i.e. next added character will start a new word). */
+			/**	Checks are we at a word boundary (meaning the next added character will start a new word). */
 			bool isAtWordBoundary() const;
 
 			/**	Returns the total number of characters on this line. */

+ 470 - 470
Source/BansheeCore/Include/BsTexture.h

@@ -1,471 +1,471 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsResource.h"
-#include "BsHardwareBuffer.h"
-#include "BsPixelUtil.h"
-#include "BsTextureView.h"
-
-namespace BansheeEngine 
-{
-	/** @addtogroup Resources
-	 *  @{
-	 */
-
-	/**	Flags that describe how is a texture used. */
-    enum TextureUsage
-    {
-		TU_STATIC = GBU_STATIC, /**< A regular texture that is not often or ever updated from the CPU. */
-		TU_DYNAMIC = GBU_DYNAMIC, /**< A regular texture that is often updated by the CPU. */
-		TU_RENDERTARGET = 0x200, /**< Texture that can be rendered to by the GPU. */
-		TU_DEPTHSTENCIL = 0x400, /**< Texture used as a depth/stencil buffer by the GPU. */
-		TU_LOADSTORE = 0x800, /**< Texture that allows load/store operations from the GPU program. */
-		TU_CPUCACHED = 0x1000, /**< Ensures all texture data will also be cached in system memory. */
-		TU_DEFAULT = TU_STATIC
-    };
-
-	/**	Available texture types. */
-    enum TextureType
-    {
-		TEX_TYPE_1D = 1, /**< One dimensional texture. Just a row of pixels. */
-		TEX_TYPE_2D = 2, /**< Two dimensional texture. */
-		TEX_TYPE_3D = 3, /**< Three dimensional texture. */
-		TEX_TYPE_CUBE_MAP = 4 /**< Texture consisting out of six 2D textures describing an inside of a cube. Allows special sampling. */
-    };
-
-	/**	Texture mipmap options. */
-	enum TextureMipmap
-	{
-		MIP_UNLIMITED = 0x7FFFFFFF /**< Create all mip maps down to 1x1. */
-	};
-
-	/** Properties of a Texture. Shared between sim and core thread versions of a Texture. */
-	class BS_CORE_EXPORT TextureProperties
-	{
-	public:
-		TextureProperties();
-		TextureProperties(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
-			PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount);
-
-		/**	Gets the type of texture. */
-        TextureType getTextureType() const { return mTextureType; }
-
-        /**
-		 * Gets the number of mipmaps to be used for this texture. This number excludes the top level map (which is always
-		 * assumed to be present).
-         */
-        UINT32 getNumMipmaps() const {return mNumMipmaps;}
-
-		/** Gets whether this texture will be set up so that on sampling it, hardware gamma correction is applied. */
-		bool isHardwareGammaEnabled() const { return mHwGamma; }
-
-		/**	Gets the number of samples used for multisampling (0 if multisampling is not used). */
-		UINT32 getMultisampleCount() const { return mMultisampleCount; }
-
-        /**	Returns the height of the texture.  */
-        UINT32 getHeight() const { return mHeight; }
-
-        /**	Returns the width of the texture. */
-        UINT32 getWidth() const { return mWidth; }
-
-        /**	Returns the depth of the texture (only applicable for 3D textures). */
-        UINT32 getDepth() const { return mDepth; }
-
-        /**	Returns texture usage (TextureUsage) of this texture. */
-        int getUsage() const { return mUsage; }
-
-		/**	Returns the pixel format for the texture surface. */
-		PixelFormat getFormat() const { return mFormat; }
-
-        /**	Returns true if the texture has an alpha layer. */
-        bool hasAlpha() const;
-
-        /**	Return the number of faces this texture has. */
-        UINT32 getNumFaces() const;
-
-		/**
-		 * Maps a sub-resource index to an exact face and mip level. Sub-resource indexes are used when reading or writing
-		 * to the resource.
-		 * 			
-		 * @note	
-		 * Sub-resource index is only valid for the instance it was created on. You cannot use a sub-resource index from a
-		 * different texture and expect to get valid result. Modifying the resource so the number of sub-resources changes
-		 * invalidates all sub-resource indexes.
-		 */
-		void mapFromSubresourceIdx(UINT32 subresourceIdx, UINT32& face, UINT32& mip) const;
-
-		/**
-		 * Map a face and a mip level to a sub-resource index you can use for updating or reading a specific sub-resource.
-		 * 			
-		 * @note	
-		 * Generated sub-resource index is only valid for the instance it was created on. Modifying the resource so the 
-		 * number of sub-resources changes, invalidates all sub-resource indexes.
-		 */
-		UINT32 mapToSubresourceIdx(UINT32 face, UINT32 mip) const;
-
-		/**
-		 * Allocates a buffer you may use for storage when reading or writing a sub-resource. You need to allocate such a 
-		 * buffer if you are calling readSubresource().
-		 *
-		 * You can retrieve a sub-resource index by calling mapToSubresourceIdx().
-		 * 			
-		 * @note	Thread safe.
-		 */
-		PixelDataPtr allocateSubresourceBuffer(UINT32 subresourceIdx) const;
-
-	protected:
-		friend class TextureRTTI;
-
-		UINT32 mHeight;
-		UINT32 mWidth;
-		UINT32 mDepth;
-
-		UINT32 mNumMipmaps;
-		bool mHwGamma;
-		UINT32 mMultisampleCount;
-
-		TextureType mTextureType;
-		PixelFormat mFormat;
-		int mUsage;
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Core thread version of a Texture.
-	 *
-	 * @note	Core thread.
-	 */
-	class BS_CORE_EXPORT TextureCore : public CoreObjectCore
-	{
-	public:
-		TextureCore(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
-			PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount, const PixelDataPtr& initData);
-		virtual ~TextureCore() {}
-
-
-		/** @copydoc CoreObjectCore::initialize */
-		virtual void initialize() override;
-
-		/**
-		 * Updates a part of the texture with the provided data.
-		 *
-		 * @param[in]	subresourceIdx		Index of the subresource to update, if the texture has more than one.
-		 * @param[in]	data				Data to update the texture with.
-		 * @param[in]	discardEntireBuffer When true the existing contents of the resource you are updating will be 
-		 *									discarded. This can make the operation faster. Resources with certain buffer 
-		 *									types might require this flag to be in a specific state otherwise the operation 
-		 *									will fail.
-		 */
-		virtual void writeSubresource(UINT32 subresourceIdx, const PixelData& data, bool discardEntireBuffer);
-
-		/**
-		 * Reads a part of the current resource into the provided @p data parameter.
-		 * 			Data buffer needs to be pre-allocated.
-		 *
-		 * @param[in]	subresourceIdx		Index of the subresource to update, if the texture has more than one.
-		 * @param[out]	data				Buffer that will receive the data. Should be allocated with 
-		 *									allocateSubresourceBuffer() to ensure it is of valid type and size.
-		 */
-		virtual void readSubresource(UINT32 subresourceIdx, PixelData& data);
-
-		/**
-		 * Locks the buffer for reading or writing.
-		 *
-		 * @param[in]	options 	Options for controlling what you may do with the locked data.
-		 * @param[in]	mipLevel	(optional) Mipmap level to lock.
-		 * @param[in]	face		(optional) Texture face to lock.					
-		 * @return					Pointer to the buffer data. Only valid until you call unlock().
-		 * 			
-		 * @note	
-		 * If you are just reading or writing one block of data use readData()/writeData() methods as they can be much faster
-		 * in certain situations.
-		 */
-		PixelData lock(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0);
-
-		/** 
-		 * Unlocks a previously locked buffer. After the buffer is unlocked, any data returned by lock becomes invalid. 
-		 *
-		 * @see	lock()
-		 */
-		void unlock();
-
-		/**
-		 * Copies the contents a subresource in this texture to another texture. Texture format and size of the subresource
-		 * must match.
-		 *
-		 * You are allowed to copy from a multisampled to non-multisampled surface, which will resolve the multisampled
-		 * surface before copying.
-		 *
-		 * @param[in]	srcSubresourceIdx	Index of the subresource to copy from.
-		 * @param[in]	destSubresourceIdx	Index of the subresource to copy to.
-		 * @param[in]	target				Texture that contains the destination subresource.
-		 */
-		void copy(UINT32 srcSubresourceIdx, UINT32 destSubresourceIdx, const SPtr<TextureCore>& target);
-
-		/**
-		 * Reads data from the texture buffer into the provided buffer.
-		 * 		  
-		 * @param[out]	dest		Previously allocated buffer to read data into.
-		 * @param[in]	mipLevel	(optional) Mipmap level to read from.
-		 * @param[in]	face		(optional) Texture face to read from.
-		 */
-		virtual void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
-
-		/**
-		 * Writes data from the provided buffer into the texture buffer.
-		 * 		  
-		 * @param[in]	dest				Buffer to retrieve the data from.
-		 * @param[in]	mipLevel			(optional) Mipmap level to write into.
-		 * @param[in]	face				(optional) Texture face to write into.
-		 * @param[in]	discardWholeBuffer	(optional) If true any existing texture data will be discard. This can improve 
-		 *									performance of the write operation.
-		 */
-		virtual void writeData(const PixelData& src, UINT32 mipLevel = 0, UINT32 face = 0, bool discardWholeBuffer = false) = 0;
-
-		/**
-		 * Returns true if the texture can be bound to a shader.
-		 *
-		 * @note	This is only false for some rare special cases (e.g. AA render texture in DX9). Internal method.
-		 */
-		virtual bool isBindableAsShaderResource() const { return true; }
-
-		/**	Returns properties that contain information about the texture. */
-		const TextureProperties& getProperties() const { return mProperties; }
-
-		/************************************************************************/
-		/* 								TEXTURE VIEW                      		*/
-		/************************************************************************/
-
-		/**
-		 * Requests a texture view for the specified mip and array ranges. Returns an existing view of one for the specified
-		 * ranges already exists, otherwise creates a new one. You must release all views by calling releaseView() when done.
-		 *
-		 * @note	Core thread only.
-		 */
-		static TextureViewPtr requestView(const SPtr<TextureCore>& texture, UINT32 mostDetailMip, UINT32 numMips,
-			UINT32 firstArraySlice, UINT32 numArraySlices, GpuViewUsage usage);
-
-		/**
-		 * Releases the view. View won't actually get destroyed until all references to it are released.
-		 *
-		 * @note	Core thread only.
-		 */
-		static void releaseView(const TextureViewPtr& view);
-
-	protected:
-		/** @copydoc lock */
-		virtual PixelData lockImpl(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
-
-		/** @copydoc unlock */
-		virtual void unlockImpl() = 0;
-
-		/** @copydoc copy */
-		virtual void copyImpl(UINT32 srcFace, UINT32 srcMipLevel, UINT32 destFace, UINT32 destMipLevel, 
-			const SPtr<TextureCore>& target) = 0;
-
-		/************************************************************************/
-		/* 								TEXTURE VIEW                      		*/
-		/************************************************************************/
-
-		/**	Creates a new empty/undefined texture view. */
-		virtual TextureViewPtr createView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& desc);
-
-		/**
-		 * Releases all internal texture view references. Views won't get destroyed if there are external references still 
-		 * held.
-		 */
-		void clearBufferViews();
-
-		/** Holds a single texture view with a usage reference count. */
-		struct TextureViewReference
-		{
-			TextureViewReference(TextureViewPtr _view)
-				:view(_view), refCount(0)
-			{ }
-
-			TextureViewPtr view;
-			UINT32 refCount;
-		};
-
-		UnorderedMap<TEXTURE_VIEW_DESC, TextureViewReference*, TextureView::HashFunction, TextureView::EqualFunction> mTextureViews;
-		TextureProperties mProperties;
-		PixelDataPtr mInitData;
-	};
-
-	/** @endcond */
-
-	/**
-	 * Abstract class representing a texture. Specific render systems have their own Texture implementations. Internally
-	 * represented as one or more surfaces with pixels in a certain number of dimensions, backed by a hardware buffer.
-	 *
-	 * @note	Sim thread.
-	 */
-    class BS_CORE_EXPORT Texture : public Resource
-    {
-    public:
-		/**
-		 * Updates the texture with new data. The actual write will be queued for later execution on the core thread. 
-		 * Provided data buffer will be locked until the operation completes.
-		 *
-		 * @param[in]	accessor	Accessor to queue the operation on.
-		 * @return					Async operation object you can use to track operation completion.
-		 *
-		 * @see		TextureCore::writeSubresource
-		 */
-		AsyncOp writeSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const PixelDataPtr& data, 
-			bool discardEntireBuffer);
-
-		/**
-		 * Reads internal texture data to the provided previously allocated buffer. The read is queued for execution on the
-		 * core thread and not executed immediately. Provided data buffer will be locked until the operation completes.
-		 *
-		 * @param[in]	accessor	Accessor to queue the operation on.
-		 * @return					Async operation object you can use to track operation completion.
-		 *
-		 * @see		TextureCore::readSubresource
-		 */
-		AsyncOp readSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const PixelDataPtr& data);
-
-		/**
-		 * Reads data from the cached system memory texture buffer into the provided buffer. 
-		 * 		  
-		 * @param[out]	dest		Previously allocated buffer to read data into.
-		 * @param[in]	mipLevel	(optional) Mipmap level to read from.
-		 * @param[in]	face		(optional) Texture face to read from.
-		 *
-		 * @note	
-		 * The data read is the cached texture data. Any data written to the texture from the GPU or core thread will not 
-		 * be reflected in this data. Use readSubresource() if you require those changes.
-		 * @note
-		 * The texture must have been created with TU_CPUCACHED usage otherwise this method will not return any data.
-		 */
-		void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0);
-
-		/**	Returns properties that contain information about the texture. */
-		const TextureProperties& getProperties() const { return mProperties; }
-
-		/**	Retrieves a core implementation of a texture usable only from the core thread. */
-		SPtr<TextureCore> getCore() const;
-
-		/************************************************************************/
-		/* 								STATICS		                     		*/
-		/************************************************************************/
-
-		/**
-		 * Creates a new empty texture.
-		 *
-		 * @param[in]	texType				Type of the texture.
-		 * @param[in]	width				Width of the texture in pixels.
-		 * @param[in]	height				Height of the texture in pixels.
-		 * @param[in]	depth				Depth of the texture in pixels (Must be 1 for 2D textures).
-		 * @param[in]	numMips				Number of mip-maps the texture has. This number excludes the full resolution map.
-		 * @param[in]	format				Format of the pixels.
-		 * @param[in]	usage				Describes how we plan on using the texture in the pipeline.
-		 * @param[in]	hwGammaCorrection	If true the texture data is assumed to have been gamma corrected and will be
-		 *									converted back to linear space when sampled on GPU.
-		 * @param[in]	multisampleCount	If higher than 1, texture containing multiple samples per pixel is created.
-		 */
-		static HTexture create(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
-			int numMips, PixelFormat format, int usage = TU_DEFAULT,
-			bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
-
-
-		/**
-		 * Creates a new empty texture.
-		 *
-		 * @param[in]	texType				Type of the texture.
-		 * @param[in]	width				Width of the texture in pixels.
-		 * @param[in]	height				Height of the texture in pixels.
-		 * @param[in]	numMips				Number of mip-maps the texture has. This number excludes the full resolution map.
-		 * @param[in]	format				Format of the pixels.
-		 * @param[in]	usage				Describes planned texture use.
-		 * @param[in]	hwGammaCorrection	If true the texture data is assumed to have been gamma corrected and will be
-		 *									converted back to linear space when sampled on GPU.
-		 * @param[in]	multisampleCount	If higher than 1, texture containing multiple samples per pixel is created.
-		 */
-		static HTexture create(TextureType texType, UINT32 width, UINT32 height, int numMips,
-			PixelFormat format, int usage = TU_DEFAULT,
-			bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
-
-		/**
-		 * Creates a new 2D or 3D texture initialized using the provided pixel data. Texture will not have any mipmaps.
-		 *
-		 * @param[in]	pixelData			Data to initialize the texture width.
-		 * @param[in]	usage				Describes planned texture use.
-		 * @param[in]	hwGammaCorrection	If true the texture data is assumed to have been gamma corrected and will be
-		 *									converted back to linear space when sampled on GPU.
-		 */
-		static HTexture create(const PixelDataPtr& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
-
-		/**
-		 * @copydoc	create(TextureType, UINT32, UINT32, UINT32, int, PixelFormat, int, bool, UINT32)
-		 *
-		 * @note	Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
-		 */
-		static TexturePtr _createPtr(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
-			int num_mips, PixelFormat format, int usage = TU_DEFAULT,
-			bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
-
-		/**
-		 * @copydoc	create(TextureType, UINT32, UINT32, int, PixelFormat, int, bool, UINT32)
-		 *
-		 * @note	Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
-		 */
-		static TexturePtr _createPtr(TextureType texType, UINT32 width, UINT32 height, int num_mips,
-			PixelFormat format, int usage = TU_DEFAULT, bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
-
-		/**
-		 * @copydoc	create(const PixelDataPtr&, int, bool)
-		 *
-		 * @note	Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
-		 */
-		static TexturePtr _createPtr(const PixelDataPtr& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
-
-    protected:
-		friend class TextureManager;
-
-		Texture(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
-			PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount);
-
-		Texture(const PixelDataPtr& pixelData, int usage, bool hwGamma);
-
-		/** @copydoc Resource::initialize */
-		void initialize() override;
-
-		/** @copydoc CoreObject::createCore */
-		SPtr<CoreObjectCore> createCore() const override;
-
-		/** @copydoc Resource::calculateSize */
-		UINT32 calculateSize() const;
-
-		/**
-		 * Creates buffers used for caching of CPU texture data.
-		 *
-		 * @note	Make sure to initialize all texture properties before calling this.
-		 */
-		void createCPUBuffers();
-
-		/**	Updates the cached CPU buffers with new data. */
-		void updateCPUBuffers(UINT32 subresourceIdx, const PixelData& data);
-
-	protected:
-		Vector<PixelDataPtr> mCPUSubresourceData;
-		TextureProperties mProperties;
-		mutable PixelDataPtr mInitData;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		Texture(); // Serialization only
-
-		friend class TextureRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-    };
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsResource.h"
+#include "BsHardwareBuffer.h"
+#include "BsPixelUtil.h"
+#include "BsTextureView.h"
+
+namespace BansheeEngine 
+{
+	/** @addtogroup Resources
+	 *  @{
+	 */
+
+	/**	Flags that describe how is a texture used. */
+    enum TextureUsage
+    {
+		TU_STATIC = GBU_STATIC, /**< A regular texture that is not often or ever updated from the CPU. */
+		TU_DYNAMIC = GBU_DYNAMIC, /**< A regular texture that is often updated by the CPU. */
+		TU_RENDERTARGET = 0x200, /**< Texture that can be rendered to by the GPU. */
+		TU_DEPTHSTENCIL = 0x400, /**< Texture used as a depth/stencil buffer by the GPU. */
+		TU_LOADSTORE = 0x800, /**< Texture that allows load/store operations from the GPU program. */
+		TU_CPUCACHED = 0x1000, /**< Ensures all texture data will also be cached in system memory. */
+		TU_DEFAULT = TU_STATIC
+    };
+
+	/**	Available texture types. */
+    enum TextureType
+    {
+		TEX_TYPE_1D = 1, /**< One dimensional texture. Just a row of pixels. */
+		TEX_TYPE_2D = 2, /**< Two dimensional texture. */
+		TEX_TYPE_3D = 3, /**< Three dimensional texture. */
+		TEX_TYPE_CUBE_MAP = 4 /**< Texture consisting out of six 2D textures describing an inside of a cube. Allows special sampling. */
+    };
+
+	/**	Texture mipmap options. */
+	enum TextureMipmap
+	{
+		MIP_UNLIMITED = 0x7FFFFFFF /**< Create all mip maps down to 1x1. */
+	};
+
+	/** Properties of a Texture. Shared between sim and core thread versions of a Texture. */
+	class BS_CORE_EXPORT TextureProperties
+	{
+	public:
+		TextureProperties();
+		TextureProperties(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
+			PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount);
+
+		/**	Gets the type of texture. */
+        TextureType getTextureType() const { return mTextureType; }
+
+        /**
+		 * Gets the number of mipmaps to be used for this texture. This number excludes the top level map (which is always
+		 * assumed to be present).
+         */
+        UINT32 getNumMipmaps() const {return mNumMipmaps;}
+
+		/** Gets whether this texture will be set up so that on sampling it, hardware gamma correction is applied. */
+		bool isHardwareGammaEnabled() const { return mHwGamma; }
+
+		/**	Gets the number of samples used for multisampling (0 if multisampling is not used). */
+		UINT32 getMultisampleCount() const { return mMultisampleCount; }
+
+        /**	Returns the height of the texture.  */
+        UINT32 getHeight() const { return mHeight; }
+
+        /**	Returns the width of the texture. */
+        UINT32 getWidth() const { return mWidth; }
+
+        /**	Returns the depth of the texture (only applicable for 3D textures). */
+        UINT32 getDepth() const { return mDepth; }
+
+        /**	Returns texture usage (TextureUsage) of this texture. */
+        int getUsage() const { return mUsage; }
+
+		/**	Returns the pixel format for the texture surface. */
+		PixelFormat getFormat() const { return mFormat; }
+
+        /**	Returns true if the texture has an alpha layer. */
+        bool hasAlpha() const;
+
+        /**	Return the number of faces this texture has. */
+        UINT32 getNumFaces() const;
+
+		/**
+		 * Maps a sub-resource index to an exact face and mip level. Sub-resource indexes are used when reading or writing
+		 * to the resource.
+		 * 			
+		 * @note	
+		 * Sub-resource index is only valid for the instance it was created on. You cannot use a sub-resource index from a
+		 * different texture and expect to get valid result. Modifying the resource so the number of sub-resources changes
+		 * invalidates all sub-resource indexes.
+		 */
+		void mapFromSubresourceIdx(UINT32 subresourceIdx, UINT32& face, UINT32& mip) const;
+
+		/**
+		 * Map a face and a mip level to a sub-resource index you can use for updating or reading a specific sub-resource.
+		 * 			
+		 * @note	
+		 * Generated sub-resource index is only valid for the instance it was created on. Modifying the resource so the 
+		 * number of sub-resources changes, invalidates all sub-resource indexes.
+		 */
+		UINT32 mapToSubresourceIdx(UINT32 face, UINT32 mip) const;
+
+		/**
+		 * Allocates a buffer you may use for storage when reading or writing a sub-resource. You need to allocate such a 
+		 * buffer if you are calling readSubresource().
+		 *
+		 * You can retrieve a sub-resource index by calling mapToSubresourceIdx().
+		 * 			
+		 * @note	Thread safe.
+		 */
+		PixelDataPtr allocateSubresourceBuffer(UINT32 subresourceIdx) const;
+
+	protected:
+		friend class TextureRTTI;
+
+		UINT32 mHeight;
+		UINT32 mWidth;
+		UINT32 mDepth;
+
+		UINT32 mNumMipmaps;
+		bool mHwGamma;
+		UINT32 mMultisampleCount;
+
+		TextureType mTextureType;
+		PixelFormat mFormat;
+		int mUsage;
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Core thread version of a Texture.
+	 *
+	 * @note	Core thread.
+	 */
+	class BS_CORE_EXPORT TextureCore : public CoreObjectCore
+	{
+	public:
+		TextureCore(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
+			PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount, const PixelDataPtr& initData);
+		virtual ~TextureCore() {}
+
+
+		/** @copydoc CoreObjectCore::initialize */
+		virtual void initialize() override;
+
+		/**
+		 * Updates a part of the texture with the provided data.
+		 *
+		 * @param[in]	subresourceIdx		Index of the subresource to update, if the texture has more than one.
+		 * @param[in]	data				Data to update the texture with.
+		 * @param[in]	discardEntireBuffer When true the existing contents of the resource you are updating will be 
+		 *									discarded. This can make the operation faster. Resources with certain buffer 
+		 *									types might require this flag to be in a specific state otherwise the operation 
+		 *									will fail.
+		 */
+		virtual void writeSubresource(UINT32 subresourceIdx, const PixelData& data, bool discardEntireBuffer);
+
+		/**
+		 * Reads a part of the current resource into the provided @p data parameter.
+		 * 			Data buffer needs to be pre-allocated.
+		 *
+		 * @param[in]	subresourceIdx		Index of the subresource to update, if the texture has more than one.
+		 * @param[out]	data				Buffer that will receive the data. Should be allocated with 
+		 *									allocateSubresourceBuffer() to ensure it is of valid type and size.
+		 */
+		virtual void readSubresource(UINT32 subresourceIdx, PixelData& data);
+
+		/**
+		 * Locks the buffer for reading or writing.
+		 *
+		 * @param[in]	options 	Options for controlling what you may do with the locked data.
+		 * @param[in]	mipLevel	(optional) Mipmap level to lock.
+		 * @param[in]	face		(optional) Texture face to lock.					
+		 * @return					Pointer to the buffer data. Only valid until you call unlock().
+		 * 			
+		 * @note	
+		 * If you are just reading or writing one block of data use readData()/writeData() methods as they can be much faster
+		 * in certain situations.
+		 */
+		PixelData lock(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0);
+
+		/** 
+		 * Unlocks a previously locked buffer. After the buffer is unlocked, any data returned by lock becomes invalid. 
+		 *
+		 * @see	lock()
+		 */
+		void unlock();
+
+		/**
+		 * Copies the contents a subresource in this texture to another texture. Texture format and size of the subresource
+		 * must match.
+		 *
+		 * You are allowed to copy from a multisampled to non-multisampled surface, which will resolve the multisampled
+		 * surface before copying.
+		 *
+		 * @param[in]	srcSubresourceIdx	Index of the subresource to copy from.
+		 * @param[in]	destSubresourceIdx	Index of the subresource to copy to.
+		 * @param[in]	target				Texture that contains the destination subresource.
+		 */
+		void copy(UINT32 srcSubresourceIdx, UINT32 destSubresourceIdx, const SPtr<TextureCore>& target);
+
+		/**
+		 * Reads data from the texture buffer into the provided buffer.
+		 * 		  
+		 * @param[out]	dest		Previously allocated buffer to read data into.
+		 * @param[in]	mipLevel	(optional) Mipmap level to read from.
+		 * @param[in]	face		(optional) Texture face to read from.
+		 */
+		virtual void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
+
+		/**
+		 * Writes data from the provided buffer into the texture buffer.
+		 * 		  
+		 * @param[in]	dest				Buffer to retrieve the data from.
+		 * @param[in]	mipLevel			(optional) Mipmap level to write into.
+		 * @param[in]	face				(optional) Texture face to write into.
+		 * @param[in]	discardWholeBuffer	(optional) If true any existing texture data will be discard. This can improve 
+		 *									performance of the write operation.
+		 */
+		virtual void writeData(const PixelData& src, UINT32 mipLevel = 0, UINT32 face = 0, bool discardWholeBuffer = false) = 0;
+
+		/**
+		 * Returns true if the texture can be bound to a shader.
+		 *
+		 * @note	This is only false for some rare special cases (for example AA render texture in DX9). Internal method.
+		 */
+		virtual bool isBindableAsShaderResource() const { return true; }
+
+		/**	Returns properties that contain information about the texture. */
+		const TextureProperties& getProperties() const { return mProperties; }
+
+		/************************************************************************/
+		/* 								TEXTURE VIEW                      		*/
+		/************************************************************************/
+
+		/**
+		 * Requests a texture view for the specified mip and array ranges. Returns an existing view of one for the specified
+		 * ranges already exists, otherwise creates a new one. You must release all views by calling releaseView() when done.
+		 *
+		 * @note	Core thread only.
+		 */
+		static TextureViewPtr requestView(const SPtr<TextureCore>& texture, UINT32 mostDetailMip, UINT32 numMips,
+			UINT32 firstArraySlice, UINT32 numArraySlices, GpuViewUsage usage);
+
+		/**
+		 * Releases the view. View won't actually get destroyed until all references to it are released.
+		 *
+		 * @note	Core thread only.
+		 */
+		static void releaseView(const TextureViewPtr& view);
+
+	protected:
+		/** @copydoc lock */
+		virtual PixelData lockImpl(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
+
+		/** @copydoc unlock */
+		virtual void unlockImpl() = 0;
+
+		/** @copydoc copy */
+		virtual void copyImpl(UINT32 srcFace, UINT32 srcMipLevel, UINT32 destFace, UINT32 destMipLevel, 
+			const SPtr<TextureCore>& target) = 0;
+
+		/************************************************************************/
+		/* 								TEXTURE VIEW                      		*/
+		/************************************************************************/
+
+		/**	Creates a new empty/undefined texture view. */
+		virtual TextureViewPtr createView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& desc);
+
+		/**
+		 * Releases all internal texture view references. Views won't get destroyed if there are external references still 
+		 * held.
+		 */
+		void clearBufferViews();
+
+		/** Holds a single texture view with a usage reference count. */
+		struct TextureViewReference
+		{
+			TextureViewReference(TextureViewPtr _view)
+				:view(_view), refCount(0)
+			{ }
+
+			TextureViewPtr view;
+			UINT32 refCount;
+		};
+
+		UnorderedMap<TEXTURE_VIEW_DESC, TextureViewReference*, TextureView::HashFunction, TextureView::EqualFunction> mTextureViews;
+		TextureProperties mProperties;
+		PixelDataPtr mInitData;
+	};
+
+	/** @endcond */
+
+	/**
+	 * Abstract class representing a texture. Specific render systems have their own Texture implementations. Internally
+	 * represented as one or more surfaces with pixels in a certain number of dimensions, backed by a hardware buffer.
+	 *
+	 * @note	Sim thread.
+	 */
+    class BS_CORE_EXPORT Texture : public Resource
+    {
+    public:
+		/**
+		 * Updates the texture with new data. The actual write will be queued for later execution on the core thread. 
+		 * Provided data buffer will be locked until the operation completes.
+		 *
+		 * @param[in]	accessor	Accessor to queue the operation on.
+		 * @return					Async operation object you can use to track operation completion.
+		 *
+		 * @see		TextureCore::writeSubresource
+		 */
+		AsyncOp writeSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const PixelDataPtr& data, 
+			bool discardEntireBuffer);
+
+		/**
+		 * Reads internal texture data to the provided previously allocated buffer. The read is queued for execution on the
+		 * core thread and not executed immediately. Provided data buffer will be locked until the operation completes.
+		 *
+		 * @param[in]	accessor	Accessor to queue the operation on.
+		 * @return					Async operation object you can use to track operation completion.
+		 *
+		 * @see		TextureCore::readSubresource
+		 */
+		AsyncOp readSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const PixelDataPtr& data);
+
+		/**
+		 * Reads data from the cached system memory texture buffer into the provided buffer. 
+		 * 		  
+		 * @param[out]	dest		Previously allocated buffer to read data into.
+		 * @param[in]	mipLevel	(optional) Mipmap level to read from.
+		 * @param[in]	face		(optional) Texture face to read from.
+		 *
+		 * @note	
+		 * The data read is the cached texture data. Any data written to the texture from the GPU or core thread will not 
+		 * be reflected in this data. Use readSubresource() if you require those changes.
+		 * @note
+		 * The texture must have been created with TU_CPUCACHED usage otherwise this method will not return any data.
+		 */
+		void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0);
+
+		/**	Returns properties that contain information about the texture. */
+		const TextureProperties& getProperties() const { return mProperties; }
+
+		/**	Retrieves a core implementation of a texture usable only from the core thread. */
+		SPtr<TextureCore> getCore() const;
+
+		/************************************************************************/
+		/* 								STATICS		                     		*/
+		/************************************************************************/
+
+		/**
+		 * Creates a new empty texture.
+		 *
+		 * @param[in]	texType				Type of the texture.
+		 * @param[in]	width				Width of the texture in pixels.
+		 * @param[in]	height				Height of the texture in pixels.
+		 * @param[in]	depth				Depth of the texture in pixels (Must be 1 for 2D textures).
+		 * @param[in]	numMips				Number of mip-maps the texture has. This number excludes the full resolution map.
+		 * @param[in]	format				Format of the pixels.
+		 * @param[in]	usage				Describes how we plan on using the texture in the pipeline.
+		 * @param[in]	hwGammaCorrection	If true the texture data is assumed to have been gamma corrected and will be
+		 *									converted back to linear space when sampled on GPU.
+		 * @param[in]	multisampleCount	If higher than 1, texture containing multiple samples per pixel is created.
+		 */
+		static HTexture create(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
+			int numMips, PixelFormat format, int usage = TU_DEFAULT,
+			bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
+
+
+		/**
+		 * Creates a new empty texture.
+		 *
+		 * @param[in]	texType				Type of the texture.
+		 * @param[in]	width				Width of the texture in pixels.
+		 * @param[in]	height				Height of the texture in pixels.
+		 * @param[in]	numMips				Number of mip-maps the texture has. This number excludes the full resolution map.
+		 * @param[in]	format				Format of the pixels.
+		 * @param[in]	usage				Describes planned texture use.
+		 * @param[in]	hwGammaCorrection	If true the texture data is assumed to have been gamma corrected and will be
+		 *									converted back to linear space when sampled on GPU.
+		 * @param[in]	multisampleCount	If higher than 1, texture containing multiple samples per pixel is created.
+		 */
+		static HTexture create(TextureType texType, UINT32 width, UINT32 height, int numMips,
+			PixelFormat format, int usage = TU_DEFAULT,
+			bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
+
+		/**
+		 * Creates a new 2D or 3D texture initialized using the provided pixel data. Texture will not have any mipmaps.
+		 *
+		 * @param[in]	pixelData			Data to initialize the texture width.
+		 * @param[in]	usage				Describes planned texture use.
+		 * @param[in]	hwGammaCorrection	If true the texture data is assumed to have been gamma corrected and will be
+		 *									converted back to linear space when sampled on GPU.
+		 */
+		static HTexture create(const PixelDataPtr& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
+
+		/**
+		 * @copydoc	create(TextureType, UINT32, UINT32, UINT32, int, PixelFormat, int, bool, UINT32)
+		 *
+		 * @note	Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
+		 */
+		static TexturePtr _createPtr(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
+			int num_mips, PixelFormat format, int usage = TU_DEFAULT,
+			bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
+
+		/**
+		 * @copydoc	create(TextureType, UINT32, UINT32, int, PixelFormat, int, bool, UINT32)
+		 *
+		 * @note	Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
+		 */
+		static TexturePtr _createPtr(TextureType texType, UINT32 width, UINT32 height, int num_mips,
+			PixelFormat format, int usage = TU_DEFAULT, bool hwGammaCorrection = false, UINT32 multisampleCount = 0);
+
+		/**
+		 * @copydoc	create(const PixelDataPtr&, int, bool)
+		 *
+		 * @note	Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
+		 */
+		static TexturePtr _createPtr(const PixelDataPtr& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
+
+    protected:
+		friend class TextureManager;
+
+		Texture(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
+			PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount);
+
+		Texture(const PixelDataPtr& pixelData, int usage, bool hwGamma);
+
+		/** @copydoc Resource::initialize */
+		void initialize() override;
+
+		/** @copydoc CoreObject::createCore */
+		SPtr<CoreObjectCore> createCore() const override;
+
+		/** @copydoc Resource::calculateSize */
+		UINT32 calculateSize() const;
+
+		/**
+		 * Creates buffers used for caching of CPU texture data.
+		 *
+		 * @note	Make sure to initialize all texture properties before calling this.
+		 */
+		void createCPUBuffers();
+
+		/**	Updates the cached CPU buffers with new data. */
+		void updateCPUBuffers(UINT32 subresourceIdx, const PixelData& data);
+
+	protected:
+		Vector<PixelDataPtr> mCPUSubresourceData;
+		TextureProperties mProperties;
+		mutable PixelDataPtr mInitData;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		Texture(); // Serialization only
+
+		friend class TextureRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+    };
+
+	/** @} */
 }

+ 99 - 99
Source/BansheeCore/Include/BsTextureView.h

@@ -1,100 +1,100 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Data describing a texture view. */
-	struct BS_CORE_EXPORT TEXTURE_VIEW_DESC
-	{
-		/**
-		 * First mip level of the parent texture the view binds (0 - base level). This applied to all array slices 
-		 * specified below.
-		 */
-		UINT32 mostDetailMip;
-
-		/** Number of mip levels to bind to the view. This applied to all array slices specified below. */
-		UINT32 numMips;
-
-		/**
-		 * First array slice the view binds to. This will be array index for 1D and 2D array textures, texture slice index 
-		 * for 3D textures, and face index for cube textures(cube index * 6).
- 		 */
-		UINT32 firstArraySlice;
-
-		/**
-		 * Number of array slices to bind tot he view. This will be number of array elements for 1D and 2D array textures, 
-		 * number of slices for 3D textures, and number of cubes for cube textures.
-		 */
-		UINT32 numArraySlices;
-
-		/** Type of texture view. */
-		GpuViewUsage usage;
-	};
-
-	/**
-	 * Texture views allow you to reference only a party of a texture. They may reference one or multiple mip-levels on one
-	 * or multiple texture array slices. Selected mip level will apply to all slices.
-	 *
-	 * They also allow you to re-purpose a texture. (e.g. make a render target  a bindable texture).
-	 *
-	 * @note	Core thread.
-	 */
-	class BS_CORE_EXPORT TextureView
-	{
-	public:
-		class HashFunction
-		{
-		public:
-			size_t operator()(const TEXTURE_VIEW_DESC &key) const;
-		};
-
-		class EqualFunction
-		{
-		public:
-			bool operator()(const TEXTURE_VIEW_DESC &a, const TEXTURE_VIEW_DESC &b) const;
-		};
-
-		virtual ~TextureView();
-
-		/**	Returns the most detailed mip level visible by the view. */
-		UINT32 getMostDetailedMip() const { return mDesc.mostDetailMip; }
-
-		/**	Returns the number of mip levels in a single slice visible by the view. */
-		UINT32 getNumMips() const { return mDesc.numMips; }
-
-		/**	Returns the first array slice index visible by this view. */
-		UINT32 getFirstArraySlice() const { return mDesc.firstArraySlice; }
-
-		/**	Returns the number of array slices visible by this view. */
-		UINT32 getNumArraySlices() const { return mDesc.numArraySlices; }
-
-		/**	Returns texture view usage. This determines where on the pipeline can be bind the view. */
-		GpuViewUsage getUsage() const { return mDesc.usage; }
-
-		/**	Returns the descriptor structure used for initializing the view. */
-		const TEXTURE_VIEW_DESC& getDesc() const { return mDesc; }
-
-		/**	Gets the owner texture the view is referencing. */
-		SPtr<TextureCore> getTexture() const { return mOwnerTexture; }
-
-	protected:
-		TextureView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& _desc);
-
-	protected:
-		friend class TextureCore;
-
-		TEXTURE_VIEW_DESC mDesc;
-		SPtr<TextureCore> mOwnerTexture;
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Data describing a texture view. */
+	struct BS_CORE_EXPORT TEXTURE_VIEW_DESC
+	{
+		/**
+		 * First mip level of the parent texture the view binds (0 - base level). This applied to all array slices 
+		 * specified below.
+		 */
+		UINT32 mostDetailMip;
+
+		/** Number of mip levels to bind to the view. This applied to all array slices specified below. */
+		UINT32 numMips;
+
+		/**
+		 * First array slice the view binds to. This will be array index for 1D and 2D array textures, texture slice index 
+		 * for 3D textures, and face index for cube textures(cube index * 6).
+ 		 */
+		UINT32 firstArraySlice;
+
+		/**
+		 * Number of array slices to bind tot he view. This will be number of array elements for 1D and 2D array textures, 
+		 * number of slices for 3D textures, and number of cubes for cube textures.
+		 */
+		UINT32 numArraySlices;
+
+		/** Type of texture view. */
+		GpuViewUsage usage;
+	};
+
+	/**
+	 * Texture views allow you to reference only a party of a texture. They may reference one or multiple mip-levels on one
+	 * or multiple texture array slices. Selected mip level will apply to all slices.
+	 *
+	 * They also allow you to re-purpose a texture (for example make a render target a bindable texture).
+	 *
+	 * @note	Core thread.
+	 */
+	class BS_CORE_EXPORT TextureView
+	{
+	public:
+		class HashFunction
+		{
+		public:
+			size_t operator()(const TEXTURE_VIEW_DESC &key) const;
+		};
+
+		class EqualFunction
+		{
+		public:
+			bool operator()(const TEXTURE_VIEW_DESC &a, const TEXTURE_VIEW_DESC &b) const;
+		};
+
+		virtual ~TextureView();
+
+		/**	Returns the most detailed mip level visible by the view. */
+		UINT32 getMostDetailedMip() const { return mDesc.mostDetailMip; }
+
+		/**	Returns the number of mip levels in a single slice visible by the view. */
+		UINT32 getNumMips() const { return mDesc.numMips; }
+
+		/**	Returns the first array slice index visible by this view. */
+		UINT32 getFirstArraySlice() const { return mDesc.firstArraySlice; }
+
+		/**	Returns the number of array slices visible by this view. */
+		UINT32 getNumArraySlices() const { return mDesc.numArraySlices; }
+
+		/**	Returns texture view usage. This determines where on the pipeline can be bind the view. */
+		GpuViewUsage getUsage() const { return mDesc.usage; }
+
+		/**	Returns the descriptor structure used for initializing the view. */
+		const TEXTURE_VIEW_DESC& getDesc() const { return mDesc; }
+
+		/**	Gets the owner texture the view is referencing. */
+		SPtr<TextureCore> getTexture() const { return mOwnerTexture; }
+
+	protected:
+		TextureView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& _desc);
+
+	protected:
+		friend class TextureCore;
+
+		TEXTURE_VIEW_DESC mDesc;
+		SPtr<TextureCore> mOwnerTexture;
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 230 - 230
Source/BansheeCore/Include/BsVertexDeclaration.h

@@ -1,231 +1,231 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-#include "BsColor.h"
-#include "BsCoreObject.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/** Semantics that are used for identifying the meaning of vertex buffer elements. */
-	enum VertexElementSemantic 
-	{
-		VES_POSITION = 1,
-		VES_BLEND_WEIGHTS = 2,
-        VES_BLEND_INDICES = 3,
-		VES_NORMAL = 4,
-		VES_COLOR = 5,
-		VES_TEXCOORD = 6,
-        VES_BITANGENT = 7,
-        VES_TANGENT = 8,
-		VES_POSITIONT = 9,
-		VES_PSIZE = 10
-	};
-
-	/**	Types used to identify base types of vertex element contents. */
-    enum VertexElementType
-    {
-        VET_FLOAT1 = 0,
-        VET_FLOAT2 = 1,
-        VET_FLOAT3 = 2,
-        VET_FLOAT4 = 3,
-		VET_COLOR = 4,
-		VET_SHORT1 = 5,
-		VET_SHORT2 = 6,
-		VET_SHORT3 = 7,
-		VET_SHORT4 = 8,
-        VET_UBYTE4 = 9,
-        VET_COLOR_ARGB = 10,
-        VET_COLOR_ABGR = 11,
-		VET_UINT4 = 12,
-		VET_SINT4 = 13
-    };
-
-	/**	Describes a single vertex element in a vertex declaration. */
-	class BS_CORE_EXPORT VertexElement
-    {
-    public:
-		VertexElement() {}
-        VertexElement(UINT16 source, UINT32 offset, VertexElementType theType,
-			VertexElementSemantic semantic, UINT16 index = 0);
-
-		bool operator== (const VertexElement& rhs) const;
-		bool operator!= (const VertexElement& rhs) const;
-
-		/**	Returns index of the vertex buffer from which this element is stored. */
-		UINT16 getStreamIdx() const { return mSource; }
-
-		/**
-		 * Returns an offset into the buffer where this vertex is stored. This value might be in bytes but doesn't have to
-		 * be, it's likely to be render API specific.
-		 */
-        UINT32 getOffset() const { return mOffset; }
-
-		/** Gets the base data type of tis element. */
-        VertexElementType getType() const { return mType; }
-
-		/**	Gets a semantic that describes what this element contains. */
-        VertexElementSemantic getSemantic() const { return mSemantic; }
-
-		/**
-		 * Gets an index of this element. Only relevant when you have multiple elements with the same semantic, 
-		 * e.g. uv0, uv1.
-		 */
-		UINT16 getSemanticIdx() const { return mIndex; }
-
-		/** Returns the size of this element in bytes. */
-		UINT32 getSize() const;
-
-		/**	Returns the size of a base element type. */
-		static UINT32 getTypeSize(VertexElementType etype);
-
-		/** Returns the number of values in the provided base element type. e.g. float4 has four values. */
-		static UINT16 getTypeCount(VertexElementType etype);
-
-		/**	Gets packed color vertex element type used by the active render system. */
-		static VertexElementType getBestColorVertexElementType();
-
-	protected:
-		UINT16 mSource;
-		UINT32 mOffset;
-		VertexElementType mType;
-		VertexElementSemantic mSemantic;
-		UINT16 mIndex;
-    };
-
-	BS_ALLOW_MEMCPY_SERIALIZATION(VertexElement);
-
-	/**	Contains information about a vertex declaration. */
-	class BS_CORE_EXPORT VertexDeclarationProperties
-	{
-	public:
-		VertexDeclarationProperties(const List<VertexElement>& elements);
-
-		bool operator== (const VertexDeclarationProperties& rhs) const;
-		bool operator!= (const VertexDeclarationProperties& rhs) const;
-
-		/**	Get the number of elements in the declaration. */
-        UINT32 getElementCount() const { return (UINT32)mElementList.size(); }
-        
-		/**	Returns a list of vertex elements in the declaration. */
-		const List<VertexElement>& getElements() const { return mElementList; }
-
-		/**	Returns a single vertex element at the specified index. */
-		const VertexElement* getElement(UINT16 index) const;
-
-		/**
-		 * Attempts to find an element by the given semantic and semantic index. If no element can be found null is returned.
-		 */
-		virtual const VertexElement* findElementBySemantic(VertexElementSemantic sem, UINT16 index = 0) const;
-
-		/**	Returns a list of all elements that use the provided source index. */
-		virtual List<VertexElement> findElementsBySource(UINT16 source) const;
-
-		/**	Returns the total size of all vertex elements using the provided source index. */
-		virtual UINT32 getVertexSize(UINT16 source) const;
-
-	protected:
-		friend class VertexDeclaration;
-		friend class VertexDeclarationRTTI;
-
-		List<VertexElement> mElementList;
-	};
-
-	/** @cond INTERNAL */
-
-	/**
-	 * Core thread portion of a VertexDeclaration.
-	 *
-	 * @note	Core thread.
-	 */
-	class BS_CORE_EXPORT VertexDeclarationCore : public CoreObjectCore
-    {
-	public:
-		virtual ~VertexDeclarationCore() { }
-
-		/** @copydoc CoreObjectCore::initialize */
-		void initialize() override;
-
-		/**	Returns properties describing the vertex declaration. */
-		const VertexDeclarationProperties& getProperties() const { return mProperties; }
-
-		/**	Returns an ID unique to this declaration. */
-		UINT32 getId() const { return mId; }
-
-		/**
-		 * Checks can a vertex buffer declared with this declaration be bound to a shader defined with the provided 
-		 * declaration.
-		 */
-		bool isCompatible(const SPtr<VertexDeclarationCore>& shaderDecl);
-
-		/**
-		 * Returns a list of vertex elements that the provided shader's vertex declaration expects but aren't present in 
-		 * this vertex declaration.
-		 */
-		Vector<VertexElement> getMissingElements(const SPtr<VertexDeclarationCore>& shaderDecl);
-
-    protected:
-		friend class HardwareBufferCoreManager;
-
-		VertexDeclarationCore(const List<VertexElement>& elements);
-
-		VertexDeclarationProperties mProperties;
-		UINT32 mId;
-
-		static UINT32 NextFreeId;
-    };
-
-	/** @endcond */
-
-	/**
-	 * Describes a set of vertex elements, used for describing contents of a vertex buffer or inputs to a vertex GPU program.
-	 *
-	 * @note	Sim thread.
-	 */
-	class BS_CORE_EXPORT VertexDeclaration : public IReflectable, public CoreObject
-    {
-	public:
-		virtual ~VertexDeclaration() { }
-
-		/** Returns properties describing the vertex declaration. */
-		const VertexDeclarationProperties& getProperties() const { return mProperties; }
-
-		/**	Retrieves a core implementation of a vertex declaration usable only from the core thread. */
-		SPtr<VertexDeclarationCore> getCore() const;
-
-		/** @copydoc HardwareBufferManager::createVertexDeclaration */
-		static VertexDeclarationPtr createVertexDeclaration(const List<VertexElement>& elements);
-
-    protected:
-		friend class HardwareBufferManager;
-
-		VertexDeclaration(const List<VertexElement>& elements);
-
-		/** @copydoc CoreObject::createCore */
-		SPtr<CoreObjectCore> createCore() const override;
-
-	protected:
-		VertexDeclarationProperties mProperties;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-	public:
-		friend class VertexDeclarationRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-    };
-
-	/**	Converts a vertex semantic enum to a readable name. */
-	BS_CORE_EXPORT String toString(const VertexElementSemantic& val);
-
-	/**	Converts a vertex semantic enum to a readable name. */
-	BS_CORE_EXPORT WString toWString(const VertexElementSemantic& val);
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+#include "BsColor.h"
+#include "BsCoreObject.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/** Semantics that are used for identifying the meaning of vertex buffer elements. */
+	enum VertexElementSemantic 
+	{
+		VES_POSITION = 1,
+		VES_BLEND_WEIGHTS = 2,
+        VES_BLEND_INDICES = 3,
+		VES_NORMAL = 4,
+		VES_COLOR = 5,
+		VES_TEXCOORD = 6,
+        VES_BITANGENT = 7,
+        VES_TANGENT = 8,
+		VES_POSITIONT = 9,
+		VES_PSIZE = 10
+	};
+
+	/**	Types used to identify base types of vertex element contents. */
+    enum VertexElementType
+    {
+        VET_FLOAT1 = 0,
+        VET_FLOAT2 = 1,
+        VET_FLOAT3 = 2,
+        VET_FLOAT4 = 3,
+		VET_COLOR = 4,
+		VET_SHORT1 = 5,
+		VET_SHORT2 = 6,
+		VET_SHORT3 = 7,
+		VET_SHORT4 = 8,
+        VET_UBYTE4 = 9,
+        VET_COLOR_ARGB = 10,
+        VET_COLOR_ABGR = 11,
+		VET_UINT4 = 12,
+		VET_SINT4 = 13
+    };
+
+	/**	Describes a single vertex element in a vertex declaration. */
+	class BS_CORE_EXPORT VertexElement
+    {
+    public:
+		VertexElement() {}
+        VertexElement(UINT16 source, UINT32 offset, VertexElementType theType,
+			VertexElementSemantic semantic, UINT16 index = 0);
+
+		bool operator== (const VertexElement& rhs) const;
+		bool operator!= (const VertexElement& rhs) const;
+
+		/**	Returns index of the vertex buffer from which this element is stored. */
+		UINT16 getStreamIdx() const { return mSource; }
+
+		/**
+		 * Returns an offset into the buffer where this vertex is stored. This value might be in bytes but doesn't have to
+		 * be, it's likely to be render API specific.
+		 */
+        UINT32 getOffset() const { return mOffset; }
+
+		/** Gets the base data type of tis element. */
+        VertexElementType getType() const { return mType; }
+
+		/**	Gets a semantic that describes what this element contains. */
+        VertexElementSemantic getSemantic() const { return mSemantic; }
+
+		/**
+		 * Gets an index of this element. Only relevant when you have multiple elements with the same semantic, 
+		 * for example uv0, uv1.
+		 */
+		UINT16 getSemanticIdx() const { return mIndex; }
+
+		/** Returns the size of this element in bytes. */
+		UINT32 getSize() const;
+
+		/**	Returns the size of a base element type. */
+		static UINT32 getTypeSize(VertexElementType etype);
+
+		/** Returns the number of values in the provided base element type. For example float4 has four values. */
+		static UINT16 getTypeCount(VertexElementType etype);
+
+		/**	Gets packed color vertex element type used by the active render system. */
+		static VertexElementType getBestColorVertexElementType();
+
+	protected:
+		UINT16 mSource;
+		UINT32 mOffset;
+		VertexElementType mType;
+		VertexElementSemantic mSemantic;
+		UINT16 mIndex;
+    };
+
+	BS_ALLOW_MEMCPY_SERIALIZATION(VertexElement);
+
+	/**	Contains information about a vertex declaration. */
+	class BS_CORE_EXPORT VertexDeclarationProperties
+	{
+	public:
+		VertexDeclarationProperties(const List<VertexElement>& elements);
+
+		bool operator== (const VertexDeclarationProperties& rhs) const;
+		bool operator!= (const VertexDeclarationProperties& rhs) const;
+
+		/**	Get the number of elements in the declaration. */
+        UINT32 getElementCount() const { return (UINT32)mElementList.size(); }
+        
+		/**	Returns a list of vertex elements in the declaration. */
+		const List<VertexElement>& getElements() const { return mElementList; }
+
+		/**	Returns a single vertex element at the specified index. */
+		const VertexElement* getElement(UINT16 index) const;
+
+		/**
+		 * Attempts to find an element by the given semantic and semantic index. If no element can be found null is returned.
+		 */
+		virtual const VertexElement* findElementBySemantic(VertexElementSemantic sem, UINT16 index = 0) const;
+
+		/**	Returns a list of all elements that use the provided source index. */
+		virtual List<VertexElement> findElementsBySource(UINT16 source) const;
+
+		/**	Returns the total size of all vertex elements using the provided source index. */
+		virtual UINT32 getVertexSize(UINT16 source) const;
+
+	protected:
+		friend class VertexDeclaration;
+		friend class VertexDeclarationRTTI;
+
+		List<VertexElement> mElementList;
+	};
+
+	/** @cond INTERNAL */
+
+	/**
+	 * Core thread portion of a VertexDeclaration.
+	 *
+	 * @note	Core thread.
+	 */
+	class BS_CORE_EXPORT VertexDeclarationCore : public CoreObjectCore
+    {
+	public:
+		virtual ~VertexDeclarationCore() { }
+
+		/** @copydoc CoreObjectCore::initialize */
+		void initialize() override;
+
+		/**	Returns properties describing the vertex declaration. */
+		const VertexDeclarationProperties& getProperties() const { return mProperties; }
+
+		/**	Returns an ID unique to this declaration. */
+		UINT32 getId() const { return mId; }
+
+		/**
+		 * Checks can a vertex buffer declared with this declaration be bound to a shader defined with the provided 
+		 * declaration.
+		 */
+		bool isCompatible(const SPtr<VertexDeclarationCore>& shaderDecl);
+
+		/**
+		 * Returns a list of vertex elements that the provided shader's vertex declaration expects but aren't present in 
+		 * this vertex declaration.
+		 */
+		Vector<VertexElement> getMissingElements(const SPtr<VertexDeclarationCore>& shaderDecl);
+
+    protected:
+		friend class HardwareBufferCoreManager;
+
+		VertexDeclarationCore(const List<VertexElement>& elements);
+
+		VertexDeclarationProperties mProperties;
+		UINT32 mId;
+
+		static UINT32 NextFreeId;
+    };
+
+	/** @endcond */
+
+	/**
+	 * Describes a set of vertex elements, used for describing contents of a vertex buffer or inputs to a vertex GPU program.
+	 *
+	 * @note	Sim thread.
+	 */
+	class BS_CORE_EXPORT VertexDeclaration : public IReflectable, public CoreObject
+    {
+	public:
+		virtual ~VertexDeclaration() { }
+
+		/** Returns properties describing the vertex declaration. */
+		const VertexDeclarationProperties& getProperties() const { return mProperties; }
+
+		/**	Retrieves a core implementation of a vertex declaration usable only from the core thread. */
+		SPtr<VertexDeclarationCore> getCore() const;
+
+		/** @copydoc HardwareBufferManager::createVertexDeclaration */
+		static VertexDeclarationPtr createVertexDeclaration(const List<VertexElement>& elements);
+
+    protected:
+		friend class HardwareBufferManager;
+
+		VertexDeclaration(const List<VertexElement>& elements);
+
+		/** @copydoc CoreObject::createCore */
+		SPtr<CoreObjectCore> createCore() const override;
+
+	protected:
+		VertexDeclarationProperties mProperties;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+	public:
+		friend class VertexDeclarationRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+    };
+
+	/**	Converts a vertex semantic enum to a readable name. */
+	BS_CORE_EXPORT String toString(const VertexElementSemantic& val);
+
+	/**	Converts a vertex semantic enum to a readable name. */
+	BS_CORE_EXPORT WString toWString(const VertexElementSemantic& val);
+
+	/** @} */
 }

+ 112 - 112
Source/BansheeCore/Include/BsVideoModeInfo.h

@@ -1,113 +1,113 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsCorePrerequisites.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup RenderAPI
-	 *  @{
-	 */
-
-	/**
-	 * Video mode contains information about how a render window presents its information to an output device like a 
-	 * monitor.
-	 */
-	class BS_CORE_EXPORT VideoMode
-	{
-	public:
-		VideoMode() {}
-
-		/**
-		 * Creates a new video mode.
-		 *
-		 * @param[in]	width		Width of the frame buffer in pixels.
-		 * @param[in]	height		Height of the frame buffer in pixels.
-		 * @param[in]	refreshRate	How often should the output device refresh the output image in hertz.
-		 * @param[in]	outputIdx	Output index of the output device. Normally this means output monitor. 0th index always
-		 *							represents the primary device while order of others is undefined.
-		 */
-		VideoMode(UINT32 width, UINT32 height, float refreshRate = 60.0f, UINT32 outputIdx = 0);
-		virtual ~VideoMode();
-
-		bool operator== (const VideoMode& other) const;
-
-		/**	Width of the front/back buffer in pixels. */
-		UINT32 getWidth() const { return mWidth; }
-
-		/**	Height of the front/back buffer in pixels. */
-		UINT32 getHeight() const { return mHeight; }
-
-		/**	Returns a refresh rate in hertz. */
-		virtual float getRefreshRate() const { return mRefreshRate; }
-
-		/**	Returns information about the parent output. */
-		UINT32 getOutputIdx() const { return mOutputIdx; }
-
-		/**
-		 * Determines was video mode user created or provided by the API/OS. API/OS created video modes can contain 
-		 * additional information that allows the video mode to be used more accurately and you should use them when possible.
-		 */
-		bool isCustom() const { return mIsCustom;  }
-	protected:
-		UINT32 mWidth = 1280;
-		UINT32 mHeight = 720;
-		float mRefreshRate = 60.0f;
-		UINT32 mOutputIdx = 0;
-		bool mIsCustom = true;
-	};
-
-	/** Contains information about a video output device, including a list of all available video modes. */
-	class BS_CORE_EXPORT VideoOutputInfo
-	{
-	public:
-		VideoOutputInfo() { }
-		virtual ~VideoOutputInfo();
-
-		VideoOutputInfo(const VideoOutputInfo&) = delete; // Make non-copyable
-		VideoOutputInfo& operator=(const VideoOutputInfo&) = delete; // Make non-copyable
-
-		/**	Name of the output device. */
-		const String& getName() const { return mName; }
-
-		/**	Number of available video modes for this output. */
-		UINT32 getNumVideoModes() const { return (UINT32)mVideoModes.size(); }
-
-		/**	Returns video mode at the specified index. */
-		const VideoMode& getVideoMode(UINT32 idx) const { return *mVideoModes.at(idx); }
-
-		/**	Returns the video mode currently used by the desktop. */
-		const VideoMode& getDesktopVideoMode() const { return *mDesktopVideoMode; }
-
-	protected:
-		String mName;
-		Vector<VideoMode*> mVideoModes;
-		VideoMode* mDesktopVideoMode = nullptr;
-	};
-
-	/** Contains information about available output devices (e.g. monitor) and their video modes. */
-	class BS_CORE_EXPORT VideoModeInfo
-	{
-	public:
-		VideoModeInfo() { }
-		virtual ~VideoModeInfo();
-
-		VideoModeInfo(const VideoModeInfo&) = delete; // Make non-copyable
-		VideoModeInfo& operator=(const VideoModeInfo&) = delete; // Make non-copyable
-
-		/**	Returns the number of available output devices. */
-		UINT32 getNumOutputs() const { return (UINT32)mOutputs.size(); }
-
-		/**
-		 * Returns video mode information about a specific output device. 0th index always represents the primary device 
-		 * while order of others is undefined.
-		 */
-		const VideoOutputInfo& getOutputInfo(UINT32 idx) const { return *mOutputs[idx]; }
-
-	protected:
-		Vector<VideoOutputInfo*> mOutputs;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsCorePrerequisites.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup RenderAPI
+	 *  @{
+	 */
+
+	/**
+	 * Video mode contains information about how a render window presents its information to an output device like a 
+	 * monitor.
+	 */
+	class BS_CORE_EXPORT VideoMode
+	{
+	public:
+		VideoMode() {}
+
+		/**
+		 * Creates a new video mode.
+		 *
+		 * @param[in]	width		Width of the frame buffer in pixels.
+		 * @param[in]	height		Height of the frame buffer in pixels.
+		 * @param[in]	refreshRate	How often should the output device refresh the output image in hertz.
+		 * @param[in]	outputIdx	Output index of the output device. Normally this means output monitor. 0th index always
+		 *							represents the primary device while order of others is undefined.
+		 */
+		VideoMode(UINT32 width, UINT32 height, float refreshRate = 60.0f, UINT32 outputIdx = 0);
+		virtual ~VideoMode();
+
+		bool operator== (const VideoMode& other) const;
+
+		/**	Width of the front/back buffer in pixels. */
+		UINT32 getWidth() const { return mWidth; }
+
+		/**	Height of the front/back buffer in pixels. */
+		UINT32 getHeight() const { return mHeight; }
+
+		/**	Returns a refresh rate in hertz. */
+		virtual float getRefreshRate() const { return mRefreshRate; }
+
+		/**	Returns information about the parent output. */
+		UINT32 getOutputIdx() const { return mOutputIdx; }
+
+		/**
+		 * Determines was video mode user created or provided by the API/OS. API/OS created video modes can contain 
+		 * additional information that allows the video mode to be used more accurately and you should use them when possible.
+		 */
+		bool isCustom() const { return mIsCustom;  }
+	protected:
+		UINT32 mWidth = 1280;
+		UINT32 mHeight = 720;
+		float mRefreshRate = 60.0f;
+		UINT32 mOutputIdx = 0;
+		bool mIsCustom = true;
+	};
+
+	/** Contains information about a video output device, including a list of all available video modes. */
+	class BS_CORE_EXPORT VideoOutputInfo
+	{
+	public:
+		VideoOutputInfo() { }
+		virtual ~VideoOutputInfo();
+
+		VideoOutputInfo(const VideoOutputInfo&) = delete; // Make non-copyable
+		VideoOutputInfo& operator=(const VideoOutputInfo&) = delete; // Make non-copyable
+
+		/**	Name of the output device. */
+		const String& getName() const { return mName; }
+
+		/**	Number of available video modes for this output. */
+		UINT32 getNumVideoModes() const { return (UINT32)mVideoModes.size(); }
+
+		/**	Returns video mode at the specified index. */
+		const VideoMode& getVideoMode(UINT32 idx) const { return *mVideoModes.at(idx); }
+
+		/**	Returns the video mode currently used by the desktop. */
+		const VideoMode& getDesktopVideoMode() const { return *mDesktopVideoMode; }
+
+	protected:
+		String mName;
+		Vector<VideoMode*> mVideoModes;
+		VideoMode* mDesktopVideoMode = nullptr;
+	};
+
+	/** Contains information about available output devices (for example monitor) and their video modes. */
+	class BS_CORE_EXPORT VideoModeInfo
+	{
+	public:
+		VideoModeInfo() { }
+		virtual ~VideoModeInfo();
+
+		VideoModeInfo(const VideoModeInfo&) = delete; // Make non-copyable
+		VideoModeInfo& operator=(const VideoModeInfo&) = delete; // Make non-copyable
+
+		/**	Returns the number of available output devices. */
+		UINT32 getNumOutputs() const { return (UINT32)mOutputs.size(); }
+
+		/**
+		 * Returns video mode information about a specific output device. 0th index always represents the primary device 
+		 * while order of others is undefined.
+		 */
+		const VideoOutputInfo& getOutputInfo(UINT32 idx) const { return *mOutputs[idx]; }
+
+	protected:
+		Vector<VideoOutputInfo*> mOutputs;
+	};
+
+	/** @} */
 }

+ 1 - 1
Source/BansheeD3D11RenderAPI/Include/BsD3D11Driver.h

@@ -10,7 +10,7 @@ namespace BansheeEngine
 	 *  @{
 	 */
 
-	/**	Provides information about a driver (e.g. hardware GPU driver or software emulated). */
+	/**	Provides information about a driver (for example hardware GPU driver or software emulated). */
 	class D3D11Driver
 	{
 	public:

+ 1 - 1
Source/BansheeD3D11RenderAPI/Include/BsD3D11GpuBufferView.h

@@ -13,7 +13,7 @@ namespace BansheeEngine
 
 	/**
 	 * Represents a specific view of a GpuBuffer. Different views all of the same buffer be used in different situations
-	 * (e.g. for reading from a shader, or for a unordered read/write operation).
+	 * (for example for reading from a shader, or for a unordered read/write operation).
 	 */
 	class BS_D3D11_EXPORT D3D11GpuBufferView : public GpuBufferView
 	{

+ 5 - 0
Source/BansheeEditor/Include/BsEditorPrerequisites.h

@@ -4,6 +4,10 @@
 
 #include "BsPrerequisites.h"
 
+/** @addtogroup Layers
+ *  @{
+ */
+
 /** @defgroup Editor Editor
  *	Provides functionality specific to the Banshee Editor.
  *  @{
@@ -62,6 +66,7 @@
  */
 
 /** @} */
+/** @} */
 
 #if (BS_PLATFORM == BS_PLATFORM_WIN32) && !defined(__MINGW32__)
 #	ifdef BS_ED_EXPORTS

+ 4 - 2
Source/BansheeEditor/Include/BsEditorWidget.h

@@ -91,7 +91,9 @@ namespace BansheeEngine
 		Event<void(EditorWidgetContainer*)> onParentChanged; /**< Triggered whenever widget parent container changes. */
 		Event<void(bool)> onFocusChanged; /**< Triggered whenever widget receives or loses focus. */
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**	Changes the size of the widget (and its internal GUI panel). */
 		void _setSize(UINT32 width, UINT32 height);
@@ -114,7 +116,7 @@ namespace BansheeEngine
 		/**	Enables the widget making its previously hidden GUI contents visible. */
 		void _enable();
 
-		/** @endcond */
+		/** @} */
 	protected:
 		friend class EditorWidgetManager;
 

+ 92 - 90
Source/BansheeEditor/Include/BsGUIColor.h

@@ -1,91 +1,93 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsGUIElement.h"
-#include "BsImageSprite.h"
-#include "BsGUIContent.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI-Editor
-	 *  @{
-	 */
-
-	/** GUI element that displays the set color. RGB and alpha values are displayed separately. */
-	class GUIColor : public GUIElement
-	{
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles. */
-		static const String& getGUITypeName();
-
-		/**
-		 * Creates a new GUI color element.
-		 *
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUIColor* create(const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI color element.
-		 *
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
-		 *								override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUIColor* create(const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-		/**	Sets the color to display. */
-		void setColor(const Color& color);
-
-		/**	Returns the currently displayed color. */
-		Color getColor() const { return mValue; }
-
-		Event<void()> onClicked; /**< Triggered when the user clicks on the GUI element. */
-
-		/** @cond INTERNAL */
-
-		/** @copydoc GUIElement::_getOptimalSize */
-		virtual Vector2I _getOptimalSize() const override;
-
-		/** @endcond */
-	protected:
-		GUIColor(const String& styleName, const GUIDimensions& dimensions);
-		virtual ~GUIColor();
-
-		/** @copydoc GUIElement::_getNumRenderElements() */
-		virtual UINT32 _getNumRenderElements() const override;
-
-		/** @copydoc GUIElement::_getMaterial() */
-		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_getNumQuads() */
-		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_fillBuffer() */
-		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
-			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::updateRenderElementsInternal() */
-		virtual void updateRenderElementsInternal() override;
-
-		/** @copydoc GUIElement::_mouseEvent() */
-		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
-
-	private:
-		static const float ALPHA_SPLIT_POSITION;
-
-		ImageSprite* mColorSprite;
-		ImageSprite* mAlphaSprite;
-
-		IMAGE_SPRITE_DESC mColorImageDesc;
-		IMAGE_SPRITE_DESC mAlphaImageDesc;
-
-		Color mValue;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsGUIElement.h"
+#include "BsImageSprite.h"
+#include "BsGUIContent.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI-Editor
+	 *  @{
+	 */
+
+	/** GUI element that displays the set color. RGB and alpha values are displayed separately. */
+	class GUIColor : public GUIElement
+	{
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles. */
+		static const String& getGUITypeName();
+
+		/**
+		 * Creates a new GUI color element.
+		 *
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUIColor* create(const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI color element.
+		 *
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
+		 *								override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUIColor* create(const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+		/**	Sets the color to display. */
+		void setColor(const Color& color);
+
+		/**	Returns the currently displayed color. */
+		Color getColor() const { return mValue; }
+
+		Event<void()> onClicked; /**< Triggered when the user clicks on the GUI element. */
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** @copydoc GUIElement::_getOptimalSize */
+		virtual Vector2I _getOptimalSize() const override;
+
+		/** @} */
+	protected:
+		GUIColor(const String& styleName, const GUIDimensions& dimensions);
+		virtual ~GUIColor();
+
+		/** @copydoc GUIElement::_getNumRenderElements() */
+		virtual UINT32 _getNumRenderElements() const override;
+
+		/** @copydoc GUIElement::_getMaterial() */
+		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_getNumQuads() */
+		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_fillBuffer() */
+		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
+			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::updateRenderElementsInternal() */
+		virtual void updateRenderElementsInternal() override;
+
+		/** @copydoc GUIElement::_mouseEvent() */
+		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
+
+	private:
+		static const float ALPHA_SPLIT_POSITION;
+
+		ImageSprite* mColorSprite;
+		ImageSprite* mAlphaSprite;
+
+		IMAGE_SPRITE_DESC mColorImageDesc;
+		IMAGE_SPRITE_DESC mAlphaImageDesc;
+
+		Color mValue;
+	};
+
+	/** @} */
 }

+ 254 - 252
Source/BansheeEditor/Include/BsGUIFieldBase.h

@@ -1,253 +1,255 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsGUIElementContainer.h"
-#include "BsGUIContent.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	/** Base class for all editor GUI fields. All fields are a combination of an optional label and an input field. */
-	class BS_ED_EXPORT GUIFieldBase : public GUIElementContainer
-	{
-	protected:
-		struct PrivatelyConstruct {};
-
-	public:
-		/**	Returns the style type name for the internal label element. */
-		static const String& getLabelStyleType()
-		{
-			static String LABEL_STYLE_TYPE = "EditorFieldLabel";
-			return LABEL_STYLE_TYPE;
-		}
-
-		GUIFieldBase(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
-			const String& labelStyle, const GUIDimensions& dimensions, bool withLabel);
-
-		/** @cond INTERNAL */
-
-		/** @copydoc GUIElementContainer::_updateLayoutInternal */
-		void _updateLayoutInternal(const GUILayoutData& data) override;
-
-		/** @copydoc GUIElementContainer::_getOptimalSize */
-		virtual Vector2I _getOptimalSize() const override;
-
-		/** @endcond */
-	protected:
-		virtual ~GUIFieldBase() { }
-
-		/** @copydoc GUIElementContainer::styleUpdated */
-		virtual void styleUpdated() override;
-
-		static const UINT32 DEFAULT_LABEL_WIDTH;
-
-		GUILayout* mLayout;
-		GUILabel* mLabel;
-	};
-
-	/**	Templated GUI field class that provides common methods needed for constructing an editor field. */
-	template <class T>
-	class TGUIField : public GUIFieldBase
-	{
-	public:
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const GUIContent& labelContent, UINT32 labelWidth, const GUIOptions& options,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), labelContent, labelWidth, *curStyle,
-				GUIDimensions::create(options), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
-		 *								override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const GUIContent& labelContent, const GUIOptions& options,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), labelContent, DEFAULT_LABEL_WIDTH, *curStyle,
-				GUIDimensions::create(options), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const HString& labelText, UINT32 labelWidth, const GUIOptions& options,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), labelWidth, *curStyle,
-				GUIDimensions::create(options), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const HString& labelText, const GUIOptions& options,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), DEFAULT_LABEL_WIDTH, *curStyle,
-				GUIDimensions::create(options), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field without a label.
-		 *
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const GUIOptions& options, const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), GUIContent(), 0, *curStyle,
-				GUIDimensions::create(options), false);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const GUIContent& labelContent, UINT32 labelWidth,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), labelContent, labelWidth, *curStyle, GUIDimensions::create(), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const GUIContent& labelContent,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), labelContent, DEFAULT_LABEL_WIDTH, *curStyle,
-				GUIDimensions::create(), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const HString& labelText, UINT32 labelWidth,
-			const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), labelWidth, *curStyle,
-				GUIDimensions::create(), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field with a label.
-		 *
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const HString& labelText, const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), DEFAULT_LABEL_WIDTH, *curStyle,
-				GUIDimensions::create(), true);
-		}
-
-		/**
-		 * Creates a new GUI editor field without a label.
-		 *
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static T* create(const String& style = StringUtil::BLANK)
-		{
-			const String* curStyle = &style;
-			if (*curStyle == StringUtil::BLANK)
-				curStyle = &T::getGUITypeName();
-
-			return bs_new<T>(PrivatelyConstruct(), GUIContent(), 0, *curStyle,
-				GUIDimensions::create(), false);
-		}
-
-		TGUIField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
-			const String& style, const GUIDimensions& dimensions, bool withLabel)
-			:GUIFieldBase(dummy, labelContent, labelWidth, style, dimensions, withLabel)
-		{ }
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsGUIElementContainer.h"
+#include "BsGUIContent.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	/** Base class for all editor GUI fields. All fields are a combination of an optional label and an input field. */
+	class BS_ED_EXPORT GUIFieldBase : public GUIElementContainer
+	{
+	protected:
+		struct PrivatelyConstruct {};
+
+	public:
+		/**	Returns the style type name for the internal label element. */
+		static const String& getLabelStyleType()
+		{
+			static String LABEL_STYLE_TYPE = "EditorFieldLabel";
+			return LABEL_STYLE_TYPE;
+		}
+
+		GUIFieldBase(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
+			const String& labelStyle, const GUIDimensions& dimensions, bool withLabel);
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** @copydoc GUIElementContainer::_updateLayoutInternal */
+		void _updateLayoutInternal(const GUILayoutData& data) override;
+
+		/** @copydoc GUIElementContainer::_getOptimalSize */
+		virtual Vector2I _getOptimalSize() const override;
+
+		/** @} */
+	protected:
+		virtual ~GUIFieldBase() { }
+
+		/** @copydoc GUIElementContainer::styleUpdated */
+		virtual void styleUpdated() override;
+
+		static const UINT32 DEFAULT_LABEL_WIDTH;
+
+		GUILayout* mLayout;
+		GUILabel* mLabel;
+	};
+
+	/**	Templated GUI field class that provides common methods needed for constructing an editor field. */
+	template <class T>
+	class TGUIField : public GUIFieldBase
+	{
+	public:
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const GUIContent& labelContent, UINT32 labelWidth, const GUIOptions& options,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), labelContent, labelWidth, *curStyle,
+				GUIDimensions::create(options), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
+		 *								override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const GUIContent& labelContent, const GUIOptions& options,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), labelContent, DEFAULT_LABEL_WIDTH, *curStyle,
+				GUIDimensions::create(options), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const HString& labelText, UINT32 labelWidth, const GUIOptions& options,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), labelWidth, *curStyle,
+				GUIDimensions::create(options), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const HString& labelText, const GUIOptions& options,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), DEFAULT_LABEL_WIDTH, *curStyle,
+				GUIDimensions::create(options), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field without a label.
+		 *
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const GUIOptions& options, const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), GUIContent(), 0, *curStyle,
+				GUIDimensions::create(options), false);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const GUIContent& labelContent, UINT32 labelWidth,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), labelContent, labelWidth, *curStyle, GUIDimensions::create(), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const GUIContent& labelContent,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), labelContent, DEFAULT_LABEL_WIDTH, *curStyle,
+				GUIDimensions::create(), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const HString& labelText, UINT32 labelWidth,
+			const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), labelWidth, *curStyle,
+				GUIDimensions::create(), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field with a label.
+		 *
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const HString& labelText, const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), GUIContent(labelText), DEFAULT_LABEL_WIDTH, *curStyle,
+				GUIDimensions::create(), true);
+		}
+
+		/**
+		 * Creates a new GUI editor field without a label.
+		 *
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static T* create(const String& style = StringUtil::BLANK)
+		{
+			const String* curStyle = &style;
+			if (*curStyle == StringUtil::BLANK)
+				curStyle = &T::getGUITypeName();
+
+			return bs_new<T>(PrivatelyConstruct(), GUIContent(), 0, *curStyle,
+				GUIDimensions::create(), false);
+		}
+
+		TGUIField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
+			const String& style, const GUIDimensions& dimensions, bool withLabel)
+			:GUIFieldBase(dummy, labelContent, labelWidth, style, dimensions, withLabel)
+		{ }
+	};
+
+	/** @} */
 }

+ 103 - 101
Source/BansheeEditor/Include/BsGUIFloatField.h

@@ -1,102 +1,104 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsGUIFieldBase.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI-Editor
-	 *  @{
-	 */
-
-	/**
-	 * A composite GUI object representing an editor field. Editor fields are a combination of a label and an input field.
-	 * Label is optional. This specific implementation displays a floating point input field.
-	 */
-	class BS_ED_EXPORT GUIFloatField : public TGUIField<GUIFloatField>
-	{
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles.  */
-		static const String& getGUITypeName();
-
-		/** Style type name for the internal input box. */
-		static const String& getInputStyleType();
-
-		GUIFloatField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
-			const String& style, const GUIDimensions& dimensions, bool withLabel);
-
-		/**	Returns the value of the input field. */
-		float getValue() const { return mValue; }
-
-		/**	Sets a new value in the input field. */
-		void setValue(float value);
-
-		/**
-		 * Sets a minimum and maximum allow values in the input field. Set to large negative/positive values if you don't
-		 * require clamping.
-		 */
-		void setRange(float min, float max);
-
-		/**	Checks is the input field currently active. */
-		bool hasInputFocus() const { return mHasInputFocus; }
-
-		/** @copydoc	GUIElement::setTint */
-		void setTint(const Color& color) override;
-
-		Event<void(float)> onValueChanged; /**< Triggers when the field value changes. */
-		Event<void()> onConfirm; /**< Triggered when the user hits the Enter key with the input box in focus. */
-
-		/** @cond INTERNAL */
-
-		/**
-		 * Sets a new value in the input field, and also allows you to choose should the field trigger an onValueChanged
-		 * event.
-		 */
-		void _setValue(float value, bool triggerEvent);
-
-		/** @endcond */
-	protected:
-		virtual ~GUIFloatField();
-
-		/** @copydoc GUIElementContainer::_hasCustomCursor */
-		bool _hasCustomCursor(const Vector2I position, CursorType& type) const override;
-
-		/** @copydoc GUIElementContainer::_mouseEvent */
-		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
-
-		/** @copydoc GUIElementContainer::styleUpdated */
-		void styleUpdated() override;
-
-		/**	Triggered when the input box value changes. */
-		void valueChanged(const WString& newValue);
-
-		/**
-		 * Triggered when the input box value changes, but unlike the previous overload the value is parsed into a floating
-		 * point value.
-		 */
-		void valueChanged(float newValue);
-
-		/**	Triggers when the input box receives or loses keyboard focus. */
-		void focusChanged(bool focus);
-
-		/**	Triggered when the users confirms input in the input box. */
-		void inputConfirmed();
-
-		/** Callback that checks can the provided string be converted to a floating point value. */
-		static bool floatFilter(const WString& str);
-
-		static const float DRAG_SPEED;
-
-		GUIInputBox* mInputBox;
-		float mValue;
-		INT32 mLastDragPos;
-		float mMinValue;
-		float mMaxValue;
-		bool mIsDragging;
-		bool mHasInputFocus;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsGUIFieldBase.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI-Editor
+	 *  @{
+	 */
+
+	/**
+	 * A composite GUI object representing an editor field. Editor fields are a combination of a label and an input field.
+	 * Label is optional. This specific implementation displays a floating point input field.
+	 */
+	class BS_ED_EXPORT GUIFloatField : public TGUIField<GUIFloatField>
+	{
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles.  */
+		static const String& getGUITypeName();
+
+		/** Style type name for the internal input box. */
+		static const String& getInputStyleType();
+
+		GUIFloatField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
+			const String& style, const GUIDimensions& dimensions, bool withLabel);
+
+		/**	Returns the value of the input field. */
+		float getValue() const { return mValue; }
+
+		/**	Sets a new value in the input field. */
+		void setValue(float value);
+
+		/**
+		 * Sets a minimum and maximum allow values in the input field. Set to large negative/positive values if you don't
+		 * require clamping.
+		 */
+		void setRange(float min, float max);
+
+		/**	Checks is the input field currently active. */
+		bool hasInputFocus() const { return mHasInputFocus; }
+
+		/** @copydoc	GUIElement::setTint */
+		void setTint(const Color& color) override;
+
+		Event<void(float)> onValueChanged; /**< Triggers when the field value changes. */
+		Event<void()> onConfirm; /**< Triggered when the user hits the Enter key with the input box in focus. */
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Sets a new value in the input field, and also allows you to choose should the field trigger an onValueChanged
+		 * event.
+		 */
+		void _setValue(float value, bool triggerEvent);
+
+		/** @} */
+	protected:
+		virtual ~GUIFloatField();
+
+		/** @copydoc GUIElementContainer::_hasCustomCursor */
+		bool _hasCustomCursor(const Vector2I position, CursorType& type) const override;
+
+		/** @copydoc GUIElementContainer::_mouseEvent */
+		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
+
+		/** @copydoc GUIElementContainer::styleUpdated */
+		void styleUpdated() override;
+
+		/**	Triggered when the input box value changes. */
+		void valueChanged(const WString& newValue);
+
+		/**
+		 * Triggered when the input box value changes, but unlike the previous overload the value is parsed into a floating
+		 * point value.
+		 */
+		void valueChanged(float newValue);
+
+		/**	Triggers when the input box receives or loses keyboard focus. */
+		void focusChanged(bool focus);
+
+		/**	Triggered when the users confirms input in the input box. */
+		void inputConfirmed();
+
+		/** Callback that checks can the provided string be converted to a floating point value. */
+		static bool floatFilter(const WString& str);
+
+		static const float DRAG_SPEED;
+
+		GUIInputBox* mInputBox;
+		float mValue;
+		INT32 mLastDragPos;
+		float mMinValue;
+		float mMaxValue;
+		bool mIsDragging;
+		bool mHasInputFocus;
+	};
+
+	/** @} */
 }

+ 104 - 102
Source/BansheeEditor/Include/BsGUIIntField.h

@@ -1,103 +1,105 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsGUIFieldBase.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI-Editor
-	 *  @{
-	 */
-
-	/**
-	 * A composite GUI object representing an editor field. Editor fields are a combination of a label and an input field.
-	 * Label is optional. This specific implementation displays a integer input field.
-	 */
-	class BS_ED_EXPORT GUIIntField : public TGUIField<GUIIntField>
-	{
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles. */
-		static const String& getGUITypeName();
-
-		/** Style type name for the internal input box. */
-		static const String& getInputStyleType();
-
-		GUIIntField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
-			const String& style, const GUIDimensions& dimensions, bool withLabel);
-
-		/**	Returns the value of the input field. */
-		INT32 getValue() const { return mValue; }
-
-		/**	Sets a new value in the input field. */
-		void setValue(INT32 value);
-
-		/**
-		 * Sets a minimum and maximum allow values in the input field. Set to large negative/positive values if you don't
-		 * require clamping.
-		 */
-		void setRange(INT32 min, INT32 max);
-
-		/**	Checks is the input field currently active. */
-		bool hasInputFocus() const { return mHasInputFocus; }
-
-		/** @copydoc GUIElement::setTint */
-		void setTint(const Color& color) override;
-
-		Event<void(INT32)> onValueChanged; /**< Triggers when the internal value changes. */
-		Event<void()> onConfirm; /**< Triggered when the user hits the Enter key with the input box in focus. */
-
-		/** @cond INTERNAL */
-
-		/**
-		 * Sets a new value in the input field, and also allows you to choose should the field trigger an onValueChanged 
-		 * event.
-		 */
-		void _setValue(INT32 value, bool triggerEvent);
-
-		/** @endcond */
-	protected:
-		virtual ~GUIIntField();
-
-		/** @copydoc GUIElement::_hasCustomCursor */
-		bool _hasCustomCursor(const Vector2I position, CursorType& type) const override;
-
-		/** @copydoc GUIElement::_mouseEvent */
-		bool _mouseEvent(const GUIMouseEvent& ev)  override;
-
-		/** @copydoc GUIElement::styleUpdated */
-		void styleUpdated() override;
-
-		/**	Triggered when the input box value changes. */
-		void valueChanged(const WString& newValue);
-
-		/**
-		 * Triggered when the input box value changes, but unlike the previous overload the value is parsed into an integer
-		 * value.
-		 */
-		void valueChanged(INT32 newValue);
-
-		/**	Triggers when the input box receives or loses keyboard focus. */
-		void focusChanged(bool focus);
-
-		/**	Triggered when the users confirms input in the input box. */
-		void inputConfirmed();
-
-		/**	Callback that checks can the provided string be converted to an integer value. */
-		static bool intFilter(const WString& str);
-
-		static const INT32 DRAG_SPEED;
-
-		GUIInputBox* mInputBox;
-		INT32 mValue;
-		INT32 mLastDragPos;
-		INT32 mMinValue;
-		INT32 mMaxValue;
-		bool mIsDragging;
-		bool mIsDragCursorSet;
-		bool mHasInputFocus;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsGUIFieldBase.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI-Editor
+	 *  @{
+	 */
+
+	/**
+	 * A composite GUI object representing an editor field. Editor fields are a combination of a label and an input field.
+	 * Label is optional. This specific implementation displays a integer input field.
+	 */
+	class BS_ED_EXPORT GUIIntField : public TGUIField<GUIIntField>
+	{
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles. */
+		static const String& getGUITypeName();
+
+		/** Style type name for the internal input box. */
+		static const String& getInputStyleType();
+
+		GUIIntField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth,
+			const String& style, const GUIDimensions& dimensions, bool withLabel);
+
+		/**	Returns the value of the input field. */
+		INT32 getValue() const { return mValue; }
+
+		/**	Sets a new value in the input field. */
+		void setValue(INT32 value);
+
+		/**
+		 * Sets a minimum and maximum allow values in the input field. Set to large negative/positive values if you don't
+		 * require clamping.
+		 */
+		void setRange(INT32 min, INT32 max);
+
+		/**	Checks is the input field currently active. */
+		bool hasInputFocus() const { return mHasInputFocus; }
+
+		/** @copydoc GUIElement::setTint */
+		void setTint(const Color& color) override;
+
+		Event<void(INT32)> onValueChanged; /**< Triggers when the internal value changes. */
+		Event<void()> onConfirm; /**< Triggered when the user hits the Enter key with the input box in focus. */
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Sets a new value in the input field, and also allows you to choose should the field trigger an onValueChanged 
+		 * event.
+		 */
+		void _setValue(INT32 value, bool triggerEvent);
+
+		/** @} */
+	protected:
+		virtual ~GUIIntField();
+
+		/** @copydoc GUIElement::_hasCustomCursor */
+		bool _hasCustomCursor(const Vector2I position, CursorType& type) const override;
+
+		/** @copydoc GUIElement::_mouseEvent */
+		bool _mouseEvent(const GUIMouseEvent& ev)  override;
+
+		/** @copydoc GUIElement::styleUpdated */
+		void styleUpdated() override;
+
+		/**	Triggered when the input box value changes. */
+		void valueChanged(const WString& newValue);
+
+		/**
+		 * Triggered when the input box value changes, but unlike the previous overload the value is parsed into an integer
+		 * value.
+		 */
+		void valueChanged(INT32 newValue);
+
+		/**	Triggers when the input box receives or loses keyboard focus. */
+		void focusChanged(bool focus);
+
+		/**	Triggered when the users confirms input in the input box. */
+		void inputConfirmed();
+
+		/**	Callback that checks can the provided string be converted to an integer value. */
+		static bool intFilter(const WString& str);
+
+		static const INT32 DRAG_SPEED;
+
+		GUIInputBox* mInputBox;
+		INT32 mValue;
+		INT32 mLastDragPos;
+		INT32 mMinValue;
+		INT32 mMaxValue;
+		bool mIsDragging;
+		bool mIsDragCursorSet;
+		bool mHasInputFocus;
+	};
+
+	/** @} */
 }

+ 111 - 111
Source/BansheeEditor/Include/BsGUIStatusBar.h

@@ -1,112 +1,112 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsGUIElementContainer.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup GUI-Editor
-	 *  @{
-	 */
-
-	/** Editor window status bar that displays log messages and various other information. */
-	class BS_ED_EXPORT GUIStatusBar : public GUIElementContainer
-	{
-		struct PrivatelyConstruct {};
-
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles. */
-		static const String& getGUITypeName();
-
-		/** Returns type name of the internal background GUI element. */
-		static const String& getGUIBackgroundTypeName();
-
-		/** Returns type name of the internal message button GUI element. */
-		static const String& getGUIMessageTypeName();
-
-		/**
-		 * Creates a new GUI status bar.
-		 *
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUIStatusBar* create(const GUIOptions& options, const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI status bar.
-		 *
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUIStatusBar* create(const String& style = StringUtil::BLANK);
-
-		GUIStatusBar(const PrivatelyConstruct& dummy, const String& style, const GUIDimensions& dimensions);
-
-		/**
-		 * Updates the active project displayed on the status bar.
-		 * 	
-		 * @param[in]	name		Name of the project.
-		 * @param[in]	modified	Should the project be displayed as modified (i.e. needs saving).
-		 */
-		void setProject(const WString& name, bool modified);
-
-		/**
-		 * Updates the active scene displayed on the status bar.
-		 * 	
-		 * @param[in]	name		Name of the scene.
-		 * @param[in]	modified	Should the scene be displayed as modified (i.e. needs saving).
-		 */
-		void setScene(const WString& name, bool modified);
-
-		/**	Activates or deactivates the "compilation in progress" visuals on the status bar. */
-		void setIsCompiling(bool compiling);
-
-		/** @copydoc GUIElement::setTint */
-		virtual void setTint(const Color& color) override;
-
-		/** @copydoc GUIElement::_updateLayoutInternal */
-		void _updateLayoutInternal(const GUILayoutData& data) override;
-
-		/** @copydoc GUIElement::_getOptimalSize */
-		Vector2I _getOptimalSize() const override;
-
-		Event<void()> onMessageClicked; /**< Triggered when the user clicks on the console message. */
-	private:
-		virtual ~GUIStatusBar();
-
-		/** @copydoc GUIElement::styleUpdated */
-		void styleUpdated() override;
-
-		/**	Triggered when the debug Log was modified. */
-		void logModified();
-
-		/**	Triggered when the user clicks on the message display. */
-		void messageBtnClicked();
-
-	private:
-		static const Color COLOR_INFO;
-		static const Color COLOR_WARNING;
-		static const Color COLOR_ERROR;
-
-		GUIPanel* mPanel;
-		GUIPanel* mBgPanel;
-		GUIButton* mMessage;
-		GUILabel* mScene;
-		GUILabel* mProject;
-		GUILabel* mCompiling;
-		GUITexture* mBackground;
-
-		HEvent mLogEntryAddedConn;
-		HEvent mMessageBtnPressedConn;
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsGUIElementContainer.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup GUI-Editor
+	 *  @{
+	 */
+
+	/** Editor window status bar that displays log messages and various other information. */
+	class BS_ED_EXPORT GUIStatusBar : public GUIElementContainer
+	{
+		struct PrivatelyConstruct {};
+
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles. */
+		static const String& getGUITypeName();
+
+		/** Returns type name of the internal background GUI element. */
+		static const String& getGUIBackgroundTypeName();
+
+		/** Returns type name of the internal message button GUI element. */
+		static const String& getGUIMessageTypeName();
+
+		/**
+		 * Creates a new GUI status bar.
+		 *
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUIStatusBar* create(const GUIOptions& options, const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI status bar.
+		 *
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUIStatusBar* create(const String& style = StringUtil::BLANK);
+
+		GUIStatusBar(const PrivatelyConstruct& dummy, const String& style, const GUIDimensions& dimensions);
+
+		/**
+		 * Updates the active project displayed on the status bar.
+		 * 	
+		 * @param[in]	name		Name of the project.
+		 * @param[in]	modified	Should the project be displayed as modified (and needs saving).
+		 */
+		void setProject(const WString& name, bool modified);
+
+		/**
+		 * Updates the active scene displayed on the status bar.
+		 * 	
+		 * @param[in]	name		Name of the scene.
+		 * @param[in]	modified	Should the scene be displayed as modified (and needs saving).
+		 */
+		void setScene(const WString& name, bool modified);
+
+		/**	Activates or deactivates the "compilation in progress" visuals on the status bar. */
+		void setIsCompiling(bool compiling);
+
+		/** @copydoc GUIElement::setTint */
+		virtual void setTint(const Color& color) override;
+
+		/** @copydoc GUIElement::_updateLayoutInternal */
+		void _updateLayoutInternal(const GUILayoutData& data) override;
+
+		/** @copydoc GUIElement::_getOptimalSize */
+		Vector2I _getOptimalSize() const override;
+
+		Event<void()> onMessageClicked; /**< Triggered when the user clicks on the console message. */
+	private:
+		virtual ~GUIStatusBar();
+
+		/** @copydoc GUIElement::styleUpdated */
+		void styleUpdated() override;
+
+		/**	Triggered when the debug Log was modified. */
+		void logModified();
+
+		/**	Triggered when the user clicks on the message display. */
+		void messageBtnClicked();
+
+	private:
+		static const Color COLOR_INFO;
+		static const Color COLOR_WARNING;
+		static const Color COLOR_ERROR;
+
+		GUIPanel* mPanel;
+		GUIPanel* mBgPanel;
+		GUIButton* mMessage;
+		GUILabel* mScene;
+		GUILabel* mProject;
+		GUILabel* mCompiling;
+		GUITexture* mBackground;
+
+		HEvent mLogEntryAddedConn;
+		HEvent mMessageBtnPressedConn;
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 211 - 209
Source/BansheeEditor/Include/BsGUITextField.h

@@ -1,210 +1,212 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsGUIElementContainer.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI-Editor
-	 *  @{
-	 */
-
-	/**
-	 * A composite GUI object representing an editor field. Editor fields are a combination of a label and an input field.
-	 * Label is optional. This specific implementation displays a text input field.
-	 */
-	class BS_ED_EXPORT GUITextField : public GUIElementContainer
-	{
-		struct PrivatelyConstruct {};
-
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles. */
-		static const String& getGUITypeName();
-
-		/** Returns style type name of the internal GUILabel element. */
-		static const String& getLabelStyleType();
-
-		/** Returns style type name of the internal GUIInputBox element. */
-		static const String& getInputStyleType();
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
-		 *								override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const GUIContent& labelContent, UINT32 labelWidth, const GUIOptions& options,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const GUIContent& labelContent, const GUIOptions& options,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const HString& labelText, UINT32 labelWidth, const GUIOptions& options,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const HString& labelText, const GUIOptions& options,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field without a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const GUIOptions& options, const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const GUIContent& labelContent, UINT32 labelWidth,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelContent	Content to display in the editor field label.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const GUIContent& labelContent,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	labelWidth		Width of the label in pixels.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const HString& labelText, UINT32 labelWidth,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field with a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	labelText		String to display in the editor field label.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const HString& labelText,
-			const String& style = StringUtil::BLANK);
-
-		/**
-		 * Creates a new GUI text editor field without a label.
-		 *
-		 * @param[in]	multiline		Should the input box accept multiple lines of input.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style is used.
-		 */
-		static GUITextField* create(bool multiline, const String& style = StringUtil::BLANK);
-
-		GUITextField(const PrivatelyConstruct& dummy, bool multiline, const GUIContent& labelContent, UINT32 labelWidth,
-			const String& style, const GUIDimensions& dimensions, bool withLabel);
-
-		/**	Returns the value currently input in the text field. */
-		WString getValue() const { return mValue; }
-
-		/**	Sets a new value in the text field. */
-		void setValue(const WString& value);
-
-		/**	Checks whether the element currently has keyboard focus. */
-		bool hasInputFocus() const { return mHasInputFocus; }
-
-		/** @copydoc GUIElement::setTint */
-		void setTint(const Color& color) override;
-		
-		Event<void(const WString&)> onValueChanged; /** Triggered when the value in the field changes. */
-		Event<void()> onConfirm; /**< Triggered when the user hits the Enter key with the input box in focus. */
-
-		/** @cond INTERNAL */
-
-		/**
-		 * Sets a new value in the input field, and also allows you to choose should the field trigger an onValueChanged
-		 * event.
-		 */
-		void _setValue(const WString& value, bool triggerEvent);
-
-		/** @endcond */
-	protected:
-		static const UINT32 DEFAULT_LABEL_WIDTH;
-
-		virtual ~GUITextField();
-
-		/** @copydoc GUIElement::styleUpdated */
-		void styleUpdated() override;
-
-		/** @copydoc GUIElement::_updateLayoutInternal */
-		void _updateLayoutInternal(const GUILayoutData& data) override;
-
-		/** @copydoc GUIElement::_getOptimalSize */
-		Vector2I _getOptimalSize() const override;
-
-		/**	Triggered when the value in the internal input box changes. */
-		void valueChanged(const WString& newValue);
-
-		/**	Triggers when the input box receives or loses keyboard focus. */
-		void focusChanged(bool focus);
-
-		/**	Triggered when the users confirms input in the input box. */
-		void inputConfirmed();
-
-		GUIInputBox* mInputBox;
-		GUILayout* mLayout;
-		GUILabel* mLabel;
-		bool mHasInputFocus;
-		WString mValue;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsGUIElementContainer.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI-Editor
+	 *  @{
+	 */
+
+	/**
+	 * A composite GUI object representing an editor field. Editor fields are a combination of a label and an input field.
+	 * Label is optional. This specific implementation displays a text input field.
+	 */
+	class BS_ED_EXPORT GUITextField : public GUIElementContainer
+	{
+		struct PrivatelyConstruct {};
+
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles. */
+		static const String& getGUITypeName();
+
+		/** Returns style type name of the internal GUILabel element. */
+		static const String& getLabelStyleType();
+
+		/** Returns style type name of the internal GUIInputBox element. */
+		static const String& getInputStyleType();
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
+		 *								override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const GUIContent& labelContent, UINT32 labelWidth, const GUIOptions& options,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const GUIContent& labelContent, const GUIOptions& options,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const HString& labelText, UINT32 labelWidth, const GUIOptions& options,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const HString& labelText, const GUIOptions& options,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field without a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const GUIOptions& options, const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const GUIContent& labelContent, UINT32 labelWidth,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelContent	Content to display in the editor field label.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const GUIContent& labelContent,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	labelWidth		Width of the label in pixels.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const HString& labelText, UINT32 labelWidth,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field with a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	labelText		String to display in the editor field label.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const HString& labelText,
+			const String& style = StringUtil::BLANK);
+
+		/**
+		 * Creates a new GUI text editor field without a label.
+		 *
+		 * @param[in]	multiline		Should the input box accept multiple lines of input.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style is used.
+		 */
+		static GUITextField* create(bool multiline, const String& style = StringUtil::BLANK);
+
+		GUITextField(const PrivatelyConstruct& dummy, bool multiline, const GUIContent& labelContent, UINT32 labelWidth,
+			const String& style, const GUIDimensions& dimensions, bool withLabel);
+
+		/**	Returns the value currently input in the text field. */
+		WString getValue() const { return mValue; }
+
+		/**	Sets a new value in the text field. */
+		void setValue(const WString& value);
+
+		/**	Checks whether the element currently has keyboard focus. */
+		bool hasInputFocus() const { return mHasInputFocus; }
+
+		/** @copydoc GUIElement::setTint */
+		void setTint(const Color& color) override;
+		
+		Event<void(const WString&)> onValueChanged; /** Triggered when the value in the field changes. */
+		Event<void()> onConfirm; /**< Triggered when the user hits the Enter key with the input box in focus. */
+
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Sets a new value in the input field, and also allows you to choose should the field trigger an onValueChanged
+		 * event.
+		 */
+		void _setValue(const WString& value, bool triggerEvent);
+
+		/** @} */
+	protected:
+		static const UINT32 DEFAULT_LABEL_WIDTH;
+
+		virtual ~GUITextField();
+
+		/** @copydoc GUIElement::styleUpdated */
+		void styleUpdated() override;
+
+		/** @copydoc GUIElement::_updateLayoutInternal */
+		void _updateLayoutInternal(const GUILayoutData& data) override;
+
+		/** @copydoc GUIElement::_getOptimalSize */
+		Vector2I _getOptimalSize() const override;
+
+		/**	Triggered when the value in the internal input box changes. */
+		void valueChanged(const WString& newValue);
+
+		/**	Triggers when the input box receives or loses keyboard focus. */
+		void focusChanged(bool focus);
+
+		/**	Triggered when the users confirms input in the input box. */
+		void inputConfirmed();
+
+		GUIInputBox* mInputBox;
+		GUILayout* mLayout;
+		GUILabel* mLabel;
+		bool mHasInputFocus;
+		WString mValue;
+	};
+
+	/** @} */
 }

+ 5 - 3
Source/BansheeEditor/Include/BsGUITreeView.h

@@ -120,12 +120,14 @@ namespace BansheeEngine
 		/**	Starts rename operation on the currently selected element. */
 		void renameSelected();
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/** Updates tree view if dirty, among other operations. Must be called every frame. */
 		void _update();
 
-		/** @endcond */
+		/** @} */
 
 	protected:
 		GUITreeView(const String& backgroundStyle, const String& elementBtnStyle, 
@@ -173,7 +175,7 @@ namespace BansheeEngine
 		void disableEdit(bool acceptChanges);
 
 		/**
-		 * Triggered when the Foldout button for a tree element was been toggled (i.e. something was expanded or collapsed).
+		 * Triggered when the Foldout button for a tree element was been toggled (something was expanded or collapsed).
 		 */
 		void elementToggled(TreeElement* element, bool toggled);
 

+ 5 - 3
Source/BansheeEditor/Include/BsGizmoManager.h

@@ -223,7 +223,9 @@ namespace BansheeEngine
 		 */
 		HSceneObject getSceneObject(UINT32 gizmoIdx);
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**
 		 * Updates all the gizmo meshes to reflect all draw calls submitted since clearGizmos().
@@ -243,12 +245,12 @@ namespace BansheeEngine
 		 */
 		void renderForPicking(const CameraPtr& camera, std::function<Color(UINT32)> idxToColorCallback);
 
-		/** @endcond */
+		/** @} */
 
 	private:
 		friend class GizmoManagerCore;
 
-		/**	Supported types of gizmo materials (i.e. shaders) */
+		/**	Supported types of gizmo materials (shaders) */
 		enum class GizmoMaterial
 		{
 			Solid, Wire, Line, Picking, PickingAlpha, Text

+ 165 - 165
Source/BansheeEditor/Include/BsHandleSlider.h

@@ -1,166 +1,166 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsVector2I.h"
-#include "BsMatrix4.h"
-#include "BsQuaternion.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Handles
-	 *  @{
-	 */
-
-	/**
-	 * Base class for all handle sliders. A handle slider is geometry that the user can interact with by selecting or 
-	 * dragging (i.e. sliding) it. Sliders generally output a one- or multi-dimensional delta value that signals the drag 
-	 * amount (and/or direction).
-	 */
-	class BS_ED_EXPORT HandleSlider
-	{
-	public:
-		/** Possible states the slider can be in. */
-		enum class State
-		{
-			Inactive, /**< Slider is not being interacted with. */
-			Active, /**< Slider is clicked on and being dragged. */
-			Hover /**< Slider is being hovered over but isn't clicked on. */
-		};
-
-		/**
-		 * Constructs a new handle slider.
-		 *
-		 * @param[in]	fixedScale	If true the handle slider will always try to maintain the same visible area in the 
-		 *							viewport regardless of distance from camera. 
-		 * @param[in]	layer		Layer that allows filtering of which sliders are interacted with from a specific camera.
-		 */
-		HandleSlider(bool fixedScale, UINT64 layer);
-		virtual ~HandleSlider() { }
-
-		/**
-		 * Attempts to find an intersection between the provided ray and the slider geometry.
-		 *
-		 * @param[in]	ray	Ray in world space to try to interect with geometry.
-		 * @param[in]	t	Position of the intersection along the ray. Only if intersection happened.
-		 * @return			Whether an intersection was detected.
-		 */
-		virtual bool intersects(const Ray& ray, float& t) const = 0;
-
-		/**
-		 * Updates a slider that is currently active (being dragged).
-		 *
-		 * @param[in]	camera		Camera through which we're interacting with the slider.
-		 * @param[in]	inputDelta	Pointer movement since the last time this method was called.
-		 */
-		virtual void handleInput(const CameraPtr& camera, const Vector2I& inputDelta) = 0;
-
-		/**
-		 * Updates the state of the slider. Must be called every frame.
-		 *
-		 * @param[in]	camera	Camera through which we're interacting with the slider.
-		 */
-		void update(const CameraPtr& camera);
-
-		/** Returns the state the slider is currently in. */
-		State getState() const { return mState; }
-		
-		/**
-		 * Returns if fixed scale is enabled. If enabled the handle slider will always try to maintain the same visible 
-		 * area in the viewport regardless of distance from camera.
-		 */
-		bool getFixedScale() const { return mFixedScale; }
-
-		/** Returns a layer that determines which sliders are interacted with from a specific camera. */
-		UINT64 getLayer() const { return mLayer; }
-
-		/**	Sets the world position of the slider. */
-		void setPosition(const Vector3& position);
-
-		/**	Sets the world rotation of the slider. */
-		void setRotation(const Quaternion& rotation);
-
-		/**	Sets the scale of the slider. */
-		void setScale(const Vector3& scale);
-
-		/**	Enables or disabled the slider, making it interactable or not. */
-		void setEnabled(bool enabled);
-
-		/**	Gets the world position of the slider. */
-		const Vector3& getPosition() const { return mPosition; }
-
-		/**	Gets the world rotation of the slider. */
-		const Quaternion& getRotation() const { return mRotation; }
-
-		/**	Gets the scale of the slider. */
-		const Vector3& getScale() const { return mScale; }
-
-		/**	Checks whether the slider can be interacted with or not. */
-		bool getEnabled() const { return mEnabled; }
-
-	protected:
-		friend class HandleSliderManager;
-
-		/**	Toggles the slider state to inactive. */
-		void setInactive();
-
-		/**
-		 * Toggles the slider state to active.
-		 *
-		 * @param[in]	camera		Camera through which the slider was activated.
-		 * @param[in]	pointerPos	Position of the pointer when the slider was activated.
-		 */
-		void setActive(const CameraPtr& camera, const Vector2I& pointerPos);
-
-		/**	Toggles the slider state to hovered. */
-		void setHover();
-
-		/**	Gets the slider transform depending on set position, rotation and scale values. */
-		const Matrix4& getTransform() const;
-
-		/**	Gets the inverse of the slider transform depending on set position, rotation and scale values. */
-		const Matrix4& getTransformInv() const;
-
-		/** Triggered when the slider state is changed to active. */
-		virtual void activate(const CameraPtr& camera, const Vector2I& pointerPos) { }
-
-		/**	Triggered when the slider state is changed from active to some other state. */
-		virtual void reset() { }
-
-		/**	Updates the internal transform from the stored position, rotation and scale values. */
-		void updateCachedTransform() const;
-
-		/**
-		 * Calculates amount of movement along the provided ray depending on pointer movement.
-		 *
-		 * @param[in]	camera			Camera on which the pointer movement is occurring.
-		 * @param[in]	position		Position of the ray to calculate movement on.
-		 * @param[in]	direction		Direction of the ray to calculate movement on. Must be normalized.
-		 * @param[in]	pointerStart	Starting position of the pointer when movement started, in pixels relative to 
-		 *								provided camera.
-		 * @param[in]	pointerEnd		Current position of the pointer, in pixels relative to provided camera.
-		 */
-		float calcDelta(const CameraPtr& camera, const Vector3& position, const Vector3& direction,
-			const Vector2I& pointerStart, const Vector2I& pointerEnd);
-
-		bool mFixedScale;
-		UINT64 mLayer;
-
-		Vector3 mPosition;
-		Quaternion mRotation;
-		Vector3 mScale;
-		float mDistanceScale;
-
-		Vector2I mStartPointerPos;
-		Vector2I mCurrentPointerPos;
-		State mState;
-		bool mEnabled;
-
-		mutable bool mTransformDirty;
-		mutable Matrix4 mTransform;
-		mutable Matrix4 mTransformInv;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsVector2I.h"
+#include "BsMatrix4.h"
+#include "BsQuaternion.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Handles
+	 *  @{
+	 */
+
+	/**
+	 * Base class for all handle sliders. A handle slider is geometry that the user can interact with by selecting or 
+	 * dragging (sliding) it. Sliders generally output a one- or multi-dimensional delta value that signals the drag 
+	 * amount (and/or direction).
+	 */
+	class BS_ED_EXPORT HandleSlider
+	{
+	public:
+		/** Possible states the slider can be in. */
+		enum class State
+		{
+			Inactive, /**< Slider is not being interacted with. */
+			Active, /**< Slider is clicked on and being dragged. */
+			Hover /**< Slider is being hovered over but isn't clicked on. */
+		};
+
+		/**
+		 * Constructs a new handle slider.
+		 *
+		 * @param[in]	fixedScale	If true the handle slider will always try to maintain the same visible area in the 
+		 *							viewport regardless of distance from camera. 
+		 * @param[in]	layer		Layer that allows filtering of which sliders are interacted with from a specific camera.
+		 */
+		HandleSlider(bool fixedScale, UINT64 layer);
+		virtual ~HandleSlider() { }
+
+		/**
+		 * Attempts to find an intersection between the provided ray and the slider geometry.
+		 *
+		 * @param[in]	ray	Ray in world space to try to interect with geometry.
+		 * @param[in]	t	Position of the intersection along the ray. Only if intersection happened.
+		 * @return			Whether an intersection was detected.
+		 */
+		virtual bool intersects(const Ray& ray, float& t) const = 0;
+
+		/**
+		 * Updates a slider that is currently active (being dragged).
+		 *
+		 * @param[in]	camera		Camera through which we're interacting with the slider.
+		 * @param[in]	inputDelta	Pointer movement since the last time this method was called.
+		 */
+		virtual void handleInput(const CameraPtr& camera, const Vector2I& inputDelta) = 0;
+
+		/**
+		 * Updates the state of the slider. Must be called every frame.
+		 *
+		 * @param[in]	camera	Camera through which we're interacting with the slider.
+		 */
+		void update(const CameraPtr& camera);
+
+		/** Returns the state the slider is currently in. */
+		State getState() const { return mState; }
+		
+		/**
+		 * Returns if fixed scale is enabled. If enabled the handle slider will always try to maintain the same visible 
+		 * area in the viewport regardless of distance from camera.
+		 */
+		bool getFixedScale() const { return mFixedScale; }
+
+		/** Returns a layer that determines which sliders are interacted with from a specific camera. */
+		UINT64 getLayer() const { return mLayer; }
+
+		/**	Sets the world position of the slider. */
+		void setPosition(const Vector3& position);
+
+		/**	Sets the world rotation of the slider. */
+		void setRotation(const Quaternion& rotation);
+
+		/**	Sets the scale of the slider. */
+		void setScale(const Vector3& scale);
+
+		/**	Enables or disabled the slider, making it interactable or not. */
+		void setEnabled(bool enabled);
+
+		/**	Gets the world position of the slider. */
+		const Vector3& getPosition() const { return mPosition; }
+
+		/**	Gets the world rotation of the slider. */
+		const Quaternion& getRotation() const { return mRotation; }
+
+		/**	Gets the scale of the slider. */
+		const Vector3& getScale() const { return mScale; }
+
+		/**	Checks whether the slider can be interacted with or not. */
+		bool getEnabled() const { return mEnabled; }
+
+	protected:
+		friend class HandleSliderManager;
+
+		/**	Toggles the slider state to inactive. */
+		void setInactive();
+
+		/**
+		 * Toggles the slider state to active.
+		 *
+		 * @param[in]	camera		Camera through which the slider was activated.
+		 * @param[in]	pointerPos	Position of the pointer when the slider was activated.
+		 */
+		void setActive(const CameraPtr& camera, const Vector2I& pointerPos);
+
+		/**	Toggles the slider state to hovered. */
+		void setHover();
+
+		/**	Gets the slider transform depending on set position, rotation and scale values. */
+		const Matrix4& getTransform() const;
+
+		/**	Gets the inverse of the slider transform depending on set position, rotation and scale values. */
+		const Matrix4& getTransformInv() const;
+
+		/** Triggered when the slider state is changed to active. */
+		virtual void activate(const CameraPtr& camera, const Vector2I& pointerPos) { }
+
+		/**	Triggered when the slider state is changed from active to some other state. */
+		virtual void reset() { }
+
+		/**	Updates the internal transform from the stored position, rotation and scale values. */
+		void updateCachedTransform() const;
+
+		/**
+		 * Calculates amount of movement along the provided ray depending on pointer movement.
+		 *
+		 * @param[in]	camera			Camera on which the pointer movement is occurring.
+		 * @param[in]	position		Position of the ray to calculate movement on.
+		 * @param[in]	direction		Direction of the ray to calculate movement on. Must be normalized.
+		 * @param[in]	pointerStart	Starting position of the pointer when movement started, in pixels relative to 
+		 *								provided camera.
+		 * @param[in]	pointerEnd		Current position of the pointer, in pixels relative to provided camera.
+		 */
+		float calcDelta(const CameraPtr& camera, const Vector3& position, const Vector3& direction,
+			const Vector2I& pointerStart, const Vector2I& pointerEnd);
+
+		bool mFixedScale;
+		UINT64 mLayer;
+
+		Vector3 mPosition;
+		Quaternion mRotation;
+		Vector3 mScale;
+		float mDistanceScale;
+
+		Vector2I mStartPointerPos;
+		Vector2I mCurrentPointerPos;
+		State mState;
+		bool mEnabled;
+
+		mutable bool mTransformDirty;
+		mutable Matrix4 mTransform;
+		mutable Matrix4 mTransformInv;
+	};
+
+	/** @} */
 }

+ 67 - 67
Source/BansheeEditor/Include/BsHandleSliderLine.h

@@ -1,68 +1,68 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsHandleSlider.h"
-#include "BsCapsule.h"
-#include "BsSphere.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Handles
-	 *  @{
-	 */
-
-	/**
-	 * Handle slider that returns a delta value as you drag the pointer along a line. For intersection purposes the line
-	 * is internally by a capsule and a sphere at its cap (assuming this will be used for arrow-like handles).
-	 */
-	class BS_ED_EXPORT HandleSliderLine : public HandleSlider
-	{
-	public:
-		/**
-		 * Constructs a new line slider.
-		 *
-		 * @param[in]	direction	Direction of the line.
-		 * @param[in]	length		Length of the slider (i.e. the line).
-		 * @param[in]	fixedScale	If true the handle slider will always try to maintain the same visible area in the
-		 *							viewport regardless of distance from camera.
-		 * @param[in]	layer		Layer that allows filtering of which sliders are interacted with from a specific camera.
-		 */
-		HandleSliderLine(const Vector3& direction, float length, bool fixedScale, UINT64 layer);
-		~HandleSliderLine();
-
-		/** @copydoc	HandleSlider::intersects */
-		bool intersects(const Ray& ray, float& t) const override;
-
-		/** @copydoc	HandleSlider::handleInput */
-		void handleInput(const CameraPtr& camera, const Vector2I& inputDelta) override;
-
-		/**
-		 * Returns a delta value that is the result of dragging/sliding the pointer along the line. This changes every
-		 * frame and will be zero unless the slider is active.
-		 */
-		float getDelta() const { return mDelta; }
-
-	protected:
-		/** @copydoc HandleSlider::activate */
-		void activate(const CameraPtr& camera, const Vector2I& pointerPos) override { mStartPosition = getPosition(); }
-
-		/** @copydoc HandleSlider::reset */
-		void reset() override { mDelta = 0.0f; }
-
-		static const float CAPSULE_RADIUS;
-		static const float SPHERE_RADIUS;
-
-		Vector3 mDirection;
-		float mLength;
-
-		float mDelta;
-		Vector3 mStartPosition;
-
-		Capsule mCapsuleCollider;
-		Sphere mSphereCollider;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsHandleSlider.h"
+#include "BsCapsule.h"
+#include "BsSphere.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Handles
+	 *  @{
+	 */
+
+	/**
+	 * Handle slider that returns a delta value as you drag the pointer along a line. For intersection purposes the line
+	 * is internally by a capsule and a sphere at its cap (assuming this will be used for arrow-like handles).
+	 */
+	class BS_ED_EXPORT HandleSliderLine : public HandleSlider
+	{
+	public:
+		/**
+		 * Constructs a new line slider.
+		 *
+		 * @param[in]	direction	Direction of the line.
+		 * @param[in]	length		Length of the slider.
+		 * @param[in]	fixedScale	If true the handle slider will always try to maintain the same visible area in the
+		 *							viewport regardless of distance from camera.
+		 * @param[in]	layer		Layer that allows filtering of which sliders are interacted with from a specific camera.
+		 */
+		HandleSliderLine(const Vector3& direction, float length, bool fixedScale, UINT64 layer);
+		~HandleSliderLine();
+
+		/** @copydoc	HandleSlider::intersects */
+		bool intersects(const Ray& ray, float& t) const override;
+
+		/** @copydoc	HandleSlider::handleInput */
+		void handleInput(const CameraPtr& camera, const Vector2I& inputDelta) override;
+
+		/**
+		 * Returns a delta value that is the result of dragging/sliding the pointer along the line. This changes every
+		 * frame and will be zero unless the slider is active.
+		 */
+		float getDelta() const { return mDelta; }
+
+	protected:
+		/** @copydoc HandleSlider::activate */
+		void activate(const CameraPtr& camera, const Vector2I& pointerPos) override { mStartPosition = getPosition(); }
+
+		/** @copydoc HandleSlider::reset */
+		void reset() override { mDelta = 0.0f; }
+
+		static const float CAPSULE_RADIUS;
+		static const float SPHERE_RADIUS;
+
+		Vector3 mDirection;
+		float mLength;
+
+		float mDelta;
+		Vector3 mStartPosition;
+
+		Capsule mCapsuleCollider;
+		Sphere mSphereCollider;
+	};
+
+	/** @} */
 }

+ 74 - 74
Source/BansheeEditor/Include/BsModalWindow.h

@@ -1,75 +1,75 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsEditorWindowBase.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup EditorWindow
-	 *  @{
-	 */
-
-	/**
-	 * Base implementation of a window that when open doesn't allow you to interact with other windows. Modal windows are
-	 * similar to editor windows but cannot be docked, and are meant to be used for temporary operations like dialog boxes
-	 * and progress bars.
-	 */
-	class BS_ED_EXPORT ModalWindow : public EditorWindowBase
-	{
-	public:
-		virtual ~ModalWindow();
-
-		/** @copydoc EditorWindowBase::update */
-		virtual void update() override;
-
-		/** @copydoc EditorWindowBase::close */
-		virtual void close() override;
-
-		/**	Changes the text in the modal window title bar. */
-		void setTitle(const HString& title);
-
-		/** Converts screen pointer coordinates into coordinates relative to the window content's GUI panel. */
-		Vector2I screenToWindowPos(const Vector2I& screenPos) const;
-
-		/** Converts pointer coordinates relative to the window content's GUI panel into screen coordinates. */
-		Vector2I windowToScreenPos(const Vector2I& windowPos) const;
-
-	protected:
-		friend class EditorWindowManager;
-
-		ModalWindow(const HString& title, bool hasCloseButton = false);
-
-		/**
-		 * Returns the area in which the GUI contents are displayed (i.e. not including title bar and other default 
-		 * elements). Area is relative to window.
-		 */
-		Rect2I getContentArea() const;
-
-		/** @copydoc EditorWindowBase::resized */
-		virtual void resized() override;
-
-	private:
-		/**
-		 * Updates the placement of child GUI elements and their non-client areas (used for OS move/resize operations). 
-		 * Should be called after window size changes.
-		 */
-		void updateSize();
-
-		/**	Returns the height in pixels taken up by the title bar. */
-		UINT32 getTitleBarHeight() const;
-
-		GUIPanel* mTitleBarPanel;
-		GUIPanel* mTitleBarBgPanel;
-
-		GUILabel* mTitle;
-		GUIButton* mCloseButton;
-		GUITexture* mTitleBarBg;
-
-	protected:
-		GUIPanel* mContents;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsEditorWindowBase.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup EditorWindow
+	 *  @{
+	 */
+
+	/**
+	 * Base implementation of a window that when open doesn't allow you to interact with other windows. Modal windows are
+	 * similar to editor windows but cannot be docked, and are meant to be used for temporary operations like dialog boxes
+	 * and progress bars.
+	 */
+	class BS_ED_EXPORT ModalWindow : public EditorWindowBase
+	{
+	public:
+		virtual ~ModalWindow();
+
+		/** @copydoc EditorWindowBase::update */
+		virtual void update() override;
+
+		/** @copydoc EditorWindowBase::close */
+		virtual void close() override;
+
+		/**	Changes the text in the modal window title bar. */
+		void setTitle(const HString& title);
+
+		/** Converts screen pointer coordinates into coordinates relative to the window content's GUI panel. */
+		Vector2I screenToWindowPos(const Vector2I& screenPos) const;
+
+		/** Converts pointer coordinates relative to the window content's GUI panel into screen coordinates. */
+		Vector2I windowToScreenPos(const Vector2I& windowPos) const;
+
+	protected:
+		friend class EditorWindowManager;
+
+		ModalWindow(const HString& title, bool hasCloseButton = false);
+
+		/**
+		 * Returns the area in which the GUI contents are displayed (not including title bar and other default 
+		 * elements). Area is relative to window.
+		 */
+		Rect2I getContentArea() const;
+
+		/** @copydoc EditorWindowBase::resized */
+		virtual void resized() override;
+
+	private:
+		/**
+		 * Updates the placement of child GUI elements and their non-client areas (used for OS move/resize operations). 
+		 * Should be called after window size changes.
+		 */
+		void updateSize();
+
+		/**	Returns the height in pixels taken up by the title bar. */
+		UINT32 getTitleBarHeight() const;
+
+		GUIPanel* mTitleBarPanel;
+		GUIPanel* mTitleBarBgPanel;
+
+		GUILabel* mTitle;
+		GUIButton* mCloseButton;
+		GUITexture* mTitleBarBg;
+
+	protected:
+		GUIPanel* mContents;
+	};
+
+	/** @} */
 }

+ 55 - 55
Source/BansheeEditor/Include/BsProjectLibraryEntries.h

@@ -1,56 +1,56 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsProjectLibrary.h"
-#include "BsIReflectable.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Library
-	 *  @{
-	 */
-
-	/**
-	 * Contains a list of entries used by the ProjectLibrary. Used primarily for serialization purposes, i.e. persisting
-	 * ProjectLibrary state between application runs.
-	 */
-	class ProjectLibraryEntries : public IReflectable
-	{
-		struct ConstructPrivately { };
-
-	public:
-		explicit ProjectLibraryEntries(const ConstructPrivately& dummy);
-		ProjectLibraryEntries(const ProjectLibrary::DirectoryEntry& rootEntry);
-
-		/**
-		 * Creates new project library entries based on a ProjectLibrary root directory entry.
-		 *
-		 * @param[in]	rootEntry	Root directory entry in ProjectLibrary.
-		 */
-		static std::shared_ptr<ProjectLibraryEntries> create(const ProjectLibrary::DirectoryEntry& rootEntry);
-		
-		/**	Returns the root directory entry that references the entire entry hierarchy. */
-		const ProjectLibrary::DirectoryEntry& getRootEntry() const { return mRootEntry; }
-
-	private:
-		ProjectLibrary::DirectoryEntry mRootEntry;
-
-		/************************************************************************/
-		/* 								SERIALIZATION                      		*/
-		/************************************************************************/
-
-		/** Creates new empty project library entries object. Used for serialization purposes. */
-		static std::shared_ptr<ProjectLibraryEntries> createEmpty();
-
-	public:
-		friend class ProjectLibraryEntriesRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsProjectLibrary.h"
+#include "BsIReflectable.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Library
+	 *  @{
+	 */
+
+	/**
+	 * Contains a list of entries used by the ProjectLibrary. Used primarily for serialization purposes (persisting
+	 * ProjectLibrary state between application runs).
+	 */
+	class ProjectLibraryEntries : public IReflectable
+	{
+		struct ConstructPrivately { };
+
+	public:
+		explicit ProjectLibraryEntries(const ConstructPrivately& dummy);
+		ProjectLibraryEntries(const ProjectLibrary::DirectoryEntry& rootEntry);
+
+		/**
+		 * Creates new project library entries based on a ProjectLibrary root directory entry.
+		 *
+		 * @param[in]	rootEntry	Root directory entry in ProjectLibrary.
+		 */
+		static std::shared_ptr<ProjectLibraryEntries> create(const ProjectLibrary::DirectoryEntry& rootEntry);
+		
+		/**	Returns the root directory entry that references the entire entry hierarchy. */
+		const ProjectLibrary::DirectoryEntry& getRootEntry() const { return mRootEntry; }
+
+	private:
+		ProjectLibrary::DirectoryEntry mRootEntry;
+
+		/************************************************************************/
+		/* 								SERIALIZATION                      		*/
+		/************************************************************************/
+
+		/** Creates new empty project library entries object. Used for serialization purposes. */
+		static std::shared_ptr<ProjectLibraryEntries> createEmpty();
+
+	public:
+		friend class ProjectLibraryEntriesRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 139 - 139
Source/BansheeEditor/Include/BsSceneGrid.h

@@ -1,140 +1,140 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsEditorPrerequisites.h"
-#include "BsVector2I.h"
-#include "BsColor.h"
-#include "BsMaterial.h"
-
-namespace BansheeEngine
-{
-	/** @cond INTERNAL */
-	/** @addtogroup Scene-Editor
-	 *  @{
-	 */
-
-	class SceneGridCore;
-
-	/** Determines how is the scene grid drawn. */
-	enum class GridMode
-	{
-		Perspective, /**< Grid is drawn in XZ plane, at Y = 0. */
-		OrthoX, /**< Grid is drawn in YZ plane, always visible along positive X. */
-		OrthoY, /**< Grid is drawn in XZ plane, always visible along positive Y. */
-		OrthoZ, /**< Grid is drawn in XY plane, always visible along positive Z. */
-		OrthoNegX, /**< Grid is drawn in YZ plane, always visible along negative X. */
-		OrthoNegY, /**< Grid is drawn in XZ plane, always visible along negative Y. */
-		OrthoNegZ /**< Grid is drawn in XY plane, always visible along negative Z. */
-	};
-
-	/**	Handles rendering of the grid in the scene view. */
-	class BS_ED_EXPORT SceneGrid
-	{
-	public:
-		SceneGrid(const CameraPtr& camera);
-		~SceneGrid();
-
-		/**	Sets the total width/height of the grid in XZ plane. */
-		void setSize(UINT32 size);
-		
-		/**	Sets the spacing between grid lines. */
-		void setSpacing(float spacing);
-
-		/** Determines in what position and orientation is the grid drawn. */
-		void setMode(GridMode mode);
-
-		/** Changes the active editor settings. Grid properties will be updated internally when editor settings change. */
-		void setSettings(const EditorSettingsPtr& settings);
-
-		/** Called once per frame. */
-		void _update();
-	private:
-		/** Updates internal grid parameters from the attached settings object. */
-		void updateFromEditorSettings();
-
-		/**	Rebuilds the scene grid mesh. Call this whenever grid parameters change. */
-		void updateGridMesh();
-
-		/**
-		 * Initializes the core thread portion of the scene grid renderer.
-		 *
-		 * @param[in]	material	Material used for drawing the grid.
-		 * @param[in]	camera		Camera to render the scene grid to.
-		 */
-		void initializeCore(const SPtr<CameraCore>& camera, const SPtr<MaterialCore>& material);
-
-		/** Destroys the core thread portion of the draw manager. */
-		void destroyCore(SceneGridCore* core);
-
-		float mSpacing = 1.0f;
-		UINT32 mSize = 256;
-		GridMode mMode = GridMode::Perspective;
-		bool mCoreDirty;
-
-		EditorSettingsPtr mSettings;
-		UINT32 mSettingsHash = 0;
-
-		HMesh mGridMesh;
-		VertexDataDescPtr mVertexDesc;
-		std::atomic<SceneGridCore*> mCore;
-	};
-
-	/** Handles scene grid rendering on the core thread. */
-	class SceneGridCore
-	{
-	public:
-		SceneGridCore() { }
-		~SceneGridCore();
-
-	private:
-		friend class SceneGrid;
-
-		/**
-		 * Initializes the object. Must be called right after construction and before any use.
-		 *
-		 * @param[in]	material	Material used for drawing the grid.
-		 * @param[in]	camera		Camera to render the scene grid to.
-		 */
-		void initialize(const SPtr<CameraCore>& camera, const SPtr<MaterialCore>& material);
-
-		/**
-		 * Updates the grid mesh to render.
-		 * 			
-		 * @param[in]	mesh			Grid mesh to render.
-		 * @param[in]	spacing			Spacing between the grid lines.
-		 * @param[in]	fadeGrid		Determines should the grid fade out at larger distances.
-		 * @param[in]	gridPlaneNormal	Normal to the plane to render the grid on. Must be one of the basis vectors
-		 *								(i.e. can't be arbitrary).						
-		 */
-		void updateData(const SPtr<MeshCore>& mesh, float spacing, bool fadeGrid, const Vector3& gridPlaneNormal);
-
-		/**	Callback triggered by the renderer, actually draws the grid mesh. */
-		void render();
-
-		SPtr<CameraCore> mCamera;
-		SPtr<MeshCore> mGridMesh;
-		SPtr<MaterialCore> mGridMaterial;
-		float mSpacing = 1.0f;
-		bool mFadeGrid = true;
-		Vector3 mGridPlaneNormal;
-
-		MaterialParamMat4Core mViewProjParam;
-		MaterialParamVec4Core mWorldCameraPosParam;
-		MaterialParamColorCore mGridColorParam;
-		MaterialParamFloatCore mGridSpacingParam;
-		MaterialParamFloatCore mGridBorderWidthParam;
-		MaterialParamFloatCore mGridFadeOutStartParam;
-		MaterialParamFloatCore mGridFadeOutEndParam;
-		MaterialParamVec3Core mGridPlaneNormalParam;
-
-		static const Color GRID_LINE_COLOR;
-		static const float LINE_WIDTH;
-		static const float LINE_BORDER_WIDTH;
-		static const float FADE_OUT_START;
-		static const float FADE_OUT_END;
-	};
-
-	/** @} */
-	/** @endcond */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsEditorPrerequisites.h"
+#include "BsVector2I.h"
+#include "BsColor.h"
+#include "BsMaterial.h"
+
+namespace BansheeEngine
+{
+	/** @cond INTERNAL */
+	/** @addtogroup Scene-Editor
+	 *  @{
+	 */
+
+	class SceneGridCore;
+
+	/** Determines how is the scene grid drawn. */
+	enum class GridMode
+	{
+		Perspective, /**< Grid is drawn in XZ plane, at Y = 0. */
+		OrthoX, /**< Grid is drawn in YZ plane, always visible along positive X. */
+		OrthoY, /**< Grid is drawn in XZ plane, always visible along positive Y. */
+		OrthoZ, /**< Grid is drawn in XY plane, always visible along positive Z. */
+		OrthoNegX, /**< Grid is drawn in YZ plane, always visible along negative X. */
+		OrthoNegY, /**< Grid is drawn in XZ plane, always visible along negative Y. */
+		OrthoNegZ /**< Grid is drawn in XY plane, always visible along negative Z. */
+	};
+
+	/**	Handles rendering of the grid in the scene view. */
+	class BS_ED_EXPORT SceneGrid
+	{
+	public:
+		SceneGrid(const CameraPtr& camera);
+		~SceneGrid();
+
+		/**	Sets the total width/height of the grid in XZ plane. */
+		void setSize(UINT32 size);
+		
+		/**	Sets the spacing between grid lines. */
+		void setSpacing(float spacing);
+
+		/** Determines in what position and orientation is the grid drawn. */
+		void setMode(GridMode mode);
+
+		/** Changes the active editor settings. Grid properties will be updated internally when editor settings change. */
+		void setSettings(const EditorSettingsPtr& settings);
+
+		/** Called once per frame. */
+		void _update();
+	private:
+		/** Updates internal grid parameters from the attached settings object. */
+		void updateFromEditorSettings();
+
+		/**	Rebuilds the scene grid mesh. Call this whenever grid parameters change. */
+		void updateGridMesh();
+
+		/**
+		 * Initializes the core thread portion of the scene grid renderer.
+		 *
+		 * @param[in]	material	Material used for drawing the grid.
+		 * @param[in]	camera		Camera to render the scene grid to.
+		 */
+		void initializeCore(const SPtr<CameraCore>& camera, const SPtr<MaterialCore>& material);
+
+		/** Destroys the core thread portion of the draw manager. */
+		void destroyCore(SceneGridCore* core);
+
+		float mSpacing = 1.0f;
+		UINT32 mSize = 256;
+		GridMode mMode = GridMode::Perspective;
+		bool mCoreDirty;
+
+		EditorSettingsPtr mSettings;
+		UINT32 mSettingsHash = 0;
+
+		HMesh mGridMesh;
+		VertexDataDescPtr mVertexDesc;
+		std::atomic<SceneGridCore*> mCore;
+	};
+
+	/** Handles scene grid rendering on the core thread. */
+	class SceneGridCore
+	{
+	public:
+		SceneGridCore() { }
+		~SceneGridCore();
+
+	private:
+		friend class SceneGrid;
+
+		/**
+		 * Initializes the object. Must be called right after construction and before any use.
+		 *
+		 * @param[in]	material	Material used for drawing the grid.
+		 * @param[in]	camera		Camera to render the scene grid to.
+		 */
+		void initialize(const SPtr<CameraCore>& camera, const SPtr<MaterialCore>& material);
+
+		/**
+		 * Updates the grid mesh to render.
+		 * 			
+		 * @param[in]	mesh			Grid mesh to render.
+		 * @param[in]	spacing			Spacing between the grid lines.
+		 * @param[in]	fadeGrid		Determines should the grid fade out at larger distances.
+		 * @param[in]	gridPlaneNormal	Normal to the plane to render the grid on. Must be one of the basis vectors
+		 *								(can't be arbitrary).						
+		 */
+		void updateData(const SPtr<MeshCore>& mesh, float spacing, bool fadeGrid, const Vector3& gridPlaneNormal);
+
+		/**	Callback triggered by the renderer, actually draws the grid mesh. */
+		void render();
+
+		SPtr<CameraCore> mCamera;
+		SPtr<MeshCore> mGridMesh;
+		SPtr<MaterialCore> mGridMaterial;
+		float mSpacing = 1.0f;
+		bool mFadeGrid = true;
+		Vector3 mGridPlaneNormal;
+
+		MaterialParamMat4Core mViewProjParam;
+		MaterialParamVec4Core mWorldCameraPosParam;
+		MaterialParamColorCore mGridColorParam;
+		MaterialParamFloatCore mGridSpacingParam;
+		MaterialParamFloatCore mGridBorderWidthParam;
+		MaterialParamFloatCore mGridFadeOutStartParam;
+		MaterialParamFloatCore mGridFadeOutEndParam;
+		MaterialParamVec3Core mGridPlaneNormalParam;
+
+		static const Color GRID_LINE_COLOR;
+		static const float LINE_WIDTH;
+		static const float LINE_BORDER_WIDTH;
+		static const float FADE_OUT_START;
+		static const float FADE_OUT_END;
+	};
+
+	/** @} */
+	/** @endcond */
 }

+ 118 - 116
Source/BansheeEngine/Include/BsCGUIWidget.h

@@ -1,117 +1,119 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsComponent.h"
-#include "BsRect2I.h"
-#include "BsGUIWidget.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI
-	 *  @{
-	 */
-
-	/** Component wrapper for GUIWidget. */
-	class BS_EXPORT CGUIWidget : public Component
-	{
-	public:
-		virtual ~CGUIWidget();
-
-		/** @copydoc GUIWidget::setSkin */
-		void setSkin(const HGUISkin& skin);
-
-		/** @copydoc GUIWidget::getSkin */
-		const GUISkin& getSkin() const;
-
-		/** @copydoc GUIWidget::getSkinResource */
-		const HGUISkin& getSkinResource() const;
-
-		/** @copydoc GUIWidget::getPanel */
-		GUIPanel* getPanel() const;
-
-		/** @copydoc GUIWidget::getDepth */
-		UINT8 getDepth() const;
-
-		/** @copydoc GUIWidget::setDepth */
-		void setDepth(UINT8 depth);
-
-		/** @copydoc GUIWidget::inBounds */
-		bool inBounds(const Vector2I& position) const;
-
-		/** @copydoc GUIWidget::getBounds */
-		const Rect2I& getBounds() const;
-
-		/** @copydoc GUIWidget::isDirty */
-		bool isDirty(bool cleanIfDirty);
-
-		/** @copydoc GUIWidget::getTarget */
-		Viewport* getTarget() const;
-
-		/** @copydoc GUIWidget::getCamera */
-		CameraPtr getCamera() const;
-
-		/** @copydoc GUIWidget::getElements */
-		const Vector<GUIElement*>& getElements() const;
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** Returns the internal GUIWidget that is wrapped by this component. */
-		GUIWidget* _getInternal() const { return mInternal.get(); };
-
-		/** @endcond */
-
-	protected:
-		friend class SceneObject;
-		friend class GUIElementBase;
-		friend class GUIManager;
-
-		/**
-		 * Constructs a new GUI widget attached to the specified parent scene object. Widget elements will be rendered on
-		 * the provided camera.
-		 */
-		CGUIWidget(const HSceneObject& parent, const CameraPtr& camera);
-
-		/**
-		 * Constructs a new GUI widget attached to the specified parent scene object. Widget elements will be rendered on
-		 * the provided camera.
-		 */
-		CGUIWidget(const HSceneObject& parent, const HCamera& camera);
-
-		/** @copydoc Component::update */
-		void update() override;
-
-		/** @copydoc Component::onDestroyed */
-		void onDestroyed() override;
-
-		/**	Called when the viewport size changes and widget elements need to be updated. */
-		virtual void ownerTargetResized() { }
-
-		/**	Called when the parent window gained or lost focus. */
-		virtual void ownerWindowFocusChanged() { }
-
-	private:
-		CGUIWidget(const CGUIWidget& other) { }
-
-		SPtr<GUIWidget> mInternal;
-		HEvent mOwnerTargetResizedConn;
-		HEvent mOwnerWindowFocusChangedConn;
-
-		CameraPtr mCamera;
-		UINT32 mParentHash;
-
-		/************************************************************************/
-		/* 								RTTI		                     		*/
-		/************************************************************************/
-	public:
-		friend class CGUIWidgetRTTI;
-		static RTTITypeBase* getRTTIStatic();
-		virtual RTTITypeBase* getRTTI() const override;
-
-		CGUIWidget() { } // Serialization only
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsComponent.h"
+#include "BsRect2I.h"
+#include "BsGUIWidget.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI
+	 *  @{
+	 */
+
+	/** Component wrapper for GUIWidget. */
+	class BS_EXPORT CGUIWidget : public Component
+	{
+	public:
+		virtual ~CGUIWidget();
+
+		/** @copydoc GUIWidget::setSkin */
+		void setSkin(const HGUISkin& skin);
+
+		/** @copydoc GUIWidget::getSkin */
+		const GUISkin& getSkin() const;
+
+		/** @copydoc GUIWidget::getSkinResource */
+		const HGUISkin& getSkinResource() const;
+
+		/** @copydoc GUIWidget::getPanel */
+		GUIPanel* getPanel() const;
+
+		/** @copydoc GUIWidget::getDepth */
+		UINT8 getDepth() const;
+
+		/** @copydoc GUIWidget::setDepth */
+		void setDepth(UINT8 depth);
+
+		/** @copydoc GUIWidget::inBounds */
+		bool inBounds(const Vector2I& position) const;
+
+		/** @copydoc GUIWidget::getBounds */
+		const Rect2I& getBounds() const;
+
+		/** @copydoc GUIWidget::isDirty */
+		bool isDirty(bool cleanIfDirty);
+
+		/** @copydoc GUIWidget::getTarget */
+		Viewport* getTarget() const;
+
+		/** @copydoc GUIWidget::getCamera */
+		CameraPtr getCamera() const;
+
+		/** @copydoc GUIWidget::getElements */
+		const Vector<GUIElement*>& getElements() const;
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** Returns the internal GUIWidget that is wrapped by this component. */
+		GUIWidget* _getInternal() const { return mInternal.get(); };
+
+		/** @} */
+
+	protected:
+		friend class SceneObject;
+		friend class GUIElementBase;
+		friend class GUIManager;
+
+		/**
+		 * Constructs a new GUI widget attached to the specified parent scene object. Widget elements will be rendered on
+		 * the provided camera.
+		 */
+		CGUIWidget(const HSceneObject& parent, const CameraPtr& camera);
+
+		/**
+		 * Constructs a new GUI widget attached to the specified parent scene object. Widget elements will be rendered on
+		 * the provided camera.
+		 */
+		CGUIWidget(const HSceneObject& parent, const HCamera& camera);
+
+		/** @copydoc Component::update */
+		void update() override;
+
+		/** @copydoc Component::onDestroyed */
+		void onDestroyed() override;
+
+		/**	Called when the viewport size changes and widget elements need to be updated. */
+		virtual void ownerTargetResized() { }
+
+		/**	Called when the parent window gained or lost focus. */
+		virtual void ownerWindowFocusChanged() { }
+
+	private:
+		CGUIWidget(const CGUIWidget& other) { }
+
+		SPtr<GUIWidget> mInternal;
+		HEvent mOwnerTargetResizedConn;
+		HEvent mOwnerWindowFocusChangedConn;
+
+		CameraPtr mCamera;
+		UINT32 mParentHash;
+
+		/************************************************************************/
+		/* 								RTTI		                     		*/
+		/************************************************************************/
+	public:
+		friend class CGUIWidgetRTTI;
+		static RTTITypeBase* getRTTIStatic();
+		virtual RTTITypeBase* getRTTI() const override;
+
+		CGUIWidget() { } // Serialization only
+	};
+
+	/** @} */
 }

+ 4 - 2
Source/BansheeEngine/Include/BsCamera.h

@@ -516,7 +516,9 @@ namespace BansheeEngine
 		static CameraPtr create(RenderTargetPtr target = nullptr,
 			float left = 0.0f, float top = 0.0f, float width = 1.0f, float height = 1.0f);
 
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**	Returns the hash value that can be used to identify if the internal data needs an update. */
 		UINT32 _getLastModifiedHash() const { return mLastUpdateHash; }
@@ -524,7 +526,7 @@ namespace BansheeEngine
 		/**	Sets the hash value that can be used to identify if the internal data needs an update. */
 		void _setLastModifiedHash(UINT32 hash) { mLastUpdateHash = hash; }
 
-		/** @endcond */
+		/** @} */
 
 	protected:
 		Camera(RenderTargetPtr target = nullptr,

+ 77 - 75
Source/BansheeEngine/Include/BsGUIButton.h

@@ -1,76 +1,78 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsGUIButtonBase.h"
-#include "BsGUIContent.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI
-	 *  @{
-	 */
-
-	/** GUI button that can be clicked. Has normal, hover and active states with an optional label. */
-	class BS_EXPORT GUIButton : public GUIButtonBase
-	{
-	public:
-		/**
-		 * Returns type name of the GUI element used for finding GUI element styles. 
-		 */
-		static const String& getGUITypeName();
-
-		/**
-		 * Creates a new button with the specified label.
-		 *
-		 * @param[in]	text		Label to display on the button.
-		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *							GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUIButton* create(const HString& text, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new button with the specified label.
-		 *
-		 * @param[in]	text			Label to display on the button.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. 
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUIButton* create(const HString& text, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new button with the specified label.
-		 *
-		 * @param[in]	content		Content to display on a button. May include a label, image and a tooltip.
-		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the 
-		 *							GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUIButton* create(const GUIContent& content, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new button with the specified label.
-		 *
-		 * @param[in]	content		Content to display on a button. May include a label, image and a tooltip.
-		 * @param[in]	options		Options that allow you to control how is the element positioned and sized. This will 
-		 *							override any similar options set by style.
-		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the 
-		 *							GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUIButton* create(const GUIContent& content, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** @copydoc GUIElement::getElementType */
-		virtual ElementType _getElementType() const override { return ElementType::Button; }
-
-		/** @endcond */
-	private:
-		GUIButton(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsGUIButtonBase.h"
+#include "BsGUIContent.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI
+	 *  @{
+	 */
+
+	/** GUI button that can be clicked. Has normal, hover and active states with an optional label. */
+	class BS_EXPORT GUIButton : public GUIButtonBase
+	{
+	public:
+		/**
+		 * Returns type name of the GUI element used for finding GUI element styles. 
+		 */
+		static const String& getGUITypeName();
+
+		/**
+		 * Creates a new button with the specified label.
+		 *
+		 * @param[in]	text		Label to display on the button.
+		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *							GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUIButton* create(const HString& text, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new button with the specified label.
+		 *
+		 * @param[in]	text			Label to display on the button.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. 
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUIButton* create(const HString& text, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new button with the specified label.
+		 *
+		 * @param[in]	content		Content to display on a button. May include a label, image and a tooltip.
+		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the 
+		 *							GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUIButton* create(const GUIContent& content, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new button with the specified label.
+		 *
+		 * @param[in]	content		Content to display on a button. May include a label, image and a tooltip.
+		 * @param[in]	options		Options that allow you to control how is the element positioned and sized. This will 
+		 *							override any similar options set by style.
+		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the 
+		 *							GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUIButton* create(const GUIContent& content, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** @copydoc GUIElement::getElementType */
+		virtual ElementType _getElementType() const override { return ElementType::Button; }
+
+		/** @} */
+	private:
+		GUIButton(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
+	};
+
+	/** @} */
 }

+ 117 - 115
Source/BansheeEngine/Include/BsGUIButtonBase.h

@@ -1,116 +1,118 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsGUIElement.h"
-#include "BsImageSprite.h"
-#include "BsTextSprite.h"
-#include "BsGUIContent.h"
-#include "BsEvent.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	/**	Base class for a clickable GUI button element. */	
-	class BS_EXPORT GUIButtonBase : public GUIElement
-	{
-	public:
-		/**	Change content displayed by the button. */
-		void setContent(const GUIContent& content);
-
-		/**	Triggered when button is clicked. */
-		Event<void()> onClick;
-
-		/**	Triggered when pointer hovers over the button. */
-		Event<void()> onHover;
-
-		/**	Triggered when pointer that was previously hovering leaves the button. */
-		Event<void()> onOut;
-
-		/**	Triggered when button is clicked twice in rapid succession. */
-		Event<void()> onDoubleClick;
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Change the button "on" state. This state determines whether the button uses normal or "on" fields specified in 
-		 * the GUI style.
-		 */
-		void _setOn(bool on);
-
-		/**
-		 * Retrieves the button "on" state. This state determines whether the button uses normal or "on" fields specified
-		 * in the GUI style.
-		 */
-		bool _isOn() const;
-
-		/**	Change the internal button state, changing the button look depending on set style. */
-		void _setState(GUIElementState state);
-
-		/** @copydoc GUIElement::_getOptimalSize */
-		virtual Vector2I _getOptimalSize() const override;
-
-		/** @copydoc GUIElement::_getRenderElementDepthRange */
-		virtual UINT32 _getRenderElementDepthRange() const override;
-
-		/** @endcond */
-	protected:
-		GUIButtonBase(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
-		virtual ~GUIButtonBase();
-
-		/** @copydoc GUIElement::_getNumRenderElements */
-		virtual UINT32 _getNumRenderElements() const override;
-
-		/** @copydoc GUIElement::_getMaterial */
-		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_getNumQuads */
-		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_fillBuffer */
-		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
-			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::updateRenderElementsInternal */
-		virtual void updateRenderElementsInternal() override;
-
-		/** @copydoc GUIElement::mouseEvent */
-		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
-
-		/** @copydoc GUIElement::_getRenderElementDepth */
-		virtual UINT32 _getRenderElementDepth(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_getTooltip */
-		virtual WString _getTooltip() const override;
-
-		/** Creates or destroys the content image sprite depending if there is a content image for the active state. */
-		void refreshContentSprite();
-
-		/**	Gets the text sprite descriptor used for creating/updating the internal text sprite. */
-		TEXT_SPRITE_DESC getTextDesc() const;
-
-		/**	Retrieves internal button state. */
-		GUIElementState getState() const { return mActiveState; }
-
-		/**	Returns the active sprite texture, depending on the current state. */
-		const HSpriteTexture& getActiveTexture() const;
-
-		/**	Returns the active text color, depending on the current state. */
-		Color getActiveTextColor() const;
-	private:
-		ImageSprite* mImageSprite;
-		ImageSprite* mContentImageSprite;
-		TextSprite* mTextSprite;
-		GUIElementState mActiveState;
-
-		IMAGE_SPRITE_DESC mImageDesc;
-		GUIContent mContent;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsGUIElement.h"
+#include "BsImageSprite.h"
+#include "BsTextSprite.h"
+#include "BsGUIContent.h"
+#include "BsEvent.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	/**	Base class for a clickable GUI button element. */	
+	class BS_EXPORT GUIButtonBase : public GUIElement
+	{
+	public:
+		/**	Change content displayed by the button. */
+		void setContent(const GUIContent& content);
+
+		/**	Triggered when button is clicked. */
+		Event<void()> onClick;
+
+		/**	Triggered when pointer hovers over the button. */
+		Event<void()> onHover;
+
+		/**	Triggered when pointer that was previously hovering leaves the button. */
+		Event<void()> onOut;
+
+		/**	Triggered when button is clicked twice in rapid succession. */
+		Event<void()> onDoubleClick;
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Change the button "on" state. This state determines whether the button uses normal or "on" fields specified in 
+		 * the GUI style.
+		 */
+		void _setOn(bool on);
+
+		/**
+		 * Retrieves the button "on" state. This state determines whether the button uses normal or "on" fields specified
+		 * in the GUI style.
+		 */
+		bool _isOn() const;
+
+		/**	Change the internal button state, changing the button look depending on set style. */
+		void _setState(GUIElementState state);
+
+		/** @copydoc GUIElement::_getOptimalSize */
+		virtual Vector2I _getOptimalSize() const override;
+
+		/** @copydoc GUIElement::_getRenderElementDepthRange */
+		virtual UINT32 _getRenderElementDepthRange() const override;
+
+		/** @} */
+	protected:
+		GUIButtonBase(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
+		virtual ~GUIButtonBase();
+
+		/** @copydoc GUIElement::_getNumRenderElements */
+		virtual UINT32 _getNumRenderElements() const override;
+
+		/** @copydoc GUIElement::_getMaterial */
+		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_getNumQuads */
+		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_fillBuffer */
+		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
+			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::updateRenderElementsInternal */
+		virtual void updateRenderElementsInternal() override;
+
+		/** @copydoc GUIElement::mouseEvent */
+		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
+
+		/** @copydoc GUIElement::_getRenderElementDepth */
+		virtual UINT32 _getRenderElementDepth(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_getTooltip */
+		virtual WString _getTooltip() const override;
+
+		/** Creates or destroys the content image sprite depending if there is a content image for the active state. */
+		void refreshContentSprite();
+
+		/**	Gets the text sprite descriptor used for creating/updating the internal text sprite. */
+		TEXT_SPRITE_DESC getTextDesc() const;
+
+		/**	Retrieves internal button state. */
+		GUIElementState getState() const { return mActiveState; }
+
+		/**	Returns the active sprite texture, depending on the current state. */
+		const HSpriteTexture& getActiveTexture() const;
+
+		/**	Returns the active text color, depending on the current state. */
+		Color getActiveTextColor() const;
+	private:
+		ImageSprite* mImageSprite;
+		ImageSprite* mContentImageSprite;
+		TextSprite* mTextSprite;
+		GUIElementState mActiveState;
+
+		IMAGE_SPRITE_DESC mImageDesc;
+		GUIContent mContent;
+	};
+
+	/** @} */
 }

+ 4 - 2
Source/BansheeEngine/Include/BsGUIElement.h

@@ -83,7 +83,9 @@ namespace BansheeEngine
 		Event<void(bool)> onFocusChanged;
 
 	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
+		/** @name Internal
+		 *  @{
+		 */
 
 		/**
 		 * Returns the number of separate render elements in the GUI element.
@@ -249,7 +251,7 @@ namespace BansheeEngine
 		/**	Returns a clip rectangle relative to the element, used for clipping	the input text. */
 		virtual Rect2I _getTextInputRect() const { return Rect2I(); }
 
-		/** @endcond */
+		/** @} */
 
 	protected:
 		/**	Called whenever render elements are dirty and need to be rebuilt. */

+ 332 - 330
Source/BansheeEngine/Include/BsGUIElementBase.h

@@ -1,331 +1,333 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsGUIDimensions.h"
-#include "BsGUILayoutData.h"
-#include "BsRect2I.h"
-#include "BsVector2I.h"
-#include "BsRectOffset.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	/**	Base class for all GUI elements (visible or layout). */
-	class BS_EXPORT GUIElementBase
-	{
-	public:
-		/**	Valid types of GUI base elements. */
-		enum class Type
-		{
-			Layout,
-			Element,
-			FixedSpace,
-			FlexibleSpace,
-			Panel
-		};
-
-	protected:
-		/**	Flags that signal the state of the GUI element. */
-		enum GUIElementFlags
-		{
-			GUIElem_Dirty = 0x01,
-			GUIElem_Hidden = 0x02,
-			GUIElem_Inactive = 0x04,
-			GUIElem_HiddenSelf = 0x08,
-			GUIElem_InactiveSelf = 0x10,
-			GUIElem_Disabled = 0x20,
-			GUIElem_DisabledSelf = 0x40
-		};
-
-	public:
-		GUIElementBase();
-		GUIElementBase(const GUIDimensions& dimensions);
-		virtual ~GUIElementBase();
-
-		/**
-		 * Sets element position relative to parent GUI panel.
-		 *
-		 * @note	
-		 * Be aware that this value will be ignored if GUI element is part of a layout since then the layout controls its
-		 * placement.
-		 */
-		void setPosition(INT32 x, INT32 y);
-
-		/**	Sets element width in pixels.  */
-		void setWidth(UINT32 width);
-
-		/**
-		 * Sets element width in pixels. Element will be resized according to its contents and parent layout but will 
-		 * always stay within the provided range. If maximum width is zero, the element is allowed to expand as much as
-		 * it needs.
-		 */
-		void setFlexibleWidth(UINT32 minWidth = 0, UINT32 maxWidth = 0);
-
-		/**	Sets element height in pixels. */
-		void setHeight(UINT32 height);
-
-		/**
-		 * Sets element height in pixels. Element will be resized according to its contents and parent layout but will 
-		 * always stay within the provided range. If maximum height is zero, the element is allowed to expand as much as
-		 * it needs.
-		 */
-		void setFlexibleHeight(UINT32 minHeight = 0, UINT32 maxHeight = 0);
-
-		/**	Resets element dimensions to their initial values dictated by the element's style. */
-		virtual void resetDimensions();
-
-		/**
-		 * Hides or shows this element and recursively applies the same state to all the child elements. This will not
-		 * remove the element from the layout, the room for it will still be reserved but it just won't be visible.
-		 */
-		void setVisible(bool visible);
-
-		/**
-		 * Activates or deactives this element and recursively applies the same state to all the child elements. This has 
-		 * the same effect as setVisible(), but when disabled it will also remove the element from the layout, essentially
-		 * having the same effect is if you destroyed the element.
-		 */
-		void setActive(bool active);
-
-		/** Disables or enables the element. Disabled elements cannot be interacted with and have a faded out appearance. */
-		void setDisabled(bool disabled);
-
-		/**
-		 * Returns non-clipped bounds of the GUI element. Relative to a parent GUI panel.
-		 *
-		 * @param[in]	relativeTo	Parent panel of the provided element relative to which to return the bounds. If null 
-		 *							the bounds relative to the first parent panel are returned. Behavior is undefined if 
-		 *							provided panel is not a parent of the element.
-		 *
-		 * @note	This call can be potentially expensive if the GUI state is dirty.
-		 */
-		Rect2I getBounds(GUIPanel* relativeTo = nullptr);
-
-		/**
-		 * Sets the bounds of the GUI element. Relative to a parent GUI panel. Equivalent to calling setPosition(), 
-		 * setWidth() and setHeight().
-		 */
-		void setBounds(const Rect2I& bounds);
-
-		/**
-		 * Returns non-clipped bounds of the GUI element. Relative to a parent GUI widget.
-		 *
-		 * @note	This call can be potentially expensive if the GUI state is dirty.
-		 */
-		Rect2I getGlobalBounds();
-
-		/**
-		 * Returns non-clipped visible bounds of the GUI element (bounds exclude the margins). Relative to the parent GUI 
-		 * panel.
-		 *
-		 * @note	This call can be potentially expensive as the bounds need to be calculated based on current GUI state.
-		 */
-		virtual Rect2I getVisibleBounds();
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/**
-		 * Updates child elements positions, sizes, clip rectangles and depths so they fit into the provided bounds, while
-		 * respecting their layout options. 
-		 *
-		 * @param[in]	data	Layout data containing the necessary bounds and restrictions to use for calculating the 
-		 *						child element layout data.
-		 *
-		 * @note	Internal method.
-		 */
-		virtual void _updateLayout(const GUILayoutData& data);
-
-		/** Calculates optimal sizes of all child elements, as determined by their style and layout options. */
-		virtual void _updateOptimalLayoutSizes();
-
-		/** @copydoc _updateLayout */
-		virtual void _updateLayoutInternal(const GUILayoutData& data);
-
-		/**
-		 * Calculates positions & sizes of all elements in the layout. This method expects a pre-allocated array to store 
-		 * the data in.
-		 *
-		 * @param[in]	layoutArea		Parent layout area to position the child elements in.
-		 * @param[out]	elementAreas	Array to hold output areas. Must be the same size as the number of child elements.
-		 * @param[in]	numElements		Size of the element areas array.
-		 * @param[in]	sizeRanges		Ranges of possible sizes used for the child elements. Array must be same size as 
-		 *								elements array.
-		 * @param[in]	mySizeRange		Size range of this element.
-		 */
-		virtual void _getElementAreas(const Rect2I& layoutArea, Rect2I* elementAreas, UINT32 numElements,
-			const Vector<LayoutSizeRange>& sizeRanges, const LayoutSizeRange& mySizeRange) const;
-
-		/** Updates layout data that determines GUI elements final position & depth in the GUI widget. */
-		virtual void _setLayoutData(const GUILayoutData& data) { mLayoutData = data; }
-
-		/** Retrieves layout data that determines GUI elements final position & depth in the GUI widget. */
-		const GUILayoutData& _getLayoutData() const { return mLayoutData; }
-
-		/**	Sets a new parent for this element. */
-		void _setParent(GUIElementBase* parent);
-
-		/**	Returns number of child elements. */
-		UINT32 _getNumChildren() const { return (UINT32)mChildren.size(); }
-
-		/**	Return the child element at the specified index.*/
-		GUIElementBase* _getChild(UINT32 idx) const { return mChildren[idx]; }
-
-		/**	Returns previously calculated optimal size for this element. */
-		virtual Vector2I _getOptimalSize() const = 0;
-
-		/**	Returns layout options that determine how is the element positioned and sized. */
-		const GUIDimensions& _getDimensions() const { return mDimensions; }
-
-		/**	Calculates element size range constrained by its layout options. */
-		virtual LayoutSizeRange _calculateLayoutSizeRange() const ;
-
-		/**
-		 * Returns element size range constrained by its layout options. This is different from _calculateLayoutSizeRange()
-		 * because this method may return cached size range. 
-		 */
-		virtual LayoutSizeRange _getLayoutSizeRange() const;
-
-		/**
-		 * Returns element padding that determines how far apart to space out this element from other elements in a layout.
-		 */
-		virtual const RectOffset& _getPadding() const = 0;
-
-		/**	Returns specific sub-type of this object. */
-		virtual Type _getType() const = 0;
-
-		/**	Returns parent GUI base element. */
-		GUIElementBase* _getParent() const { return mParentElement; }
-
-		/**
-		 * Returns the parent element whose layout needs to be updated when this elements contents change.
-		 *
-		 * @note	
-		 * Due to the nature of the GUI system, when a child element bounds or contents change, its parents and siblings
-		 * usually need their layout bound updated. This function returns the first parent of all the elements that require
-		 * updating. This parent usually has fixed bounds or some other property that allows its children to be updated
-		 * independently from the even higher-up elements.
-		 */
-		GUIElementBase* _getUpdateParent() const { return mUpdateParent; }
-
-		/**	Returns parent GUI widget, can be null. */
-		GUIWidget* _getParentWidget() const { return mParentWidget; }
-
-		/**	Checks if element is visible or hidden. */
-		bool _isVisible() const { return (mFlags & GUIElem_Hidden) == 0; }
-
-		/**
-		 * Checks if element is active or inactive. Inactive elements are not visible, don't take up space
-		 * in their parent layouts, and can't be interacted with. 
-		 */
-		bool _isActive() const { return (mFlags & GUIElem_Inactive) == 0; }
-
-		/** Checks if element is disabled. Disabled elements cannot be interacted with and have a faded out appearance. */
-		bool _isDisabled() const { return (mFlags & GUIElem_Disabled) != 0; }
-
-		/**
-		 * Internal version of setVisible() that doesn't modify local visibility, instead it is only meant to be called
-		 * on child elements of the element whose visibility was modified.
-		 */
-		void _setVisible(bool visible);
-
-		/**
-		 * Internal version of ::setActive that doesn't modify local state, instead it is only meant to be called
-		 * on child elements of the element whose state was modified.
-		 *  
-		 * @copydoc setActive
-		 */
-		void _setActive(bool active);
-
-		/**
-		 * Internal version of ::setDisabled that doesn't modify local state, instead it is only meant to be called
-		 * on child elements of the element whose state was modified.
-		 *  
-		 * @copydoc setDisabled
-		 */
-		void _setDisabled(bool disabled);
-
-		/**
-		 * Changes the active GUI element widget. This allows you to move an element to a different viewport, or change
-		 * element style by using a widget with a different skin. You are allowed to pass null here, but elements with no
-		 * parent will be unmanaged. You will be responsible for deleting them manually, and they will not render anywhere.
-		 */
-		virtual void _changeParentWidget(GUIWidget* widget);
-
-		/**Registers a new child element. */
-		void _registerChildElement(GUIElementBase* element);
-
-		/**	Unregisters an existing child element. */
-		void _unregisterChildElement(GUIElementBase* element);
-
-		/**	Checks if element has been destroyed and is queued for deletion. */
-		virtual bool _isDestroyed() const { return false; }
-
-		/**	Marks the element's dimensions as dirty, triggering a layout rebuild. */
-		void _markLayoutAsDirty();
-
-		/**	Marks the element's contents as dirty, which causes the sprite meshes to be recreated from scratch. */
-		void _markContentAsDirty();
-
-		/**
-		 * Mark only the elements that operate directly on the sprite mesh without requiring the mesh to be recreated as 
-		 * dirty. This includes position, depth and clip rectangle. This will cause the parent widget mesh to be rebuilt
-		 * from its child element's meshes.
-		 */
-		void _markMeshAsDirty();
-
-		/**	Returns true if elements contents have changed since last update. */
-		bool _isDirty() const { return (mFlags & GUIElem_Dirty) != 0; }
-
-		/**	Marks the element contents to be up to date. (i.e. processed by the GUI system) */
-		void _markAsClean();
-
-		/** @endcond */
-
-	protected:
-		/**	Finds anchor and update parents and recursively assigns them to all children. */
-		void _updateAUParents();
-
-		/**	Refreshes update parents of all child elements. */
-		void refreshChildUpdateParents();
-
-		/**
-		 * Finds the first parent element whose size doesn't depend on child sizes.
-		 *			
-		 * @note	
-		 * This allows us to optimize layout updates and trigger them only on such parents when their child elements 
-		 * contents change, compared to doing them on the entire GUI hierarchy.
-		 */
-		GUIElementBase* findUpdateParent();
-
-		/**
-		 * Helper method for recursion in _updateAUParents(). Sets the provided anchor parent for all children recursively.
-		 * Recursion stops when a child anchor is detected.
-		 */
-		void setAnchorParent(GUIPanel* anchorParent);
-
-		/**
-		 * Helper method for recursion in _updateAUParents(). Sets the provided update parent for all children recursively.
-		 * Recursion stops when a child update parent is detected.
-		 */
-		void setUpdateParent(GUIElementBase* updateParent);
-
-		GUIWidget* mParentWidget;
-		GUIPanel* mAnchorParent;
-		GUIElementBase* mUpdateParent;
-		GUIElementBase* mParentElement;
-
-		Vector<GUIElementBase*> mChildren;	
-		UINT8 mFlags;
-
-		GUIDimensions mDimensions;
-		GUILayoutData mLayoutData;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsGUIDimensions.h"
+#include "BsGUILayoutData.h"
+#include "BsRect2I.h"
+#include "BsVector2I.h"
+#include "BsRectOffset.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	/**	Base class for all GUI elements (visible or layout). */
+	class BS_EXPORT GUIElementBase
+	{
+	public:
+		/**	Valid types of GUI base elements. */
+		enum class Type
+		{
+			Layout,
+			Element,
+			FixedSpace,
+			FlexibleSpace,
+			Panel
+		};
+
+	protected:
+		/**	Flags that signal the state of the GUI element. */
+		enum GUIElementFlags
+		{
+			GUIElem_Dirty = 0x01,
+			GUIElem_Hidden = 0x02,
+			GUIElem_Inactive = 0x04,
+			GUIElem_HiddenSelf = 0x08,
+			GUIElem_InactiveSelf = 0x10,
+			GUIElem_Disabled = 0x20,
+			GUIElem_DisabledSelf = 0x40
+		};
+
+	public:
+		GUIElementBase();
+		GUIElementBase(const GUIDimensions& dimensions);
+		virtual ~GUIElementBase();
+
+		/**
+		 * Sets element position relative to parent GUI panel.
+		 *
+		 * @note	
+		 * Be aware that this value will be ignored if GUI element is part of a layout since then the layout controls its
+		 * placement.
+		 */
+		void setPosition(INT32 x, INT32 y);
+
+		/**	Sets element width in pixels.  */
+		void setWidth(UINT32 width);
+
+		/**
+		 * Sets element width in pixels. Element will be resized according to its contents and parent layout but will 
+		 * always stay within the provided range. If maximum width is zero, the element is allowed to expand as much as
+		 * it needs.
+		 */
+		void setFlexibleWidth(UINT32 minWidth = 0, UINT32 maxWidth = 0);
+
+		/**	Sets element height in pixels. */
+		void setHeight(UINT32 height);
+
+		/**
+		 * Sets element height in pixels. Element will be resized according to its contents and parent layout but will 
+		 * always stay within the provided range. If maximum height is zero, the element is allowed to expand as much as
+		 * it needs.
+		 */
+		void setFlexibleHeight(UINT32 minHeight = 0, UINT32 maxHeight = 0);
+
+		/**	Resets element dimensions to their initial values dictated by the element's style. */
+		virtual void resetDimensions();
+
+		/**
+		 * Hides or shows this element and recursively applies the same state to all the child elements. This will not
+		 * remove the element from the layout, the room for it will still be reserved but it just won't be visible.
+		 */
+		void setVisible(bool visible);
+
+		/**
+		 * Activates or deactives this element and recursively applies the same state to all the child elements. This has 
+		 * the same effect as setVisible(), but when disabled it will also remove the element from the layout, essentially
+		 * having the same effect is if you destroyed the element.
+		 */
+		void setActive(bool active);
+
+		/** Disables or enables the element. Disabled elements cannot be interacted with and have a faded out appearance. */
+		void setDisabled(bool disabled);
+
+		/**
+		 * Returns non-clipped bounds of the GUI element. Relative to a parent GUI panel.
+		 *
+		 * @param[in]	relativeTo	Parent panel of the provided element relative to which to return the bounds. If null 
+		 *							the bounds relative to the first parent panel are returned. Behavior is undefined if 
+		 *							provided panel is not a parent of the element.
+		 *
+		 * @note	This call can be potentially expensive if the GUI state is dirty.
+		 */
+		Rect2I getBounds(GUIPanel* relativeTo = nullptr);
+
+		/**
+		 * Sets the bounds of the GUI element. Relative to a parent GUI panel. Equivalent to calling setPosition(), 
+		 * setWidth() and setHeight().
+		 */
+		void setBounds(const Rect2I& bounds);
+
+		/**
+		 * Returns non-clipped bounds of the GUI element. Relative to a parent GUI widget.
+		 *
+		 * @note	This call can be potentially expensive if the GUI state is dirty.
+		 */
+		Rect2I getGlobalBounds();
+
+		/**
+		 * Returns non-clipped visible bounds of the GUI element (bounds exclude the margins). Relative to the parent GUI 
+		 * panel.
+		 *
+		 * @note	This call can be potentially expensive as the bounds need to be calculated based on current GUI state.
+		 */
+		virtual Rect2I getVisibleBounds();
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/**
+		 * Updates child elements positions, sizes, clip rectangles and depths so they fit into the provided bounds, while
+		 * respecting their layout options. 
+		 *
+		 * @param[in]	data	Layout data containing the necessary bounds and restrictions to use for calculating the 
+		 *						child element layout data.
+		 *
+		 * @note	Internal method.
+		 */
+		virtual void _updateLayout(const GUILayoutData& data);
+
+		/** Calculates optimal sizes of all child elements, as determined by their style and layout options. */
+		virtual void _updateOptimalLayoutSizes();
+
+		/** @copydoc _updateLayout */
+		virtual void _updateLayoutInternal(const GUILayoutData& data);
+
+		/**
+		 * Calculates positions & sizes of all elements in the layout. This method expects a pre-allocated array to store 
+		 * the data in.
+		 *
+		 * @param[in]	layoutArea		Parent layout area to position the child elements in.
+		 * @param[out]	elementAreas	Array to hold output areas. Must be the same size as the number of child elements.
+		 * @param[in]	numElements		Size of the element areas array.
+		 * @param[in]	sizeRanges		Ranges of possible sizes used for the child elements. Array must be same size as 
+		 *								elements array.
+		 * @param[in]	mySizeRange		Size range of this element.
+		 */
+		virtual void _getElementAreas(const Rect2I& layoutArea, Rect2I* elementAreas, UINT32 numElements,
+			const Vector<LayoutSizeRange>& sizeRanges, const LayoutSizeRange& mySizeRange) const;
+
+		/** Updates layout data that determines GUI elements final position & depth in the GUI widget. */
+		virtual void _setLayoutData(const GUILayoutData& data) { mLayoutData = data; }
+
+		/** Retrieves layout data that determines GUI elements final position & depth in the GUI widget. */
+		const GUILayoutData& _getLayoutData() const { return mLayoutData; }
+
+		/**	Sets a new parent for this element. */
+		void _setParent(GUIElementBase* parent);
+
+		/**	Returns number of child elements. */
+		UINT32 _getNumChildren() const { return (UINT32)mChildren.size(); }
+
+		/**	Return the child element at the specified index.*/
+		GUIElementBase* _getChild(UINT32 idx) const { return mChildren[idx]; }
+
+		/**	Returns previously calculated optimal size for this element. */
+		virtual Vector2I _getOptimalSize() const = 0;
+
+		/**	Returns layout options that determine how is the element positioned and sized. */
+		const GUIDimensions& _getDimensions() const { return mDimensions; }
+
+		/**	Calculates element size range constrained by its layout options. */
+		virtual LayoutSizeRange _calculateLayoutSizeRange() const ;
+
+		/**
+		 * Returns element size range constrained by its layout options. This is different from _calculateLayoutSizeRange()
+		 * because this method may return cached size range. 
+		 */
+		virtual LayoutSizeRange _getLayoutSizeRange() const;
+
+		/**
+		 * Returns element padding that determines how far apart to space out this element from other elements in a layout.
+		 */
+		virtual const RectOffset& _getPadding() const = 0;
+
+		/**	Returns specific sub-type of this object. */
+		virtual Type _getType() const = 0;
+
+		/**	Returns parent GUI base element. */
+		GUIElementBase* _getParent() const { return mParentElement; }
+
+		/**
+		 * Returns the parent element whose layout needs to be updated when this elements contents change.
+		 *
+		 * @note	
+		 * Due to the nature of the GUI system, when a child element bounds or contents change, its parents and siblings
+		 * usually need their layout bound updated. This function returns the first parent of all the elements that require
+		 * updating. This parent usually has fixed bounds or some other property that allows its children to be updated
+		 * independently from the even higher-up elements.
+		 */
+		GUIElementBase* _getUpdateParent() const { return mUpdateParent; }
+
+		/**	Returns parent GUI widget, can be null. */
+		GUIWidget* _getParentWidget() const { return mParentWidget; }
+
+		/**	Checks if element is visible or hidden. */
+		bool _isVisible() const { return (mFlags & GUIElem_Hidden) == 0; }
+
+		/**
+		 * Checks if element is active or inactive. Inactive elements are not visible, don't take up space
+		 * in their parent layouts, and can't be interacted with. 
+		 */
+		bool _isActive() const { return (mFlags & GUIElem_Inactive) == 0; }
+
+		/** Checks if element is disabled. Disabled elements cannot be interacted with and have a faded out appearance. */
+		bool _isDisabled() const { return (mFlags & GUIElem_Disabled) != 0; }
+
+		/**
+		 * Internal version of setVisible() that doesn't modify local visibility, instead it is only meant to be called
+		 * on child elements of the element whose visibility was modified.
+		 */
+		void _setVisible(bool visible);
+
+		/**
+		 * Internal version of ::setActive that doesn't modify local state, instead it is only meant to be called
+		 * on child elements of the element whose state was modified.
+		 *  
+		 * @copydoc setActive
+		 */
+		void _setActive(bool active);
+
+		/**
+		 * Internal version of ::setDisabled that doesn't modify local state, instead it is only meant to be called
+		 * on child elements of the element whose state was modified.
+		 *  
+		 * @copydoc setDisabled
+		 */
+		void _setDisabled(bool disabled);
+
+		/**
+		 * Changes the active GUI element widget. This allows you to move an element to a different viewport, or change
+		 * element style by using a widget with a different skin. You are allowed to pass null here, but elements with no
+		 * parent will be unmanaged. You will be responsible for deleting them manually, and they will not render anywhere.
+		 */
+		virtual void _changeParentWidget(GUIWidget* widget);
+
+		/**Registers a new child element. */
+		void _registerChildElement(GUIElementBase* element);
+
+		/**	Unregisters an existing child element. */
+		void _unregisterChildElement(GUIElementBase* element);
+
+		/**	Checks if element has been destroyed and is queued for deletion. */
+		virtual bool _isDestroyed() const { return false; }
+
+		/**	Marks the element's dimensions as dirty, triggering a layout rebuild. */
+		void _markLayoutAsDirty();
+
+		/**	Marks the element's contents as dirty, which causes the sprite meshes to be recreated from scratch. */
+		void _markContentAsDirty();
+
+		/**
+		 * Mark only the elements that operate directly on the sprite mesh without requiring the mesh to be recreated as 
+		 * dirty. This includes position, depth and clip rectangle. This will cause the parent widget mesh to be rebuilt
+		 * from its child element's meshes.
+		 */
+		void _markMeshAsDirty();
+
+		/**	Returns true if elements contents have changed since last update. */
+		bool _isDirty() const { return (mFlags & GUIElem_Dirty) != 0; }
+
+		/**	Marks the element contents to be up to date (meaning it's processed by the GUI system). */
+		void _markAsClean();
+
+		/** @} */
+
+	protected:
+		/**	Finds anchor and update parents and recursively assigns them to all children. */
+		void _updateAUParents();
+
+		/**	Refreshes update parents of all child elements. */
+		void refreshChildUpdateParents();
+
+		/**
+		 * Finds the first parent element whose size doesn't depend on child sizes.
+		 *			
+		 * @note	
+		 * This allows us to optimize layout updates and trigger them only on such parents when their child elements 
+		 * contents change, compared to doing them on the entire GUI hierarchy.
+		 */
+		GUIElementBase* findUpdateParent();
+
+		/**
+		 * Helper method for recursion in _updateAUParents(). Sets the provided anchor parent for all children recursively.
+		 * Recursion stops when a child anchor is detected.
+		 */
+		void setAnchorParent(GUIPanel* anchorParent);
+
+		/**
+		 * Helper method for recursion in _updateAUParents(). Sets the provided update parent for all children recursively.
+		 * Recursion stops when a child update parent is detected.
+		 */
+		void setUpdateParent(GUIElementBase* updateParent);
+
+		GUIWidget* mParentWidget;
+		GUIPanel* mAnchorParent;
+		GUIElementBase* mUpdateParent;
+		GUIElementBase* mParentElement;
+
+		Vector<GUIElementBase*> mChildren;	
+		UINT8 mFlags;
+
+		GUIDimensions mDimensions;
+		GUILayoutData mLayoutData;
+	};
+
+	/** @} */
 }

+ 266 - 264
Source/BansheeEngine/Include/BsGUIInputBox.h

@@ -1,265 +1,267 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsGUIElement.h"
-#include "BsImageSprite.h"
-#include "BsTextSprite.h"
-#include "BsVirtualInput.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI
-	 *  @{
-	 */
-
-	/**
-	 * Input box is a GUI element that accepts Unicode textual input. It can be single or multi-line and handles various 
-	 * types of text manipulation.
-	 */
-	class BS_EXPORT GUIInputBox : public GUIElement
-	{
-		/**	Possible visual states the input box can be in. */
-		enum class State
-		{
-			Normal,
-			Hover,
-			Focused
-		};
-
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles.  */
-		static const String& getGUITypeName();
-
-		/**
-		 * Creates a new input box.
-		 *
-		 * @param[in]	multiline		If true the input box can be of arbitrary height and will accept multiple lines of 
-		 *								text.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default style for this element 
-		 *								is used.
-		 */
-		static GUIInputBox* create(bool multiline = false, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new input box.
-		 *
-		 * @param[in]	multiline		If true the input box can be of arbitrary height and will accept multiple lines of 
-		 *								text.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
-		 *								override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUIInputBox* create(bool multiline, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-
-		/**
-		 * Creates a new single-line input box.
-		 *
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
-		 *								override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUIInputBox* create(const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-		/**	Returns the text currently entered in the input box. */
-		const WString& getText() const { return mText; }
-
-		/**	Sets the text inside the input box. This will replace any current text. */
-		void setText(const WString& text);
-
-		/**
-		 * Sets an optional filter that can control what is allowed to be entered into the input box. Filter should return
-		 * true if the provided string is valid and false otherwise. Set the filter to null to deactivate filtering.
-		 */
-		void setFilter(std::function<bool(const WString&)> filter) { mFilter = filter; }
-
-		/**	Triggered whenever input text has changed. */
-		Event<void(const WString&)> onValueChanged;
-
-		/**	Triggered when the user hits the Enter key with the input box in focus. */
-		Event<void()> onConfirm;
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** @copydoc GUIElement::getElementType */
-		virtual ElementType _getElementType() const override { return ElementType::InputBox; }
-
-		/** @copydoc GUIElement::_getOptimalSize */
-		virtual Vector2I _getOptimalSize() const override;
-
-		/** @endcond */
-	protected:
-		GUIInputBox(const String& styleName, const GUIDimensions& dimensions, bool multiline);
-		virtual ~GUIInputBox();
-
-		/** @copydoc GUIElement::_getNumRenderElements() */
-		virtual UINT32 _getNumRenderElements() const override;
-
-		/** @copydoc GUIElement::_getMaterial() */
-		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_getNumQuads() */
-		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_fillBuffer() */
-		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
-			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::updateRenderElementsInternal() */
-		virtual void updateRenderElementsInternal() override;
-
-		/** @copydoc GUIElement::updateBounds() */
-		virtual void updateClippedBounds() override;
-
-		/** @copydoc GUIElement::mouseEvent */
-		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
-
-		/** @copydoc GUIElement::textInputEvent */
-		virtual bool _textInputEvent(const GUITextInputEvent& ev) override;
-
-		/** @copydoc GUIElement::commandEvent */
-		virtual bool _commandEvent(const GUICommandEvent& ev) override;
-
-		/** @copydoc GUIElement::virtualButtonEvent */
-		virtual bool _virtualButtonEvent(const GUIVirtualButtonEvent& ev) override;
-
-		/**
-		 * Returns how much to offset text due to scrolling.
-		 *
-		 * @note	
-		 * This is used when text is larger than the input box itself. As the caret moves the text will scroll so that the
-		 * caret remains visible, and how much scroll is applied is determined by this value.
-		 */
-		virtual Vector2I _getTextInputOffset() const override;
-
-		/** Returns rectangle in which the text can be displayed, in local coordinates (i.e. text will start at 0, 0). */
-		virtual Rect2I _getTextInputRect() const override;
-
-		/** @copydoc GUIElement::_getRenderElementDepth */
-		virtual UINT32 _getRenderElementDepth(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_getRenderElementDepthRange */
-		virtual UINT32 _getRenderElementDepthRange() const override;
-
-		/** @copydoc GUIElement::_hasCustomCursor */
-		virtual bool _hasCustomCursor(const Vector2I position, CursorType& type) const override;
-
-		/** @copydoc GUIElement::getContextMenu */
-		virtual GUIContextMenuPtr _getContextMenu() const override;
-	private:
-		/**
-		 * Retrieves a sprite from a render element index, and a local render element index that represents render element
-		 * within the returned sprite.
-		 */
-		Sprite* renderElemToSprite(UINT32 renderElemIdx, UINT32& localRenderElemIdx) const;
-
-		/**
-		 * Returns offset at which is the element with the provided render element index. Offset is relative to parent
-		 * widget.
-		 */
-		Vector2I renderElemToOffset(UINT32 renderElemIdx) const;
-
-		/**
-		 * Returns a clip rectangle that can be used for clipping the render element with the provided index. Rectangle is
-		 * in local coordiantes relative to element origin.
-		 */
-		Rect2I renderElemToClipRect(UINT32 renderElemIdx) const;
-
-		/** Inserts a new string into the current text at the specified index. */
-		void insertString(UINT32 charIdx, const WString& string);
-
-		/**	Inserts a new character into the current text at the specified index. */
-		void insertChar(UINT32 charIdx, UINT32 charCode);
-
-		/**	Erases a single character at the specified index. */
-		void eraseChar(UINT32 charIdx);
-
-		/**
-		 * Deletes text that is currently selected.
-		 * 			
-		 * @param[in]	internal	If internal not filter will be applied after the text is deleted, and no event will be 
-		 * 							triggered either.
-		 */
-		void deleteSelectedText(bool internal = false);
-
-		/**	Returns currently selected text. */
-		WString getSelectedText();
-
-		/**	Shows the input caret. You must position the caret manually after showing it. */
-		void showCaret();
-
-		/**	Hides the input caret. */
-		void hideCaret();
-
-		/**
-		 * Shows selection with the specified anchor position. You must position selection start and end before selection
-		 * will actually render. Anchor position determines selection behavior as the user moves the selection with the 
-		 * keyboard.
-		 */
-		void showSelection(UINT32 anchorCaretPos);
-
-		/**	Removes any active selection. */
-		void clearSelection();
-
-		/**	Adjusts the text offset (scroll) so that the caret is visible. */
-		void scrollTextToCaret();
-
-		/** Clamps the text offset (scroll)	so that the text fits in the provided bounds nicely with minimal white space. */
-		void clampScrollToBounds(Rect2I unclippedTextBounds);
-
-		/**	Returns offset at which to render the text. Relative to parent widget. */
-		Vector2I getTextOffset() const;
-
-		/**	Returns rectangle used for clipping the text. Relative to element. */
-		Rect2I getTextClipRect() const;
-
-		/**	Returns text sprite descriptor determining how is text sprite created. */
-		TEXT_SPRITE_DESC getTextDesc() const;
-
-		/**	Returns currently active input box texture, depending on active state. */
-		const HSpriteTexture& getActiveTexture() const;
-		
-		/**	Returns currently active input box text color, depending on active state. */
-		Color getActiveTextColor() const;
-
-		/**	Cuts currently selected text to clipboard. */
-		void cutText();
-
-		/**	Copies currently selected text to clipboard. */
-		void copyText();
-
-		/**	Inserts text from clipboard to current caret location. */
-		void pasteText();
-
-	private:
-		static VirtualButton mCopyVB;
-		static VirtualButton mPasteVB;
-		static VirtualButton mCutVB;
-		static VirtualButton mSelectAllVB;
-
-		// Sprites
-		ImageSprite* mImageSprite;
-		TextSprite* mTextSprite;
-		bool mIsMultiline;
-		Vector2I mTextOffset;
-		bool mHasFocus;
-		bool mIsMouseOver;
-		State mState;
-
-		IMAGE_SPRITE_DESC mImageDesc;
-		WString mText;
-		std::function<bool(const WString&)> mFilter;
-
-		bool mCaretShown;
-		bool mSelectionShown;
-		bool mDragInProgress;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsGUIElement.h"
+#include "BsImageSprite.h"
+#include "BsTextSprite.h"
+#include "BsVirtualInput.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI
+	 *  @{
+	 */
+
+	/**
+	 * Input box is a GUI element that accepts Unicode textual input. It can be single or multi-line and handles various 
+	 * types of text manipulation.
+	 */
+	class BS_EXPORT GUIInputBox : public GUIElement
+	{
+		/**	Possible visual states the input box can be in. */
+		enum class State
+		{
+			Normal,
+			Hover,
+			Focused
+		};
+
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles.  */
+		static const String& getGUITypeName();
+
+		/**
+		 * Creates a new input box.
+		 *
+		 * @param[in]	multiline		If true the input box can be of arbitrary height and will accept multiple lines of 
+		 *								text.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default style for this element 
+		 *								is used.
+		 */
+		static GUIInputBox* create(bool multiline = false, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new input box.
+		 *
+		 * @param[in]	multiline		If true the input box can be of arbitrary height and will accept multiple lines of 
+		 *								text.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
+		 *								override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUIInputBox* create(bool multiline, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+
+		/**
+		 * Creates a new single-line input box.
+		 *
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
+		 *								override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUIInputBox* create(const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+		/**	Returns the text currently entered in the input box. */
+		const WString& getText() const { return mText; }
+
+		/**	Sets the text inside the input box. This will replace any current text. */
+		void setText(const WString& text);
+
+		/**
+		 * Sets an optional filter that can control what is allowed to be entered into the input box. Filter should return
+		 * true if the provided string is valid and false otherwise. Set the filter to null to deactivate filtering.
+		 */
+		void setFilter(std::function<bool(const WString&)> filter) { mFilter = filter; }
+
+		/**	Triggered whenever input text has changed. */
+		Event<void(const WString&)> onValueChanged;
+
+		/**	Triggered when the user hits the Enter key with the input box in focus. */
+		Event<void()> onConfirm;
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** @copydoc GUIElement::getElementType */
+		virtual ElementType _getElementType() const override { return ElementType::InputBox; }
+
+		/** @copydoc GUIElement::_getOptimalSize */
+		virtual Vector2I _getOptimalSize() const override;
+
+		/** @} */
+	protected:
+		GUIInputBox(const String& styleName, const GUIDimensions& dimensions, bool multiline);
+		virtual ~GUIInputBox();
+
+		/** @copydoc GUIElement::_getNumRenderElements() */
+		virtual UINT32 _getNumRenderElements() const override;
+
+		/** @copydoc GUIElement::_getMaterial() */
+		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_getNumQuads() */
+		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_fillBuffer() */
+		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
+			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::updateRenderElementsInternal() */
+		virtual void updateRenderElementsInternal() override;
+
+		/** @copydoc GUIElement::updateBounds() */
+		virtual void updateClippedBounds() override;
+
+		/** @copydoc GUIElement::mouseEvent */
+		virtual bool _mouseEvent(const GUIMouseEvent& ev) override;
+
+		/** @copydoc GUIElement::textInputEvent */
+		virtual bool _textInputEvent(const GUITextInputEvent& ev) override;
+
+		/** @copydoc GUIElement::commandEvent */
+		virtual bool _commandEvent(const GUICommandEvent& ev) override;
+
+		/** @copydoc GUIElement::virtualButtonEvent */
+		virtual bool _virtualButtonEvent(const GUIVirtualButtonEvent& ev) override;
+
+		/**
+		 * Returns how much to offset text due to scrolling.
+		 *
+		 * @note	
+		 * This is used when text is larger than the input box itself. As the caret moves the text will scroll so that the
+		 * caret remains visible, and how much scroll is applied is determined by this value.
+		 */
+		virtual Vector2I _getTextInputOffset() const override;
+
+		/** Returns rectangle in which the text can be displayed, in local coordinates (text will start at 0, 0). */
+		virtual Rect2I _getTextInputRect() const override;
+
+		/** @copydoc GUIElement::_getRenderElementDepth */
+		virtual UINT32 _getRenderElementDepth(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_getRenderElementDepthRange */
+		virtual UINT32 _getRenderElementDepthRange() const override;
+
+		/** @copydoc GUIElement::_hasCustomCursor */
+		virtual bool _hasCustomCursor(const Vector2I position, CursorType& type) const override;
+
+		/** @copydoc GUIElement::getContextMenu */
+		virtual GUIContextMenuPtr _getContextMenu() const override;
+	private:
+		/**
+		 * Retrieves a sprite from a render element index, and a local render element index that represents render element
+		 * within the returned sprite.
+		 */
+		Sprite* renderElemToSprite(UINT32 renderElemIdx, UINT32& localRenderElemIdx) const;
+
+		/**
+		 * Returns offset at which is the element with the provided render element index. Offset is relative to parent
+		 * widget.
+		 */
+		Vector2I renderElemToOffset(UINT32 renderElemIdx) const;
+
+		/**
+		 * Returns a clip rectangle that can be used for clipping the render element with the provided index. Rectangle is
+		 * in local coordiantes relative to element origin.
+		 */
+		Rect2I renderElemToClipRect(UINT32 renderElemIdx) const;
+
+		/** Inserts a new string into the current text at the specified index. */
+		void insertString(UINT32 charIdx, const WString& string);
+
+		/**	Inserts a new character into the current text at the specified index. */
+		void insertChar(UINT32 charIdx, UINT32 charCode);
+
+		/**	Erases a single character at the specified index. */
+		void eraseChar(UINT32 charIdx);
+
+		/**
+		 * Deletes text that is currently selected.
+		 * 			
+		 * @param[in]	internal	If internal not filter will be applied after the text is deleted, and no event will be 
+		 * 							triggered either.
+		 */
+		void deleteSelectedText(bool internal = false);
+
+		/**	Returns currently selected text. */
+		WString getSelectedText();
+
+		/**	Shows the input caret. You must position the caret manually after showing it. */
+		void showCaret();
+
+		/**	Hides the input caret. */
+		void hideCaret();
+
+		/**
+		 * Shows selection with the specified anchor position. You must position selection start and end before selection
+		 * will actually render. Anchor position determines selection behavior as the user moves the selection with the 
+		 * keyboard.
+		 */
+		void showSelection(UINT32 anchorCaretPos);
+
+		/**	Removes any active selection. */
+		void clearSelection();
+
+		/**	Adjusts the text offset (scroll) so that the caret is visible. */
+		void scrollTextToCaret();
+
+		/** Clamps the text offset (scroll)	so that the text fits in the provided bounds nicely with minimal white space. */
+		void clampScrollToBounds(Rect2I unclippedTextBounds);
+
+		/**	Returns offset at which to render the text. Relative to parent widget. */
+		Vector2I getTextOffset() const;
+
+		/**	Returns rectangle used for clipping the text. Relative to element. */
+		Rect2I getTextClipRect() const;
+
+		/**	Returns text sprite descriptor determining how is text sprite created. */
+		TEXT_SPRITE_DESC getTextDesc() const;
+
+		/**	Returns currently active input box texture, depending on active state. */
+		const HSpriteTexture& getActiveTexture() const;
+		
+		/**	Returns currently active input box text color, depending on active state. */
+		Color getActiveTextColor() const;
+
+		/**	Cuts currently selected text to clipboard. */
+		void cutText();
+
+		/**	Copies currently selected text to clipboard. */
+		void copyText();
+
+		/**	Inserts text from clipboard to current caret location. */
+		void pasteText();
+
+	private:
+		static VirtualButton mCopyVB;
+		static VirtualButton mPasteVB;
+		static VirtualButton mCutVB;
+		static VirtualButton mSelectAllVB;
+
+		// Sprites
+		ImageSprite* mImageSprite;
+		TextSprite* mTextSprite;
+		bool mIsMultiline;
+		Vector2I mTextOffset;
+		bool mHasFocus;
+		bool mIsMouseOver;
+		State mState;
+
+		IMAGE_SPRITE_DESC mImageDesc;
+		WString mText;
+		std::function<bool(const WString&)> mFilter;
+
+		bool mCaretShown;
+		bool mSelectionShown;
+		bool mDragInProgress;
+	};
+
+	/** @} */
 }

+ 106 - 104
Source/BansheeEngine/Include/BsGUILabel.h

@@ -1,105 +1,107 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsGUIElement.h"
-#include "BsTextSprite.h"
-#include "BsGUIContent.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup GUI
-	 *  @{
-	 */
-
-	/**	GUI element that displays text and optionally a content image. */
-	class BS_EXPORT GUILabel : public GUIElement
-	{
-	public:
-		/** Returns type name of the GUI element used for finding GUI element styles.  */
-		static const String& getGUITypeName();
-
-		/**
-		 * Creates a new label with the specified text.
-		 *
-		 * @param[in]	text		Text to display.
-		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the 
-		 *							GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUILabel* create(const HString& text, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new label with the specified text.
-		 *
-		 * @param[in]	text			Text to display.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
-		 *								This will override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUILabel* create(const HString& text, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new label with the specified content (text + optional image).
-		 *
-		 * @param[in]	text			Content to display.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUILabel* create(const GUIContent& content, const String& styleName = StringUtil::BLANK);
-
-		/**
-		 * Creates a new label with the specified content (text + optional image).
-		 *
-		 * @param[in]	text			Content to display.
-		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
-		 *								override any similar options set by style.
-		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
-		 *								GUIWidget the element is used on. If not specified default button style is used.
-		 */
-		static GUILabel* create(const GUIContent& content, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
-
-		/** Changes the active content of the label. */
-		void setContent(const GUIContent& content);
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** @copydoc GUIElement::_getOptimalSize */
-		virtual Vector2I _getOptimalSize() const override;
-
-		/** @copydoc GUIElement::getElementType */
-		virtual ElementType _getElementType() const override { return ElementType::Label; }
-
-		/** @endcond */
-	protected:
-		~GUILabel();
-
-		/** @copydoc GUIElement::_getNumRenderElements */
-		virtual UINT32 _getNumRenderElements() const override;
-
-		/** @copydoc GUIElement::_getMaterial */
-		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_getNumQuads */
-		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::_fillBuffer */
-		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
-			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
-
-		/** @copydoc GUIElement::updateRenderElementsInternal */
-		virtual void updateRenderElementsInternal() override;
-
-	private:
-		GUILabel(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
-
-		TextSprite* mTextSprite;
-		GUIContent mContent;
-
-		TEXT_SPRITE_DESC mDesc;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsGUIElement.h"
+#include "BsTextSprite.h"
+#include "BsGUIContent.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup GUI
+	 *  @{
+	 */
+
+	/**	GUI element that displays text and optionally a content image. */
+	class BS_EXPORT GUILabel : public GUIElement
+	{
+	public:
+		/** Returns type name of the GUI element used for finding GUI element styles.  */
+		static const String& getGUITypeName();
+
+		/**
+		 * Creates a new label with the specified text.
+		 *
+		 * @param[in]	text		Text to display.
+		 * @param[in]	styleName	Optional style to use for the element. Style will be retrieved from GUISkin of the 
+		 *							GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUILabel* create(const HString& text, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new label with the specified text.
+		 *
+		 * @param[in]	text			Text to display.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized.
+		 *								This will override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUILabel* create(const HString& text, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new label with the specified content (text + optional image).
+		 *
+		 * @param[in]	text			Content to display.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUILabel* create(const GUIContent& content, const String& styleName = StringUtil::BLANK);
+
+		/**
+		 * Creates a new label with the specified content (text + optional image).
+		 *
+		 * @param[in]	text			Content to display.
+		 * @param[in]	options			Options that allow you to control how is the element positioned and sized. This will
+		 *								override any similar options set by style.
+		 * @param[in]	styleName		Optional style to use for the element. Style will be retrieved from GUISkin of the
+		 *								GUIWidget the element is used on. If not specified default button style is used.
+		 */
+		static GUILabel* create(const GUIContent& content, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
+
+		/** Changes the active content of the label. */
+		void setContent(const GUIContent& content);
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** @copydoc GUIElement::_getOptimalSize */
+		virtual Vector2I _getOptimalSize() const override;
+
+		/** @copydoc GUIElement::getElementType */
+		virtual ElementType _getElementType() const override { return ElementType::Label; }
+
+		/** @} */
+	protected:
+		~GUILabel();
+
+		/** @copydoc GUIElement::_getNumRenderElements */
+		virtual UINT32 _getNumRenderElements() const override;
+
+		/** @copydoc GUIElement::_getMaterial */
+		virtual const SpriteMaterialInfo& _getMaterial(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_getNumQuads */
+		virtual UINT32 _getNumQuads(UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::_fillBuffer */
+		virtual void _fillBuffer(UINT8* vertices, UINT8* uv, UINT32* indices, UINT32 startingQuad, 
+			UINT32 maxNumQuads, UINT32 vertexStride, UINT32 indexStride, UINT32 renderElementIdx) const override;
+
+		/** @copydoc GUIElement::updateRenderElementsInternal */
+		virtual void updateRenderElementsInternal() override;
+
+	private:
+		GUILabel(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
+
+		TextSprite* mTextSprite;
+		GUIContent mContent;
+
+		TEXT_SPRITE_DESC mDesc;
+	};
+
+	/** @} */
 }

+ 95 - 93
Source/BansheeEngine/Include/BsGUILayout.h

@@ -1,94 +1,96 @@
-//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
-//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
-#pragma once
-
-#include "BsPrerequisites.h"
-#include "BsGUIElementBase.h"
-#include "BsVector2I.h"
-
-namespace BansheeEngine
-{
-	/** @addtogroup Implementation
-	 *  @{
-	 */
-
-	/**
-	 * Base class for layout GUI element. Layout element positions and sizes any child elements according to element styles
-	 * and layout options.
-	 */
-	class BS_EXPORT GUILayout : public GUIElementBase
-	{
-	public:
-		GUILayout(const GUIDimensions& dimensions);
-		GUILayout();
-		virtual ~GUILayout();
-
-		/**	Creates a new element and adds it to the layout after all existing elements. */
-		template<class Type, class... Args>
-		Type* addNewElement(Args &&...args)
-		{
-			Type* elem = Type::create(std::forward<Args>(args)...);
-			addElement(elem);
-			return elem;
-		}
-
-		/**	Creates a new element and inserts it before the element at the specified index. */
-		template<class Type, class... Args>
-		Type* insertNewElement(UINT32 idx, Args &&...args)
-		{
-			Type* elem = Type::create(std::forward<Args>(args)...);
-			insertElement(idx, elem);
-			return elem;
-		}
-
-		/**	Adds a new element to the layout after all existing elements. */
-		void addElement(GUIElementBase* element);
-
-		/**	Removes the specified element from the layout. */
-		void removeElement(GUIElementBase* element);
-
-		/**	Removes a child element at the specified index. */
-		void removeElementAt(UINT32 idx);
-
-		/**	Inserts a GUI element before the element at the specified index. */
-		void insertElement(UINT32 idx, GUIElementBase* element);
-
-		/**	Returns number of child elements in the layout. */
-		UINT32 getNumChildren() const { return (UINT32)mChildren.size(); }
-
-		/**	Destroy the layout. Removes it from parent and widget, and deletes it. */
-		static void destroy(GUILayout* layout);
-
-	public: // ***** INTERNAL ******
-		/** @cond INTERNAL */
-
-		/** @copydoc GUIElementBase::_getLayoutSizeRange */
-		LayoutSizeRange _getLayoutSizeRange() const override { return _getCachedSizeRange(); }
-
-		/** Returns a size range that was cached during the last GUIElementBase::_updateOptimalLayoutSizes call. */
-		LayoutSizeRange _getCachedSizeRange() const { return mSizeRange; }
-
-		/**
-		 * Returns a size ranges for all children that was cached during the last GUIElementBase::_updateOptimalLayoutSizes
-		 * call.
-		 */
-		const Vector<LayoutSizeRange>& _getCachedChildSizeRanges() const { return mChildSizeRanges; }
-
-		/** @copydoc GUIElementBase::_getOptimalSize */
-		Vector2I _getOptimalSize() const override { return mSizeRange.optimal; }
-
-		/** @copydoc GUIElementBase::_getPadding */
-		const RectOffset& _getPadding() const override;
-
-		/** @copydoc GUIElementBase::_getType */
-		virtual Type _getType() const override { return GUIElementBase::Type::Layout; }
-
-		/** @endcond */
-
-	protected:
-		Vector<LayoutSizeRange> mChildSizeRanges;
-		LayoutSizeRange mSizeRange;
-	};
-
-	/** @} */
+//********************************** Banshee Engine (www.banshee3d.com) **************************************************//
+//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
+#pragma once
+
+#include "BsPrerequisites.h"
+#include "BsGUIElementBase.h"
+#include "BsVector2I.h"
+
+namespace BansheeEngine
+{
+	/** @addtogroup Implementation
+	 *  @{
+	 */
+
+	/**
+	 * Base class for layout GUI element. Layout element positions and sizes any child elements according to element styles
+	 * and layout options.
+	 */
+	class BS_EXPORT GUILayout : public GUIElementBase
+	{
+	public:
+		GUILayout(const GUIDimensions& dimensions);
+		GUILayout();
+		virtual ~GUILayout();
+
+		/**	Creates a new element and adds it to the layout after all existing elements. */
+		template<class Type, class... Args>
+		Type* addNewElement(Args &&...args)
+		{
+			Type* elem = Type::create(std::forward<Args>(args)...);
+			addElement(elem);
+			return elem;
+		}
+
+		/**	Creates a new element and inserts it before the element at the specified index. */
+		template<class Type, class... Args>
+		Type* insertNewElement(UINT32 idx, Args &&...args)
+		{
+			Type* elem = Type::create(std::forward<Args>(args)...);
+			insertElement(idx, elem);
+			return elem;
+		}
+
+		/**	Adds a new element to the layout after all existing elements. */
+		void addElement(GUIElementBase* element);
+
+		/**	Removes the specified element from the layout. */
+		void removeElement(GUIElementBase* element);
+
+		/**	Removes a child element at the specified index. */
+		void removeElementAt(UINT32 idx);
+
+		/**	Inserts a GUI element before the element at the specified index. */
+		void insertElement(UINT32 idx, GUIElementBase* element);
+
+		/**	Returns number of child elements in the layout. */
+		UINT32 getNumChildren() const { return (UINT32)mChildren.size(); }
+
+		/**	Destroy the layout. Removes it from parent and widget, and deletes it. */
+		static void destroy(GUILayout* layout);
+
+	public: // ***** INTERNAL ******
+		/** @name Internal
+		 *  @{
+		 */
+
+		/** @copydoc GUIElementBase::_getLayoutSizeRange */
+		LayoutSizeRange _getLayoutSizeRange() const override { return _getCachedSizeRange(); }
+
+		/** Returns a size range that was cached during the last GUIElementBase::_updateOptimalLayoutSizes call. */
+		LayoutSizeRange _getCachedSizeRange() const { return mSizeRange; }
+
+		/**
+		 * Returns a size ranges for all children that was cached during the last GUIElementBase::_updateOptimalLayoutSizes
+		 * call.
+		 */
+		const Vector<LayoutSizeRange>& _getCachedChildSizeRanges() const { return mChildSizeRanges; }
+
+		/** @copydoc GUIElementBase::_getOptimalSize */
+		Vector2I _getOptimalSize() const override { return mSizeRange.optimal; }
+
+		/** @copydoc GUIElementBase::_getPadding */
+		const RectOffset& _getPadding() const override;
+
+		/** @copydoc GUIElementBase::_getType */
+		virtual Type _getType() const override { return GUIElementBase::Type::Layout; }
+
+		/** @} */
+
+	protected:
+		Vector<LayoutSizeRange> mChildSizeRanges;
+		LayoutSizeRange mSizeRange;
+	};
+
+	/** @} */
 }

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů