Sfoglia il codice sorgente

Merge pull request #9211 from sebavan/ThinSprites

Thin sprites
David Catuhe 4 anni fa
parent
commit
46c970af26

+ 4 - 4
src/Engines/thinEngine.ts

@@ -24,7 +24,7 @@ import { IPipelineContext } from './IPipelineContext';
 import { WebGLPipelineContext } from './WebGL/webGLPipelineContext';
 import { VertexBuffer } from '../Meshes/buffer';
 import { InstancingAttributeInfo } from './instancingAttributeInfo';
-import { BaseTexture } from '../Materials/Textures/baseTexture';
+import { ThinTexture } from '../Materials/Textures/thinTexture';
 import { IOfflineProvider } from '../Offline/IOfflineProvider';
 import { IEffectFallbacks } from '../Materials/iEffectFallbacks';
 import { IWebRequest } from '../Misc/interfaces/iWebRequest';
@@ -3616,7 +3616,7 @@ export class ThinEngine {
      * @param uniform The uniform to set
      * @param texture The texture to apply
      */
-    public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
+    public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<ThinTexture>): void {
         if (channel === undefined) {
             return;
         }
@@ -3649,7 +3649,7 @@ export class ThinEngine {
         return this._gl.REPEAT;
     }
 
-    protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
+    protected _setTexture(channel: number, texture: Nullable<ThinTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
         // Not ready?
         if (!texture) {
             if (this._boundTexturesCache[channel] != null) {
@@ -3749,7 +3749,7 @@ export class ThinEngine {
      * @param uniform defines the associated uniform location
      * @param textures defines the array of textures to bind
      */
-    public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
+    public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: ThinTexture[]): void {
         if (channel === undefined || !uniform) {
             return;
         }

+ 17 - 150
src/Materials/Textures/baseTexture.ts

@@ -8,10 +8,10 @@ import { InternalTexture } from "../../Materials/Textures/internalTexture";
 import { Constants } from "../../Engines/constants";
 import { IAnimatable } from '../../Animations/animatable.interface';
 import { GUID } from '../../Misc/guid';
-import { ISize, Size } from '../../Maths/math.size';
 
 import "../../Misc/fileTools";
 import { ThinEngine } from '../../Engines/thinEngine';
+import { ThinTexture } from './thinTexture';
 
 declare type Animation = import("../../Animations/animation").Animation;
 
@@ -20,7 +20,7 @@ declare type Animation = import("../../Animations/animation").Animation;
  * It groups all the common properties the materials, post process, lights... might need
  * in order to make a correct use of the texture.
  */
-export class BaseTexture implements IAnimatable {
+export class BaseTexture extends ThinTexture implements IAnimatable {
     /**
      * Default anisotropic filtering level for the application.
      * It is set to 4 as a good tradeoff between perf and quality.
@@ -121,36 +121,32 @@ export class BaseTexture implements IAnimatable {
         return this._coordinatesMode;
     }
 
-    private _wrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
     /**
-    * | Value | Type               | Description |
-    * | ----- | ------------------ | ----------- |
-    * | 0     | CLAMP_ADDRESSMODE  |             |
-    * | 1     | WRAP_ADDRESSMODE   |             |
-    * | 2     | MIRROR_ADDRESSMODE |             |
-    */
+     * | Value | Type               | Description |
+     * | ----- | ------------------ | ----------- |
+     * | 0     | CLAMP_ADDRESSMODE  |             |
+     * | 1     | WRAP_ADDRESSMODE   |             |
+     * | 2     | MIRROR_ADDRESSMODE |             |
+     */
     @serialize()
     public get wrapU() {
         return this._wrapU;
     }
-
     public set wrapU(value: number) {
         this._wrapU = value;
     }
 
-    private _wrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
     /**
-    * | Value | Type               | Description |
-    * | ----- | ------------------ | ----------- |
-    * | 0     | CLAMP_ADDRESSMODE  |             |
-    * | 1     | WRAP_ADDRESSMODE   |             |
-    * | 2     | MIRROR_ADDRESSMODE |             |
-    */
+     * | Value | Type               | Description |
+     * | ----- | ------------------ | ----------- |
+     * | 0     | CLAMP_ADDRESSMODE  |             |
+     * | 1     | WRAP_ADDRESSMODE   |             |
+     * | 2     | MIRROR_ADDRESSMODE |             |
+     */
     @serialize()
     public get wrapV() {
         return this._wrapV;
     }
-
     public set wrapV(value: number) {
         this._wrapV = value;
     }
@@ -411,13 +407,7 @@ export class BaseTexture implements IAnimatable {
         this._onDisposeObserver = this.onDisposeObservable.add(callback);
     }
 
-    /**
-     * Define the current state of the loading sequence when in delayed load mode.
-     */
-    public delayLoadState = Constants.DELAYLOADSTATE_NONE;
-
     protected _scene: Nullable<Scene> = null;
-    protected _engine: Nullable<ThinEngine> = null;
 
     /** @hidden */
     public _texture: Nullable<InternalTexture> = null;
@@ -439,6 +429,8 @@ export class BaseTexture implements IAnimatable {
      * @param sceneOrEngine Define the scene or engine the texture blongs to
      */
     constructor(sceneOrEngine: Nullable<Scene | ThinEngine>) {
+        super(null);
+
         if (sceneOrEngine) {
             if (BaseTexture._isScene(sceneOrEngine)) {
                 this._scene = sceneOrEngine;
@@ -499,14 +491,6 @@ export class BaseTexture implements IAnimatable {
     }
 
     /**
-     * Get the underlying lower level texture from Babylon.
-     * @returns the insternal texture
-     */
-    public getInternalTexture(): Nullable<InternalTexture> {
-        return this._texture;
-    }
-
-    /**
      * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
      * @returns true if ready or not blocking
      */
@@ -515,100 +499,6 @@ export class BaseTexture implements IAnimatable {
     }
 
     /**
-     * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
-     * @returns true if fully ready
-     */
-    public isReady(): boolean {
-        if (this.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) {
-            this.delayLoad();
-            return false;
-        }
-
-        if (this._texture) {
-            return this._texture.isReady;
-        }
-
-        return false;
-    }
-
-    private _cachedSize: ISize = Size.Zero();
-    /**
-     * Get the size of the texture.
-     * @returns the texture size.
-     */
-    public getSize(): ISize {
-        if (this._texture) {
-            if (this._texture.width) {
-                this._cachedSize.width = this._texture.width;
-                this._cachedSize.height = this._texture.height;
-                return this._cachedSize;
-            }
-
-            if (this._texture._size) {
-                this._cachedSize.width = this._texture._size;
-                this._cachedSize.height = this._texture._size;
-                return this._cachedSize;
-            }
-        }
-
-        return this._cachedSize;
-    }
-
-    /**
-     * Get the base size of the texture.
-     * It can be different from the size if the texture has been resized for POT for instance
-     * @returns the base size
-     */
-    public getBaseSize(): ISize {
-        if (!this.isReady() || !this._texture) {
-            return Size.Zero();
-        }
-
-        if (this._texture._size) {
-            return new Size(this._texture._size, this._texture._size);
-        }
-
-        return new Size(this._texture.baseWidth, this._texture.baseHeight);
-    }
-
-    /**
-     * Update the sampling mode of the texture.
-     * Default is Trilinear mode.
-     *
-     * | Value | Type               | Description |
-     * | ----- | ------------------ | ----------- |
-     * | 1     | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR  | Nearest is: mag = nearest, min = nearest, mip = linear |
-     * | 2     | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
-     * | 3     | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
-     * | 4     | NEAREST_NEAREST_MIPNEAREST |             |
-     * | 5    | NEAREST_LINEAR_MIPNEAREST |             |
-     * | 6    | NEAREST_LINEAR_MIPLINEAR |             |
-     * | 7    | NEAREST_LINEAR |             |
-     * | 8    | NEAREST_NEAREST |             |
-     * | 9   | LINEAR_NEAREST_MIPNEAREST |             |
-     * | 10   | LINEAR_NEAREST_MIPLINEAR |             |
-     * | 11   | LINEAR_LINEAR |             |
-     * | 12   | LINEAR_NEAREST |             |
-     *
-     *    > _mag_: magnification filter (close to the viewer)
-     *    > _min_: minification filter (far from the viewer)
-     *    > _mip_: filter used between mip map levels
-     *@param samplingMode Define the new sampling mode of the texture
-     */
-    public updateSamplingMode(samplingMode: number): void {
-        if (!this._texture) {
-            return;
-        }
-
-        const engine = this._getEngine();
-        if (!engine) {
-            return;
-        }
-
-        engine.updateTextureSamplingMode(samplingMode, this._texture);
-    }
-
-    /**
      * Scales the texture if is `canRescale()`
      * @param ratio the resize factor we want to use to rescale
      */
@@ -652,12 +542,6 @@ export class BaseTexture implements IAnimatable {
     }
 
     /**
-     * Triggers the load sequence in delayed load mode.
-     */
-    public delayLoad(): void {
-    }
-
-    /**
      * Clones the texture.
      * @returns the cloned texture
      */
@@ -742,16 +626,6 @@ export class BaseTexture implements IAnimatable {
         }
     }
 
-    /**
-     * Release and destroy the underlying lower level texture aka internalTexture.
-     */
-    public releaseInternalTexture(): void {
-        if (this._texture) {
-            this._texture.dispose();
-            this._texture = null;
-        }
-    }
-
     /** @hidden */
     public get _lodTextureHigh(): Nullable<BaseTexture> {
         if (this._texture) {
@@ -797,18 +671,11 @@ export class BaseTexture implements IAnimatable {
             this._scene = null;
         }
 
-        if (this._texture === undefined) {
-            return;
-        }
-
-        // Release
-        this.releaseInternalTexture();
-
         // Callback
         this.onDisposeObservable.notifyObservers(this);
         this.onDisposeObservable.clear();
 
-        this._engine = null;
+        super.dispose();
     }
 
     /**

+ 286 - 0
src/Materials/Textures/thinTexture.ts

@@ -0,0 +1,286 @@
+import { Nullable } from "../../types";
+import { InternalTexture } from "../../Materials/Textures/internalTexture";
+import { Constants } from "../../Engines/constants";
+
+import { ISize, Size } from '../../Maths/math.size';
+
+import { ThinEngine } from '../../Engines/thinEngine';
+
+/**
+ * Base class of all the textures in babylon.
+ * It groups all the common properties required to work with Thin Engine.
+ */
+export class ThinTexture {
+    protected _wrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
+    /**
+    * | Value | Type               | Description |
+    * | ----- | ------------------ | ----------- |
+    * | 0     | CLAMP_ADDRESSMODE  |             |
+    * | 1     | WRAP_ADDRESSMODE   |             |
+    * | 2     | MIRROR_ADDRESSMODE |             |
+    */
+    public get wrapU() {
+        return this._wrapU;
+    }
+
+    public set wrapU(value: number) {
+        this._wrapU = value;
+    }
+
+    protected _wrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
+    /**
+    * | Value | Type               | Description |
+    * | ----- | ------------------ | ----------- |
+    * | 0     | CLAMP_ADDRESSMODE  |             |
+    * | 1     | WRAP_ADDRESSMODE   |             |
+    * | 2     | MIRROR_ADDRESSMODE |             |
+    */
+    public get wrapV() {
+        return this._wrapV;
+    }
+
+    public set wrapV(value: number) {
+        this._wrapV = value;
+    }
+
+    /**
+     * | Value | Type               | Description |
+     * | ----- | ------------------ | ----------- |
+     * | 0     | CLAMP_ADDRESSMODE  |             |
+     * | 1     | WRAP_ADDRESSMODE   |             |
+     * | 2     | MIRROR_ADDRESSMODE |             |
+     */
+    public wrapR = Constants.TEXTURE_WRAP_ADDRESSMODE;
+
+    /**
+     * With compliant hardware and browser (supporting anisotropic filtering)
+     * this defines the level of anisotropic filtering in the texture.
+     * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
+     */
+    public anisotropicFilteringLevel = 4;
+
+    /**
+     * Define the current state of the loading sequence when in delayed load mode.
+     */
+    public delayLoadState = Constants.DELAYLOADSTATE_NONE;
+
+    /**
+     * How a texture is mapped.
+     * Unused in thin texture mode.
+     */
+    public get coordinatesMode(): number {
+        return 0;
+    }
+
+    /**
+     * Define if the texture is a cube texture or if false a 2d texture.
+     */
+    public get isCube(): boolean {
+        if (!this._texture) {
+            return false;
+        }
+
+        return this._texture.isCube;
+    }
+
+    public set isCube(value: boolean) {
+        if (!this._texture) {
+            return;
+        }
+
+        this._texture.isCube = value;
+    }
+
+    /**
+     * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
+     */
+    public get is3D(): boolean {
+        if (!this._texture) {
+            return false;
+        }
+
+        return this._texture.is3D;
+    }
+
+    public set is3D(value: boolean) {
+        if (!this._texture) {
+            return;
+        }
+
+        this._texture.is3D = value;
+    }
+
+    /**
+     * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.
+     */
+    public get is2DArray(): boolean {
+        if (!this._texture) {
+            return false;
+        }
+
+        return this._texture.is2DArray;
+    }
+
+    public set is2DArray(value: boolean) {
+        if (!this._texture) {
+            return;
+        }
+
+        this._texture.is2DArray = value;
+    }
+
+    /**
+     * Get the class name of the texture.
+     * @returns "ThinTexture"
+     */
+    public getClassName(): string {
+        return "ThinTexture";
+    }
+
+    /** @hidden */
+    public _texture: Nullable<InternalTexture> = null;
+
+    protected _engine: Nullable<ThinEngine> = null;
+
+    private _cachedSize: ISize = Size.Zero();
+    private _cachedBaseSize: ISize = Size.Zero();
+
+    /**
+     * Instantiates a new ThinTexture.
+     * Base class of all the textures in babylon.
+     * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache
+     * @param internalTexture Define the internalTexture to wrap
+     */
+    constructor(internalTexture: Nullable<InternalTexture>) {
+        this._texture = internalTexture;
+        if (this._texture) {
+            this._engine = this._texture.getEngine();
+        }
+    }
+
+    /**
+     * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
+     * @returns true if fully ready
+     */
+    public isReady(): boolean {
+        if (this.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) {
+            this.delayLoad();
+            return false;
+        }
+
+        if (this._texture) {
+            return this._texture.isReady;
+        }
+
+        return false;
+    }
+
+    /**
+     * Triggers the load sequence in delayed load mode.
+     */
+    public delayLoad(): void {
+    }
+
+    /**
+     * Get the underlying lower level texture from Babylon.
+     * @returns the insternal texture
+     */
+    public getInternalTexture(): Nullable<InternalTexture> {
+        return this._texture;
+    }
+
+    /**
+     * Get the size of the texture.
+     * @returns the texture size.
+     */
+    public getSize(): ISize {
+        if (this._texture) {
+            if (this._texture.width) {
+                this._cachedSize.width = this._texture.width;
+                this._cachedSize.height = this._texture.height;
+                return this._cachedSize;
+            }
+
+            if (this._texture._size) {
+                this._cachedSize.width = this._texture._size;
+                this._cachedSize.height = this._texture._size;
+                return this._cachedSize;
+            }
+        }
+
+        return this._cachedSize;
+    }
+
+    /**
+     * Get the base size of the texture.
+     * It can be different from the size if the texture has been resized for POT for instance
+     * @returns the base size
+     */
+    public getBaseSize(): ISize {
+        if (!this.isReady() || !this._texture) {
+            this._cachedBaseSize.width = 0;
+            this._cachedBaseSize.height = 0;
+            return this._cachedBaseSize;
+        }
+
+        if (this._texture._size) {
+            this._cachedBaseSize.width = this._texture._size;
+            this._cachedBaseSize.height = this._texture._size;
+            return this._cachedBaseSize;
+        }
+
+        this._cachedBaseSize.width = this._texture.baseWidth;
+        this._cachedBaseSize.height = this._texture.baseHeight;
+        return this._cachedBaseSize;
+    }
+
+    /**
+     * Update the sampling mode of the texture.
+     * Default is Trilinear mode.
+     *
+     * | Value | Type               | Description |
+     * | ----- | ------------------ | ----------- |
+     * | 1     | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR  | Nearest is: mag = nearest, min = nearest, mip = linear |
+     * | 2     | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
+     * | 3     | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
+     * | 4     | NEAREST_NEAREST_MIPNEAREST |             |
+     * | 5    | NEAREST_LINEAR_MIPNEAREST |             |
+     * | 6    | NEAREST_LINEAR_MIPLINEAR |             |
+     * | 7    | NEAREST_LINEAR |             |
+     * | 8    | NEAREST_NEAREST |             |
+     * | 9   | LINEAR_NEAREST_MIPNEAREST |             |
+     * | 10   | LINEAR_NEAREST_MIPLINEAR |             |
+     * | 11   | LINEAR_LINEAR |             |
+     * | 12   | LINEAR_NEAREST |             |
+     *
+     *    > _mag_: magnification filter (close to the viewer)
+     *    > _min_: minification filter (far from the viewer)
+     *    > _mip_: filter used between mip map levels
+     *@param samplingMode Define the new sampling mode of the texture
+     */
+    public updateSamplingMode(samplingMode: number): void {
+        if (this._texture && this._engine) {
+            this._engine.updateTextureSamplingMode(samplingMode, this._texture);
+        }
+    }
+
+    /**
+     * Release and destroy the underlying lower level texture aka internalTexture.
+     */
+    public releaseInternalTexture(): void {
+        if (this._texture) {
+            this._texture.dispose();
+            this._texture = null;
+        }
+    }
+
+    /**
+     * Dispose the texture and release its associated resources.
+     */
+    public dispose(): void {
+        if (this._texture) {
+            this.releaseInternalTexture();
+            this._engine = null;
+        }
+    }
+}

+ 3 - 3
src/Materials/effect.ts

@@ -13,7 +13,7 @@ import { IEffectFallbacks } from './iEffectFallbacks';
 
 declare type Engine = import("../Engines/engine").Engine;
 declare type InternalTexture = import("../Materials/Textures/internalTexture").InternalTexture;
-declare type BaseTexture = import("../Materials/Textures/baseTexture").BaseTexture;
+declare type ThinTexture = import("../Materials/Textures/thinTexture").ThinTexture;
 declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
 declare type PostProcess = import("../PostProcesses/postProcess").PostProcess;
 
@@ -809,7 +809,7 @@ export class Effect implements IDisposable {
      * @param channel Name of the sampler variable.
      * @param texture Texture to set.
      */
-    public setTexture(channel: string, texture: Nullable<BaseTexture>): void {
+    public setTexture(channel: string, texture: Nullable<ThinTexture>): void {
         this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture);
     }
 
@@ -827,7 +827,7 @@ export class Effect implements IDisposable {
      * @param channel Name of the variable.
      * @param textures Textures to set.
      */
-    public setTextureArray(channel: string, textures: BaseTexture[]): void {
+    public setTextureArray(channel: string, textures: ThinTexture[]): void {
         let exName = channel + "Ex";
         if (this._samplerList.indexOf(exName + "0") === -1) {
             const initialPos = this._samplerList.indexOf(channel);

+ 23 - 115
src/Sprites/sprite.ts

@@ -5,31 +5,19 @@ import { ISpriteManager, SpriteManager } from "./spriteManager";
 import { Color4 } from '../Maths/math.color';
 import { Observable } from '../Misc/observable';
 import { IAnimatable } from '../Animations/animatable.interface';
+import { ThinSprite } from './thinSprite';
+
 declare type Animation = import("../Animations/animation").Animation;
 
 /**
  * Class used to represent a sprite
  * @see https://doc.babylonjs.com/babylon101/sprites
  */
-export class Sprite implements IAnimatable {
+export class Sprite extends ThinSprite implements IAnimatable {
     /** Gets or sets the current world position */
     public position: Vector3;
     /** Gets or sets the main color */
-    public color = new Color4(1.0, 1.0, 1.0, 1.0);
-    /** Gets or sets the width */
-    public width = 1.0;
-    /** Gets or sets the height */
-    public height = 1.0;
-    /** Gets or sets rotation angle */
-    public angle = 0;
-    /** Gets or sets the cell index in the sprite sheet */
-    public cellIndex: number;
-    /** Gets or sets the cell reference in the sprite sheet, uses sprite's filename when added to sprite sheet */
-    public cellRef: string;
-    /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
-    public invertU = false;
-    /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
-    public invertV = false;
+    public color: Color4;
     /** Gets or sets a boolean indicating that this sprite should be disposed after animation ends */
     public disposeWhenFinishedAnimating: boolean;
     /** Gets the list of attached animations */
@@ -39,38 +27,18 @@ export class Sprite implements IAnimatable {
     /** Gets or sets a boolean indicating that sprite texture alpha will be used for precise picking (false by default) */
     public useAlphaForPicking = false;
 
-    /** @hidden */
-    public _xOffset: number;
-    /** @hidden */
-    public _yOffset: number;
-    /** @hidden */
-    public _xSize: number;
-    /** @hidden */
-    public _ySize: number;
-
     /**
      * Gets or sets the associated action manager
      */
     public actionManager: Nullable<ActionManager>;
 
     /**
-    * An event triggered when the control has been disposed
-    */
-   public onDisposeObservable = new Observable<Sprite>();
+     * An event triggered when the control has been disposed
+     */
+    public onDisposeObservable = new Observable<Sprite>();
 
-    private _animationStarted = false;
-    private _loopAnimation = false;
-    private _fromIndex = 0;
-    private _toIndex = 0;
-    private _delay = 0;
-    private _direction = 1;
     private _manager: ISpriteManager;
-    private _time = 0;
     private _onAnimationEnd: Nullable<() => void> = null;
-    /**
-     * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
-     */
-    public isVisible = true;
 
     /**
      * Gets or sets the sprite size
@@ -85,13 +53,6 @@ export class Sprite implements IAnimatable {
     }
 
     /**
-     * Returns a boolean indicating if the animation is started
-     */
-    public get animationStarted() {
-        return this._animationStarted;
-    }
-
-    /**
      * Gets or sets the unique id of the sprite
      */
     public uniqueId: number;
@@ -112,12 +73,13 @@ export class Sprite implements IAnimatable {
         /** defines the name */
         public name: string,
         manager: ISpriteManager) {
-        this._manager = manager;
-
-        this._manager.sprites.push(this);
+        super();
         this.uniqueId = this._manager.scene.getUniqueId();
-
+        this.color = new Color4(1.0, 1.0, 1.0, 1.0);
         this.position = Vector3.Zero();
+
+        this._manager = manager;
+        this._manager.sprites.push(this);
     }
 
     /**
@@ -129,39 +91,23 @@ export class Sprite implements IAnimatable {
     }
 
     /** Gets or sets the initial key for the animation (setting it will restart the animation)  */
-    public get fromIndex() {
-        return this._fromIndex;
-    }
-
     public set fromIndex(value: number) {
-        this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd);
+        this.playAnimation(value, this.toIndex, this.loopAnimation, this.delay, this._onAnimationEnd);
     }
 
     /** Gets or sets the end key for the animation (setting it will restart the animation)  */
-    public get toIndex() {
-        return this._toIndex;
-    }
-
     public set toIndex(value: number) {
-        this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd);
+        this.playAnimation(this.fromIndex, value, this.loopAnimation, this.delay, this._onAnimationEnd);
     }
 
     /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation)  */
-    public get loopAnimation() {
-        return this._loopAnimation;
-    }
-
     public set loopAnimation(value: boolean) {
-        this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd);
+        this.playAnimation(this.fromIndex, this.toIndex, value, this.delay, this._onAnimationEnd);
     }
 
     /** Gets or sets the delay between cell changes (setting it will restart the animation)  */
-    public get delay() {
-        return Math.max(this._delay, 1);
-    }
-
     public set delay(value: number) {
-        this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd);
+        this.playAnimation(this.fromIndex, this.toIndex, this.loopAnimation, value, this._onAnimationEnd);
     }
 
     /**
@@ -173,57 +119,19 @@ export class Sprite implements IAnimatable {
      * @param onAnimationEnd defines a callback to call when animation ends
      */
     public playAnimation(from: number, to: number, loop: boolean, delay: number, onAnimationEnd: Nullable<() => void> = null): void {
-        this._fromIndex = from;
-        this._toIndex = to;
-        this._loopAnimation = loop;
-        this._delay = delay || 1;
-        this._animationStarted = true;
-
-        if (from < to) {
-            this._direction = 1;
-        } else {
-            this._direction = -1;
-            this._toIndex = from;
-            this._fromIndex = to;
-        }
-
-        this.cellIndex = from;
-        this._time = 0;
-
         this._onAnimationEnd = onAnimationEnd;
-    }
 
-    /** Stops current animation (if any) */
-    public stopAnimation(): void {
-        this._animationStarted = false;
+        super.playAnimation(from, to, loop, delay, this._endAnimation);
     }
 
-    /** @hidden */
-    public _animate(deltaTime: number): void {
-        if (!this._animationStarted) {
-            return;
+    private _endAnimation = () => {
+        if (this._onAnimationEnd) {
+            this._onAnimationEnd();
         }
-
-        this._time += deltaTime;
-        if (this._time > this._delay) {
-            this._time = this._time % this._delay;
-            this.cellIndex += this._direction;
-            if (this._direction > 0 && this.cellIndex > this._toIndex || this._direction < 0 && this.cellIndex < this._fromIndex) {
-                if (this._loopAnimation) {
-                    this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex;
-                } else {
-                    this.cellIndex = this._toIndex;
-                    this._animationStarted = false;
-                    if (this._onAnimationEnd) {
-                        this._onAnimationEnd();
-                    }
-                    if (this.disposeWhenFinishedAnimating) {
-                        this.dispose();
-                    }
-                }
-            }
+        if (this.disposeWhenFinishedAnimating) {
+            this.dispose();
         }
-    }
+    };
 
     /** Release associated resources */
     public dispose(): void {

+ 78 - 314
src/Sprites/spriteManager.ts

@@ -1,25 +1,22 @@
 import { IDisposable, Scene } from "../scene";
 import { Nullable } from "../types";
 import { Observable, Observer } from "../Misc/observable";
-import { Buffer } from "../Meshes/buffer";
-import { VertexBuffer } from "../Meshes/buffer";
 import { Vector3, TmpVectors } from "../Maths/math.vector";
 import { Sprite } from "./sprite";
 import { SpriteSceneComponent } from "./spriteSceneComponent";
 import { PickingInfo } from "../Collisions/pickingInfo";
 import { Camera } from "../Cameras/camera";
 import { Texture } from "../Materials/Textures/texture";
-import { Effect } from "../Materials/effect";
-import { Material } from "../Materials/material";
 import { SceneComponentConstants } from "../sceneComponent";
-import { Constants } from "../Engines/constants";
 import { Logger } from "../Misc/logger";
 
 import "../Shaders/sprites.fragment";
 import "../Shaders/sprites.vertex";
-import { DataBuffer } from '../Meshes/dataBuffer';
 import { Engine } from '../Engines/engine';
 import { WebRequest } from '../Misc/webRequest';
+import { SpriteRenderer } from './spriteRenderer';
+import { ThinSprite } from './thinSprite';
+import { ISize } from '../Maths/math.size';
 declare type Ray = import("../Culling/ray").Ray;
 
 /**
@@ -111,33 +108,14 @@ export class SpriteManager implements ISpriteManager {
     public renderingGroupId = 0;
     /** Gets or sets camera layer mask */
     public layerMask: number = 0x0FFFFFFF;
-    /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
-    public fogEnabled = true;
     /** Gets or sets a boolean indicating if the sprites are pickable */
     public isPickable = false;
-    /** Defines the default width of a cell in the spritesheet */
-    public cellWidth: number;
-    /** Defines the default height of a cell in the spritesheet */
-    public cellHeight: number;
-
-    /** Associative array from JSON sprite data file */
-    private _cellData: any;
-    /** Array of sprite names from JSON sprite data file */
-    private _spriteMap: Array<string>;
-    /** True when packed cell data from JSON file is ready*/
-    private _packedAndReady: boolean = false;
-
-    private _textureContent: Nullable<Uint8Array>;
-
-    private _useInstancing = false;
 
     /**
     * An event triggered when the manager is disposed.
     */
     public onDisposeObservable = new Observable<SpriteManager>();
 
-    private _onDisposeObserver: Nullable<Observer<SpriteManager>>;
-
     /**
      * Callback called when the manager is disposed
      */
@@ -148,23 +126,6 @@ export class SpriteManager implements ISpriteManager {
         this._onDisposeObserver = this.onDisposeObservable.add(callback);
     }
 
-    private _capacity: number;
-    private _fromPacked: boolean;
-    private _spriteTexture: Texture;
-    private _epsilon: number;
-
-    private _scene: Scene;
-
-    private _vertexData: Float32Array;
-    private _buffer: Buffer;
-    private _vertexBuffers: { [key: string]: VertexBuffer } = {};
-    private _spriteBuffer: Nullable<Buffer>;
-    private _indexBuffer: DataBuffer;
-    private _effectBase: Effect;
-    private _effectFog: Effect;
-
-    private _vertexBufferSize: number;
-
     /**
      * Gets or sets the unique id of the sprite
      */
@@ -188,32 +149,56 @@ export class SpriteManager implements ISpriteManager {
      * Gets the capacity of the manager
      */
     public get capacity() {
-        return this._capacity;
+        return this._spriteRenderer.capacity;
     }
 
     /**
      * Gets or sets the spritesheet texture
      */
     public get texture(): Texture {
-        return this._spriteTexture;
+        return this._spriteRenderer.texture as Texture;
     }
-
     public set texture(value: Texture) {
-        this._spriteTexture = value;
-        this._spriteTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
-        this._spriteTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
+        value.wrapU = Texture.CLAMP_ADDRESSMODE;
+        value.wrapV = Texture.CLAMP_ADDRESSMODE;
+        this._spriteRenderer.texture = value;
         this._textureContent = null;
     }
 
-    private _blendMode = Constants.ALPHA_COMBINE;
+    /** Defines the default width of a cell in the spritesheet */
+    public get cellWidth(): number {
+        return this._spriteRenderer.cellWidth;
+    }
+    public set cellWidth(value: number) {
+        this._spriteRenderer.cellWidth = value;
+    }
+
+    /** Defines the default height of a cell in the spritesheet */
+    public get cellHeight(): number {
+        return this._spriteRenderer.cellHeight;
+    }
+    public set cellHeight(value: number) {
+        this._spriteRenderer.cellHeight = value;
+    }
+
+    /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
+    public get fogEnabled(): boolean {
+        return this._spriteRenderer.fogEnabled;
+    }
+    public set fogEnabled(value: boolean) {
+        this._spriteRenderer.fogEnabled = value;
+    }
+
     /**
      * Blend mode use to render the particle, it can be any of
      * the static Constants.ALPHA_x properties provided in this class.
      * Default value is Constants.ALPHA_COMBINE
      */
-    public get blendMode() { return this._blendMode; }
+    public get blendMode() {
+        return this._spriteRenderer.blendMode;
+    }
     public set blendMode(blendMode: number) {
-        this._blendMode = blendMode;
+        this._spriteRenderer.blendMode = blendMode;
     }
 
     /** Disables writing to the depth buffer when rendering the sprites.
@@ -222,6 +207,18 @@ export class SpriteManager implements ISpriteManager {
     */
     public disableDepthWrite: boolean = false;
 
+    private _spriteRenderer: SpriteRenderer;
+    /** Associative array from JSON sprite data file */
+    private _cellData: any;
+    /** Array of sprite names from JSON sprite data file */
+    private _spriteMap: Array<string>;
+    /** True when packed cell data from JSON file is ready*/
+    private _packedAndReady: boolean = false;
+    private _textureContent: Nullable<Uint8Array>;
+    private _onDisposeObserver: Nullable<Observer<SpriteManager>>;
+    private _fromPacked: boolean;
+    private _scene: Scene;
+
     /**
      * Creates a new sprite manager
      * @param name defines the manager's name
@@ -246,15 +243,8 @@ export class SpriteManager implements ISpriteManager {
         if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) {
             scene._addComponent(new SpriteSceneComponent(scene));
         }
-        this._capacity = capacity;
         this._fromPacked = fromPacked;
 
-        if (imgUrl) {
-            this._spriteTexture = new Texture(imgUrl, scene, true, false, samplingMode);
-            this._spriteTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
-            this._spriteTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
-        }
-
         if (cellSize.width && cellSize.height) {
             this.cellWidth = cellSize.width;
             this.cellHeight = cellSize.height;
@@ -265,74 +255,18 @@ export class SpriteManager implements ISpriteManager {
             return;
         }
 
-        this._epsilon = epsilon;
         this._scene = scene;
         this._scene.spriteManagers.push(this);
         this.uniqueId = this.scene.getUniqueId();
-        const engine = this._scene.getEngine();
-        this._useInstancing = engine.getCaps().instancedArrays;
-
-        if (!this._useInstancing) {
-            var indices = [];
-            var index = 0;
-            for (var count = 0; count < capacity; count++) {
-                indices.push(index);
-                indices.push(index + 1);
-                indices.push(index + 2);
-                indices.push(index);
-                indices.push(index + 2);
-                indices.push(index + 3);
-                index += 4;
-            }
-
-            this._indexBuffer = engine.createIndexBuffer(indices);
-        } else {
-        }
-
-        // VBO
-        // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a)
-        // 16 when using instances
-        this._vertexBufferSize = this._useInstancing ? 16 : 18;
-        this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
-        this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
-
-        var positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing);
-        var options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing);
 
-        let offset = 6;
-        var offsets: VertexBuffer;
-
-        if (this._useInstancing) {
-            var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
-            this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
-            offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2);
-        } else {
-            offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing);
-            offset += 2;
+        const engine = this._scene.getEngine();
+        this._spriteRenderer = new SpriteRenderer(engine, capacity, epsilon, scene);
+        this._spriteRenderer.cellWidth = this.cellWidth;
+        this._spriteRenderer.cellHeight = this.cellHeight;
+        if (imgUrl) {
+            this._spriteRenderer.texture = new Texture(imgUrl, scene, true, false, samplingMode);
         }
 
-        var inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing);
-        var cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing);
-        var colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing);
-
-        this._vertexBuffers[VertexBuffer.PositionKind] = positions;
-        this._vertexBuffers["options"] = options;
-        this._vertexBuffers["offsets"] = offsets;
-        this._vertexBuffers["inverts"] = inverts;
-        this._vertexBuffers["cellInfo"] = cellInfo;
-        this._vertexBuffers[VertexBuffer.ColorKind] = colors;
-
-        // Effects
-        this._effectBase = this._scene.getEngine().createEffect("sprites",
-            [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind],
-            ["view", "projection", "textureInfos", "alphaTest"],
-            ["diffuseSampler"], "");
-
-        this._effectFog = this._scene.getEngine().createEffect("sprites",
-            [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind],
-            ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"],
-            ["diffuseSampler"], "#define FOG");
-
         if (this._fromPacked) {
             this._makePacked(imgUrl, spriteJSON);
         }
@@ -416,97 +350,15 @@ export class SpriteManager implements ISpriteManager {
         }
     }
 
-    private _appendSpriteVertex(index: number, sprite: Sprite, offsetX: number, offsetY: number, baseSize: any): void {
-        var arrayOffset = index * this._vertexBufferSize;
-
-        if (offsetX === 0) {
-            offsetX = this._epsilon;
-        }
-        else if (offsetX === 1) {
-            offsetX = 1 - this._epsilon;
-        }
-
-        if (offsetY === 0) {
-            offsetY = this._epsilon;
-        }
-        else if (offsetY === 1) {
-            offsetY = 1 - this._epsilon;
-        }
-
-        // Positions
-        this._vertexData[arrayOffset] = sprite.position.x;
-        this._vertexData[arrayOffset + 1] = sprite.position.y;
-        this._vertexData[arrayOffset + 2] = sprite.position.z;
-        this._vertexData[arrayOffset + 3] = sprite.angle;
-        // Options
-        this._vertexData[arrayOffset + 4] = sprite.width;
-        this._vertexData[arrayOffset + 5] = sprite.height;
-
-        if (!this._useInstancing) {
-            this._vertexData[arrayOffset + 6] = offsetX;
-            this._vertexData[arrayOffset + 7] = offsetY;
-        } else {
-            arrayOffset -= 2;
-        }
-
-        // Inverts according to Right Handed
-        if (this._scene.useRightHandedSystem) {
-            this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;
-        }
-        else {
-            this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
-        }
-
-        this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
-        // CellIfo
-        if (this._packedAndReady) {
-            if (!sprite.cellRef) {
-                sprite.cellIndex = 0;
-            }
-            let num = sprite.cellIndex;
-            if (typeof (num) === "number" && isFinite(num) && Math.floor(num) === num) {
-                sprite.cellRef = this._spriteMap[sprite.cellIndex];
-            }
-            sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;
-            sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;
-            sprite._xSize = this._cellData[sprite.cellRef].frame.w;
-            sprite._ySize = this._cellData[sprite.cellRef].frame.h;
-            this._vertexData[arrayOffset + 10] = sprite._xOffset;
-            this._vertexData[arrayOffset + 11] = sprite._yOffset;
-            this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;
-            this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;
-        }
-        else {
-            if (!sprite.cellIndex) {
-                sprite.cellIndex = 0;
-            }
-            var rowSize = baseSize.width / this.cellWidth;
-            var offset = (sprite.cellIndex / rowSize) >> 0;
-            sprite._xOffset = (sprite.cellIndex - offset * rowSize) * this.cellWidth / baseSize.width;
-            sprite._yOffset = offset * this.cellHeight / baseSize.height;
-            sprite._xSize = this.cellWidth;
-            sprite._ySize = this.cellHeight;
-            this._vertexData[arrayOffset + 10] = sprite._xOffset;
-            this._vertexData[arrayOffset + 11] = sprite._yOffset;
-            this._vertexData[arrayOffset + 12] = this.cellWidth / baseSize.width;
-            this._vertexData[arrayOffset + 13] = this.cellHeight / baseSize.height;
-        }
-        // Color
-        this._vertexData[arrayOffset + 14] = sprite.color.r;
-        this._vertexData[arrayOffset + 15] = sprite.color.g;
-        this._vertexData[arrayOffset + 16] = sprite.color.b;
-        this._vertexData[arrayOffset + 17] = sprite.color.a;
-    }
-
     private _checkTextureAlpha(sprite: Sprite, ray: Ray, distance: number, min: Vector3, max: Vector3) {
-        if (!sprite.useAlphaForPicking || !this._spriteTexture) {
+        if (!sprite.useAlphaForPicking || !this.texture) {
             return true;
         }
 
-        let textureSize = this._spriteTexture.getSize();
+        let textureSize = this.texture.getSize();
         if (!this._textureContent) {
             this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4);
-            this._spriteTexture.readPixels(0, 0, this._textureContent);
+            this.texture.readPixels(0, 0, this._textureContent);
         }
 
         let contactPoint = TmpVectors.Vector3[0];
@@ -542,7 +394,7 @@ export class SpriteManager implements ISpriteManager {
      * @returns null if no hit or a PickingInfo
      */
     public intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
-        var count = Math.min(this._capacity, this.sprites.length);
+        var count = Math.min(this.capacity, this.sprites.length);
         var min = Vector3.Zero();
         var max = Vector3.Zero();
         var distance = Number.MAX_VALUE;
@@ -620,7 +472,7 @@ export class SpriteManager implements ISpriteManager {
      * @returns null if no hit or a PickingInfo array
      */
     public multiIntersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean): Nullable<PickingInfo[]> {
-        var count = Math.min(this._capacity, this.sprites.length);
+        var count = Math.min(this.capacity, this.sprites.length);
         var min = Vector3.Zero();
         var max = Vector3.Zero();
         var distance: number;
@@ -683,129 +535,41 @@ export class SpriteManager implements ISpriteManager {
      */
     public render(): void {
         // Check
-        if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture
-            || !this._spriteTexture.isReady() || !this.sprites.length) {
-            return;
-        }
-
         if (this._fromPacked  && (!this._packedAndReady || !this._spriteMap || !this._cellData)) {
             return;
         }
 
         var engine = this._scene.getEngine();
-        var baseSize = this._spriteTexture.getBaseSize();
-
-        // Sprites
         var deltaTime = engine.getDeltaTime();
-        var max = Math.min(this._capacity, this.sprites.length);
-
-        var offset = 0;
-        let noSprite = true;
-        for (var index = 0; index < max; index++) {
-            var sprite = this.sprites[index];
-            if (!sprite || !sprite.isVisible) {
-                continue;
-            }
-
-            noSprite = false;
-            sprite._animate(deltaTime);
-
-            this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize);
-            if (!this._useInstancing) {
-                this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize);
-                this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize);
-                this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize);
-            }
-        }
-
-        if (noSprite) {
-            return;
-        }
-
-        this._buffer.update(this._vertexData);
-
-        // Render
-        var effect = this._effectBase;
-
-        if (this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
-            effect = this._effectFog;
-        }
-
-        engine.enableEffect(effect);
-
-        var viewMatrix = this._scene.getViewMatrix();
-        effect.setTexture("diffuseSampler", this._spriteTexture);
-        effect.setMatrix("view", viewMatrix);
-        effect.setMatrix("projection", this._scene.getProjectionMatrix());
-
-        // Fog
-        if (this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
-            effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
-            effect.setColor3("vFogColor", this._scene.fogColor);
-        }
-
-        // VBOs
-        engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
-
-        // Handle Right Handed
-        const culling = engine.depthCullingState.cull || true;
-        const zOffset = engine.depthCullingState.zOffset;
-        if (this._scene.useRightHandedSystem) {
-            engine.setState(culling, zOffset, false, false);
+        if (this._packedAndReady) {
+            this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate);
         }
-
-        // Draw order
-        engine.setDepthFunctionToLessOrEqual();
-        if (!this.disableDepthWrite) {
-            effect.setBool("alphaTest", true);
-            engine.setColorWrite(false);
-            if (this._useInstancing) {
-                engine.drawArraysType(Constants.MATERIAL_TriangleFanDrawMode, 0, 4, offset);
-            } else {
-                engine.drawElementsType(Material.TriangleFillMode, 0, (offset / 4) * 6);
-            }
-            engine.setColorWrite(true);
-            effect.setBool("alphaTest", false);
+        else {
+            this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix());
         }
+    }
 
-        engine.setAlphaMode(this._blendMode);
-        if (this._useInstancing) {
-            engine.drawArraysType(Constants.MATERIAL_TriangleFanDrawMode, 0, 4, offset);
-        } else {
-            engine.drawElementsType(Material.TriangleFillMode, 0, (offset / 4) * 6);
+    private _customUpdate = (sprite: ThinSprite, baseSize: ISize): void => {
+        if (!sprite.cellRef) {
+            sprite.cellIndex = 0;
         }
-        engine.setAlphaMode(Constants.ALPHA_DISABLE);
-
-        // Restore Right Handed
-        if (this._scene.useRightHandedSystem) {
-            engine.setState(culling, zOffset, false, true);
+        let num = sprite.cellIndex;
+        if (typeof (num) === "number" && isFinite(num) && Math.floor(num) === num) {
+            sprite.cellRef = this._spriteMap[sprite.cellIndex];
         }
-
-        engine.unbindInstanceAttributes();
-    }
+        sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;
+        sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;
+        sprite._xSize = this._cellData[sprite.cellRef].frame.w;
+        sprite._ySize = this._cellData[sprite.cellRef].frame.h;
+    };
 
     /**
      * Release associated resources
      */
     public dispose(): void {
-        if (this._buffer) {
-            this._buffer.dispose();
-            (<any>this._buffer) = null;
-        }
-
-        if (this._spriteBuffer) {
-            this._spriteBuffer.dispose();
-            (<any>this._spriteBuffer) = null;
-        }
-
-        if (this._indexBuffer) {
-            this._scene.getEngine()._releaseBuffer(this._indexBuffer);
-            (<any>this._indexBuffer) = null;
-        }
-
-        if (this._spriteTexture) {
-            this._spriteTexture.dispose();
-            (<any>this._spriteTexture) = null;
+        if (this._spriteRenderer) {
+            this._spriteRenderer.dispose();
+            (<any>this._spriteRenderer) = null;
         }
 
         this._textureContent = null;

+ 396 - 0
src/Sprites/spriteRenderer.ts

@@ -0,0 +1,396 @@
+import { Nullable } from "../types";
+import { Constants } from "../Engines/constants";
+import { IMatrixLike } from '../Maths/math.like';
+import { ThinEngine } from "../Engines/thinEngine";
+import { DataBuffer } from "../Meshes/dataBuffer";
+import { Buffer, VertexBuffer } from "../Meshes/buffer";
+import { Effect } from "../Materials/effect";
+import { ThinSprite } from './thinSprite';
+import { ISize } from '../Maths/math.size';
+
+declare type ThinTexture = import("../Materials/Textures/thinTexture").ThinTexture;
+declare type Scene = import("../scene").Scene;
+
+import "../Engines/Extensions/engine.alpha";
+import "../Engines/Extensions/engine.dynamicBuffer";
+
+import "../Shaders/sprites.fragment";
+import "../Shaders/sprites.vertex";
+
+/**
+ * Class used to render sprites.
+ *
+ * It can be used either to render Sprites or ThinSriptes with ThinEngine only.
+ */
+export class SpriteRenderer {
+    /**
+     * Defines the texture of the spritesheet
+     */
+    public texture: Nullable<ThinTexture>;
+
+    /**
+     * Defines the default width of a cell in the spritesheet
+     */
+    public cellWidth: number;
+
+    /**
+     * Defines the default height of a cell in the spritesheet
+     */
+    public cellHeight: number;
+
+    /**
+     * Blend mode use to render the particle, it can be any of
+     * the static Constants.ALPHA_x properties provided in this class.
+     * Default value is Constants.ALPHA_COMBINE
+     */
+    public blendMode = Constants.ALPHA_COMBINE;
+
+    /**
+     * Gets or sets a boolean indicating if alpha mode is automatically
+     * reset.
+     */
+    public autoResetAlpha = true;
+
+    /**
+     * Disables writing to the depth buffer when rendering the sprites.
+     * It can be handy to disable depth writing when using textures without alpha channel
+     * and setting some specific blend modes.
+     */
+    public disableDepthWrite: boolean = false;
+
+    /**
+     * Gets or sets a boolean indicating if the manager must consider scene fog when rendering
+     */
+    public fogEnabled = true;
+
+    /**
+     * Gets the capacity of the manager
+     */
+    public get capacity() {
+        return this._capacity;
+    }
+
+    private readonly _engine: ThinEngine;
+    private readonly _useVAO: boolean = false;
+    private readonly _useInstancing: boolean = false;
+    private readonly _scene: Nullable<Scene>;
+
+    private readonly _capacity: number;
+    private readonly _epsilon: number;
+
+    private _vertexBufferSize: number;
+    private _vertexData: Float32Array;
+    private _buffer: Buffer;
+    private _vertexBuffers: { [key: string]: VertexBuffer } = {};
+    private _spriteBuffer: Nullable<Buffer>;
+    private _indexBuffer: DataBuffer;
+    private _effectBase: Effect;
+    private _effectFog: Effect;
+    private _vertexArrayObject: WebGLVertexArrayObject;
+
+    /**
+     * Creates a new sprite Renderer
+     * @param engine defines the engine the renderer works with
+     * @param capacity defines the maximum allowed number of sprites
+     * @param epsilon defines the epsilon value to align texture (0.01 by default)
+     * @param scene defines the hosting scene
+     */
+    constructor(
+        engine: ThinEngine,
+        capacity: number,
+        epsilon: number = 0.01,
+        scene: Nullable<Scene> = null) {
+
+        this._capacity = capacity;
+        this._epsilon = epsilon;
+
+        this._engine = engine;
+        this._useInstancing = engine.getCaps().instancedArrays;
+        this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects;
+        this._scene = scene;
+
+        if (!this._useInstancing) {
+            const indices = [];
+            let index = 0;
+            for (let count = 0; count < capacity; count++) {
+                indices.push(index);
+                indices.push(index + 1);
+                indices.push(index + 2);
+                indices.push(index);
+                indices.push(index + 2);
+                indices.push(index + 3);
+                index += 4;
+            }
+
+            this._indexBuffer = engine.createIndexBuffer(indices);
+        }
+
+        // VBO
+        // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a)
+        // 16 when using instances
+        this._vertexBufferSize = this._useInstancing ? 16 : 18;
+        this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
+        this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
+
+        const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing);
+        const options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing);
+
+        let offset = 6;
+        let offsets: VertexBuffer;
+
+        if (this._useInstancing) {
+            var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
+            this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
+            offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2);
+        } else {
+            offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing);
+            offset += 2;
+        }
+
+        const inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing);
+        const cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing);
+        const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing);
+
+        this._vertexBuffers[VertexBuffer.PositionKind] = positions;
+        this._vertexBuffers["options"] = options;
+        this._vertexBuffers["offsets"] = offsets;
+        this._vertexBuffers["inverts"] = inverts;
+        this._vertexBuffers["cellInfo"] = cellInfo;
+        this._vertexBuffers[VertexBuffer.ColorKind] = colors;
+
+        // Effects
+        this._effectBase = this._engine.createEffect("sprites",
+            [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind],
+            ["view", "projection", "textureInfos", "alphaTest"],
+            ["diffuseSampler"], "");
+
+        if (this._scene) {
+            this._effectFog = this._scene.getEngine().createEffect("sprites",
+                [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind],
+                ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"],
+                ["diffuseSampler"], "#define FOG");
+        }
+    }
+
+    /**
+     * Render all child sprites
+     * @param sprites defines the list of sprites to render
+     * @param deltaTime defines the time since last frame
+     * @param viewMatrix defines the viewMatrix to use to render the sprites
+     * @param projectionMatrix defines the projectionMatrix to use to render the sprites
+     * @param customSpriteUpdate defines a custom function to update the sprites data before they render
+     */
+    public render(sprites: ThinSprite[], deltaTime: number, viewMatrix: IMatrixLike, projectionMatrix: IMatrixLike, customSpriteUpdate: Nullable<(sprite: ThinSprite, baseSize: ISize) => void> = null): void {
+        if (!this.texture || !this.texture.isReady() || !sprites.length) {
+            return;
+        }
+
+        let effect = this._effectBase;
+        let shouldRenderFog = false;
+        if (this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0) {
+            effect = this._effectFog;
+            shouldRenderFog = true;
+        }
+
+        // Check
+        if (!effect.isReady()) {
+            return;
+        }
+
+        const engine = this._engine;
+        const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem);
+        const baseSize = this.texture.getBaseSize();
+
+        // Sprites
+        const max = Math.min(this._capacity, sprites.length);
+
+        let offset = 0;
+        let noSprite = true;
+        for (var index = 0; index < max; index++) {
+            const sprite = sprites[index];
+            if (!sprite || !sprite.isVisible) {
+                continue;
+            }
+
+            noSprite = false;
+            sprite._animate(deltaTime);
+
+            this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate);
+            if (!this._useInstancing) {
+                this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate);
+                this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate);
+                this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate);
+            }
+        }
+
+        if (noSprite) {
+            return;
+        }
+
+        this._buffer.update(this._vertexData);
+
+        const culling = engine.depthCullingState.cull || true;
+        const zOffset = engine.depthCullingState.zOffset;
+
+        // Handle Right Handed
+        if (useRightHandedSystem) {
+            this._scene!.getEngine().setState(culling, zOffset, false, false);
+        }
+
+        // Render
+        engine.enableEffect(effect);
+
+        effect.setTexture("diffuseSampler", this.texture);
+        effect.setMatrix("view", viewMatrix);
+        effect.setMatrix("projection", projectionMatrix);
+
+        // Scene Info
+        if (shouldRenderFog) {
+            const scene = this._scene!;
+
+            // Fog
+            effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
+            effect.setColor3("vFogColor", scene.fogColor);
+        }
+
+        if (this._useVAO) {
+            if (!this._vertexArrayObject) {
+                this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);
+            }
+            engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);
+        }
+        else {
+            // VBOs
+            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
+        }
+
+        // Draw order
+        engine.depthCullingState.depthFunc = Constants.LEQUAL;
+        if (!this.disableDepthWrite) {
+            effect.setBool("alphaTest", true);
+            engine.setColorWrite(false);
+            if (this._useInstancing) {
+                engine.drawArraysType(Constants.MATERIAL_TriangleFanDrawMode, 0, 4, offset);
+            } else {
+                engine.drawElementsType(Constants.MATERIAL_TriangleFillMode, 0, (offset / 4) * 6);
+            }
+            engine.setColorWrite(true);
+            effect.setBool("alphaTest", false);
+        }
+
+        engine.setAlphaMode(this.blendMode);
+        if (this._useInstancing) {
+            engine.drawArraysType(Constants.MATERIAL_TriangleFanDrawMode, 0, 4, offset);
+        } else {
+            engine.drawElementsType(Constants.MATERIAL_TriangleFillMode, 0, (offset / 4) * 6);
+        }
+
+        if (this.autoResetAlpha) {
+            engine.setAlphaMode(Constants.ALPHA_DISABLE);
+        }
+
+        // Restore Right Handed
+        if (useRightHandedSystem) {
+            this._scene!.getEngine().setState(culling, zOffset, false, true);
+        }
+
+        engine.unbindInstanceAttributes();
+    }
+
+    private _appendSpriteVertex(index: number, sprite: ThinSprite, offsetX: number, offsetY: number, baseSize: ISize, useRightHandedSystem: boolean, customSpriteUpdate: Nullable<(sprite: ThinSprite, baseSize: ISize) => void>): void {
+        var arrayOffset = index * this._vertexBufferSize;
+
+        if (offsetX === 0) {
+            offsetX = this._epsilon;
+        }
+        else if (offsetX === 1) {
+            offsetX = 1 - this._epsilon;
+        }
+
+        if (offsetY === 0) {
+            offsetY = this._epsilon;
+        }
+        else if (offsetY === 1) {
+            offsetY = 1 - this._epsilon;
+        }
+
+        if (customSpriteUpdate) {
+            customSpriteUpdate(sprite, baseSize);
+        }
+        else {
+            const rowSize = baseSize.width / this.cellWidth;
+            const offset = (sprite.cellIndex / rowSize) >> 0;
+            sprite._xOffset = (sprite.cellIndex - offset * rowSize) * this.cellWidth / baseSize.width;
+            sprite._yOffset = offset * this.cellHeight / baseSize.height;
+            sprite._xSize = this.cellWidth;
+            sprite._ySize = this.cellHeight;
+        }
+
+        // Positions
+        this._vertexData[arrayOffset] = sprite.position.x;
+        this._vertexData[arrayOffset + 1] = sprite.position.y;
+        this._vertexData[arrayOffset + 2] = sprite.position.z;
+        this._vertexData[arrayOffset + 3] = sprite.angle;
+        // Options
+        this._vertexData[arrayOffset + 4] = sprite.width;
+        this._vertexData[arrayOffset + 5] = sprite.height;
+
+        if (!this._useInstancing) {
+            this._vertexData[arrayOffset + 6] = offsetX;
+            this._vertexData[arrayOffset + 7] = offsetY;
+        } else {
+            arrayOffset -= 2;
+        }
+
+        // Inverts according to Right Handed
+        if (useRightHandedSystem) {
+            this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;
+        }
+        else {
+            this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
+        }
+
+        this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
+
+        this._vertexData[arrayOffset + 10] = sprite._xOffset;
+        this._vertexData[arrayOffset + 11] = sprite._yOffset;
+        this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;
+        this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;
+
+        // Color
+        this._vertexData[arrayOffset + 14] = sprite.color.r;
+        this._vertexData[arrayOffset + 15] = sprite.color.g;
+        this._vertexData[arrayOffset + 16] = sprite.color.b;
+        this._vertexData[arrayOffset + 17] = sprite.color.a;
+    }
+
+    /**
+     * Release associated resources
+     */
+    public dispose(): void {
+        if (this._buffer) {
+            this._buffer.dispose();
+            (<any>this._buffer) = null;
+        }
+
+        if (this._spriteBuffer) {
+            this._spriteBuffer.dispose();
+            (<any>this._spriteBuffer) = null;
+        }
+
+        if (this._indexBuffer) {
+            this._engine._releaseBuffer(this._indexBuffer);
+            (<any>this._indexBuffer) = null;
+        }
+
+        if (this._vertexArrayObject) {
+            this._engine.releaseVertexArrayObject(this._vertexArrayObject);
+            (<any>this._vertexArrayObject) = null;
+        }
+
+        if (this.texture) {
+            this.texture.dispose();
+            (<any>this.texture) = null;
+        }
+    }
+}

+ 140 - 0
src/Sprites/thinSprite.ts

@@ -0,0 +1,140 @@
+import { IVector3Like, IColor4Like } from "../Maths/math.like";
+import { Nullable } from "../types";
+
+/**
+ * ThinSprite Class used to represent a thin sprite
+ * This is the base class for sprites but can also directly be used with ThinEngine
+ * @see https://doc.babylonjs.com/babylon101/sprites
+ */
+export class ThinSprite {
+    /** Gets or sets the cell index in the sprite sheet */
+    public cellIndex: number = 0;
+    /** Gets or sets the cell reference in the sprite sheet, uses sprite's filename when added to sprite sheet */
+    public cellRef: string;
+    /** Gets or sets the current world position */
+    public position: IVector3Like;
+    /** Gets or sets the main color */
+    public color: IColor4Like;
+    /** Gets or sets the width */
+    public width = 1.0;
+    /** Gets or sets the height */
+    public height = 1.0;
+    /** Gets or sets rotation angle */
+    public angle = 0;
+    /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
+    public invertU = false;
+    /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
+    public invertV = false;
+    /** Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true */
+    public isVisible = true;
+
+    /**
+     * Returns a boolean indicating if the animation is started
+     */
+    public get animationStarted() {
+        return this._animationStarted;
+    }
+
+    /** Gets the initial key for the animation (setting it will restart the animation)  */
+    public get fromIndex() {
+        return this._fromIndex;
+    }
+
+    /** Gets or sets the end key for the animation (setting it will restart the animation)  */
+    public get toIndex() {
+        return this._toIndex;
+    }
+
+    /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation)  */
+    public get loopAnimation() {
+        return this._loopAnimation;
+    }
+
+    /** Gets or sets the delay between cell changes (setting it will restart the animation)  */
+    public get delay() {
+        return Math.max(this._delay, 1);
+    }
+
+    /** @hidden */
+    public _xOffset: number;
+    /** @hidden */
+    public _yOffset: number;
+    /** @hidden */
+    public _xSize: number;
+    /** @hidden */
+    public _ySize: number;
+
+    private _animationStarted = false;
+    private _loopAnimation = false;
+    private _fromIndex = 0;
+    private _toIndex = 0;
+    private _delay = 0;
+    private _direction = 1;
+    private _time = 0;
+    private _onBaseAnimationEnd: Nullable<() => void> = null;
+
+    /**
+     * Creates a new Thin Sprite
+     */
+    constructor() {
+        this.position = { x: 1.0, y: 1.0, z: 1.0 };
+        this.color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
+    }
+
+    /**
+     * Starts an animation
+     * @param from defines the initial key
+     * @param to defines the end key
+     * @param loop defines if the animation must loop
+     * @param delay defines the start delay (in ms)
+     * @param onAnimationEnd defines a callback for when the animation ends
+     */
+    public playAnimation(from: number, to: number, loop: boolean, delay: number, onAnimationEnd: Nullable<() => void>): void {
+        this._fromIndex = from;
+        this._toIndex = to;
+        this._loopAnimation = loop;
+        this._delay = delay || 1;
+        this._animationStarted = true;
+        this._onBaseAnimationEnd = onAnimationEnd;
+
+        if (from < to) {
+            this._direction = 1;
+        } else {
+            this._direction = -1;
+            this._toIndex = from;
+            this._fromIndex = to;
+        }
+
+        this.cellIndex = from;
+        this._time = 0;
+    }
+
+    /** Stops current animation (if any) */
+    public stopAnimation(): void {
+        this._animationStarted = false;
+    }
+
+    /** @hidden */
+    public _animate(deltaTime: number): void {
+        if (!this._animationStarted) {
+            return;
+        }
+
+        this._time += deltaTime;
+        if (this._time > this._delay) {
+            this._time = this._time % this._delay;
+            this.cellIndex += this._direction;
+            if (this._direction > 0 && this.cellIndex > this._toIndex || this._direction < 0 && this.cellIndex < this._fromIndex) {
+                if (this._loopAnimation) {
+                    this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex;
+                } else {
+                    this.cellIndex = this._toIndex;
+                    this._animationStarted = false;
+                    if (this._onBaseAnimationEnd) {
+                        this._onBaseAnimationEnd();
+                    }
+                }
+            }
+        }
+    }
+}