babylon.layer.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var BABYLON = BABYLON || {};
  2. (function () {
  3. BABYLON.Layer = function (name, imgUrl, scene, isBackground, color) {
  4. this.name = name;
  5. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  6. this.isBackground = isBackground === undefined ? true : isBackground;
  7. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  8. this._scene = scene;
  9. this._scene.layers.push(this);
  10. // VBO
  11. var vertices = [];
  12. vertices.push(1, 1);
  13. vertices.push(-1, 1);
  14. vertices.push(-1, -1);
  15. vertices.push(1, -1);
  16. this._vertexDeclaration = [2];
  17. this._vertexStrideSize = 2 * 4;
  18. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19. // Indices
  20. var indices = [];
  21. indices.push(0);
  22. indices.push(1);
  23. indices.push(2);
  24. indices.push(0);
  25. indices.push(2);
  26. indices.push(3);
  27. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28. // Effects
  29. this._effect = this._scene.getEngine().createEffect("layer",
  30. ["position"],
  31. ["textureMatrix", "color"],
  32. ["textureSampler"], "");
  33. };
  34. // Members
  35. BABYLON.Layer.prototype.onDispose = null;
  36. // Methods
  37. BABYLON.Layer.prototype.render = function () {
  38. // Check
  39. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  40. return;
  41. var engine = this._scene.getEngine();
  42. // Render
  43. engine.enableEffect(this._effect);
  44. engine.setState(false);
  45. // Texture
  46. this._effect.setTexture("textureSampler", this.texture);
  47. this._effect.setMatrix("textureMatrix", this.texture._computeTextureMatrix());
  48. // Color
  49. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  50. // VBOs
  51. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  52. // Draw order
  53. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54. engine.draw(true, 0, 6);
  55. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56. };
  57. BABYLON.Layer.prototype.dispose = function () {
  58. if (this._vertexBuffer) {
  59. //this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  60. this._vertexBuffer = null;
  61. }
  62. if (this._indexBuffer) {
  63. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64. this._indexBuffer = null;
  65. }
  66. if (this.texture) {
  67. this.texture.dispose();
  68. this.texture = null;
  69. }
  70. // Remove from scene
  71. var index = this._scene.layers.indexOf(this);
  72. this._scene.layers.splice(index, 1);
  73. // Callback
  74. if (this.onDispose) {
  75. this.onDispose();
  76. }
  77. };
  78. })();