/*
 Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.

 https://www.cocos.com/

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated engine source code (the "Software"), a limited,
 worldwide, royalty-free, non-assignable, revocable and non-exclusive license
 to use Cocos Creator solely to develop games on your target platforms. You shall
 not use Cocos Creator software for developing other software or tools that's
 used for developing games. You are not granted to publish, distribute,
 sublicense, and/or sell copies of Cocos Creator.

 The software or tools in this License Agreement are licensed, not sold.
 Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

import {dynamicAtlasManager, IAssembler, IRenderData, RenderData, sp, Sprite, Vec2, Vec3} from "cc";
import TexturePlus from "../Components/TexturePlus";


const vec3_temps: Vec3[] = [];
for (let i = 0; i < 4; i++) {
    vec3_temps.push(new Vec3());
}

/**
 * simple 组装器
 * 可通过 `UI.simple` 获取该组装器。
 */
let floatsPerVert = 9;
export const TextureAssembler: IAssembler = {

    createData(sprite: TexturePlus) {
        const renderData = sprite.requestRenderData();
        let points = sprite.uvList;
        if (!points || points.length < 3) return;
        renderData.dataLength = points.length;
        let indicesCount =  sprite.indices.length;
        renderData.resize(points.length,indicesCount);
        // @ts-ignore
        renderData.chunk.setIndexBuffer(sprite.indices);
        return renderData;
    },

    updateRenderData (sprite: Sprite) {
        const frame = sprite.spriteFrame;
        dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
        this.updateUVs(sprite);// dirty need
        //this.updateColor(sprite);// dirty need

        const renderData = sprite.renderData;
        if (renderData && frame) {
            if (renderData.vertDirty) {
                this.updateVertexData(sprite);
            }
            renderData.updateRenderData(sprite, frame);
        }
    },
    updateWorldVerts (sprite: Sprite, chunk: any) {
        const renderData = sprite.renderData!;
        const vData = chunk.vb;

        const dataList: IRenderData[] = renderData.data;
        const node = sprite.node;
        const matrix = node.worldMatrix;

        const stride = renderData.floatStride;

        const vec3_temp = vec3_temps[0];
        let offset = 0;
        for (let i = 0; i < dataList.length; i++) {
            const curData = dataList[i];
            Vec3.set(vec3_temp, curData.x, curData.y, 0);
            Vec3.transformMat4(vec3_temp, vec3_temp, matrix);
            offset = i * stride;
            vData[offset++] = vec3_temp.x;
            vData[offset++] = vec3_temp.y;
            vData[offset++] = vec3_temp.z;
        }
    },


    fillBuffers(sprite: TexturePlus, renderer: any) {
        if (sprite === null) {
            return;
        }
        const renderData = sprite.renderData!;
        const chunk = renderData.chunk;
        if (sprite.node.hasChangedFlags || renderData.vertDirty) {
            // const vb = chunk.vertexAccessor.getVertexBuffer(chunk.bufferId);
            this.updateWorldVerts(sprite, chunk);
            renderData.vertDirty = false;
        }

        const bid = chunk.bufferId;
        const vidOrigin = chunk.vertexOffset;
        // @ts-ignore
        const meshBuffer = chunk.meshBuffer;
        // @ts-ignore
        const ib = chunk.meshBuffer.iData;
        let indexOffset = meshBuffer.indexOffset;
        let vid = vidOrigin;
        const iData = sprite.indices;
        for (let i = 0, l = iData.length; i < l; i++) {
            ib[indexOffset++] = vid + iData[i];
        }
        meshBuffer.indexOffset += iData.length;
    },

    updateVertexData (sprite: TexturePlus) {
        const renderData: RenderData | null = sprite.renderData;
        if (!renderData) {
            return;
        }

        const uiTrans = sprite.node._uiProps.uiTransformComp!;
        const dataList: IRenderData[] = renderData.data;
        const cw = uiTrans.width;
        const ch = uiTrans.height;
        const appX = uiTrans.anchorX * cw;
        const appY = uiTrans.anchorY * ch;
        let l = 0;
        let b = 0;
        let r = 0;
        let t = 0;
        if (sprite.trim) {
            l = -appX;
            b = -appY;
            r = cw - appX;
            t = ch - appY;
        } else {
            const frame = sprite.spriteFrame!;
            const originSize = frame.originalSize;
            const ow = originSize.width;
            const oh = originSize.height;
            const scaleX = cw / ow;
            const scaleY = ch / oh;
            // @ts-ignore
            const trimmedBorder = frame.trimmedBorder;
            l = trimmedBorder.x * scaleX - appX;
            b = trimmedBorder.z * scaleY - appY;
            r = cw + trimmedBorder.y * scaleX - appX;
            t = ch + trimmedBorder.w * scaleY - appY;
        }
        let startX = l;
        let startY = b;
        let subX = r - l;
        let subY = t - b;
        for(let i = 0;i < sprite.uvList2.length;++i){
            let pos = sprite.uvList2[i];
            let x = sprite.flipX ? 1 - pos.x : pos.x;
            dataList[i].x = x * subX + startX;
            dataList[i].y = pos.y * subY + startY;
        }
        renderData.vertDirty = true;
    },

    updateUVs(sprite: TexturePlus) {
        if (!sprite.spriteFrame) return;
        const renderData = sprite.renderData!;
        const vData = renderData.chunk.vb;
        const uv = sprite.spriteFrame.uv;
        let polygon = sprite.uvList;
        let startX = uv[0];
        let startY = uv[1];
        let subX = uv[6] - startX;
        let subY = uv[7] - startY;
        let uvOffset = 3;
        for (let i = 0; i < polygon.length; i++) {
            let pos = polygon[i];
            let rx = sprite.flipX ? 1 - pos.x : pos.x;
            let dstOffset = floatsPerVert * i + uvOffset;
            vData[dstOffset] = startX + rx * subX;
            vData[dstOffset + 1] = startY +  pos.y * subY;
        }
    },

    updateColor(sprite: TexturePlus) {
        const renderData = sprite.renderData!;
        const vData = renderData.chunk.vb;

        let colorOffset = 5;
        const color = sprite.color;
        const colorR = color.r / 255;
        const colorG = color.g / 255;
        const colorB = color.b / 255;
        const colorA = sprite.node._uiProps.opacity;

        for (let i = 0; i < sprite.uvList.length; i++,colorOffset += renderData.floatStride) {
            vData![colorOffset] = colorR;
            vData![colorOffset + 1] = colorG;
            vData![colorOffset + 2] = colorB;
            vData![colorOffset + 3] = colorA;
        }
    },
};
