Commit c9dc3066 authored by wjf's avatar wjf

l

parent 9272db0e
......@@ -74,6 +74,13 @@ export function getRenderStyle() {
return renderStyle
}
/**
* 获取渲染canvas
*/
export function getRenderCanvas(){
return _canvas
}
/**
* 清空渲染上下文
*/
......
......@@ -2,18 +2,18 @@
* Created by rockyl on 2018/11/5.
*/
export {ScillaComponent} from "./ScillaComponent";
export {Entity} from './Entity'
export {Scene} from './Scene'
export {ScillaEvent} from './ScillaEvent'
export { ScillaComponent } from "./ScillaComponent";
export { Entity } from './Entity'
export { Scene } from './Scene'
export { ScillaEvent } from './ScillaEvent'
// export {getContext, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut, ScaleMode} from './context/RenderContext';
export { getContext, getRenderStyle, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut } from './context/RenderContextGL';
export {pagePosToCanvasPos, canvasPosToPagePos} from './context/InteractContext';
export { getContext, getRenderStyle, createCanvas, getStageSize, getStageScale, getStageCenter, shortcut, ScaleMode } from './context/RenderContextGL';
export { pagePosToCanvasPos, canvasPosToPagePos } from './context/InteractContext';
export * from './manager'
export {default as Texture, createTexture} from './Texture'
export { default as Texture, createTexture } from './Texture'
export * from './Sheet'
export * from './FrameAnimation'
//导出webgl渲染器
export {default as WebGLRenderer} from "./webgl/WebGLRenderer";
\ No newline at end of file
export { default as WebGLRenderer } from "./webgl/WebGLRenderer";
\ No newline at end of file
......@@ -2,7 +2,7 @@
/**
* Base for a common object renderer that can be used as a system renderer plugin.
*
* 渲染器插件的基类
* @class
*/
export default class ObjectRenderer {
......
This diff is collapsed.
......@@ -8,7 +8,7 @@ const BLEND_FUNC = 4;
/**
* A WebGL state machines
*
* 设置状态机状态管理类
* @class
*/
export default class WebGLState {
......
......@@ -3,7 +3,6 @@
*
* @static
* @constant
* @memberof PIXI
* @type {number}
*/
export const PI_2 = Math.PI * 2;
......@@ -13,7 +12,6 @@ export const PI_2 = Math.PI * 2;
*
* @static
* @constant
* @memberof PIXI
* @type {number}
*/
export const RAD_TO_DEG = 180 / Math.PI;
......@@ -23,7 +21,6 @@ export const RAD_TO_DEG = 180 / Math.PI;
*
* @static
* @constant
* @memberof PIXI
* @type {number}
*/
export const DEG_TO_RAD = Math.PI / 180;
......@@ -33,7 +30,7 @@ export const DEG_TO_RAD = Math.PI / 180;
*
* @static
* @constant
* @memberof PIXI
* @memberof
* @name RENDERER_TYPE
* @type {object}
* @property {number} UNKNOWN - Unknown render type.
......@@ -54,7 +51,6 @@ export const RENDERER_TYPE = {
*
* @static
* @constant
* @memberof PIXI
* @name BLEND_MODES
* @type {object}
* @property {number} NORMAL
......@@ -104,7 +100,6 @@ export const BLEND_MODES = {
*
* @static
* @constant
* @memberof PIXI
* @name DRAW_MODES
* @type {object}
* @property {number} POINTS
......@@ -133,7 +128,6 @@ export const DRAW_MODES = {
*
* @static
* @constant
* @memberof PIXI
* @name SCALE_MODES
* @type {object}
* @property {number} LINEAR Smooth scaling
......@@ -157,7 +151,6 @@ export const SCALE_MODES = {
* @static
* @constant
* @name WRAP_MODES
* @memberof PIXI
* @type {object}
* @property {number} CLAMP - The textures uvs are clamped
* @property {number} REPEAT - The texture uvs tile and repeat
......@@ -172,7 +165,7 @@ export const WRAP_MODES = {
/**
* The gc modes that are supported by
*
* The {@link settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
* The {@link settings.GC_MODE} Garbage Collection mode for JS textures is AUTO
* If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
* used for a specified period of time they will be removed from the GPU. They will of course
* be uploaded again when they are required. This is a silent behind the scenes process that
......@@ -184,7 +177,6 @@ export const WRAP_MODES = {
* @static
* @constant
* @name GC_MODES
* @memberof PIXI
* @type {object}
* @property {number} AUTO - Garbage collection will happen periodically automatically
* @property {number} MANUAL - Garbage collection will need to be called manually
......@@ -199,7 +191,6 @@ export const GC_MODES = {
*
* @static
* @constant
* @memberof PIXI
* @type {RegExp|string}
* @example `image.png`
*/
......@@ -212,7 +203,6 @@ export const URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i;
* @static
* @constant
* @name DATA_URI
* @memberof PIXI
* @type {RegExp|string}
* @example data:image/png;base64
*/
......@@ -224,7 +214,6 @@ export const DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))
* @static
* @constant
* @name SVG_SIZE
* @memberof PIXI
* @type {RegExp|string}
* @example <svg width="100" height="100"></svg>
*/
......@@ -236,7 +225,6 @@ export const SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)
* @static
* @constant
* @name SHAPES
* @memberof PIXI
* @type {object}
* @property {number} POLY Polygon
* @property {number} RECT Rectangle
......@@ -258,7 +246,6 @@ export const SHAPES = {
* @static
* @constant
* @name PRECISION
* @memberof PIXI
* @type {object}
* @property {string} LOW='lowp'
* @property {string} MEDIUM='mediump'
......@@ -276,7 +263,6 @@ export const PRECISION = {
* @static
* @constant
* @name TRANSFORM_MODE
* @memberof PIXI
* @type {object}
* @property {number} STATIC
* @property {number} DYNAMIC
......@@ -292,7 +278,6 @@ export const TRANSFORM_MODE = {
* @static
* @constant
* @name TEXT_GRADIENT
* @memberof PIXI
* @type {object}
* @property {number} LINEAR_VERTICAL Vertical gradient
* @property {number} LINEAR_HORIZONTAL Linear gradient
......@@ -303,14 +288,13 @@ export const TEXT_GRADIENT = {
};
/**
* Represents the update priorities used by internal PIXI classes when registered with
* Represents the update priorities used by internal classes when registered with
* the {@link ticker.Ticker} object. Higher priority items are updated first and lower
* priority items, such as render, should go later.
*
* @static
* @constant
* @name UPDATE_PRIORITY
* @memberof PIXI
* @type {object}
* @property {number} INTERACTION=50 Highest priority, used for {@link interaction.InteractionManager}
* @property {number} HIGH=25 High priority updating, {@link VideoBaseTexture} and {@link extras.AnimatedSprite}
......
/**
* 批处理用buffer数据
*/
export class BatchBuffer {
/**
* 顶点数据,类型化数组
* https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
*/
vertices: ArrayBuffer;
/**
* 顶点的位置信息视图,浮点数
* View on the vertices as a Float32Array for positions
*/
float32View: Float32Array;
/**
* uv及颜色值的信息视图,整数
* View on the vertices as a Uint32Array for uvs
*/
uint32View: Uint32Array;
/**
* positions,uvs,colors暂时不用做单独记录
*/
positions: any;
uvs: any;
colors: any;
/**
* @param {number} size - The size of the buffer in bytes.
*/
constructor(size) {
constructor(size: number) {
this.vertices = new ArrayBuffer(size);
/**
* View on the vertices as a Float32Array for positions
*
* @member {Float32Array}
*/
this.float32View = new Float32Array(this.vertices);
/**
* View on the vertices as a Uint32Array for uvs
*
* @member {Float32Array}
*/
this.uint32View = new Uint32Array(this.vertices);
}
......
var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0);
/**
* Helper class to create a webGL buffer
*
* 用于创建webGL buffer,顶点和索引专用
* @class
* @memberof glCore
* @param gl {WebGLRenderingContext} The current WebGL rendering context
......@@ -11,47 +10,56 @@ var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0);
* @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
*/
export class GLBuffer {
/**
* 当前上下文
* @member {WebGLRenderingContext}
*/
gl: any;
/**
* The WebGL buffer, created upon instantiation
* @member {WebGLBuffer}
*/
buffer: any;
/**
* buffer类型
* 顶点或索引
* @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER}
*/
type: any;
/**
* The draw type of the buffer
* 绘制类型
* gl.STATIC_DRAW: 缓冲区的内容可能经常使用,而不会经常更改
* gl.DYNAMIC_DRAW: 缓冲区的内容可能经常被使用,并且经常更改
* gl.STREAM_DRAW: 缓冲区的内容可能不会经常使用,且不会经常更改
* @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
*/
drawType: any;
data: ArrayBuffer;
/**
* The data in the buffer, as a typed array
* 用来表示通用的、固定长度的原始二进制数据缓冲区。ArrayBuffer 不能直接操作,
* 而是要通过类型数组对象或 DataView 对象来操作,
* 它们会将缓冲区中的数据表示为特定的格式,并通过这些格式来读写缓冲区的内容。
* @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView}
*/
data;
/**
* 更新ID
*/
_updateID: number;
constructor(gl, type?, data?, drawType?) {
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
/**
* The WebGL buffer, created upon instantiation
*
* @member {WebGLBuffer}
*/
this.buffer = gl.createBuffer();
/**
* The type of the buffer
*
* @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER}
*/
this.type = type || gl.ARRAY_BUFFER;
/**
* The draw type of the buffer
*
* @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
*/
this.drawType = drawType || gl.STATIC_DRAW;
/**
* The data in the buffer, as a typed array
*
* @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView}
*/
this.data = EMPTY_ARRAY_BUFFER;
if (data) {
......@@ -62,12 +70,13 @@ export class GLBuffer {
};
/**
* 上传数据
* Uploads the buffer to the GPU
* @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload
* @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract
* @param dontBind {Boolean} whether to bind the buffer before uploading it
* @param dontBind {Boolean} whether to bind the buffer before uploading it 是否不绑定buffer
*/
public upload(data, offset?, dontBind?) {
public upload(data, offset?:number, dontBind?:boolean) {
// todo - needed?
if (!dontBind) this.bind();
......@@ -85,9 +94,11 @@ export class GLBuffer {
this.data = data;
};
/**
* Binds the buffer
*
* 状态机接下来使用的buffer
*
*/
public bind() {
var gl = this.gl;
......@@ -100,10 +111,22 @@ export class GLBuffer {
public destroy = function () {
this.gl.deleteBuffer(this.buffer);
};
/**
* 创建顶点缓存
* @param gl
* @param data
* @param drawType
*/
public static createVertexBuffer(gl, data?, drawType?) {
return new GLBuffer(gl, gl.ARRAY_BUFFER, data, drawType);
};
/**
* 创建索引缓存
* @param gl
* @param data
* @param drawType
*/
public static createIndexBuffer(gl, data?, drawType?) {
return new GLBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType);
};
......
......@@ -3,6 +3,7 @@ import { GLTexture } from './GLTexture';
/**
* Helper class to create a webGL Framebuffer
* 帧缓存,暂时不使用,renderTarget里用,主要用于滤镜处理
*
* @class
* @memberof glCore
......
......@@ -7,7 +7,7 @@ import { generateUniformAccessObject } from './shader/generateUniformAccessObjec
/**
* Helper class to create a webGL Shader
*
* 创建webgl shader用,里面主要用到attributes和uniforms
* @class
* @memberof glCore
* @param gl {WebGLRenderingContext}
......@@ -17,17 +17,42 @@ import { generateUniformAccessObject } from './shader/generateUniformAccessObjec
* @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1}
*/
export class GLShader {
gl: any;
program: any;
/**
* The current WebGL rendering context
* @member {WebGLRenderingContext}
*/
gl: WebGLRenderingContext;
/**
* The shader program
* @member {WebGLProgram}
*/
program: WebGLProgram;
/**
* The attributes of the shader as an object containing the following properties
* {
* type,
* size,
* location,
* pointer
* }
* @member {Object}
*/
attributes: {};
uniformData: {};
/**
* The uniforms of the shader as an object containing the following properties
* {
* gl,
* data
* }
* @member {Object}
*/
uniforms: { data: {}; };
constructor(gl, vertexSrc, fragmentSrc, precision?, attributeLocations?) {
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
constructor(gl:WebGLRenderingContext, vertexSrc:string, fragmentSrc:string, precision?:string, attributeLocations?) {
this.gl = gl;
if (precision) {
......@@ -35,44 +60,21 @@ export class GLShader {
fragmentSrc = setPrecision(fragmentSrc, precision);
}
/**
* The shader program
*
* @member {WebGLProgram}
*/
// First compile the program..
this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations);
/**
* The attributes of the shader as an object containing the following properties
* {
* type,
* size,
* location,
* pointer
* }
* @member {Object}
*/
// next extract the attributes
this.attributes = extractAttributes(gl, this.program);
this.uniformData = extractUniforms(gl, this.program);
/**
* The uniforms of the shader as an object containing the following properties
* {
* gl,
* data
* }
* @member {Object}
*/
this.uniforms = generateUniformAccessObject(gl, this.uniformData);
};
/**
* Uses this shader
*
* 状态机当前使用的shader
* @return {glCore.GLShader} Returns itself.
*/
public bind() {
......
/**
* Helper class to create a WebGL Texture
*
* 用于创建WebGL Texture
* @class
* @memberof glCore
* @param gl {WebGLRenderingContext} The current WebGL context
......@@ -11,57 +11,53 @@
* @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE
*/
export class GLTexture {
gl: any;
texture: any;
/**
* 当前上下文
* The current WebGL rendering context
*/
gl: WebGLRenderingContext;
texture: WebGLTexture;
/**
* If mipmapping was used for this texture, enable and disable with enableMipmap()
* 是否对纹理进行存储缩小的各种尺寸纹理,比如原图1024*1024,存储512*512,256*256,128*128等一直到1*1;为了纹理的缩放时处理,是取相邻或线性插值
*/
mipmap: boolean;
premultiplyAlpha: boolean;
width: any;
height: any;
/**
* Set to true to enable pre-multiplied alpha
* 设置纹理预乘透明值,为true,https://blog.csdn.net/mydreamremindme/article/details/50817294
*/
premultiplyAlpha;
/**
* 纹理宽度
*/
width: number;
/**
* 纹理高度
*/
height: number;
/**
* {number} the pixel format of the texture. defaults to gl.RGBA
* 纹理格式,默认gl.RGBA 还有gl.RGB
*/
format: any;
/**
* {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE
* 纹理类型,默认gl.UNSIGNED_BYTE //https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/texImage2D
*/
type: any;
constructor(gl, width?, height?, format?, type?) {
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
constructor(gl: WebGLRenderingContext, width?: number, height?: number, format?, type?) {
this.gl = gl;
/**
* The WebGL texture
*
* @member {WebGLTexture}
*/
this.texture = gl.createTexture();
/**
* If mipmapping was used for this texture, enable and disable with enableMipmap()
*
* @member {Boolean}
*/
// some settings..
this.mipmap = false;
/**
* Set to true to enable pre-multiplied alpha
*
* @member {Boolean}
*/
this.premultiplyAlpha = false;
/**
* The width of texture
*
* @member {Number}
*/
this.width = width || -1;
/**
* The height of texture
*
* @member {Number}
*/
this.height = height || -1;
/**
......@@ -77,17 +73,16 @@ export class GLTexture {
* @member {Number}
*/
this.type = type || gl.UNSIGNED_BYTE;
};
/**
* Uploads this texture to the GPU
* GPU存储纹理数据
* @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture
*/
public upload(source) {
this.bind();
var gl = this.gl;
......@@ -99,20 +94,22 @@ export class GLTexture {
var newHeight = source.videoHeight || source.height;
if (newHeight !== this.height || newWidth !== this.width) {
//https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/texImage2D
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source);
}
else {
//https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texSubImage2D
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source);
}
// if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect.
this.width = newWidth;
this.height = newHeight;
};
/**
* Use a data source and uploads this texture to the GPU
* 数据类型的纹理
* @param data {TypedArray} the data to upload to the texture
* @param width {number} the new width of the texture
* @param height {number} the new height of the texture
......@@ -162,9 +159,10 @@ export class GLTexture {
/**
* Binds the texture
* 绑定纹理,不传location表示不激活额外纹理,绑定的纹理位置与原状态相同
* @param location
*/
public bind(location?) {
public bind(location?: number) {
var gl = this.gl;
if (location !== undefined) {
......@@ -176,6 +174,7 @@ export class GLTexture {
/**
* Unbinds the texture
* 解除纹理绑定,解除位置与原状态相同
*/
public unbind() {
var gl = this.gl;
......@@ -184,8 +183,9 @@ export class GLTexture {
/**
* @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation
* 缩小的纹理像素 按线性插值,还是按钮邻近原则
*/
public minFilter(linear) {
public minFilter(linear: boolean) {
var gl = this.gl;
this.bind();
......@@ -200,8 +200,9 @@ export class GLTexture {
/**
* @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation
* 放大的纹理像素 按线性插值,还是按钮邻近原则
*/
public magFilter(linear) {
public magFilter(linear: boolean) {
var gl = this.gl;
this.bind();
......@@ -211,6 +212,7 @@ export class GLTexture {
/**
* Enables mipmapping
* 生成缩小的纹理集,只能在图片宽高满足2的指数时使用
*/
public enableMipmap() {
var gl = this.gl;
......@@ -224,6 +226,7 @@ export class GLTexture {
/**
* Enables linear filtering
* 设置线性
*/
public enableLinearScaling() {
this.minFilter(true);
......@@ -232,6 +235,7 @@ export class GLTexture {
/**
* Enables nearest neighbour interpolation
* 设置邻近
*/
public enableNearestScaling() {
this.minFilter(false);
......@@ -240,6 +244,7 @@ export class GLTexture {
/**
* Enables clamping on the texture so WebGL will not repeat it
* 如果纹理不满足2的指数时必设,以边缘像素延申
*/
public enableWrapClamp() {
var gl = this.gl;
......@@ -252,6 +257,7 @@ export class GLTexture {
/**
* Enable tiling on the texture
* 允许纹理重复,地砖模式
*/
public enableWrapRepeat() {
var gl = this.gl;
......@@ -261,6 +267,9 @@ export class GLTexture {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
};
/**
* 镜像形式重复
*/
public enableWrapMirrorRepeat() {
var gl = this.gl;
......@@ -281,16 +290,16 @@ export class GLTexture {
};
/**
* @static
* @param gl {WebGLRenderingContext} The current WebGL context
* @param source {HTMLImageElement|ImageData} the source image of the texture
* @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha
*/
public static fromSource(gl, source, premultiplyAlpha?) {
var texture = new GLTexture(gl);
* 从图片数据创建纹理
* @static
* @param gl {WebGLRenderingContext} The current WebGL context
* @param source {HTMLImageElement|ImageData} the source image of the texture
* @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha
*/
public static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData, premultiplyAlpha?: boolean) {
var texture: GLTexture = new GLTexture(gl);
texture.premultiplyAlpha = premultiplyAlpha || false;
texture.upload(source);
return texture;
};
......
......@@ -2,12 +2,11 @@
/**
* A standard object to store the Uvs of a texture
*
* 纹理的uv,暂时不处理纹理的旋转,不用GroupD8,
* @class
* @private
*/
export class TextureUvs
{
export class TextureUvs {
x0: number;
y0: number;
x1: number;
......@@ -16,12 +15,17 @@ export class TextureUvs
y2: number;
x3: number;
y3: number;
/**
* 减少传入gpu的数据字节,所以转换成十六进制,
*/
uvsUint32: Uint32Array;
/**
*
* 00.....10
* . .
* . .
* 01.....11
*/
constructor()
{
constructor() {
this.x0 = 0;
this.y0 = 0;
......@@ -43,14 +47,13 @@ export class TextureUvs
/**
* Sets the texture Uvs based on the given frame information.
*
* 设置uv
* @private
* @param {Rectangle} frame - The frame of the texture
* @param {Rectangle} baseFrame - The base frame of the texture
* @param {Rectangle} frame - The frame of the texture 小图
* @param {Rectangle} baseFrame - The base frame of the texture,大图
* @param {number} rotate - Rotation of frame, see {@link GroupD8}
*/
set(frame, baseFrame, rotate?)
{
set(frame, baseFrame, rotate?) {
const tw = baseFrame.width;
const th = baseFrame.height;
......@@ -82,17 +85,17 @@ export class TextureUvs
// }
// else
// {
this.x0 = frame.x / tw;
this.y0 = frame.y / th;
this.x0 = frame.x / tw;
this.y0 = frame.y / th;
this.x1 = (frame.x + frame.width) / tw;
this.y1 = frame.y / th;
this.x1 = (frame.x + frame.width) / tw;
this.y1 = frame.y / th;
this.x2 = (frame.x + frame.width) / tw;
this.y2 = (frame.y + frame.height) / th;
this.x2 = (frame.x + frame.width) / tw;
this.y2 = (frame.y + frame.height) / th;
this.x3 = frame.x / tw;
this.y3 = (frame.y + frame.height) / th;
this.x3 = frame.x / tw;
this.y3 = (frame.y + frame.height) / th;
// }
this.uvsUint32[0] = (((this.y0 * 65535) & 0xFFFF) << 16) | ((this.x0 * 65535) & 0xFFFF);
......
......@@ -5,7 +5,7 @@ import { setVertexAttribArrays } from './setVertexAttribArrays';
/**
* Helper class to work with WebGL VertexArrayObjects (vaos)
* Only works if WebGL extensions are enabled (they usually are)
*
* 核心类VAOs
* @class
* @memberof glCore
* @param gl {WebGLRenderingContext} The current WebGL rendering context
......@@ -14,13 +14,29 @@ export class VertexArrayObject {
nativeVaoExtension: any;
nativeState: any;
nativeVao: any;
gl: any;
/**
* 当前上下文
*/
gl: WebGLRenderingContext;
/**
* An array of attributes
* attributes数组
*/
attributes: any[];
/**
* 索引buffer
* @member {GLBuffer}
*/
indexBuffer: any;
/**
* A boolean flag
*/
dirty: boolean;
constructor(gl, state) {
constructor(gl: WebGLRenderingContext, state) {
this.nativeVaoExtension = null;
//不要求必须使用原生时,基本都支持扩展
if (!VertexArrayObject.FORCE_NATIVE) {
this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') ||
gl.getExtension('MOZ_OES_vertex_array_object') ||
......@@ -41,35 +57,18 @@ export class VertexArrayObject {
};
}
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
/**
* An array of attributes
*
* @member {Array}
*/
this.attributes = [];
/**
* @member {glCore.GLBuffer}
*/
this.indexBuffer = null;
/**
* A boolean flag
*
* @member {Boolean}
*/
this.dirty = false;
};
/**
* Binds the buffer
* 绑定数据
*/
public bind() {
if (this.nativeVao) {
......@@ -93,6 +92,7 @@ export class VertexArrayObject {
/**
* Unbinds the buffer
* 解绑数据
*/
public unbind() {
if (this.nativeVao) {
......@@ -104,6 +104,7 @@ export class VertexArrayObject {
/**
* Uses this vao
* 激活vao
*/
public activate() {
......@@ -136,7 +137,7 @@ export class VertexArrayObject {
};
/**
*
* 添加attribute
* @param buffer {gl.GLBuffer}
* @param attribute {*}
* @param type {String}
......@@ -162,7 +163,7 @@ export class VertexArrayObject {
};
/**
*
* 添加索引数据
* @param buffer {gl.GLBuffer}
*/
public addIndex(buffer/*, options*/) {
......@@ -175,6 +176,7 @@ export class VertexArrayObject {
/**
* Unbinds this vao and disables it
* 解绑废弃vao
*/
public clear() {
// var gl = this.gl;
......@@ -192,17 +194,20 @@ export class VertexArrayObject {
};
/**
* @param type {Number}
* @param size {Number}
* @param start {Number}
* 执行绘制
* @param type {Number} gl.TRIANGLES\gl.TRIANGLE_STRIP等
* @param size {Number} 个数
* @param start {Number} 偏移
*/
public draw(type, size?, start?) {
var gl = this.gl;
if (this.indexBuffer) {
//有索引 https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements
gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2);
}
else {
//无索引 https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawArrays
// TODO need a better way to calculate size..
gl.drawArrays(type, start || 0, size || this.getSize());
}
......
......@@ -9,7 +9,12 @@ const fragTemplate = [
'}',
].join('\n');
export function checkMaxIfStatmentsInShader(maxIfs, gl) {
/**
* 检查最大纹理数是否合法
* @param maxIfs
* @param gl
*/
export function checkMaxIfStatmentsInShader(maxIfs:number, gl:WebGLRenderingContext) {
const createTempContext = !gl;
// @if DEBUG
......
/**
* Helper class to create a webGL Context
*
* @class
* @memberof glCore
* 创建webgl上下文
* @param canvas {HTMLCanvasElement} the canvas element that we will get the context from
* @param options {Object} An options object that gets passed in to the canvas element containing the context attributes,
* see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available
......
/**
* Generic Mask Stack data structure
*
* 根据图片数量创建索引数组
* 0....1
* . . .
* . . .
* 3....2
* @function createIndicesForQuads
* @private
* @param {number} size - Number of quads
* @return {Uint16Array} indices
*/
export function createIndicesForQuads(size)
export function createIndicesForQuads(size:number)
{
// the total number of indices in our array, there are 6 points per quad.
......
......@@ -8,7 +8,7 @@ const VSHADER_SOURCE =
"attribute float aTextureId;" +
"uniform mat3 projectionMatrix;" +
"uniform mat3 modelMatrix;" +
// "uniform mat3 modelMatrix;" +
"varying vec2 vTextureCoord;" +
"varying vec4 vColor;" +
......@@ -21,6 +21,7 @@ const VSHADER_SOURCE =
"vTextureId = aTextureId;" +
"vColor = aColor;" +
"}";
//片元着色器程序
const fragTemplate = [
'precision mediump float;',
'varying vec2 vTextureCoord;',
......@@ -37,7 +38,11 @@ const fragTemplate = [
].join('\n');
/**
* 创建批处理专用着色器,核心,切换纹理
* @param gl
* @param maxTextures 最大纹理数
*/
export function generateMultiTextureShader(gl, maxTextures) {
// const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8');
let fragmentSrc = fragTemplate;
......
......@@ -5,6 +5,7 @@ export { GLBuffer } from './GLBuffer';
export { VertexArrayObject } from './VertexArrayObject';
export { GLFramebuffer } from "./GLFramebuffer";
export { GLShader } from "./GLShader";
export { BatchBuffer } from "./BatchBuffer";
export { TextureUvs } from "./TextureUvs";
export { checkMaxIfStatmentsInShader } from "./checkMaxIfStatmentsInShader"
// var GL_MAP = {};
/**
* 连接attribute变量与分配给它的缓冲区对象,两种方式,与顶点着色器通信核心方法
* @param gl {WebGLRenderingContext} The current WebGL context
* @param attribs {*}
* @param state {*}
......
/**
* @class
* @memberof glCore.shader
* 编译着色器程序
* @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
* @param vertexSrc {string|string[]} The vertex shader source as an array of strings.
* @param fragmentSrc {string|string[]} The fragment shader source as an array of strings.
* @param vertexSrc The vertex shader source as an array of strings.顶点着色器
* @param fragmentSrc The fragment shader source as an array of strings.片元着色器
* @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations
* @return {WebGLProgram} the shader program
* @return {WebGLProgram} the shader program 返回着色器程序
*/
export function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations?) {
export function compileProgram(gl:WebGLRenderingContext, vertexSrc:string, fragmentSrc:string, attributeLocations?) {
var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc);
var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc);
......@@ -50,6 +49,7 @@ export function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations?)
};
/**
* 创建shader
* @private
* @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
* @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
......
......@@ -3,14 +3,14 @@ import { mapType } from './mapType';
import { mapSize } from './mapSize';
/**
* Extracts the attributes
* Extracts the attributes获取attributes属性
* @class
* @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL rendering context
* @param program {WebGLProgram} The shader program to get the attributes from
* @return attributes {Object}
*/
export function extractAttributes(gl, program) {
export function extractAttributes(gl: WebGLRenderingContext, program: WebGLProgram) {
var attributes = {};
var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
......
......@@ -2,7 +2,7 @@ import { mapType } from './mapType';
import { defaultValue } from './defaultValue';
/**
* Extracts the uniforms
* Extracts the uniforms 获取uniforms属性
* @class
* @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL rendering context
......
/**
* Extracts the attributes
* 使uniform能通过赋值直接和着色器程序通信
* @class
* @memberof glCore.shader
* @param gl {WebGLRenderingContext} The current WebGL rendering context
......
/**
* 给shader source设置precision
* Sets the float precision on the shader. If the precision is already present this function will do nothing
* @param {string} src the shader source
* @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'.
......
......@@ -2,13 +2,28 @@
// import AlphaMaskFilter from '../filters/spriteMask/SpriteMaskFilter';
/**
* @class
* 遮罩管理器
*/
export default class MaskManager {
/**
* 当前渲染器
*/
renderer: any;
/**
* 是否剪切
*/
scissor: boolean;
/**
* 剪切数据
*/
scissorData: any;
/**
* 剪切对象
*/
scissorRenderTarget: any;
/**
* 是否允许剪切
*/
enableScissor: boolean;
/**
* @param {WebGLRenderer} renderer - The renderer this manager works for.
......@@ -29,7 +44,7 @@ export default class MaskManager {
/**
* Applies the Mask and adds it to the current filter stack.
*
* 执行遮罩
* @param {DisplayObject} target - Display Object to push the mask to
* @param {Sprite|Graphics} maskData - The masking data.
*/
......@@ -62,7 +77,7 @@ export default class MaskManager {
/**
* Removes the last mask from the mask stack and doesn't return it.
*
* 移除遮罩
* @param {DisplayObject} target - Display Object to pop the mask from
* @param {Sprite|Graphics} maskData - The masking data.
*/
......@@ -114,7 +129,7 @@ export default class MaskManager {
/**
* Applies the Mask and adds it to the current filter stack.
*
* 执行模板遮罩
* @param {Sprite|Graphics} maskData - The masking data.
*/
pushStencilMask(maskData) {
......@@ -124,7 +139,7 @@ export default class MaskManager {
/**
* Removes the last filter from the filter stack and doesn't return it.
*
* 移除模板遮罩
*/
popStencilMask(target, maskData) {
this.renderer.currentRenderer.stop();
......@@ -132,7 +147,7 @@ export default class MaskManager {
}
/**
*
* 执行剪切遮罩
* @param {DisplayObject} target - Display Object to push the mask to
* @param {Graphics} maskData - The masking data.
*/
......@@ -160,8 +175,7 @@ export default class MaskManager {
}
/**
*
*
* 移除剪切遮罩
*/
popScissorMask(target, maskData) {
// this.scissorRenderTarget = null;
......
/**
* 模板缓存,实现遮罩
* @class
*/
export default class StencilManager {
/**
* 当前渲染器
*/
renderer: any;
/**
* 记录嵌套的遮罩数据
*/
stencilMaskStack: any;
/**
* @param {WebGLRenderer} renderer - The renderer this manager works for.
*/
......@@ -16,7 +24,7 @@ export default class StencilManager {
/**
* Changes the mask stack that is used by this manager.
*
* 改变mask stack
* @param {Graphics[]} stencilMaskStack - The mask stack
*/
setMaskStack(stencilMaskStack) {
......@@ -34,7 +42,7 @@ export default class StencilManager {
/**
* Applies the Mask and adds it to the current stencil stack. @alvin
*
* 应用遮罩
* @param {Graphics} graphics - The mask
*/
pushStencil(graphics) {
......@@ -51,23 +59,29 @@ export default class StencilManager {
this.stencilMaskStack.push(graphics);
// Increment the refference stencil value where the new mask overlaps with the old ones.
if(graphics.maskVisible){
//如果显示遮罩
gl.colorMask(true, true, true, true);
}else{
gl.colorMask(false, false, false, false);
}
// Increment the refference stencil value where the new mask overlaps with the old ones.
// gl.colorMask(true, true, true, true);
//设置模板检测规则,https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/stencilFunc
gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask());
//设置模板的绘制规则,模板检测未通过时,深度检测通过时,都通过时 https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp
gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
//开始绘制遮罩数据
this.renderer.plugins.graphics.render(graphics);
//应用当前遮罩,后续绘制的东西都会有效
this._useCurrent();
}
/**
* Removes the last mask from the stencil stack. @alvin
* 移除模板数据,一步一步,考虑嵌套的遮罩。
*/
popStencil() {
this.renderer.setObjectRenderer(this.renderer.plugins.graphics);
......@@ -93,6 +107,7 @@ export default class StencilManager {
/**
* Setup renderer to use the current stencil data.
* 使用当前模板数据
*/
_useCurrent() {
const gl = this.renderer.gl;
......@@ -104,7 +119,7 @@ export default class StencilManager {
/**
* Fill 1s equal to the number of acitve stencil masks.
*
* 计算用于与运算的二进制对比位
* @return {number} The bitwise mask.
*/
_getBitwiseMask() {
......
......@@ -6,37 +6,31 @@ import removeItems from '../utils/removeItems';
import {isPow2} from "../utils"
/**
* Helper class to create a webGL Texture
*
* 用于创建webGL Texture
* @class
*/
export default class TextureManager {
/**
* 当前渲染器的指向
*/
renderer: any;
/**
*
*/
gl: any;
/**
* Track textures in the renderer so we can no longer listen to them on destruction.
* 纹理集
*/
_managedTextures: any[];
/**
* @param {WebGLRenderer} renderer - A reference to the current renderer
*/
constructor(renderer) {
/**
* A reference to the current renderer
*
* @member {PIXI.WebGLRenderer}
*/
this.renderer = renderer;
/**
* The current WebGL rendering context
*
* @member {WebGLRenderingContext}
*/
this.gl = renderer.gl;
/**
* Track textures in the renderer so we can no longer listen to them on destruction.
*
* @member {Array<*>}
* @private
*/
this._managedTextures = [];
}
......@@ -58,9 +52,9 @@ export default class TextureManager {
/**
* Updates and/or Creates a WebGL texture for the renderer's context.
*
* @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update
* @param {number} location - the location the texture will be bound to.
* 更新或创建一个WebGL texture ,主要方法
* @param {BaseTexture|Texture} texture - the texture to update 暂时主要是image
* @param {number} location - the location the texture will be bound to.激活绑定纹理的位置
* @return {GLTexture} The gl texture.
*/
updateTexture(texture, location) {
......@@ -173,7 +167,7 @@ export default class TextureManager {
/**
* Deletes the texture from WebGL
*
* @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy
* @param {BaseTexture|Texture} texture - the texture to destroy
* @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
*/
destroyTexture(texture, skipRemove) {
......
import ObjectRenderer from '../ObjectRenderer';
import WebGLRenderer from '../WebGLRenderer';
import createIndicesForQuads from '../utils/createIndicesForQuads';
import { generateMultiTextureShader } from '../utils/generateMultiTextureShader';
import { createIndicesForQuads } from '../glCore/createIndicesForQuads';
import { generateMultiTextureShader } from '../glCore/generateMultiTextureShader';
import { checkMaxIfStatmentsInShader } from '../glCore/checkMaxIfStatmentsInShader';
import { BatchBuffer } from '../glCore/BatchBuffer';
import settings from '../settings';
......@@ -16,21 +16,59 @@ let TEXTURE_TICK = 0;
/**
* Renderer dedicated to drawing and batching sprites.
*
* 批处理核心插件
* @class
* @private
* @extends ObjectRenderer
*/
export default class BatchRenderer extends ObjectRenderer {
/**
* Number of values sent in the vertex buffer.
* aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5
* 顶点数据中的步长
*/
vertSize: number;
/**
* The size of the vertex information in bytes.
* 顶点数据步长的字节长度 *4
*/
vertByteSize: number;
/**
* The number of images in the SpriteRenderer before it flushes.
* 批处理最大值总数
*/
size: number;
/**
* 所有可能用到的2的指数的buffer
*/
buffers: any[];
/**
* Holds the indices of the geometry (quads) to draw
* 基于size设定的顶点索引
*/
indices: Uint16Array;
/**
* The default shaders that is used if a sprite doesn't have a more specific one.
* there is a shader for each number of textures that can be rendererd.
* These shaders will also be generated on the fly as required.
* @member {GLShader}
*/
shader: any;
/**
* 当前下标
*/
currentIndex: number;
/**
* 批处理分组
*/
groups: any[];
/**
* flush要处理的所有元素
*/
sprites: any[];
/**
* 顶点buffer
*/
vertexBuffers: any[];
vaos: any[];
vaoMax: number;
......@@ -46,49 +84,23 @@ export default class BatchRenderer extends ObjectRenderer {
constructor(renderer) {
super(renderer);
/**
* Number of values sent in the vertex buffer.
* aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5
*
* @member {number}
*/
this.vertSize = 5;
/**
* The size of the vertex information in bytes.
*
* @member {number}
*/
this.vertByteSize = this.vertSize * 4;
/**
* The number of images in the SpriteRenderer before it flushes.
*
* @member {number}
*/
this.size = settings.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop
// the total number of bytes in our batch
// let numVerts = this.size * 4 * this.vertByteSize;
//建立所有可能用到的2的指数的buffer
this.buffers = [];
for (let i = 1; i <= nextPow2(this.size); i *= 2) {
this.buffers.push(new BatchBuffer(i * 4 * this.vertByteSize));
}
/**
* Holds the indices of the geometry (quads) to draw
*
* @member {Uint16Array}
*/
this.indices = createIndicesForQuads(this.size);
/**
* The default shaders that is used if a sprite doesn't have a more specific one.
* there is a shader for each number of textures that can be rendererd.
* These shaders will also be generated on the fly as required.
* @member {Shader[]}
*/
this.shader = null;
this.currentIndex = 0;
......@@ -111,7 +123,8 @@ export default class BatchRenderer extends ObjectRenderer {
/**
* Sets up the renderer context and necessary buffers.
*
* 之前父级会设置this.renderer.on('context', this.onContextChange, this);
* 从简,直接在renderer里设置
* @private
*/
onContextChange() {
......@@ -167,7 +180,7 @@ export default class BatchRenderer extends ObjectRenderer {
/**
* Called before the renderer starts rendering.
*
* 在每帧渲染开始前执行
*/
onPrerender() {
this.vertexCount = 0;
......@@ -175,7 +188,7 @@ export default class BatchRenderer extends ObjectRenderer {
/**
* Renders the sprite object.
*
* 记录每个元素
* @param {Sprite} sprite - the sprite to render when using this spritebatch
*/
render(sprite) {
......@@ -199,7 +212,7 @@ export default class BatchRenderer extends ObjectRenderer {
/**
* Renders the content and empties the current batch.
*
* 将记录的所有元素一次绘制
*/
flush() {
if (this.currentIndex === 0) {
......@@ -286,6 +299,7 @@ export default class BatchRenderer extends ObjectRenderer {
currentTexture = nextTexture;
if (nextTexture._enabled !== TICK) {
//如果将超过最大纹理数,则跳到一个group
if (textureCount === MAX_TEXTURES) {
TICK++;
......@@ -386,7 +400,7 @@ export default class BatchRenderer extends ObjectRenderer {
_tintRGB = (num >> 16) + (num & 0xff00) + ((num & 0xff) << 16);
}
const alpha = Math.min(sprite.transform.renderAlpha*sprite.alpha, 1.0);
const alpha = Math.min(sprite.transform.renderAlpha * sprite.alpha, 1.0);
// we dont call extra function if alpha is 1.0, that's faster
const argb = alpha < 1.0 /*&& nextTexture.premultipliedAlpha*/ ? premultiplyTint(/*sprite._tintRGB*/_tintRGB, alpha)
: /*sprite._tintRGB*/_tintRGB + (alpha * 255 << 24);
......
......@@ -9,15 +9,30 @@ import { GLBuffer, VertexArrayObject } from "../glCore"
/**
* Renders the graphics object.
*暂时为遮罩处理用,shader和vao特定的
* 暂时为遮罩处理用,shader和vao特定的
* @class
* @extends ObjectRenderer
*/
export default class GraphicsRenderer extends ObjectRenderer {
/**
* 暂时不需要,存储数据
*/
graphicsDataPool: any[];
/**
* 预置的着色器
*/
primitiveShader: any;
/**
* 当前上下文
*/
gl: any;
/**
*
*/
CONTEXT_UID: number;
/**
* 当前渲染器
*/
renderer: any;
buffer: GLBuffer;
indexBuffer: GLBuffer;
......
......@@ -2,7 +2,7 @@ import Shader from './Shader';
/**
* This shader is used to draw simple primitive shapes for {@link Graphics}.
*
* 为图形使用的着色器
* @class
* @extends Shader
*/
......
......@@ -25,7 +25,7 @@ function checkPrecision(src, def)
/**
* Wrapper class, webGL Shader
* Adds precision string if vertexSrc or fragmentSrc have no mention of it.
*
* 为了给着色器加精度
* @class
* @extends GLShader
*/
......
/**
* 批处理buffer数据类
*/
export default class Buffer {
/**
* 顶点类型化数组
*/
vertices: ArrayBuffer;
/**
* View on the vertices as a Float32Array for positions
* @member {Float32Array}
*/
float32View: Float32Array;
/**
* View on the vertices as a Uint32Array for uvs
* @member {Uint32Array}
*/
uint32View: Uint32Array;
positions: any;
uvs: any;
colors: any;
/**
* @param {number} size - The size of the buffer in bytes.
*/
constructor(size) {
this.vertices = new ArrayBuffer(size);
this.float32View = new Float32Array(this.vertices);
this.uint32View = new Uint32Array(this.vertices);
}
/**
* Destroys the buffer.
*
*/
destroy() {
this.vertices = null;
this.positions = null;
this.uvs = null;
this.colors = null;
}
}
......@@ -5,6 +5,7 @@ import settings from '../settings';
import { GLFramebuffer,GLTexture } from '../glCore';
import { getStageSize } from "../../../core/context/RenderContextGL"
/**
* 渲染对象,暂时只用到root
* @class
*/
export default class RenderTarget {
......
/**
* 检测ios设备,若是,则返回不能同帧上传同一buffer
*/
export default function canUploadSameBuffer() {
// Uploading the same buffer multiple times in a single frame can cause perf issues.
// Apparent on IOS so only check for that at the moment
......
/**
* Generic Mask Stack data structure
*
* @function createIndicesForQuads
* @private
* @param {number} size - Number of quads
* @return {Uint16Array} indices
*/
export default function createIndicesForQuads(size)
{
// the total number of indices in our array, there are 6 points per quad.
const totalIndices = size * 6;
const indices = new Uint16Array(totalIndices);
// fill the indices with the quads to draw
for (let i = 0, j = 0; i < totalIndices; i += 6, j += 4)
{
indices[i + 0] = j + 0;
indices[i + 1] = j + 1;
indices[i + 2] = j + 2;
indices[i + 3] = j + 0;
indices[i + 4] = j + 2;
indices[i + 5] = j + 3;
}
return indices;
}
import { GLShader } from '../glCore/GLShader';
//顶点着色器程序
const VSHADER_SOURCE =
" precision highp float;" +
"attribute vec2 aVertexPosition;" +
"attribute vec2 aTextureCoord;" +
"attribute vec4 aColor;" +
"attribute float aTextureId;" +
"uniform mat3 projectionMatrix;" +
// "uniform mat3 modelMatrix;" +
"varying vec2 vTextureCoord;" +
"varying vec4 vColor;" +
"varying float vTextureId;" +
"void main(void){" +
"gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
// "gl_Position = vec4((projectionMatrix *modelMatrix* vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
"vTextureCoord = aTextureCoord;" +
"vTextureId = aTextureId;" +
"vColor = aColor;" +
"}";
const fragTemplate = [
'precision mediump float;',
'varying vec2 vTextureCoord;',
'varying vec4 vColor;',
'varying float vTextureId;',
'uniform sampler2D uSamplers[%count%];',
'void main(void){',
'vec4 color;',
'float textureId = floor(vTextureId+0.5);',
'%forloop%',
'gl_FragColor = color * vColor;',
'}',
].join('\n');
export function generateMultiTextureShader(gl, maxTextures) {
// const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8');
let fragmentSrc = fragTemplate;
fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures);
fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures));
// console.log(fragmentSrc)
const shader = new GLShader(gl, VSHADER_SOURCE, fragmentSrc);
const sampleValues = [];
for (let i = 0; i < maxTextures; i++) {
sampleValues[i] = i;
}
shader.bind();
shader.uniforms["uSamplers"] = sampleValues;
// console.log(fragmentSrc)
return shader;
}
function generateSampleSrc(maxTextures) {
let src = '';
src += '\n';
src += '\n';
for (let i = 0; i < maxTextures; i++) {
if (i > 0) {
src += '\nelse ';
}
if (i < maxTextures - 1) {
src += `if(textureId == ${i}.0)`;
}
src += '\n{';
src += `\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`;
src += '\n}';
}
src += '\n';
src += '\n';
return src;
}
/**
* premultiplies tint
*
* 颜色与透明度预先处理
* @memberof utils
* @param {number} tint integet RGB
* @param {number} alpha floating point alpha (0.0-1.0)
* @returns {number} tint multiplied by alpha
*/
export function premultiplyTint(tint, alpha) {
export function premultiplyTint(tint:number, alpha:number) {
if (alpha === 1.0) {
return (alpha * 255 << 24) + tint;
}
......@@ -23,7 +23,10 @@ export function premultiplyTint(tint, alpha) {
return (alpha * 255 << 24) + (R << 16) + (G << 8) + B;
}
/**
* 求下一个最接近2的指数,数值
* @param v
*/
export function nextPow2(v) {
v += v === 0;
--v;
......@@ -35,6 +38,10 @@ export function nextPow2(v) {
return v + 1;
}
/**
* 求2为底的对数
* @param v
*/
export function log2(v: number) {
var r, shift;
r = Number(v > 0xFFFF) << 4; v >>>= r;
......@@ -44,13 +51,17 @@ export function log2(v: number) {
return r | (v >> 1);
}
/**
* 是否2的指数式
* @param v
*/
export function isPow2(v) {
return !(v & (v - 1)) && (!!v);
}
/**
* Converts a hex color number to an [R, G, B] array
*
* 0xffffff转[R,G,B]
* @memberof utils
* @function hex2rgb
* @param {number} hex - The number to convert
......
import {Device} from './Device';
/**
* 获取合适的最大纹理数量
* @param max
*/
export default function maxRecommendedTextures(max)
{
if (Device.tablet || Device.phone)
......
/**
* Remove a range of items from an array
*
* 从数组移除一定范围下标的元素
* @function removeItems
* @param {Array<*>} arr The target array
* @param {number} startIdx The index to begin removing from (inclusive)
......
/**
* 检查gl是否有效,主要检查模板缓存是否可用
*/
export default function validateContext(gl)
{
const attributes = gl.getContextAttributes();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment