System.register(["__unresolved_0", "cc", "__unresolved_1"], function (_export, _context) {
  "use strict";

  var _reporterNs, _cclegacy, __checkObsolete__, __checkObsoleteInNamespace__, _decorator, Component, RenderTexture, sys, UITransform, gfx, director, Texture2D, view, Vec3, _cc, Util, _dec, _class, _crd, cc, ccclass, property, scene2;

  function _reportPossibleCrUseOfUtil(extras) {
    _reporterNs.report("Util", "../Util", _context.meta, extras);
  }

  return {
    setters: [function (_unresolved_) {
      _reporterNs = _unresolved_;
    }, function (_cc2) {
      _cclegacy = _cc2.cclegacy;
      __checkObsolete__ = _cc2.__checkObsolete__;
      __checkObsoleteInNamespace__ = _cc2.__checkObsoleteInNamespace__;
      _decorator = _cc2._decorator;
      Component = _cc2.Component;
      RenderTexture = _cc2.RenderTexture;
      sys = _cc2.sys;
      UITransform = _cc2.UITransform;
      gfx = _cc2.gfx;
      director = _cc2.director;
      Texture2D = _cc2.Texture2D;
      view = _cc2.view;
      Vec3 = _cc2.Vec3;
      _cc = _cc2;
    }, function (_unresolved_2) {
      Util = _unresolved_2.Util;
    }],
    execute: function () {
      _crd = true;

      _cclegacy._RF.push({}, "c7ad9Uv91xGG5u6d7Q8RHwV", "scene2b", undefined);

      __checkObsolete__(['_decorator', 'Component', 'Node', 'Camera', 'RenderTexture', 'sys', 'UITransform', 'gfx', 'director', 'ImageAsset', 'Texture2D', 'SpriteFrame', 'Sprite', 'view', 'tween', 'Vec3', 'isValid']);

      cc = __checkObsoleteInNamespace__(_cc);
      ({
        ccclass,
        property
      } = _decorator);

      _export("scene2", scene2 = (_dec = ccclass('scene2'), _dec(_class = class scene2 extends Component {
        constructor(...args) {
          super(...args);
          this.lastTime = void 0;
        }

        onLoad() {
          //禁用动态合图
          cc.DynamicAtlasManager.instance.enabled = false;
          let node = cc.find("Canvas/node");
          let img = cc.find("Canvas/img");
          let img2 = cc.find("Canvas/img2");
          let button = cc.find("Canvas/Button");
          var uit = node.getComponent(cc.UITransform);
          var nodeWW = uit.width,
              nodeHH = uit.height;
          var rt;
          button.on(cc.Node.EventType.TOUCH_END, () => {
            let tKey = "draw"; // node = cc.find("Canvas/node/Sprite-002");

            var uit0 = node.getComponent(cc.UITransform);
            nodeWW = uit0.width, nodeHH = uit0.height;
            let viewS = view.getVisibleSize();
            let box = this.getNodeBounds(node, false);
            let renderSize = null;
            let addSize = null;

            if (box.x < 0 || box.xMax > viewS.width) {
              let widthAdd = Math.max(Math.abs(box.x), box.xMax - viewS.width);
              let ww = viewS.width + widthAdd * 2;
              let hh = Math.round(ww / viewS.width * viewS.height);
              renderSize = new cc.Size(ww, hh);
              addSize = new cc.Size(widthAdd, Math.round((hh - viewS.height) / 2));
            }

            var dd = this.drawToRenderTexture2(node, renderSize);
            rt = dd;
            let texture = new cc.Texture2D();
            console.time(tKey);
            var sp = img.getComponent(cc.Sprite);
            sp.spriteFrame = new cc.SpriteFrame();
            sp.spriteFrame.texture = dd;
            sp.spriteFrame.flipUVY = true; // sp.updateMaterial()

            let uit = img.getComponent(cc.UITransform);
            uit.width = view.getVisibleSize().width;
            uit.height = view.getVisibleSize().height; // console.timeEnd(tKey)

            nodeWW = box.width, nodeHH = box.height;
            let buff = this.getTextureBuff(node, dd, box, addSize); //传了box表示用指定区域截图，不传则使用node自身UITransform尺寸截图
            // let imgA = new ImageAsset({
            //     _data:buff,
            //     _compressed: false,
            //     width: nodeWW,
            //     height: nodeHH,
            //     format: cc.Texture2D.PixelFormat.RGBA8888
            // })
            // let texture = new cc.Texture2D();
            // texture.setFilters(cc.Texture2D.Filter.NONE,cc.Texture2D.Filter.NONE)
            // texture.image = imgA;
            //包含 RGBA 四通道的 32 位整形像素格式：RGBA8888。 一字节8位

            texture.reset({
              width: nodeWW,
              height: nodeHH,
              format: Texture2D.PixelFormat.RGBA8888,
              mipmapLevel: 0
            });
            texture.uploadData(buff, 0, 0);
            texture.updateImage();
            console.timeEnd(tKey); // this.validateNow()

            var sp2 = img2.getComponent(cc.Sprite);
            sp2.spriteFrame = new cc.SpriteFrame();
            sp2.spriteFrame.texture = texture;
            sp2.spriteFrame.flipUVY = true;
            let uit2 = img2.getComponent(cc.UITransform);
            uit2.width = nodeWW; // uit2.width = nodeWW/3;

            uit2.height = nodeHH;
            img2.setScale(1, 1, 1);
            setTimeout(() => {// img.active = false;
              // dd.destroy();
            }, 1000);
            window.ss = texture;
          }, this);
          let maskCon = cc.find("Canvas/maskCon2");
          maskCon.active = false;
          let maskbtn = cc.find("Canvas/maskbtn");
          maskbtn.on(cc.Node.EventType.TOUCH_END, () => {
            maskCon.active = true;
            var sp = maskCon.getComponent(cc.Sprite);
            sp.spriteFrame = new cc.SpriteFrame(); // sp.spriteFrame.texture = rt;

            sp.spriteFrame.texture = window.ss;
            let uit = maskCon.getComponent(cc.UITransform);
            uit.width = view.getVisibleSize().width;
            uit.height = view.getVisibleSize().height;
            uit.width = nodeWW;
            uit.height = nodeHH;
          }, this);
          let nodes5 = cc.find("Canvas/node/Sprite-002");
          let box = nodes5.getComponent(cc.UITransform).getBoundingBox();
          box = this.getNodeBounds(nodes5);
          nodes5.parent.addChild((_crd && Util === void 0 ? (_reportPossibleCrUseOfUtil({
            error: Error()
          }), Util) : Util).createStroke(0xff0000, box.x, box.y, box.width, box.height));
          console.time("nextFrame");
          this.scheduleOnce(() => {
            console.timeEnd("nextFrame"); //55毫秒

            console.log('This is executed in the next frame.');
          }, 0); //帧事件，按顺序从上到下

          let time = Date.now();
          cc.director.once(cc.Director.EVENT_BEGIN_FRAME, dt => {
            console.log(1, dt);
          });
          cc.director.once(cc.Director.EVENT_BEFORE_UPDATE, dt => {
            console.log(2, dt);
          });
          cc.director.once(cc.Director.EVENT_AFTER_UPDATE, dt => {
            console.log(3, dt);
          });
          cc.director.once(cc.Director.EVENT_BEFORE_PHYSICS, dt => {
            console.log(4, dt);
          });
          cc.director.once(cc.Director.EVENT_AFTER_PHYSICS, dt => {
            console.log(5, dt);
          });
          cc.director.once(cc.Director.EVENT_BEFORE_DRAW, dt => {
            console.log(6, dt);
          });
          cc.director.once(cc.Director.EVENT_BEFORE_COMMIT, dt => {
            console.log(7, dt);
          });
          cc.director.once(cc.Director.EVENT_BEFORE_RENDER, dt => {
            console.log(8, dt);
          });
          cc.director.once(cc.Director.EVENT_AFTER_RENDER, dt => {
            console.log(9, dt);
          });
          cc.director.once(cc.Director.EVENT_AFTER_DRAW, dt => {
            console.log(10, dt);
          });
          cc.director.once(cc.Director.EVENT_END_FRAME, dt => {
            console.log(11, dt);
          });
        }

        getNodeBounds(node, worldSpace) {
          var _node$parent;

          const uiTransform = node.getComponent(cc.UITransform);
          if (!uiTransform) return new cc.Rect(); // 获取当前节点的包围盒的四个顶点（在本地坐标系）

          const box = uiTransform.getBoundingBox();
          const topLeft = new Vec3(box.xMin, box.yMin, 0);
          const bottomRight = new Vec3(box.xMax, box.yMax, 0); // 将当前节点的包围盒范围转换到父节点坐标空间

          const parentTransform = (_node$parent = node.parent) == null ? void 0 : _node$parent.getComponent(UITransform);

          if (parentTransform) {
            parentTransform.convertToWorldSpaceAR(topLeft, topLeft);
            parentTransform.convertToWorldSpaceAR(bottomRight, bottomRight);
          } // 初始最小和最大值


          let xMin = topLeft.x;
          let yMin = topLeft.y;
          let xMax = bottomRight.x;
          let yMax = bottomRight.y; // 遍历子节点合并包围盒

          node.children.forEach(child => {
            const childBounds = this.getNodeBounds(child, true); // 更新最小值和最大值

            xMin = Math.min(xMin, childBounds.x);
            yMin = Math.min(yMin, childBounds.y);
            xMax = Math.max(xMax, childBounds.x + childBounds.width);
            yMax = Math.max(yMax, childBounds.y + childBounds.height);
          }); // 返回包含所有子节点的最小包围盒
          // let result = new cc.Rect(xMin, yMin, xMax - xMin, yMax - yMin);

          let result = new cc.Rect(Math.round(xMin), Math.round(yMin), Math.round(xMax - xMin), Math.round(yMax - yMin));

          if (!worldSpace) {
            topLeft.x = result.xMin;
            topLeft.y = result.yMin; // 将包围盒世界坐标系转换为当前节点在父容器的坐标

            if (parentTransform) {
              parentTransform.convertToNodeSpaceAR(topLeft, topLeft);
            }

            result.x = Math.round(topLeft.x);
            result.y = Math.round(topLeft.y);
          }

          return result;
        }

        getTextureBuff(targetNode, renderTex, box, addSize) {
          let uit = targetNode.getComponent(UITransform);
          let width = uit.width,
              height = uit.height; // width = 720, height=1386;

          let worldPos = targetNode.getWorldPosition();
          let region = new gfx.BufferTextureCopy();
          region.texOffset.x = Math.round(worldPos.x - width * uit.anchorPoint.x);
          region.texOffset.y = Math.round(worldPos.y - height * uit.anchorPoint.y); // region.texOffset.y = view.getVisibleSize().height - region.texOffset.y - height;
          // region.texOffset.x = region.texOffset.y=0;

          let widthAdd = (addSize == null ? void 0 : addSize.width) || 0;
          let heightAdd = (addSize == null ? void 0 : addSize.height) || 0;

          if (box) {
            let worldPos22 = targetNode.parent.getWorldPosition();
            region.texOffset.x = Math.round(Math.max(0, worldPos22.x + box.x + widthAdd));
            region.texOffset.y = Math.round(Math.max(0, worldPos22.y + box.y + heightAdd));
            width = box.width;
            height = box.height;
          }

          let texBuffers = [];
          texBuffers[0] = new Uint8Array(width * height * 4);
          region.texExtent.width = width;
          region.texExtent.height = height;
          director.root.device.copyTextureToBuffers(renderTex.getGFXTexture(), texBuffers, [region]); // renderTex._getGFXDevice().copyTextureToBuffers(renderTex.getGFXTexture(), texBuffers, [region]);

          let _buffer = texBuffers[0]; // this.saveAsImage(width, height, _buffer);

          return _buffer;
        }

        saveAsImage(width, height, arrayBuffer) {
          width = Math.round(width);
          height = Math.round(height);

          if (sys.isBrowser) {
            let _canvas = document.createElement('canvas');

            _canvas.width = width;
            _canvas.height = height;

            let ctx = _canvas.getContext('2d');

            let rowBytes = width * 4;

            for (let row = 0; row < height; row++) {
              let sRow = height - 1 - row;
              let imageData = ctx.createImageData(width, 1);
              let start = sRow * width * 4;

              for (let i = 0; i < rowBytes; i++) {
                imageData.data[i] = arrayBuffer[start + i];
              }

              ctx.putImageData(imageData, 0, row);
            } //这2个方法都可以


            this.eliFoTevas(_canvas, "", "aa.png", null, null);
          }
        }

        eliFoTevas(canvas, type, filePath, rect, encoderOptions) {
          // var base64 = toDataURL.call(this, type, rect, encoderOptions);
          let base64 = canvas.toDataURL("image/png");

          if (base64 == null) {
            return;
          }

          var href = base64.replace(/^data:image[^;]*/, "data:image/octet-stream");
          var aLink = document.createElement('a');
          aLink['download'] = filePath;
          aLink.href = href;
          var evt = document.createEvent('MouseEvents');
          evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          aLink.dispatchEvent(evt);
        }

        update(deltaTime) {// console.log("ss", deltaTime); //等于cc.game.frameTime
        }

        changeLayer(node, layer) {
          node.children.map(item => {
            this.changeLayer(item, layer);
          });
          node.layer = layer;
        }

        drawToRenderTexture2(node, renderSize) {
          let oldLayer = node.layer;
          let drawLayer = cc.Layers.nameToLayer("drawNode") + 1;

          if (oldLayer != drawLayer) {
            this.changeLayer(node, drawLayer);
          }

          renderSize = renderSize || view.getVisibleSize();
          let renderTex = new RenderTexture();
          renderTex.reset({
            width: renderSize.width,
            height: renderSize.height
          });
          let node2 = new cc.Node('CaptureUtils'); // node2.setScale(1, -1, 1);

          this.node.addChild(node2);
          let camera = node2.addComponent(cc.Camera);
          camera.projection = cc.Camera.ProjectionType.ORTHO;
          camera.near = 0;
          /* 默认1，必须改为0否则黑屏 */

          camera.visibility = cc.Layers.nameToLayer("drawNode") + 1;
          camera.orthoHeight = renderSize.width; //640

          camera.clearColor = camera.clearColor.fromHEX("00000000");
          camera.targetTexture = renderTex;
          (_crd && Util === void 0 ? (_reportPossibleCrUseOfUtil({
            error: Error()
          }), Util) : Util).validateNow();
          camera.targetTexture = null;
          node2.parent = null;
          this.changeLayer(node, oldLayer);
          return renderTex;
        }

      }) || _class));

      _cclegacy._RF.pop();

      _crd = false;
    }
  };
});
//# sourceMappingURL=e8a05998cb1dad5598a686df9fbbf95ae32c75ce.js.map