const { ccclass, property } = cc._decorator;

@ccclass
export class TextureCamera extends cc.Component {

    private static _instance: TextureCamera = null;
    public static getInstance() {
        return this._instance;
    }

    private canvas: cc.Node;
    private textureCamera: cc.Camera = null;

    onLoad() {
        this.canvas = cc.find("Canvas");
        this.textureCamera = this.node.getComponent(cc.Camera);
        TextureCamera._instance = this;
    }

    public GenerateTexture(target: cc.Node): cc.Texture2D {
        let width: number = target.width;
        let height: number = target.height;
        // 挂载
        target.group = "TextureCapture";
        target.setPosition(cc.Vec2.ZERO);
        target.parent = this.canvas;
        // 生成纹理
        let texture = new cc.RenderTexture;
        texture.initWithSize(width, height);
        this.textureCamera.targetTexture = texture;
        this.textureCamera.render(target);
        // 卸载
        target.group = "default";
        target.parent = null;
        target.destroy();
        target = null;
        // 翻转
        let data = texture.readPixels();
        let length = data.length;
        let data2 = new Uint8Array(length);
        for (let i = 0; i < length; i++) {
            let row02 = parseInt(i / (4 * width) + "");
            let row01 = height - row02 - 1;
            let index = row01 * width * 4 + i % (4 * width);
            data2[i] = data[index];
        }
        let tex = new cc.RenderTexture();
        tex.initWithData(data2, texture.getPixelFormat(), width, height);
        //texture.destroy();
        return tex;
    }

}
